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)
{
timer.Stop();

if (formType == 2) // 2 = Update
{
// ... Do work here ...
}
}
};
timer.Start();


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.