CRM 2013 – using Entity.GetAttributeValue instead of Entity.Contains

I found myself writing this tried and tested code, which I have written many times before

if (entity.Contains("salutation"))
{
     title = ( string)entity.Attributes["salutation"];
}

before you can get a value from the entity attributes you need to check the field is included in the list of parameters. I traditionally use to do this using entity.Contains(“fieldname”), if the field specified exists in the list of parameters it will return true. The reason this works is because CRM doesn’t pass null values in the parameter list, so if its null it won’t exist.

Often in code you will lines and lines of Entity.Contains code, checking the field exists before assigned the value.

Is there a better way

I remember an excellent post featured on CRM MCC Guido on his blog CRM Answers
Entity.GetAttributeValue and ActivityParty

The article was about using Entity.GetAttributeValue and in this blog he linked to an excellent and detailed explanation of how Entity.GetAttributeValue works from CRM MVP Dave Berry

Entity.GetAttributeValue Explained

I had a classic case of reading how to do something in a better way but automatically doing it the way I always did it, except I now had a chance to do it differently and that’s what I did.

 

What is the Entity Class

The Entity class is the base class in CRM development and this class holds some key details about what entity it is

LogicalName – logical name of the record e.g. contact,account, lead
Id – ID of the record

The other important values are the Attributes. The attributes are a collection of attributes, e.g. all the fields in the entity/record.

What is the difference between an entity and a record

Entity

The entity e.g. account, contact, lead.  This is the design of an entity but doesn’t hold any values.  I would liken this to an object and an instance of an object.

Record

A record is an entity but with values, e.g. someone has created a New contact and this creates an instance of an entity (the design) and makes a record with individual values (e.g. name = Hosk, description = marvellous);

It uses object to enable it hold the various different variable types possible, it will mean if you are using late binding you will need to cast the values into the type you are expecting.

 

Trying Entity.GetAttributeValue

I thought I would try it out because it would save me wrapping if statements round things and seemed a better way to do things.

initially I removed the contains if statement and I got a variable doesn’t exist type error, hmm this isn’t meant to happen , I then realised it was a user error

I actually hadn’t typed it in but just removed the if
title = (string)entity.Attributes[ “title”];

I then added the proper method
title = entity.GetAttributeValue(“title”);

 

When developing I usually test my plugin code by making my plugin code take a iOrganisationService instance and an entity and put these in a separate class. This means the plugin can call my class but more importantly it means I can call this class by creating an iOrganisationService and an Entity object and not worry about any of the other plugin stuff. This enables me to call my new code in a console app which creates an IOrganisationService connected to the Dev environment and then do a service.Retrieve(“contact”, guid, columnset);

So I kicked of my console app and this retrieved a contact record and selected the title record and in this case the value was null and the code set the string title variable to null.

 

So I used this to retrieve a OptionSetValue and string and it worked fine.

it’s important to note this will bring null back if there is no value or the value is null.

Also remember for some types it will bring back the default value if something doesn’t exist and this might not be what your code is expecting.  In Dave’s blog he has a handy table

Type Return
Numerical (int, decimal, double) 0
Boolean false
DateTime DateTime.MinValue
Guid Guid.Empty

 

Why isn’t Hosk using Early binding

A question you are asking is why is the Hosk using Entity instead of an early bound class like Contact or Lead.  Great question, I’m glad you asked 🙂

The reason I am using the entity class is because the plugin was going to run on the contact and lead entity and maybe some other entities in the future.  The fields had he same name on the different entities, this enabled me to write the code (using Entity) which would work on both Contact and Lead.

CRM 2011/2013 – using ITracingServicing and Mocking it up

I was writing a plugin and I wanted to step through the code whilst writing it but we had a looming deadline and I didn’t have time to write some unit tests, so I decided just to access the plugin console app.

The other plugins were using the ITracingService and I wanted to keep it similar but this ended up causing me a little bit of a problem.

You will often see ITracingService initialized in plugins like this

// Obtain the tracing service from the service provider.

this.TracingService = (ITracingService)serviceProvider.GetService(typeof (ITracingService));

if you use the CRM Developer toolkit you will see this

IPluginExecutionContext context = localContext.PluginExecutionContext;
localContext.TracingService

What is happening here is it does the line above in the Plugin class.  The plugin class does a bunch of donkey work you have to do in all plugins, like get the CRM Service, extending IPlugin.  and the all important method
 

void Execute(IServiceProvider serviceProvider);

 

New to Plugin Development

if you are new to writing plugins, I recommend you check out my blog posts and video on the subject of plugins

https://crmbusiness.wordpress.com/2014/04/07/crm-2013-step-by-step-update-plugin-tutorial-using-the-crm-2013-development-toolkit/

video – Setting up Developer Toolkit for Microsoft Dynamics CRM

blog – Setting up visual studio with the developer toolkit

video – CRM 2013 – Create a simple plugin in CRM 2013 using the CRM Development Toolkit

blog – CRM 2013 – simple update plugin

 

Getting starting with Tracing in plugins

Whilst searching for information about the Tracing, I found a blog I had written back in Feb 2011!!!

CRM 2011 – You can now add tracing to your plugins

https://crmbusiness.wordpress.com/2011/02/08/crm-2011-you-can-now-add-tracing-to-your-plugins/

This is also a good blog on getting started with tracing in plugins

http://inogic.com/blog/2011/01/use-tracing-in-crm-2011-plugins/

 

I know this post is about creating a mock TracingService but whilst I’m here I might as well explain what tracing is used for.

 

Tracing is used to log statements (progress) in your plugins and then if there is an error and you throw a InvalidPluginExecutionException, you see you tracing lines in the error.  This is useful for the basic plugin debugging where you can put in numbered tracing lines and then see what stage you have got to before the InvalidPluginExecutionException was thrown.

here you can see the screen shot from inogic, you can see the tracing was used to show what stage the plugin had reached and some values

 

Back to my problem – creating a Mock tracing object

The reason I needed to create a tracing service because our plugins used the tracing service to log messages and it had a check if it was null and then threw an error.

So I needed to create a TracingService but unfortunatly I could just create a new TracingService e.g.

TracingService tracingService = new TracingService();

TracingService doesn’t roll that way people.

 

To get round the problem , I created a mock tracing service which implemented the TracingService interface and then I would be able to create a new object.

To view the ITracingService interfaced, I right clicked and went to definition, it will display the interface below

[code language="csharp"]
namespace Microsoft.Xrm.Sdk
{
    public interface ITracingService
    {
        void Trace( string format, params object[] args);
    }
}

 [/code]

So I only had one method to stub and in my example I didn’t want to do anything my code called the trace method.

Looking at the trace has a format and then some objects. The code uses this the message is the string format and that is really the only bit I was interested in. So now my MockTracing object prints the Trace text out to the output window.

[code language="csharp"]
  class MockTracing : ITracingService
    {

    public void Trace(string format, params object[] args)
    {

    }

}
[/code]

then I thought perhaps it would useful to show the messages in the Output window in visual studio

[code language="csharp"]
    public void Trace(string format, params object[] args)
    {
        Debug.WriteLine(format);
    }

 [/code]

This worked quite nicely because I could see my progress without throwing an error. I was also able to step through the code.So I finally got to step through my plugin code in my console app and I refreshed my mind on how tracing works in CRM with the added bonus of improving my understanding of tracing in CRM plugins.

Hosk Dynamic CRM blog is featured in the top 25 Dynamic CRM sites

I saw this week the Hosk blog was featured on the top 25 Dynamic CRM Sites

https://community.dynamics.com/crm/b/dynamics101trainingcentercrm/archive/2014/09/29/top-25-dynamics-crm-sites.aspx

It’s a great list of CRM blogs, it’s a good wide selection of writers and most of them are CRM MVP’s, who tend to do very good in depth blog posts.  I would recommend subscribing to all of these blogs.

Another good source of good CRM blogs is the blogs featured in the dynamic community page

https://community.dynamics.com/crm/b/default.aspx

I also noticed I am featured as one of the TOP Bloggers.  The list of blogs on the Microsoft Dynamic community page is also a great collection of CRM blogs, a good mixture of technical and non technical.

Hosk’s other blogs

As you are reading this on my blog, you probably know the Hosk blog is great but I thought I would also promote my Other blogs, particularly as I off work today, so I thought I would have a day off blogging about CRM.

You may be wondering why I have created other blogs, the reason for this is I wanted to keep this blog focused on Microsoft Dynamics CRM and CRM Development.  I wanted to keep this blog a technical blog.

Using different blogs means not everyone subscribed to this blog has to read about career related blog posts and the LinkedIn blog focuses on more general topics and not technical

But… you might be interested by some of the content of my other blogs

Hosk Career blog

http://hosksdynamiccareer.blogspot.de/

 

CRM 2013 interview questions

Career questions emailed to the Hosk (if you have a career question or a CRM question in general – email the Hosk – ben.hosking@gmail.com)

Someone emailed asking me to do a aggregate fetch XML plugin, which sounds like a great idea and something I will get round to soon.

Quick summary guides of features in CRM (business rules, patches etc)

career paths, skills needed, what certifications you should study

All areas

 

This blog post summarizes what the blog is about

http://hosksdynamiccareer.blogspot.de/2014/07/welcome-to-hosks-dynamic-career-blog.html

  • Summary information about Microsoft Dynamics CRM 2013 features
  • Quick summary guides of features in CRM (business rules, patches etc)
  • Articles on career e.g. LinkedIn Profiles, using LinkedIn,
  • Interview questions and understanding what the interview is asking
  • Career advice, discussing what you should learn for different careers e.g. Developer, Consultant, Solution Architect.
  • Answers to readers questions questions from readers of the blog about Microsoft Dynamics CRM Careers
  • Thoughts on career paths
  • Ideas on being productive
  • Things to consider when moving jobs/positions

 

Here are a few sample blog posts

CRM 2013 – Quick Guide to Business Rules

Ask the Hosk – I have passed MB2-703 should I take the equivalent CRM 2011 certification

CRM 2013 Interview Question – What things should you consider when choosing between CRM online or on Premise

Average wages for Dynamics Professionals in CRM 2013 and why you should know them

Hosk’s LinkedIn Blog

Here I post general career advice (networking, interview tips, Microsoft in General).  Below are a selection of LinkedIn blog posts

Don’t be afraid to ask questions

How will Microsoft Social Listening sell?

Are people starting to like Microsoft again?

What is the Microsoft CEO actually saying?

Annoying practices of bad recruitment consultant

Networking will find you your next job

How to make things happen at work

Should you keep up with Microsoft Dynamics CRM release cycle?

I read this article

Microsoft Dynamics CRM Rapid Release Cycle and Why You Should Try To Keep Up

written by CRM MVP Joel Lindstrom and he makes some excellent points. I would summarize as this

  • keeping up with the latest release means less work when another release comes out (e.g. not two or three upgrades at once)
  • The latest patches/rollups will often have performance enhancments and bugs fixed
  • Microsoft is developing tablet/phone apps rapidly, if you want to use these you need to have the latest version

I enjoy Microsoft is constantly changing/improving because it forces you to stay up to date with what’s happening in CRM and means you are constantly learning new functionality.

Sometimes I do question why Microsoft has made certain choices (CRM 2013 navigation, Autosave) but overall I feel they are improving the Microsoft Dynamics CRM and am happy to support their rapid release cycle

In CRM 2015 they seem to be adding quite a few enhancements raised on the connect site (field security on out of the box fields).  CRM 2015 is completing some of the partial enhancements (business rules)

 

I agree with Joel in some aspects it’s better to keep up with the latest release because the sooner you start using it the sooner it won’t be an issue.  I would add a few counterpoints to Joel’s excellent article.

 

CRM 2011 to CRM 2013 – Code

The jump from CRM 2011 to CRM 2013 is quite major, if you were on a low CRM 2011 patch (e.g. pre rollup 11 and the multi browser code) the customization update is going to be a major piece of work.

A lot of the CRM 2011 projects I worked on were highly customized and the most of the new functionality in CRM 2013 wouldn’t be used.  For this reason I can see little benefit in justifying the cost of upgrading the customization code and then disabling a lot of the new CRM 2013 functionality (quick forms, autosave, layout) just to be on the latest version.

 

CRM 2013 – Training

The CRM 2013 navigation completely changed and some people may suggest made it more difficult to navigate.  It would involve training all the users to use the new GUI and for highly customized CRM systems, I’m not sure the benefit would be worth it.  For some reason I often compare upgrading to CRM 2013 from CRM 2011 a bit like upgrading from windows 7 to Windows 8, is it really worth doing?  This is a consideration for one users but what if you have 10000 users, who will all need training?

CRM 2015

Are there features users would really want here?  A lot of the new functionality in CRM 2015 is the Add on’s Microsoft have acquired and now have working with CRM 2015.  The quesiton is how many customers want social listening, paracture, unified helpdesk and dynamics marketing?  Not only would they need to justify the cost of upgrading but also add the cost of the licences.

On the plus side I think the jump from CRM 2013 to CRM 2015 will be a small one and probably less than the previous upgrade paths e.g CRM 4 to CRM 2011 and CRM 2011 to CR 2013.

 

Supported software

Joel mentions by keeping up to date with the latest version you will get the best performance from IE browsers etc.  I have found a lot of companies don’t use newer browsers until they have throughly tested the new browsers don’t break their other applications.  This can see customers clinging on to version 6 of IE, relunctantly upgrading to IE 7 or 8.  Having to use the latest browser would be a major cost (in testing and rollout) to companies and this can be one of the major reason not to upgrade.

Cost

The new CRM versions may cause a customer to upgrade to higher SQL Server/Windows Server/ETC/ETC and once again this could add more cost to an upgrade (along with upgrade of customizations, migration, testing etc)

 

New Versions can be a bumpy ride

Accompanying the rapid release of CRM has been  a new release with a number of significant bugs.  It seemed Microsoft didn’t have time to test all the functionality of a new release but released it because they had a deadline to meet.  This meant there were some big bugs in the initial release, a lot of these bugs were fixed in the first few patches but this can be very frustrating for users and developers

 

Something slightly different – online rollups

I know Joel wasn’t talking about rollups but I have a few unanswered questions I have with rollups and was hoping perhaps one of readers will comment

 

Why our on premise and online different

Why two different upgrade paths for online and on premise
I don’t understand the logic behind this, is it extra work or is it having more benefits on the online version to persuade people to choose it.

The downside of this is it makes CRM developers/consultants work harder trying to remember/work out what version is on the online and on premise and what functionality you can use.

If there are any benefits I can’t really work out what they are.

 

Online rollups

I often use to wonder what online customers did when it came to creating enhancements, they had no where to test them (e.g. no DEV/TEST environments), unless they paid a CRM partner to develop the changes on an on premise development environment.   This issue has been resolved with sandboxes (but I have some concerns about data costs and paying for amount of data used by the GB, surely this can only keep going up and up)

This brings me to my online rollup issue.  If I understand things correctly (which I might not) but with CRM online the patches get applied automatically.   How do CRM online customers do regression tests of their customizations with new rollups.  If you can delay the rollup, I can’t imagine you have long to test it and if the rollup does break your customizations they are still going to be deployed.   Is this how it works?  How do online customer rapidly regression test?

 

Picture from here

CRM 2011 – error using Xrm.Utility.OpenEntityForm

I was fixing some code where the code passes a field to a form and then opens it using the excellent Xrm.Utility.openEntityForm

I added a new parameter, parameter_2.  This was going to pass the name of a field I wanted to use

    this.SelectCustomer = function () {

        /// <summary>

        /// Passes customer field values into the customer search screen for a user to create / search

        /// for their workshop entry

        /// </summary>

        var parameters = {};

        parameters[ “paramater_1”] = “name”;

        parameters[ “paramater_2”] = “hosk_searchfield”;

        Xrm.Utility.openEntityForm( “Hosk_Search”, null,  parameters);

    };

 

I wanted to add one more field but when I added a new field, the form didn’t open and I just got an error.  A generic, which doesn’t tell you anything, I have been getting quite a few of these errors the last couple of weeks

error screen

I tried to debug the javascript onload but it wasn’t even being called.

I took away the new field and it worked.

FRUSTRATTTTING

calm down, be logical, engage brain.

I started with the SDK/documentation, lets see what should happen

lets look at the parameters section
parameters
Type: Object

Optional: A dictionary object that passes extra query string parameters to the form. Invalid query string parameters will cause an error. Valid extra query string parameters are:

It turns out the parameters are an optional dictionary object and more importantly

Invalid query parameters will cause an error

So basically when I passed an extra variable but I hadn’t added the variable to the form so it was erroring.

 

So where do you add these pesky form variables

  • go to the form
  • Form Properties
  • Parameters
Field Form

So I added in the new parameter, saved and published and boom, everything was working, hazaar.

 

Who thought CRM would have been so picky, ok hands down everyone

Hosk’s Top CRM articles of the week 3rd October 2014

Thumbs up for friday everyone

Articles of the Week

I will add this as one of my top articles, it’s not really an article but it’s very useful because the blogs on the list are excellent

The top 25 CRM blogs

 

This article from Guido is great, it takes a question from the forum, an answer from CRM MVP Scott Durow, followed by some hard work by Guido to create the full solution, great work.

Check if a User has a specific Privilege

 

I will add another because I can, it’s from the snooze Berry, Dave Berry.  It was written when Dave use to blog (pre snooze), although I have been informed from the great Berry himself he is busying doing great things with TypeScript and CRM

Entity.GetAttributeValue<T> Explained

 

Best of the Rest

 

Interesting article showing  you how to compare 2 lines in your fiddler trace

Comparing Sessions in Fiddler

 

A quick definition on business rules
CRM 2013 – Quick Guide to Business Rules

 

Add CRM DLL’s via the internet not you local drive

Don’t load CRM dll’s from the local folder, go to the internet

 

How to convert HTML to plain text for an email with a plugin

CRM 2013 – Convert Email HTML to Plain Text

 

The error and the solution

Assembly generation failed — referenced assembly does not have a strong name

 

Great article from Guido with a reference to Dave Berry

http://www.crmanswers.net/2014/09/getattributevalue-activityparty.html

 

An error caused by Odata query with null guid value

CRM 2011 – UnRecognized ‘Edm.Guid’ literal ‘guid’null

 

Are people starting to like Microsoft again?

Common things to check if your CRM is down

Microsoft Dynamics CRM not working? check these common causes

 

Hosk learnt a few things whilst reviewing javascript

CRM 2011 – Things learnt when reviewing Javascript code on form loads

A quick start to getting started with fiddler

Getting Started with Fiddler and CRM

 

A tool you can add (at a cost) to performance test CRM 2013 using fiddler

Performance testing with stress Stimulus in CRM 2013

Timers in CRM 2013 and ways to use them

The Best Little Microsoft Dynamics CRM 2013 Feature You Might Not Know What To Do With: Timers

How to debug those pesky ribbons
CRM Ribbon Problems

 

A new CRM 2015 feature

Nested Quick Create in Microsoft Dynamics CRM 2015

 

Using goals to schedule a daily job, very clever

Scheduling Recurring Workflows for a Nightly Processing Service

 

CRM 2013 interview question and things to consider

CRM 2013 Interview Question – What things should you consider when choosing between CRM online or on Premise

 

Great description of leads

Leads are like Zombies

 

CRM Exams are reduced in price until December

15 percent of CRM exams until DEC with these codes

 

How will Microsoft Social Listening sell?

 

Quick Guide – What are Rollups in CRM 2013

great idea allowing people to write their own help, good listening Microsoft

Write custom help in CRM 2015

Question on the Hosk CRM Career blog

I have passed MB2-703 should I take the equivalent CRM 2011 certification

 

OTHER HOSK STUFF

Watch out for career climate change

Don’t be afraid to ask stupid questions

Are people starting to like Microsoft again?

How will Microsoft Social Listening sell?

CRM 2011/2013 – Ribbon problems

The investigation and problem I experienced where in CRM 2011 but I think it would be the same in CRM 2013, I had a problem with the ribbon javascript but I didn’t have a clue where it was because I had never seen a syntax error in the Javascript ribbon.

I put a debugger statement in the ribbon, so it would drop into the debugger.  The reason you  put the debugger statement into the Javascript code is because when the ribbon is loaded it is loaded in dynamic Javascript script block, this means when you press F5 it creates a brand new script file and you won’t have time to put a breakpoint in it if you bring up the debugger by pressing F12.

 

So I put my debugger line in and then the code hit my various display/enable javascript methods and I could step through them but the syntax error kept appearing.

I still wasn’t sure where/what the problem was.

I pressed F12 to bring up the debugger and this was bring up a syntax error

syntax error

I turned on fiddler and found on one of the calls I was getting a nasty red triangle on one of the calls.

The thing which kept bugging me was it was a syntax error

I could see the code and it looked fine (although syntax errors are not obvious to the naked eye). The file compiled in Visual studio and pressing F12 to get the debugger didn’t throw an error, so this would suggest the javascript syntax was not the problem

 

frustrating

I fired up the Visual Ribbon Editor for CRM 2011/2013

In the Visual Ribbon Editor here you have display rules, enable rules and action.

There was no disable rule

there was an enable rule and an action rule which both called a javascript function, you can see below

ribbon enable
ribbon action

Slowly something clicked, the error was trying to call the action, why was it calling the action whilst loading the form. Logically the ribbon has to make sure the Javascript method exists so when the user presses the button something will happen but why was it triggering a syntax error whislt loading the ribbon?

Syntax error, ribbon load…..hmmmmm

Look at the two rules, although I’m not showing you the actual file, look at the position of the library and the function boxes!

Finally after hours and dragging more eyes to the problem, my colleague found the problem by exporting the Ribbon xml, hazaaar the problem was obvious

The library and function values from the enable rule had been copied into the action rule, only this didn’t work because the function and library boxes are in different places.

He found the library – which should be the javascript library was pointing to a function.

Ribbon object not found

A new day a new ribbon problem.  Today on one of the forms the ribbon wasn’t loading and I was getting an error

 

SCRIPT5007: Unable to get value of the property Ribbon ‘value’ of undefined or null reference

 

The first thing I checked was to see if the function and library values were correct, they were.

In the Javascript files we use we build up the names spaces so the function calls are like this

Hosk.Functions.Account.Ribbon.NewAccount()

To find the problem I had to put debugger statements in the enable/action javascript rules and walk through them.

 

Eventually I found one where Javascript file hadn’t been loaded, so when it it was trying to call a function the javascript file was loaded, the function didn’t exist and we got a null reference.