fredag 14 augusti 2015

Exchange rates per record, or any color you like

Since I started working with Dynamics CRM the "issue" of one exchange rate per currency has come up a couple of times. How do you handle it, when do you update, what do you do if you want to... 
A customer of ours wanted to have an exchange rate per record so how can you fix that and still be able to use the rest of the functionality.

This is by no means THE solution but it is one. I was fiddling around a bit with CRM when I got the problem. Could I write directly to the base currency, was there any other way around the issue, should we use some other field?

I started looking on the web for solutions and I found this short blog http://www.crmsoftwareblog.com/2012/11/dynamics-crm-2011-multiple-exchange-rates-for-currencies/ which pointed be in the direction of the RetrieveExchangeRate message. Having no idea, I had a look in the plugin registration and yes, there was indeed still such a message



















(Yes, I'm still using the 2011 plugin registration tool, it works and you can store multiple connections...)

So, having found this message and having no idea how to use it, I didn't find anything about it in the SDK either, so I started out with a pretty empty plugin which was called by the message which I step debugged in VS to see what was going on.

It would prove to be fired before everything else and the calling object was present as context.ParentContext. After that quick test I started getting stuff together. So, this is what I did:

IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
            Entity parentTarget = ((Entity)context.ParentContext.InputParameters["Target"]);
            IPluginExecutionContext parentContext = context.ParentContext;


The usual suspects, set stuff up.

if (parentTarget.LogicalName == "crmk_testentity")
            {


Run the code only when we are interested of the result. Now you can do pretty much what you want, in my case we had the exchange rate in a parent object so I had to fetch that, it could also be the case that the currency was the base currency and the plugin didn't need to do anything. This meant I needed to fetch the currency and the wanted exchange rate. 

The magic happens with the output from the RetrieveExchangeRate plugin,  
context.OutputParameters["ExchangeRate"] = exch; 

"exch" is a decimal and you can set it to whatever you want and then CRM behaves as if it just retrieved the exchange rate from the system. Since we're using a plugin message and not doing anything realy naughty, more than pretty much a man in the middle attack on the system itself, this should be supported.

Happy coding

Rickard Norström
Developer at CRM-Konsulterna
www.crmkonsulterna.se  
 

Inga kommentarer:

Skicka en kommentar