Dynamics 365 Tooling – Object of type ‘Microsoft.Xrm.Sdk.Entity’ cannot be converted to type ‘Type’

I think that most of you who are writing applications connecting to Dynamics 365 already wrote thousands of some similar code:

It’s simply connecting to Dynamics 365 using connection string and querying contacts. Connection string looks like that:

<add name=”D365″ connectionString=”Url=https://organization.crm4.dynamics.com; Username=user@domain.com; Password=password; authtype=Office365;” />

For many years it was working like a charm. If you have upgraded to latest XrmTooling version which is at the time of writing this post, this code will throw exception:


System.ArgumentException: ‘Object of type ‘Microsoft.Xrm.Sdk.Entity’ cannot be converted to type ‘Contact’.’

Some of you may remember this error and while googling for it you will come across some posts from years ago when it was simply a mistake of not calling “EnableProxyTypes” function. This is from times when we had to manually create OrganizationServiceProxy object. Without calling “EnableProxyTypes” service did not know how to deserialize result into proper object (so Contact in this example). Some more details were provided by James Wood and myslef in this StackOverflow question

So what is the fix, because I don’t believe anybody will rewrite the code to cast all Entities to Contacts manually. Fortunately there is a quick fox for that, simply add SkipDiscovery=false to your query string, because it looks like it’s default value changed from false to true between versions and So your connection string should look like this:

<add name=”D365″ connectionString=”Url=https://organization.crm4.dynamics.com; Username=user@domain.com; Password=password; authtype=Office365; SkipDiscovery=false;” />

And it should work 🙂


Creating empty XRM Environment in PowerApps

If you are following the latest news regarding Dynamics 365 ecosystem, you are probably aware of the fact that Microsoft decided to put everything upside down, change the naming of every technology and use the old names with some new things. Of course I’m exaggerating a little here, but some changes are really crucial and can cause confusion. I’m also pretty sure that some of them are not final, so I will probably have to go back to this post in few months to update it.

There are a lot of great blog posts already there but the really short summary of what we know so far:

  1. There will be a common data model for all Microsoft business apps (Dynamics 365 world apps), which is called currently Common Data Model. Basically, we want to have the same Account in CRM as the Account in Talent or Marketing, currently in every system, all the entities do not follow any common schema. CDM specification is held on github and you can check out its current state here: https://github.com/Microsoft/CDM
  2. There will also be a data service that would allow CRUD for all the entities across your Environment. Basically you will reuse the same Account entity in your CRM and in your ERP, so any integrations will not be necessary (or at least fairly easy to develop). This will be called Common Data Service for Apps (and has nothing to do with current CDS)
  3. PowerApps is now becoming a term that includes all customizable business apps  – the old PowerApps from now on called Canvas Apps and applications like Dynamics 365 Customer Engagement are called Model Apps. Both types of apps can use CDS for Apps and CDM. Basically this is our new UI layer over CDS and CDM
  4. The underlying technology for all these new toys is Dynamics 365 CE platform, also known as XRM platform. So if you know Dynamics CRM, you should already be familiar with everything that CDS for Apps, CDM and Model Apps in PowerApps have to offer.
  5. What we currently know as Organization, we should from now on refer to as an Instance. Once the whole new ecosystem is finished, it should be called Environment 

That’s the shortest summary which highlights everything  important from the perspective of technical guys like developers and solution architects. Looks pretty exciting right? At least for Dynamics CRM Developers, who are currently becoming the specialists of the development platform for all new technologies (as a comparison, look at Office 365 applications, where most of applications are SharePoint based).

Ok, so that’s still a theory, we can take that into our minds and wait until the machinery starts running, right? Wrong, we already can start playing with all of that!

I would like to show you how to get started with some new Model App based on CDM.

You will need a Dynamics 365 9.0 environment (can be a trial of course). Log into your Organization and go to the following link:


You should see something like that


Now click on New environment button


Enter Environment name (for me it’s XRM), choose your region and Environment type (I would not go with Production just yet, but if you want, be my guest). Click Create environment.


Ok so we have a new Environment, so in the world that we already know – we have a CRM instance but without any Organization. That’s not very useful, so let’s create a database.


Looks like the Organization creator for Dynamics CRM installation, doesn’t it? So we have to put there our desired Currency and Language. I unchecked the sample data, as I would like this app to be as clean as possible. After clicking Create database we will have to wait few minutes:


After DB is provisioned we will see something like that:


If we will now switch to the old, well-known Dynamics 365 Administration Center, we will see that we have a new CRM organization:


Let’s open it! We will see quote “raw” CRM organization:


No Sales, Service, Marketing tiles, only Settings. Let’s see what we have in Customizations:


You can see only the entities from Common Data Model, so there are only System entities that are required to use all the features of the system (Users, Teams, Views, etc) and some really basic entities (like Account and Contact) – there are no Cases, Opportunities, Leads, Goals etc. Simply a clean XRM platform that we can use to create a totally custom application!

No let’s see the new customizations interface. Open the following link:



And on top right corner choose your newly created Environment. Now open your entities:


Now click on some entity, I chose Account entity:


On top pane, you can see all the well-known sections like Fields, Keys, Relationships, Views etc. Let’s create a new field called Short Name


After clicking on Save entity, open again Customizations in your empty Organization


The field is there!

Once you start playing with all the customizations, you will see that there are still many places where you are redirected to the “old-CRM2011-UI” because there is still no new UI for that, but you can already see that things are heading in the right direction.

For sure Microsoft will need some more time to finish all this new features. Let’s keep our fingers crossed that everything goes as expected, because future looks really exciting!

PoC – speech to text notes in Dynamics 365

In case you did not notice that yet, Dynamics 365 9.0 ships features that will allow developers to achieve really powerful custom components, working across all D365-supported devices. Unified Interface – as its name suggests – works pretty much the same on all devices, which means that we are no longer sandboxed by some “metadata rebuilding in progress” nightmare (people who used the old mobile app understand what I mean by that). Personally I believe that Custom Control Framework will be something that will really make D365 shine as a modern technology, but so far we don’t know when it would be available (hopefully we will learn something more about it on Extreme 365, so see you there!). Waiting for that big thing I was playing a little bit with the new mobile App. Right now it’s super easy on mobile to add picture, video or recorded audio as an attachment to a record. While adding a note you will see the icons representing each of these:


Clicking camera will of course open your camera app and will attach resulting picture to annotation, microphone will open a recorder etc.

I had recently a question from my customer – they were creating a sound notes all the time and there was a person dedicated for rewriting them as text in CRM. Can we simplify that? Using some fancy AI technology, we can!.

If we create a sound note on our mobile device, it will be attached as a .wav file. So we can use some kind of speech recognition system to convert this audio file into text. My first choice was Azure Cognitive Services and Bing Speech API:


It has 30 days free trial and has a REST API which can convert up to 15 seconds long audio files (only .wav files, unfortunately). Although I’m a fan of Microsoft technology, to be host Google Speech API looks much more mature:


Really big number of available languages and no constraints on audio files length and many more available formats is something that looks really impressive and sets the bar high for Microsoft to catch up. There are also many other speech recognition systems, so simply choose what’s best for you. I’ve chosen Azure Cognitive Services for the sake of this PoC.

Having said all that, now we only have to write a plugin that will call our service and convert the audio file when annotation is created:

ServiceResponse class looks like this:

FromJSON is just an extension method that uses JSON.NET library to deserialize JSON string to my object (no I’m not merging JSON.NET library using IlMerge or any other merging technique which I try to avoid in most cases – I always attach the full source code of this great library in my plugins – recently almost every project I’m working on, requires some kind of serialization/deserialization inside plugins – mostly for HTTP API calls).

This plugin is registered on Annotation creation message. We just check, if annotation contains an attachment and if the type of attachment is “audio/wav” we call the Bing Speech API to convert this audio file to text. The response looks like this:


Believe me or not, I actually said “Hello world” when I was making the sound note. So basically the result says that it’s 92,5% sure that I said “Hello world” and 79% that I said “Hello”. There can be more matches of course – how we handle those matches is a different story. We can prepare some sort of machine learning algorithm, maybe use something that’s already there on Azure or maybe some neural network algorithm – whatever you like. I’m simply taking the match with the highest Confidence parameter, I guess that in many cases it will be wrong, but for a PoC it’s good enough for me.

And as a result we get our note with audio file and text in the note text:


It works 🙂 Happy coding!

Dynamics 365 Server-side validation


Defining required and optional fields are always an important part of every Dynamics 365 project that I have ever worked on. Have you ever thought properly about the server-side validation on that matter? From my experience, Dynamics CRM Customizers/Developers usually just create fields with proper value in  “Field requirement” field. I hope that everyone is aware of the fact that this is only client-side validation, which can be easily changed from client-side code (JS) or Business Rules. This usually is enough, because CRM users were not aware of how this application works and would not run any malicious JavaScript on the form (wishful thinking…). Unfortunately, there are some great Chrome extensions, that allow to disable all the client-side validations in a single click and more and more users are aware of their existence, “hacking” the input for CRM for their convenience. Of course, more advanced CRM users were always aware of the fact that they can override the system behavior by using simple Import or some tools from XrmToolBox, so they even did not not have to know programming and CRM SDK. That’s why it’s sometimes really important to prepare some sort of Server-Side validation logic for really vital data, to avoid situation when a salesman does not fill Tax Number for a client, because he did not have time to search for the data before putting it inside CRM.

Maybe you already know that but there is a built-in functionality for Server-Side validation in CRM. These are simply Business Rules, which are set to “Entity” scope. Most of you know the Business Rules as something that allows CRM Power Users to perform some simplified tasks on the form without writing any JavaScript. Although I am still not a big fan of Business Rules as something that replaces JS, they come in very handy when it comes to this server-side validation. Just have a look at the following rule:


If we register it for “Entity” scope we will not be able to save the record not only using standard forms:


but also using SDK or Import:


What if we have so many entities and fields that creating and maintaining Business Rules for all of them is a nightmare? It’s quite easy to create a plugin that we can register on Pre-Validation and it will do all the dirty job for us. Have a look at this example:

You should register this plugin on Pre-Validation of Create/Update of any entity (for Update you should also register PreImage). It will retrieve the entity metadata and check all the required attributes. If any of this attributes is missing, it will fire an exception that will prevent saving of the bad data. This is just an example, the full code of the plugin can be found here:


Multi-language JavaScript messages in Dynamics 365 9.0 using RESX files

One of the not-so-shiny-and-mentioned-on-twitter-and-blogs feature of Dynamics 365 9.0 is simplification of localization of Web Resources. If you have ever worked on a international Dynamics CRM project, which required multiple Language Packs and not all users were using the same language, you probably had some difficulties when trying to show some message on the form using JavaScript or throw an exception with a message from plugin. There was no out-of-the-box localization strategy – some common dictionary with values for multiple languages from which we could easily get the value in current system user language. Of course there are a lot of possibilities here, all of which include usage of some kind of Web Resource like XML or JSON just to store the proper value in all required languages.

Dynamics 365 9.0 introduces new Web Resource type – RESX. This is the very well known, plain old resources file, which we have always used, long before JavaScript has become the leading technology in web development. It was (and still is) super easy to apply multiple languages on pages for our application using this kind of files. There is also a great Visual Studio addon – ResXManager which made it even easier to handle all the translations (so I strongly recommend to use it, if you have never heard of it). You can use this RESX types quite easily in your scripts to display messages in different languages based on current user preferred language.

How to achieve that? Firstly, you should prepare your RESX files in Visual Studio. As an example, I prepared 3 files – for English, Polish and German language:


Each file contains one key:


Now, let’s import the files into CRM system. The most important part here is that name of the Web Resource should be built using the following convention:


So for example:


for Polish messages.

There are some other possibilities here, I will write more about that in a second. You must remember to choose proper “Language” value when creating web resource. So you should end up with something like this:


Now we are ready to use them in our scripts. We should first register all the required resources as dependencies for script in which we want to use them, so if I want to use them in my lead.js I should go to the new tab “Dependencies” in properties of my lead.js Web Resource:


If you did not hear about this new functionality of D365 9.0 – dependencies allow you to register dependent libraries for your script, so if it uses jQuery, react.js and your custom common.js, you can simply register them as dependencies and don’t have to register all this scripts always together with lead.js (this is also working in ribbons, so no more isNaN dummy calls!)

After all that we can simply call Xrm.Utility.getResourceString function to get the proper token:


And we can happily see our translated message, when we change to Polish language:


We can switch to English and we will see:


Really easy, isn’t it?

How this getResourceString function works? Well it simply looks for the proper Web Resource based on the current user preferred language, but it must have the proper name. If, for example, we call Xrm.Utility.getResourceString(“messages”, “myKey”) and our current language is Polish (and our Organization base language is English), it will be looking for the following files:


Then it will choose whichever first of these will have matching Language chosen in WebResource properties. That’s why I suggested to use NAME.LCID.resx – although there are some other possible ways of naming, this one looks the most clear and consistent for me.

Dynamics 365 9.0 Client-side navigation

In Dynamics 365 there has been a serious re-arrangement of all the namespaces and methods available for client-side scripting. If you are not aware of that already, please take some time to digest the following article:


There are many changes, but today I would like to focus on new namespace: Xrm.Navigation, which, as the name states, contains methods used for moving around the system and opening some resources. This functionality was previously inside Xrm.Utility namespace. Methods which we can use are the following:

  • openAlertDialog
  • openConfirmDialog
  • openErrorDialog
  • openFile
  • openForm
  • openUrl
  • openWebResource

Let’s look closely on each of them.

Previously we had Xrm.Utility.alertDialog which did not have that much features and in Web Client showed as the plain old alert, which was the same as from standard JavaScript “alert” function. Right now the alert is much better-looking, overlaying piece of html:


Looks much better right? The function can be called the following way:


alertStrings and alertOptions are JSON objects specifying texts shown on the dialog and height/width of the dialog.

Example usage can look like that:

The equivalent of the deprecated Xrm.Utility.confirmDialog. This method looks now like that:


Like before, confirmStrings and confirmOptions are JSON objects with some configuration. Have a look at the example:



There was no equivalent of this one before 9.0. This can simply show the error message which we are used to, but with all options (including the contents of the error log) specified by the developer. Again the method looks pretty straightforward:


Look at the example to check what errorOptions object consists of:


Error dialog

This is also something new. This function allows us to open a file for example from an annotation in a supported way. Function looks like that:


file is a JSON object specifying the file name and contents, while openFileOptions can have value of 1 to open file, and 2 to save file (behaviour of course depends on browser settings, most likely both these options will show file save confirmation dialog from the browser). Example usage:



It replaces the old Xrm.Utility.openEntityForm and Xrm.Utility.openQuickCreate functions. Function is quite generic, the usage looks like that:


To open account entity with some field prepopulation you can go with:

Result (see that the name has been populated):


There are many, many options here, including createFromEntity which will designate a record to prepopulate fields based on the mapping, opening in new window or specifying business process flow that should be displayed on the form. Really go through the documentation on this one.

Opens specified URL and also there was no relevant function before 9.0 (so basic functionality, no comment…). Function is really simple:


Example usage:



The old version (Xrm.Utility.openWebResource) was usually not very useful as we had no control on how it is opened and it was always a new window. The new version gives us possibility to specify if it should be new window or not but still it lacks the most important feature – to show as a dialog overlaying the current page. As I checked already it almost as useless as the old one, unfortunately 😦 The current version can be called the following way:



What’s coming for Developers in Dynamics 365 Customer Engagement 9.0

Dynamics 365 9.0 is going to introduce many changes for us developers. I would like to share with you my thoughts and hopes regarding the newest version of Dynamics 365 Customer Engagement.

Virtual entities

This feature was announced quite some time ago and it’s great that it’s going to finally be included in version 9.0 of Dynamics 365. What exactly are Virtual Entities? Basically they are entities that are obtained from some external system and they are not stored in D365 database. By properly implementing Retrieve and RetrieveMultiple for such entities, you will be able to show any external data inside CRM lookups and grids. Because there is no database table created for Virtual Entity, it will not use any space in the database, which is a nice feature for Online deployments, where every byte counts. If it will work as described, I’m sure that this particular feature can change the technical approach in many projects.

Web API improvements

Not much to say here – Microsoft already decided to deprecate SOAP endpoint in Dynamics365, so Web API MUST provide all the functionality that was previously in his older brother. Very useful will be GrantAccess and ModifyAccess messages, that will make it easier to handle record sharing using JavaScript. I believe that before 9.0 is publicly released, we will hear about much more new messages available in Web API

Client API enhancements

Of course it’s good thing that Microsoft is tidying up the JS API, which has always been a mess with its inconsistent naming of methods and namespaces which were totally unintuitive. Version 9.0 will introduce a lot (and by a lot I mean really a lot) of changes in this area. I believe that the most crucial change here is replacing Xrm.Page.context with Xrm.Utility.getGlobalContext. I believe that every single D365 deployment out there will require some JavaScript refresh because of that change. I strongly encourage you to read carefully the following article:


Most of the methods are only renamed or replaced by some other methods, but there are some (like addOnKeyPress for example) that will be removed in the next major release after 9.0, so it’s a good thing to remove them from your code right now (and remember not to use them in upcoming projects).

From many introduced methods, I personally believe that relatedEntities collection on entity, getEntityMetadata, getResourceString (related to new RESX support for webresources), show/hideProgressIndicator and refreshParentGrid will be the most important ones. There will be also new methods for controls like editable grid or timer, so hopefully we will have more control over their customization.

Timeline control API

For sure you’ve heard already that in Unified Interface, old control showing Posts, Activities and Notes will be replaced by a Timeline control, which will consolidate everything in one place. This is not only UI specific change – together with the new control we will get quite a few new methods that will allow to customize a little bit this control (which was impossible with the old control) with the most important among the others – refresh function (finally!)

Apps improvements

In Dynamics 365 we already have something called Apps – functionality which allows customizers to pack some pack of functionality (for example regarding Service or Sales) in an App – with specific SiteMap and only specific entities. This feature has proven to be very useful in systems used by many different divisions which not necessarily should have the same functionality exposed (of course by properly handling Security Roles it was always possible to show/hide entities for specific users, but preparing different SiteMaps with specific order of things adapted to current user is very useful and was not possible before Apps were introduced). Version 9.0 will bring us more improvements in this field – with the possibility to create an App using SDK being the most important from my point of view. Also new methods for JS API (getCurrentAppUrl, getCurrentAppName, getCurrentAppProperties) probably will bring new possibilities for ISVs

Multi-select option set

This feature will be really helpful in many scenarios and will probably encourage many customizers to re-create some functionalities in their systems because for sure it can simplify how we can approach things. Previously selecting multiple values was only possible by creating some related entity and showing subgrid on the form, which had many drawbacks (being not able to associate anything before creating record was the most painful). Right now all such scenarios will be handled by this out-of-the-box control and I keep fingers crossed that it will not be as buggy as editable grid, which proven almost unusable in most scenarios, because of the lack of configuration and many bugs.

Custom Controls

For me the most important feature of all, but currently Microsoft did not provide a lot of information regarding this. In theory we will have a framework that will allow us to build custom controls available for all types of devices. If this will be true, that can be a real game changer for Dynamics 365 and maybe the end of “this cannot be done in Dynamics 365” or “this will not work on mobile client” at least from UI perspective. Of course we still don’t know what this magic CCF will be like and what possibilities it will provide, but if it will allow to use HTML5 and whatever JS library you want – I believe that soon we will be flooded with packs of really great reusable controls, totally changing user experience of Dynamics 365

WebHooks integration

WebHooks is a lightweight HTTP pattern for connecting APIs and services with a publish/subscribe model. In a nutshell, it will be possible to register a WebHook for “Lead created” event and whatever client will subscribe to that WebHook will be immediately notified about such event. I believe that this can take integration scenarios to another level – especially for Online deployments it was always a pain to notify any external system (which is usually not in the cloud) that something happened in CRM. Right now this external system can just listen to a specific WebHook and if anything happens it can do whatever needs to be done (for example update some Account specific data). Really cool feature, which of course could have been used earlier but version 9.0 will make it much easier.

Vector image web resources

Using SVG icons will make it easier to apply icons for entities – as you will no longer need to upload both 16×16 and 32×32 icons for each entity. Maybe a small thing, but I think that will be useful.

Support for localizable solutions

The prayers of all ISVs around the globe were heard and we will finally have out-of-the-box localization feature for web resources. It should be possible to create RESX files with different languages and reuse them among web resources using new client-side API. If that’s not awesome, I don’t know what is awesome.

JavaScript Web Resource dependencies

Have you ever added a JavaScript web resource calling function isNaN, just to make it load in current context for reuse in some different web resource? Well, you will not have to do that anymore – in 9.0 it should be possible to define which web resources are dependencies for current resource. This will make our life much easier.

Override the default open behavior of data rows in an entity-bound grid

This feature will allow to override the default “double-click” opening of the record from a grid. If we want to redirect user to some external page after such event – in version 9.0 it will be possible. If it would be also possible to use for Virtual entities, it will make one powerful feature – allowing to redirect user to another system directly from a grid, without any “Ribbon-button” workarounds.

There are many more features to be introduced in 9.0, but I don’t see them as important as the ones that I described (like for example further Business Process Flow enhancements, which personally I believe the least useful feature in the system – although it looks really nice on presentations, in most cases for my clients there was always a show stopper for using this feature and I don’t believe things will change with the next release.

For the full list of new features look here: