Hosk’s Top CRM Articles of the week – 1st May

Article of the Week

Great detailed blog on conditional formatting with CRM Charts

Highlighting contribution using conditional formatting in CRM charts

The article of the week is a pair of blogs by Adam Vero on charting.  The article will show you how to tinker with the chart XML to give you more control over what is displayed.

Best of the Rest

CRM 2013 – Create Enumerations for option sets

How and why you should Enum for your option set in your CRM code

GETTING STARTED WITH MICROSOFT DYNAMICS CRM 2015 ROLLUP FIELDS

A look at rollup fields in CRM 2015

Experiences of Unit testing with Microsoft Dynamics CRM Projects

Hosk experiences of unit testing in CRM projects

LINQPad 4 Driver for Dynamics CRM is available on CodePlex

A new version of LINQPad has been released

Don’t just test the happy path

Don’t just test the happy path, test the other paths as well

Setting up your Dynamics CRM Development & Source Control Environment

CRM 2013 – Investigation into replacing the Assign functionality

Hosk was trying to find a solution to a requirement

GetAttributeValue demystified

GetAttributeValue will stop putting null checks in your code

CRM 2015 – How to change the option set default value

Find where the option set default value is kept

Debug / Unit Test CRM 2011 JavaScript Rest/Soap in visual studio for on-premise CRM installation

Good article on unit testing Javascript in CRM

Why you shouldn’t put unsupported customizations in Microsoft Dynamics CRM

Don’t go down the dark side of CRM development, don’t put in unsupported customizations

Deployment Options

The deployment options for CRM

Microsoft Dynamics CRM Online patterns & principles for solution builders

White paper on building solutions for CRM online

What is max degree of parallelism option setting in SQL Server?

An SQL server setting you can change, but what does it do

programming

Get Visual code here

Microsoft releases free code editor for Mac and Linux!!

C# Coding Conventions (C# Programming Guide)

Screaming Architecture

Great article from Uncle Bob on architecture

TEST YOUR SAD PATH FIRST

Happy path testing

Lessons Learned in Software Development

other

The Timeless Nature of the Herd Mentality

Mental Model: Bias from Overconfidence

Last Weeks Top CRM Articles

Hosk’s Top CRM Articles of the week – 24th April

Useful Hosk Links

Hosk list Of CRM 2013 Tools

A list and review of CRM 2013 tools, this will probably work in CRM 2015 as well

Hosk’s CRM Developer Articles

A collection of my favourite CRM Developer articles I have written

MB2-703 – CRM 2013 Customization and Configuration Certification Information

All the CRM 2013 content to help you pass the exam

HoskWisdom – Hosk Developer Quotes

 Words of Wisdom from the Hosk.  I have written over 900 articles, surely I should have said a few memorable things

CRM 2013 – Investigation into replacing the Assign functionality

I had a small one line change request for a CRM 2013 implementation

Replace Assign functionality with will show users of the current users team.

I thought it would be easy to write a technical specification for this requirement.

First thoughts

Assign form is a special CRM form, I know this cannot be edited or manipulated (in a supported way).

This was much trickier than I initially thought it would be.  As an added bonus finding what users are in a team is not straight forward and you have to use a link entity when you do it in an advanced find.

Here are my thoughts of possibles solutions

Method 1

Create a new form to replace the Assign form.

Work

  • Create ASP page to include a filter lookup to CRM
  • Interact with CRM SDK to retrieve rows and update values
  • Ribbon button change

Pro’s

It would offer the functionality required

Con’s

It would take quite a bit of effort for a seemingly small change

 

Method 2

Open a standard lookup form, calling the lookup form in CRM and filter it

I researched this idea (which I found very difficult to find on the internet)

I go this page

HowTo: Open standard lookup window and get selected record(s)

CRM 2013 Open lookup as dialog in Custom HTML

This method wasn’t suitable because it’s unsupported and I couldn’t see how to filter the lookup.

Method 3

Using a dialog to first return the a list of teams the user is a member.

The user would select a team, press next

This would then return a list of users

Work

Create a dialog

Create custom workflows 1.  retrieve the users team, 2.  Retrieve users in team.

A ribbon button could call the dialog (This can be done using the Ribbon workbench Create a Dialog Short-Cut Ribbon Button)

Pro’s

It should deliver the functionality required

Con’s

Dialog’s are not the quickest

There is still quite a bit of work, two custom workflows and a dialog

 

Method 4

The easiest solution would be to add a user lookup on the form and if the set a value I could trigger a plugin or workflow to assign the records.

The lookup would need be filtered to the team.

I had heard CRM 2013 had prefilters, which allowed you to add filter to a lookup.  When investigating this it turns out you cannot create a filter with a linked entity and can only filter on values which exist on the SystemUser (user) entity.

This excellent blog post

CRM 2013 Using addCustomFilter() to get Filtered Lookup Field based on Linked Entity

Mentions the problem and you can get around it by using the addcustomview but this means you have to create a whole view.

Instead I tried out the functionality in Miss Dynamics CRM blog and use the addCustomFilter()

I thought I would try this out because I had not yet used the AddCustomFilter() solution and this seemed the easiest and quickest

First I created a view in the Advanced find (Why the advanced find is a CRM Developers best friend)

Assign Team problem

 

I then got downloaded the Fetch XML and put it into the FetchXML Builder

Assign Team problem 1

I could then get the guids, Aileen Gusni mentioned some workarounds in her blog to get  AddCustomFilter() to work you could use OData to retrieve the data you needed and


var Hosk = Hosk || { __namespace: true };
Hosk.Functions = Hosk.Functions || { __namespace: true };
Hosk.Functions.HoskTest = Hosk.Functions.HoskTest || { __namespace: true };

; (function () {

this.formLoad = function () {
addEventHandler();

};

function addEventHandler() {
// add the event handler for PreSearch Event
Xrm.Page.getControl("hosk_userassignid").addPreSearch(addFilter);
};

function addFilter() {
//create a filter xml
var filter =
"<filter type='and'>" +
"<condition attribute='systemuserid' operator='in'>" +
"<value>{9fed63fe-c0cc-e411-80c7-000c292122be}</value>" +
"<value>{cba24eea-bacc-e411-80c7-000c292122be}</value>" +
"<value>{2ed69167-0bcf-e411-80c7-000c292122be}</value>" +
"<value>{92c6d456-7bdf-e411-80c8-000c292122be}</value>" +
"</condition>" +
"</filter>";

//add filter
Xrm.Page.getControl("hosk_userassignid").addCustomFilter(filter);
}
}).apply(Hosk.Functions.HoskTest);

The code work, I had filtered the User lookup to those records.

Assign Team problem 2

The filtering kept true even when you clicked look up more records.

The next step I could retrieve the data from an OData call and Dynamically create the line

“<value>{cba24eea-bacc-e411-80c7-000c292122be}</value>” +

Then have a workflow/plugin to assign the records

Work

new field

Javascript change to add filtering

plugin/workflow to assign records.

PRO’s

The quickest solution in time to create and running time

Con’s

It’s different from the current assign button, this may confuse users

The option chosen was….

After spending time thinking about the problem and coming up with some choices the customer decided they didn’t want it.

This is something which happens to developers, one day you can create a change and the next day a customer decides they don’t want it and you have to take it out.

The customer didn’t want the change but I did get to investigate some CRM functionality I hadn’t used yet.

If you have a better solution please leave it in the comments.

CRM 2015 – How to change the option set default value

I recently had a few issues with Status Reasons and the number associated with a status reason

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

This lead me to have to add a Status Reason into CRM using CRM SDK because I couldn’t figure out where the default number of a new status reason was being calculated.

CRM 2013 – How add a status reason using the CRM SDK

Default option set value

Today I figured out where the number was coming from when you create a new option set.  This value is set in the publisher.  There is a field called Option Value Prefix

OptionSet default value

When I go into my Hosk Solution, which uses the Hosk Publisher and create a new option set, it takes the default value from the publisher

OptionSet default value 1

The default value is also used for new Status Reasons

OptionSet default value 2

Customize from the default solution

The default solution includes all the customizations in CRM and this is the solution you access when you choose customize the system.

To understand solutions read more in the blog post below

CRM 2013 – Understanding Solutions and how they work

What values will be used when you add a new option set or status reason when editing the default solution

The status reason seemed to still use the default value in my new publisher.  This was unusual because I would have expected it to use the value in the Default publisher which was 10000 because this is the publisher specified in the Default Solution?  The default publisher is read only so this cannot be changed.

OptionSet default value 4

I did a bit more digging and found CRM seems to calculate which solution the entity is in and then uses the solution option value prefix even if you edit it using whilst in the default solution.

When I added a new optionset it did use the value in the default publisher

OptionSet default value 3

Don’t just test the happy path

The original title of this blog post was – Developers should stop being so happy.  I found the old title amusing because over the years I have met some extremely grumpy developers.  Classic old school developers who liked to sit in dark corner and not be disturbed.

The point of this article is grumpy developers can still skip and dance down the happy path when it comes to writing and testing their code.

I am continuing to read Code Complete 2 (it’s over 900 pages long it will take me a while), today I came to an interesting paragraph.

Avoid Failure

Petroski argues that many spectacular bridge failures have occurred because of focusing on previous successes and not adequately considering possible failure modes. He concludes that failures like the Tacoma Narrows bridge could have been avoided if the designers had carefully considered the ways the bridge might fail and not just copied the attributes of other successful designs

 

Developers are too happy

The process of development usually goes

  • Requirements gathered
  • Functional requirement specified
  • Technical requirements specified
  • Code written to deliver requirements
  • Test –> fix bugs cycle

Developers often focus on delivering the functionality, which is often known as following the happy path

Wiki describes as the Happy Path

In the context of software or information modeling, a happy path is a default scenario featuring no exceptional or error conditions, and comprises the sequence of activities executed if everything goes as expected.[1][2] For example, the happy path for a function validating credit card numbers would be where none of the validation rules raise an error, thus letting execution continue successfully to the end, generating a positive response.

 

Focusing on the happy path and creating the required functionality leaves room for bugs in production, when end users stray from the happy path into the alternative path or the exception path.

Developers naturally gravitate towards the happy path, often focusing on happy path testing.  One possible reason for this behaviour is the developer doesn’t see the functionality from the end users point of view, instead the functionality is viewed primarily from the code point of view.

It isn’t obvious to developer why end users would supply different values to what they are expecting, how the end users will use the functionality or what they are trying to achieve using the functionality.

Happy path testing can leave gaps for nulls, incorrect values and a host of error checking/validating errors to slip into a production system because no one has tested these paths.

The other area bugs come in is, is developer under estimate the random actions of end users.

Developers are not good testers

Developers often are poor at testing, this is a badly kept secret of the programming world (developers often dislike testing as well).  Developers are so poor at testing their own code it’s considered good practise to get other people to test the code.

One  reason CRM developers miss bugs in CRM is they test everything using the System Administrator role which avoids many permission bugs, I have written about in this blog

The System Administrator role is a benefit and a curse to CRM developers

Developers are not good at testing because after writing the code it’s difficult to step back and test the functionality rather than test the code.  This is similar to writers editing their own writing, they feel attached to their creation to the extent they find it hard to evaluate it dispassionately.

How to avoid failure

An effective way of avoiding failure is writing unit tests for the code.  The act of writing unit tests make the developer think

  • What should this functionality do e.g. what am I testing
  • What values (min, max) are allowed
  • What alternative values might be presented
  • What should happen when an error happens

Thinking before coding is always beneficial, sometimes developers are eager to get coding they miss this step out.

Once the code is written is unappealing for developers to write unit tests, so the best method of unit testing is to write unit tests while you create the code and use those unit tests to make sure it’s working as expected.

Thinking about errors and failures is very beneficial.  You will capture and avoid many errors.  The developer will decide how to handle errors and its usually a choice

  • Fail fast, abort action
  • continue and warn the user

Errors are not good but code which has blundered on and changed half the values it was expecting can make a greater mess and take longer to clean up, so it’s better to have a plan up front.

Don’t let these often simple errors slip out of your development environment to the end user, make sure you harden your code.

If you don’t write unit tests you should consider doing it

Why CRM Developers should unit test their code

Experiences of Unit testing with Microsoft Dynamics CRM Projects

If you still are not persuaded to write unit tests make sure you go through you code and look for potential errors, validation checks.  Make sure you have decided how you will handle errors in the code.  It’s much better/quicker/easier to manage errors in a dev environment than having to add it in at a later date.

More reading for you

TEST YOUR SAD PATH FIRST

Happy Path Testing

Experiences of Unit testing with Microsoft Dynamics CRM Projects

Many moons ago when I was a Java developer and learning how to code, I remember two things which had a big impact on my coding.  One was learning about Design patterns and the other was learning about Test Driven Development.

Writing unit tests for your code before you actually write the code seems like a strange thing to do and I didn’t meet many developers who did this or in fact bother writing unit test at all.

I found writing code which you knew was going to be tested with units tests forced me to write modular/reusable code.  It makes you write code which can be tested and usually this means each function does only one thing (because that’s easier to test).

The code is more likely to Single responsibility principle and each class and method doing one thing, the reason for this is because it’s easier to test something which only does one thing.

Pro and Con’s of Unit Testing

When unit tests and writing unit tests are mentioned this question is not usually far behind

What’s the benefit of writing extra code to test your code?

This can be a hard sell to some developers, it would be similar to trying to explain to a messy teenager the benefits of cleaning your room.   One the major complaints raised against writing tests is it takes extra time and we developers don’t have time to do it.

Writing unit tests involves thought and effort creating dummy data, deciding where to mock or stub to get enough data to test the code.  This can feel like a lot of wasted time when you can spend half a day getting the data created to test your code.

This effort can be too much for some developers and they will never like writing units and always view it as a waste of time.  This point of view is a common initial thought until the developer tries it and starts to see the benefits with the improved confidence of their code.

The irony of the aversion to unit testing is developers test their code by creating console apps or debugging the code. Unit testing is taking this process and making it reusable and self-contained

When writing unit test you stop and think about how the code and objects are going to be used.

Below is my experiences of unit testing and CRM, there are probably lots of companies and CRM developers are are unit testing their code

PRO’s of Unit Testing

  • confident the code works because it has been tested
  • Higher quality code (more modularised/reusable) to enable tests to be written
  • Any changes to the code can be tested quickly with no extra effort once tests have been written
  • unit tests can help developers new to a project understand how the code (should) work
  • very useful for testing refactored or bugfixed code
  • It’s easier to debug unit tests than deployed CRM code

CON’s of  Unit Testing

  • It takes extra time to write the unit tests and prepare the data
  • Unit tests have to be maintained and updated
  • You have to learn the testing framework and how to write tests (this is non-revenue generating time)
  • A feeling of not moving forward

My Experience of CRM Unit Testing

Unit tests and CRM in my experience have never really happened for a number of reasons/excuses, I have listed them below

Smaller projects

Smaller projects usually remove all non development tasks and reduce everything to the bar bones.  Unit tests were seen as non productive time the customer didn’t want to pay for.

Often small projects had a very limited about of code customizations

Time

Developers never have enough time to do everything the customer wants and usually the first thing to get snipped out is testing and unit tests.  See Why rushed projects/code doesn’t save time and reduces quality

Best Practise/Best Testing framework

Most CRM projects I have worked on haven’t used unit testing.  below I detail some of the reasons this (I’m not saying I agree with them but stating them).  I would say I wasn’t always keen to unit test my code but part of the reason was because the code in the projects wasn’t unit tested.

Cost

Some unit test frameworks do have a cost associated with them.  Microsoft Fakes used to only be included in the Ultimate version of Visual studio (which was very expensive) but it got voted into visual studio premium on Jan 30th 2013.

CRM developers didn’t seem to know (or maybe care) about this because I didn’t meet any CRM developers who liked or did any unit testing of the plugins/custom workflows until recently when I joined my current company.

Joining a project with no unit tests

The decision to unit test usually happens at the start of the project.  Many of the projects I have worked on didn’t have unit tests.

Legacy code impossible to test

Most people don’t bother to try and write unit tests for legacy code.  I can understand this because it would be very difficult

Plugin/Custom workflows hard to test

What do I mean hard to test?  Plugins/custom workflows need a IPluginExecutionContext context so you can test the plugins.  So to properly test a plugin you would need to create a IPluginExecutionContext with the correct attributes.

This would take quite a bit of effort.  To get an idea of all the data created you can use the debugging with the plugin profiler as an example.  When you debug with plugin registration tool, you set it to record the data for a certain plugin, run through triggering it in CRM.  This will create an xml file with all the fields and values.

You can then use this file to recreate the scenario you ran through in CRM and it will pass all those field choices into your Visual studio debugger.   This blog runs through the process

No insistence of unit tests

The projects I worked on, no one insisted unit tests were created, apart from one project.   Instead the code would be tested by each developer and then put forward to an integration test.
Unit testing has to be a company or project policy or something which developers of a company are doing.

Senior developers weren’t doing it

Junior developers learn good and bad habits from senior developers.  In most of the projects I have worked on there were no unit tests.  I haven’t met any (1 or 2) CRM developers who write unit tests and most do not promote unit testing.

Examples to copy

When you type CRM and unit tests you do not get many results back and this suggests unit testing CRM code is not common practise.  More examples and blog posts would make it easier for CRM developers to use this code in their projects.

How Hosk tested his Code

The way I developed my code customizations was to create the code in separate class outside of the plugin code.  I would then create a console app and test the code by passing in a IOrganisationservice, TracingService and Entity.  This allowed me to walk through the code and retrieve data from the development CRM organisation.

I’m not entirely sure how other developers would test their code, I have a sneaky suspicion most would use integration testing (deploy and test it using CRM) and look at the log files.

This article was in draft status for quite a while and in the mean time I have started writing unit tests. I first tried using RhinoMocks and then found Microsoft fakes was free in the premium edition.

I have written the article

Why CRM Developers should unit test their code

I am now a firm believer CRM developers should be writing units for their customizations and there isn’t any excuses why unit tests are not written.  The lack of unit tests is not limited to CRM Development but wide spread in a lot of programming.

There are some difficulties in writing unit tests in CRM but it is achievable using Microsoft fakes.

CRM Project with Tests

There has been a drive to test the code in a project and the developers are writing tests for code which already exists.

I won’t lie this is a tricky a task.  When code hasn’t been written with testing in mind it can be very difficult to test.

I will say some tests are definitely better than no tests and the code was decently structured so a lot of the code plugins are using is now separately tested.

It has taken some time for developers to get to grips with the testing framework and the testing methodology.  Testing is a different mindset and it takes  bit of time to learn the tips and tricks and common testing methods.

The benefits have been

  • Tests any developer can run
  • The business logic is quite complex in the project, so having a method to step through parts of the code is very useful.
  • Tests can be run be developers who didn’t create the code, much quicker than trying to test the code yourself.
  • Easier to see if your code has broken other parts of system

Plugins and testing

Some developers can have a blinkered view of testing the plugins themselves.  Plugins are not always easy to test and sometimes a plugin doesn’t do much.

A create plugin might validate values

A plugin could update related records

I personally remove all the code from the plugin and create separate classes where the constructors take IOrganisationService and TracingService.  The method can then take an entity record which has triggered the plugin.

Unit tests can be run against the code which is split up into small focused classes/methods.

At the end you plug all the small tested parts together and link it to the plugin.

Why have I changed my mind about unit tests and CRM

 

Looking at the list of reasons why unit testing was done on the CRM projects I worked, I can see they are not reasons they are excuses.   Most disappointingly is some of the excuses for not writing unit code are excuses I have been making to myself.

I have been reading  Clean Code: A Handbook of Agile Software Craftsmanship (Robert C. Martin) and Uncle Bob mentions we as developers/programmers should be testing our code and our code should be good.

He has this quote in Clean Code

Why does good code rot so quickly into bad code? We have lots of explanations for it. We complain that the requirements changed in ways that thwart the original design. We bemoan the schedules that were too tight to do things right. We blather about stupid managers and intolerant customers and useless marketing types and telephone sanitizers. But the fault, dear Dilbert, is not in our stars, but in ourselves. We are unprofessional.

This year I have been thinking about the quality of CRM code/customizations and have been coming to the conclusion the quality of code in CRM projects need to be better.

I re read my post –  The Frustrations of a CRM Developer many of the frustrations come from poor code.

Quite a few of the CRM Developers articles I have written this year are focused on creating quality customizations

Before reading Clean code I knew I should be writing unit tests but took the easy option of not doing it.  After writing some unit tests for my current development, it has been so much easier refactoring my code and making changes.  Having 40 unit tests testing code change gives me confidence the refactored code works.

Unit testing helps projects from falling into a state of Legacy code because writing code you can tests makes the developer

  • Think about the code design
  • Think about what the functionality should do
  • Test the code more thoroughly
  • Creates reusable tests to all developers on the project

I hope this and future blog posts will get more CRM developers to start unit testing their code.

The biggest driver for unit testing code should come from the developer, who has pride in their work and wants to deliver high quality code.  This is an attitude, it’s a desire to create quality code.

The benefits of unit testing are undeniable and if you start unit testing your work you will soon enjoy the benefits.  If you are already writing unit tests then keep up the good work and write a blog about it to encourage other CRM developers.

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

 

 

What is max degree of parallelism option setting in SQL Server?

A ticket opened recently with Microsoft support involved changing a the  max degree of parallelism on the SQL server.

I had not used or heard of this setting before, which isn’t a surprise I tend to leave SQL Server settings to the people who know more about the consequences.

Early in the year I did look at effects of changing the SQL Server trace flag 8780 which resulted in reports running faster but is unsupported unless Microsoft support teams advices you to do it!

CRM SQL Query go faster trick – SQL Server trace flag 8780

My goal in this blog is to give an overview about max degree of parallelism Option and some links to more information.

Remember to always consider the effects of changing flags and options, they can change results/efficiency in other SQL queries

What is max degree of parallelism Option 

The place to start is the MSDN article

max degree of parallelism Option

When SQL Server runs on a computer with more than one microprocessor or CPU, it detects the best degree of parallelism, that is, the number of processors employed to run a single statement, for each parallel plan execution. You can use the max degree of parallelism option to limit the number of processors to use in parallel plan execution. The default value of 0 uses all available processors up to 64 CPUs

You can learn more about Degree of Parallelism in this specific article

This setting is sometimes known as MAXDOP (max degree of parallelism)

Hosk understanding

This max degree of parallelism controls how many processors in the SQL server can be used on any one single query.

The default value for Max degree of parallelism is set to 0, this means there is no limit to the number of processors.

If you change the option to a number e.g. 1, you are then limiting the SQL server to use one processor for each query.

This setting seems to be changed when users want to limit the number of processors used in single queries to stop SQL server taking all the processors for single queries.

The setting is also used to increase the number to improve performance in single queries.

This is a server side setting so you need to consider how changing this setting could effect the performance of all SQL queries on the SQL server (and maybe not just CRM)

More information

This article is very useful because it mentions limitations and restrictions and recommedations

Configure the max degree of parallelism Server Configuration Option

This recommendations I found interesting

  • This option is an advanced option and should be changed only by an experienced database administrator or certified SQL Server technician.
  • To enable the server to determine the maximum degree of parallelism, set this option to 0, the default value. Setting maximum degree of parallelism to 0 allows SQL Server to use all the available processors up to 64 processors. To suppress parallel plan generation, set max degree of parallelism to 1. Set the value to a number from 1 to 32,767 to specify the maximum number of processor cores that can be used by a single query execution. If a value greater than the number of available processors is specified, the actual number of available processors is used. If the computer has only one processor, the max degree of parallelism value is ignored.
  • You can override the max degree of parallelism value in queries by specifying the MAXDOP query hint in the query statement. For more information, see Query Hints (Transact-SQL).

It seems to suggest you can set it on an individual query basis.

Here is another article

Recommendations and guidelines for the “max degree of parallelism” configuration option in SQL Server

How to change the Max degree of parallelism Option

It’s an SQL option so set the value using an sql statement.

I took the code from this page

https://msdn.microsoft.com/en-us/library/dd979074(v=crm.6).aspx


exec sp_configure 'show adv', 1;

RECONFIGURE WITH OVERRIDE;

exec sp_configure 'max degree', 1

RECONFIGURE WITH OVERRIDE;

Exec sp_configure

This is a server wide setting, so it would effect all the CRM organisations you have on the SQL Server and other databases.

How does is this setting used with CRM

Take into account I have not had any personal experience changing this setting, I saw it was mentioned as a possible resolution, I decided to investigate.  

This setting usually effects CRM if you have multiple long running queries.  It can cause the CRM performance to slow.

This article talks about CRM 4

Microsoft Dynamics CRM Server performance is less than expected

In the example above it seems the SQL server was using all the processors on one long running query which caused performance of CRM in general to slow down.  It limits sets the MAXDOP to 1 to stop this.

This article is very good and the blog looks into the setting in detail

Max degree of Parallelism in SQL Server

The article concludes it’s probably best to tinker with this setting only if your having slow performance from your SQL server/CRM.

Other articles

Case Study: Part 1: CXPACKET Wait Stats & ‘max degree of parallelism’ Option: Introduction to Using Wait Stats to Identify & Remediate Query Parallelism Bottlenecks

Case Study: Part 2: CXPACKET Wait Stats & ‘max degree of parallelism’ Option: Suppressing Query Parallelism Eliminated CXPACKET Waits & Liberated 30% of CPU

Interesting forum discussions

Max degree of parallelism setting