The CRM Grid – A Microsoft CRM Blog

Greg Owens’ rose-tinted MS-CRM mumblings

Checking the ExecuteFetchRequest message

Sorry no updates for so long – NDAs with my main client and 5 hours commuting a day is hammering my blog time!

Just a quick note: new version of the CRM SDK is out now – version 4.0.12.

One of the items I noted was a technique to improve the performance of plugins that operate on the Execute message. I have been developing various plugins for my client which change and/or calculate data that gets passed to the UI, by harnessing the Retrieve and RetrieveMultiple messages. When data is being displayed a CRMGrid control however, CRM uses the Execute message instead (specifically the ExecuteFetchRequest message, but this can’t be checked directly).

Given the pervasive nature of Execute message calls (tested thanks to David Jennaway’s work here), we’d already determined that checks were necessary to processing the majority of calls to the Execute message. After discovering that the Execute message’s InputParameters only contain a FetchXml property when a grid is being processed, we can exit the plugin code much quicker thereby improving system performance. It’s nice to know that this is actually the preferred method too!

Here’s a little sample:

    public class ExecuteHandler : IPlugin
    {
        public void Execute(IPluginExecutionContext context)
        {
            if (context.InputParameters.Contains("FetchXml"))
            {
                if (context.OutputParameters.Contains("FetchXmlResult"))
                {
                     // here I intercept and change some values in the FetchXmlResult fragment
                }
            }
        }

Windows Update killed my app pool!

Tried to access my client’s development server today to find that CRM 4.0 was down. First thing I did was to check IIS, to find that the CRMAppPool was stopped. I tried to restart it – it looked like it had worked, but alas a refresh showed that it had failed to start properly.

After first blaming the client’s visiting tech who was also working on the server (sorry ‘Cheung!), I checked the Event Viewer and the System Log showed a series of messages from my attempt to restart the Application Pool:

A process serving application pool ‘CRMAppPool’ terminated unexpectedly. The process id was ‘3432’. The process exit code was ‘0xffffffff’.

After a few attempts, W3SVC had given up:

Application pool ‘CRMAppPool’ is being automatically disabled due to a series of failures in the process(es) serving that application pool.

Scrolling down, it became clear that the new prime suspect was Windows Update. A number of updates had been installed early this morning. I checked the KB articles for each one until I came across KB973917 (Extended Protection for Authentication in Internet Information Services). I read the article and although some extra configuration was required, it didn’t seem to fit my scenario (aka, this is a development server and there was a lot of text in the article and I needed to get back to development, rather than poncing about with security updates). The solution for me was to simply uninstall KB973917 and reboot the server.

Microsoft Dynamics CRM 4.0 is now working just fine, though this probably needs some more investigation. I quick straw poll of some of my CRM buddies did not suggest a widespread issue (yet?) but maybe this was because of the particular setup we are using here?

I’m not about to fully troubleshoot now, but here is some information about the server that was stricken – maybe it will help you all to pinpoint any issue with your own servers:

    Microsoft Dynamics CRM 4.0 – Update Rollup 5
    Microsoft Windows 2003 SP2
    Internet Information Services 6.0
    Microsoft SQL Server 2005 SP3
    All running on one box
    Application pools running under default Network Service account

I believe this will not be limited to just CRM – at least one other report online of it affecting WSS.

Update 1:
Already a lot of hits today – if this solution works for you, please post and let everyone know. Also summarise your setup so we can work out when this is happening ūüôā

Update 2:
Kudos to Richard (who has commented below) for discovering that Microsoft have now rushed out a KB article to explain the problem and propose a longer-term fix: http://support.microsoft.com/Default.aspx?kbid=2009746. In short, reinstall Windows 2003 SP2.

Restarting the CRM application pool

So you’re developing plug-ins and you need to redeploy your DLL periodically since it is otherwise “in use” or there is some other reason that is asking for a full iisreset. Since a full reset is a bit invasive and global (e.g. this is a production server which also runs SharePoint, website or goodness knows what else), why not recycle the application pool instead?

Of course, we can do this via IIS Manager with a bit of point and click – but this can’t be automated and it’s a bit fiddly. Instead, do it from the command line with this handy bit of text:

cscript c:\windows\system32\iisapp.vbs /a "CrmAppPool" /r

Recycling the application pool is distinctly quicker than doing a full iisreset (though admittedly there are some scenarios when recycling the application pool is insufficient – no idea on the specifics though! See here, perhaps). I find this especially useful in the post-build events of Visual Studio (Project > %ProjectName% Properties > Build Events) to ensure that copying my DLLs always works without manually intervention.

Event execution order with ‘onbeforeunload’

Recommended JavaScript Book!

I'd also like to highly recommend this JavaScript book by Douglas Crockford - it will definitely improve the quality of your JavaScript development experience!


Recently I had a requirement to conditionally add some dynamic script to the onClose event for a CRM form. Given the flexiblility demanded by the requirements,¬†it was not practical to write script in the¬†form’s onClose() event hander in the CRM Form Properties window. Instead, I used¬†Internet Explorer’s attachEvent method.¬†

The problem with the attachEvent method is that the collection of functions that are appended to the event are executed in “random order”. “Random” is rarely a desirable sequence ¬†in my experience and in this case one cannot guarantee that a custom dynamic “validation check” (for example) will be executed before the default event handler (i.e. the one that may ask “Are you sure you want to navigate away from this page?”).

Alas a simple solution is at hand, thanks to¬†this post made by “Adios” over at CodingForums.com. The function¬†below will effectively inject your function call before the default event handler.¬†¬†Obviously this¬†function can be easily amended to deal with any¬†type of event but the example¬† below is hard-coded to deal with the “onbeforeunload” event handler.

Define this function in your form onLoad script (or somewhere in your global code, if you have adopted a custom solution for centralising your JavaScripts):

function addbeforeunloadEvent(func)
{
    var oldonbeforeunload = window.onbeforeunload;
    if (typeof window.onbeforeunload != 'function') {
        window.onbeforeunload = func;
    } else {
        window.onbeforeunload = function() {
            oldonbeforeunload();
            func();
        }
    }
}

Then use the following snippet to insert your function ahead of the default or existing event handler:

//TODO: replace myFunctionName and myParameter list to match your custom function signature
addbeforeunloadEvent(function(){myFunctionName(myParameterList);});

Update Rollup 4 for Microsoft CRM 4.0 is available

More info and download here

MSCRM Update Rollup 3 is available

Just a quickie – it appears that Update Rollup 3 has been released for Microsoft Dynamics CRM 4.0.

This fixes about a dozen issues that are acknowledged in KB articles and more than 50 previously undocumented items too. The list of issues addressed can be found on KB961768

onLoad code not running

Another strange problem encountered and fixed today. The form onLoad code “suddenly” stopped working. I say “suddenly” because in fact this was a red herring and the problem turned out to be the result of a change. The symptoms were however unexpected.

Normally when a scripting error occurs in MSCRM, Internet Explorer will throw a script error dialog as the form loads (e.g. “There was an error with this field’s customized event.”):

scripterror

There was an error with this field's customized event

  Or alternatively a warning is shown at the bottom left of the Internet Explorer screen:

Error on page

Error on page

But on this occasion, there were no warnings. My first thought was to place a debugger statement into the code, but even after publishing this too failed to execute. I tried a simple alert() statement but this also failed. Odd.

Replacing all the code in the event handler with a simple alert() statement did work, so clearly this was a syntax problem, but very odd that it didn’t throw any error and in fact even blocked the debugger statement. If I were to delve deeper I’m sure I’d find that this is due to try…catch handling within the MSCRM ASPX pages…

In the end, the problem was caused by an htmlEncoded chevron character which had somehow been pasted into the javascript code (< ) while setting up a for loop.

Thanks due to Douglas Croxford’s JsLint for speeding the time to resolution somewhat.

Corrupted entity – NullReferenceException when publishing or exporting

A corrupted entity
I ran into a problem today with my client which frankly had me stumped. For some reason that I have yet to determine (though possibly related to a broken install of Update Rollup 2), the account entity got corrupted. We discovered this when somebody attempted to publish their changes to the account entity and ran into a “red”¬†error dialog: “An error has occurred…please contact your system administrator”. This error was replicated if we tried to publish, delete any attributes from the entity or export the entity customizations. Not much scope for fixing the situation!

Troubleshooting…
After studying the server trace logs (thanks to CrmDiagTool4 and Michael Hoehne’s Trace Log Viewer for easing this process), the situation wasn’t much clearer. The underlying error was:

Request URL: http://localhost/MyOrgName/AppWebServices/SystemCustomization.asmx
Stack Trace Info: [NullReferenceException: Object reference not set to an instance of an object.]
at Microsoft.Crm.ObjectModel.OrganizationUIService.LabelLoaderAllLanguages.LoadMetadataLabel(Int32 entityType, String attributeName, ExecutionContext context)

I also did a SQL Trace using SQL Profiler on the server, but this didn’t really provide anything new at all.

So, when faced with a problem I can’t resolve myself, I turned to Google for help. I managed to find KB article 947096 which seemed very near to my problem, but sadly none of the resolution steps would help me. I then tried importing a known good copy of the account entity customizations but that failed too. At this point I looked back at the Trace Log and tried to determine what was going on “under the hood” prior to the failure…

It was clear from the logs that CRM was trying to pull in LocalizedLabel information for my entity attributes and form controls, however I couldn’t quite fathom out which attribute was causing the NullReferenceException (it seems that the last statement in the logs – MetadataProcessObject.ExecuteQuery – was successfully completing its SQL command and the following statement which was failing was not logging any parameters and therefore didn’t provide me with a “smoking gun”). In fact there were many calls to both CrmDbConnection.InternalExecuteReader and MetadataProcessObject.ExecuteQuery so clearly there was an interative loop going on. I didn’t know which mechanism within the CRM server black box was selecting the list of attributes to process, so I looked further back and found that this loop was likely being “triggered” by the FormXML property on the OrganisationUI view.

At this point¬†everything¬†clicked into place: the problem, somehow, was with the published version of my form (some of you may have realised this long ago). This form xml was being re-evaluated (for some reason) prior to every publish, export or delete request and then failing some integrity or logical check. Re-importing a known good copy would not help, since it would need to be published to take effect. I only had one option left – to break all the rules and manually amend the database in order to correct the corrupted FormXml property…

So here’s what I did:

Resolution
Took a backup of the current formXml property by running the following SQL statement within SQL Server Management Studio in the “_MSCRM” database (then right click on results tab and click “save as”…):


select organizationui0.ObjectTypeCode organizationui0.FormXml as 'formxml',
from OrganizationUI as organizationui0
where (organizationui0.InProduction = 1 and (organizationui0.ObjectTypeCode = 1))

Next I found my “good” copy of the customizations file. I identified the start and end node that was required in order to match the same format as the existing formXML property (the starting tags were <form><entity…>). Next I copied this xml to a new file and removed all tabs and new lines, to give a single continuous string.

I saved this xml file onto my CRM server then went back to SQL Management Studio and ran the following SQL to import this long string directly into the SQL table:

declare @xmlText varchar(max)
select @xmlText =(select * from openrowset (bulk 'c:\amendedformxml.txt',SINGLE_CLOB)x)
update dbo.OrganizationUI
set FormXml = @xmlText
where (InProduction = 1 and (ObjectTypeCode = 1))

This effectively “forced” my old formXML into a published state and magically fixed my problems. Further, once I clicked “Publish” following these steps, the formXML was consequently re-evaluated again and the hitherto unpublished customizations become published (as expected) and therefore effectively no information had been lost by importing the older xml.

Conclusion
So I still don’t know what caused this issue… I’d love to know if anyone else has had a similar situation. I’m not entirely comfortable with the way I had to fix the problem either, but then sometimes your hand is forced into doing things you don’t want to do. I’ll monitor the situation and let you all know if there are any repercussions. In the meantime, the usual caveats apply – the steps above are definitely unsupported and could definitely render your CRM installation inoperable, so use the steps above at your own risk!

Minor problem after installing MSCRM 4.0 Update Rollup 2

Edit: It seems that the issue below was limited to my client’s machine only. I’ve reinstalled Update Rollup 2 and the problem went away… The rest of this post is here for reference:

It seems that there is a small bug introduced It seems that my client has encountered an issue with Update Rollup 2 for Microsoft CRM. After installing, the form labels shown in the form designer are incorrectly reading from the published entity definitions, rather than the unpublished definitions. The result of this is that if you update a field label and click save, it appears not to have worked. If you ignore this apparent effect and publish your entity, lo! The field labels are indeed automagically updated after all.

Steps to reproduce:

  1. Open any entity for via Settings > Customization > Customize Entities > …
  2. Go to Forms and Views > Form
  3. Double-click any existing field and change the Label attribute then click OK
  4. At this point, the amend appears correctly
  5. Click the Save button on the form
  6. Note that your label amendment appears to have been backed out…(!)
  7. Close the form designer screen and from the entity record, click Actions > Publish
  8. Go back to the form designer via Forms and Views > Form
  9. Note that your label amendment has indeed persisted and is now also in production too

Edit: so we fixed this by removing UR2, rebooting, downloading UR2 afresh, reinstalling UR2 and rebooting again. Can’t imagine what failed – perhaps I had an early release of Update Rollup 2 with a bug – I seem to recall that it was silently reissued shortly after release.

Microsoft CRM Event Management Accelerator released!

Great news – the much anticipated CRM Accelerators are finally starting to be released!

Initially there were two releases available on PartnerSource only, but now more code is appearing on Codeplex too: http://www.codeplex.com/crmaccelerators¬†– specifically, we can now get our hands on the first really exciting one – the Event Management accelerator. This doesn’t appear to have been publicised so well just yet so I thought I’d shout up!

At the time of writing, it is now possible to download the following:

  • Event Management (Codeplex only at present)
    “Ability to manage the planning, execution, tracking and reporting requirements for events…” including an example external website allowing delegates to register themselves on your events and reports to measure effectiveness of your events.
  • Notifications
    Subscriptions to business events (e.g. new leads for current user) which are delivered via RSS feeds
  • Extended Sales Forecasting
    Primarily, new reports to allow better visibility of sales forecasts, including individualised sales pipeline and per salesperson performance against forecast by time period

Happy playing!