Saturday, July 30, 2011

CRM 2011, Silverlight and Refresh Issue

When I added a Silverlight 4.0 application to a CRM form, I discovered a problem when you referesh the page in the browser. The issue is that on refresh the Silverlight application is ready before the Xrm.Page.ui is loaded and ready to access from Silverlight.

This was a major problem for me as I needed to know what CRM Form Type was, which is done by invoking the "getFormType" method on the Xrm.Page.iu property of the form.

After trying a number of things, I found the only way to reliably access the form type was to attempt to keep accessing form type until a value was succesfully returned.

So, for those interested, here's a snipped from my silverlight application which might help you:

            // To get around problem that form may not yet be full loaded
// and so javascript can't be invoked yet, keep trying until
// we can get the form type, waiting a second between each try.
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick += (object s, EventArgs args) =>
int? formType = null;

// Attempt to get the Form Type
try { formType = CrmUtility.GetFormType(); }
catch { }

if (formType != null)

if (formType == 2) // 2 = Update
// ... Do work here ...

Note that all GetFormType() method does is find the Xrm.Page.ui property and then calls .Invoke("getFormType") to get the current Form Mode from the regular Crm Javascript methods.

Also, you would expect this code to go somewhere in the initialization of your Silverlight Application.


sermoc said...

I think that your code could be useful for me. I'm getting an error when I load by the first time my crm form with silverlight control... It displays a window with the next error message : "onload error: " and no more description here.
I debugged and I have realised that it occurs when I call the silverlight function from js.
Do you know what could be the problem?

Matthew Hunter said...

Is it possible that you are trying to invoke the Silverlight app before it's ready?

If this is the case, perhaps what might be better is to have Silverlight call a javacript method, called something like "SilverlightLoaded()" when Silverlight is loaded.

Inside the Javascript method, you could then invoke Silverlight in the way you want.

sermoc said...

Yes, it's a good idea. I'm going to try it.

sermoc said...

Hi Matthew,
I have changed my code according to suggestion and I think my problem's gone out. Now I invoke my JS function from Silverlight and for the moment no onload error again.


Anonymous said...

this really helps. Thanks