Tuesday, January 7, 2014

Lessons Learned Deleting 312 Million Records From CRM’s PrincipalObjectAccess Table

Unrestrained growth of the POA (PrincipalObjectAccess) SQL table in CRM is nothing new.  Performance of on premise CRM installations can start to be noticeably affected at 10 million records or so.  You can imagine my surprise when I learned my client had just over 1/3 of a billion records!  Microsoft has a script to clean it up, which probably works great at cleaning up a couple million records, but is not really an option when needing to clean up 312 million. 

After multiple modifications to Microsoft's scripts in our test environments we ended up splitting/modifying the Microsoft into 4 different scripts.

  1. Create and populate ToDeletePOAEntries Table.
  2. Drop the existing indexes on the POA table, add a single index just with the columns needed for the join
  3. Delete the POA records
  4. Reset the index changes made in Script 2.

The smartest thing we did was probably sending an e-mail, every time the script deleted a million records.  This allowed us to see trends in how long it was taking to delete and attempt to fix the issue.

Here is a graph of the e-mails received for the first 82 million, which took just over 9 hours:

First82Million

 

We wrongly assumed that the increase in deletions was due to the indexes needing to be rebuilt, but rebuilding the index didn’t change the trend.  We then decided to try rebuilding the ToDeletePOAEntries table and this is what we saw for the next 48 million over the course of 4 hours:

MiddleMillions

We then edited the script to make the cleanup of the ToDeletePOAEntries automatic.  If I had to do it over again, I’d add an Identity column to the ToDeletePOAEntries table, and update the where of the join for each loop to start at the next batch of entries.  This is what we then saw with the noticeable peeks required to recreate the ToDeletePOAEntries table every 25 million:FinalMillions

 

Here are the scripts that were used.  Hopefully they’ll be helpful for anyone else out there in the same position we were in. It took just over 30 hours to delete 312 million records with CRM itself completely shutdown.

Script 1: Creates ToDeletePOAEntries table, populating it with all of the records that need to be removed out of the POA table.  This is basically the first part of the Microsoft script,

USE [Contoso_MSCRM]
GO

IF NOT EXISTS (SELECT * FROM sys.sysobjects
WHERE id = object_id(N'[dbo].[ToDeletePOAEntries]')
AND ObjectProperty(id, N'IsUserTable') = 1)

create table ToDeletePoaEntries
(
ObjectId uniqueidentifier,
Otc int
)
IF NOT EXISTS (SELECT * FROM sys.sysindexes si
INNER JOIN sys.sysobjects so ON si.id = so.id
WHERE so.id = OBJECT_ID(N'[dbo].[ToDeletePoaEntries]')
AND OBJECTPROPERTY(so.id, N'IsUserTable') = 1
AND si.name LIKE '%mainindex%')

CREATE UNIQUE NONCLUSTERED INDEX [mainindex] ON [dbo].[ToDeletePoaEntries]
(
[ObjectId] ASC,
[Otc] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

----- Insert records to be deleted in ToDeletePoaEntries

-- go through all user-owned entities which are not replicated and don't support duplicate detection
declare entity_cursor cursor local FORWARD_ONLY READ_ONLY
for select distinct e.ObjectTypeCode, e.BaseTableName, a.PhysicalName from EntityView e
inner join AttributeView a on e.EntityId = a.EntityId and a.IsPKAttribute = 1
where e.IsReplicated = 0 and e.IsDuplicateCheckSupported = 0 and e.OwnershipTypeMask & 1 = 1

open entity_cursor

declare @baseTableName sysname
declare @otc nvarchar(20)
declare @primaryKey sysname
declare @totalCollected int = 0
declare @currentCollected int
declare @tempRowCount int = 0
declare @collectstatement nvarchar(max)fetch next from entity_cursor
into @otc, @baseTableName, @primaryKeywhile @@FETCH_STATUS = 0
begin
print 'Cleaning up POA for ' + @baseTableName

set @currentCollected = 0


set @collectstatement = 'insert into ToDeletePoaEntries(ObjectId, Otc)
select distinct poa.ObjectId, poa.ObjectTypeCode
from PrincipalObjectAccess poa left join '
 + @baseTableName + ' e on poa.ObjectId = e.' + @primaryKey +
' where e.' + @primaryKey + ' is null and poa.ObjectTypeCode = ' + @otc;

print @collectstatement

exec(@collectstatement)
set @tempRowCount = @@ROWCOUNT
set @currentCollected = @currentCollected + @tempRowCount
print CAST(@currentCollected as nvarchar(20)) + ' records collected for ' + @baseTableName
set @totalCollected = @totalCollected + @currentCollected

fetch next from entity_cursor
into @otc, @baseTableName, @primaryKey
end

close entity_cursor
deallocate entity_cursor

print CAST(@totalCollected as nvarchar(20)) + ' total records collected'

Script 2: Drop the existing indexes on the POA table, add a single index just with the columns needed for the join.  This isn’t included in Microsoft’s script, and I don’t have any data as far as how helpful this was, but it should result in the least amount of work required by the database in order to delete a record.

USE [Contoso_MSCRM]

go

/****** Object:  Index [ndx_PrimaryKey_PrincipalObjectAccess]    Script Date: 12/18/2013 08:44:05 ******/
IF EXISTS (SELECT *
           FROM   sys.indexes
           WHERE  object_id = Object_id(N'[dbo].[PrincipalObjectAccess]')
                  AND name = N'ndx_PrimaryKey_PrincipalObjectAccess')
  ALTER TABLE [dbo].[principalobjectaccess]
    DROP CONSTRAINT [ndx_PrimaryKey_PrincipalObjectAccess]

go

/****** Object:  Index [ndx_Cover]    Script Date: 12/18/2013 08:44:15 ******/
IF EXISTS (SELECT *
           FROM   sys.indexes
           WHERE  object_id = Object_id(N'[dbo].[PrincipalObjectAccess]')
                  AND name = N'ndx_Cover')
  DROP INDEX [ndx_Cover] ON [dbo].[PrincipalObjectAccess] WITH ( online = OFF )

go

/****** Object:  Index [fndx_Sync_VersionNumber]    Script Date: 12/18/2013 08:44:33 ******/
IF EXISTS (SELECT *
           FROM   sys.indexes
           WHERE  object_id = Object_id(N'[dbo].[PrincipalObjectAccess]')
                  AND name = N'fndx_Sync_VersionNumber')
  DROP INDEX [fndx_Sync_VersionNumber] ON [dbo].[PrincipalObjectAccess] WITH (
  online = OFF )

go

/****** Object:  Index [cndx_PrincipalObjectAccess]    Script Date: 12/18/2013 08:44:45 ******/
IF EXISTS (SELECT *
           FROM   sys.indexes
           WHERE  object_id = Object_id(N'[dbo].[PrincipalObjectAccess]')
                  AND name = N'cndx_PrincipalObjectAccess')
  DROP INDEX [cndx_PrincipalObjectAccess] ON [dbo].[PrincipalObjectAccess] WITH
  (
  online = OFF )

go

/****** Object:  Index [UQ_PrincipalObjectAccess]    Script Date: 12/18/2013 08:45:56 ******/
IF EXISTS (SELECT *
           FROM   sys.indexes
           WHERE  object_id = Object_id(N'[dbo].[PrincipalObjectAccess]')
                  AND name = N'UQ_PrincipalObjectAccess')
  ALTER TABLE [dbo].[principalobjectaccess]
    DROP CONSTRAINT [UQ_PrincipalObjectAccess]

go

CREATE NONCLUSTERED INDEX [IX_CleanupIndex]
  ON [dbo].[PrincipalObjectAccess] ( [objectid] ASC, [objecttypecode] ASC )
  WITH (statistics_norecompute = OFF, sort_in_tempdb = OFF, ignore_dup_key = OFF
, drop_existing = OFF, online = OFF, allow_row_locks = ON, allow_page_locks = ON
) ON [PRIMARY]

go 

Script 3: Delete the POA records.  This script has the most changes from the Microsoft version.  It wasn’t until we actually started running the scripts in Prod that we finally figured out our main bottle neck, the join of the POA table to the ToDeletePOAEntries.  For every million records deleted, the next time through the loop, the SQL server would attempt to find records that had just been deleted first, before joining on the records not yet deleted.  There is vast rooms for improvement here I’m sure, but this is what we came up with over winter holiday.

USE [Contoso_MSCRM]

go

-- Delete query
-- This scripts cleans up orphaned POA records for selected entities
DECLARE @deleteBatchSize INT = 50000
DECLARE @deleteBatchSizeNVarChar NVARCHAR(10) = Cast(
        @deleteBatchSize AS NVARCHAR(10))
DECLARE @totalDeleted INT = 0
DECLARE @currentDeleted INT
DECLARE @deletestatement NVARCHAR(max)
DECLARE @retry INT = 1
DECLARE @tempRowCount INT = 0
DECLARE @recipientList NVARCHAR(1000) = 'MSmith@Contoso.com;JDoe@Contoso.com'
DECLARE @backupScript NVARCHAR(1000)
DECLARE @backupCount INT = 0
DECLARE @bodyText NVARCHAR(4000)
DECLARE @subjectText NVARCHAR(1000)
DECLARE @baseTableName SYSNAME
DECLARE @otc NVARCHAR(20)
DECLARE @primaryKey SYSNAME
DECLARE @totalCollected INT = 0
DECLARE @currentCollected INT
DECLARE @tempRowCountRecreate INT = 0
DECLARE @collectstatement NVARCHAR(max)

WHILE ( @retry > 0 )
  BEGIN
      BEGIN try
          SET @currentDeleted = 0
          SET @tempRowCount = 0
          -- delete all records of the current entity type which don't have corresponding object in the base table
          SET @deletestatement = 'delete top (' + @deleteBatchSizeNVarChar
                                 +
') from PrincipalObjectAccess from PrincipalObjectAccess poa join ToDeletePoaEntries e on poa.ObjectId = e.ObjectId and poa.ObjectTypeCode = e.Otc'

    PRINT @deletestatement

    -- delete PrincipalObjectAccess records in batches
    EXEC(@deletestatement)

    SET @tempRowCount = @@ROWCOUNT
    SET @currentDeleted = @currentDeleted + @tempRowCount

    WHILE @tempRowCount = @deleteBatchSize
      BEGIN
          EXEC(@deletestatement)

          SET @tempRowCount = @@ROWCOUNT
          SET @currentDeleted = @currentDeleted + @tempRowCount

          PRINT Cast(@currentDeleted AS NVARCHAR(20))
                + ' records deleted '
                + Cast(Getutcdate() AS NVARCHAR(50))

          -- Every 1,000,000 records notify the team that we have deleted another 1,000,000 records, with the total record count
          IF ( @currentDeleted % 1000000 = 0 )
            BEGIN
                PRINT '1,000,000 records deleted'

                SET @bodyText = CONVERT(NVARCHAR(20), @currentDeleted)
                                + ' POA records deleted.';

                EXECUTE msdb.dbo.Sp_send_dbmail
                  @profile_name = 'SQLNotify Profile',
                  @recipients = @recipientList,
                  @body = @bodyText,
                  @subject = 'POA Cleanup Progress Email',
                  @importance = 'High'
            END

          -- Every 25,000,000 records Rebuild ToDeletePoaEntries
          IF ( @currentDeleted % 25000000 = 0
                OR @currentDeleted <= 100000 )
            BEGIN
                PRINT '25,000,000 records deleted'

                -- DROP AND RECREATE TABLE
                DROP INDEX [mainindex] ON [dbo].[ToDeletePoaEntries]

                DROP TABLE todeletepoaentries

                CREATE TABLE todeletepoaentries
                  (
                     objectid UNIQUEIDENTIFIER,
                     otc      INT
                  )

                ----- Insert records to be deleted in ToDeletePoaEntries
                -- go through all user-owned entities which are not replicated and don't support duplicate detection
                DECLARE entity_cursor CURSOR local forward_only read_only FOR
                  SELECT DISTINCT e.objecttypecode,
                                  e.basetablename,
                                  a.physicalname
                  FROM   entityview e
                         INNER JOIN attributeview a
                                 ON e.entityid = a.entityid
                                    AND a.ispkattribute = 1
                  WHERE  e.isreplicated = 0
                         AND e.isduplicatechecksupported = 0
                         AND e.ownershiptypemask & 1 = 1

                OPEN entity_cursor

                SET @totalCollected = 0
                SET @tempRowCountRecreate = 0

                FETCH next FROM entity_cursor INTO @otc, @baseTableName,
                @primaryKey

                WHILE @@FETCH_STATUS = 0
                  BEGIN
                      PRINT 'Cleaning up POA for ' + @baseTableName

                      SET @currentCollected = 0
                      SET @collectstatement = 'insert into ToDeletePoaEntries(ObjectId, Otc)  select distinct poa.ObjectId, poa.ObjectTypeCode  from PrincipalObjectAccess poa left join ' + @baseTableName
                                              + ' e on poa.ObjectId = e.' +
                                              @primaryKey
                                              + ' where e.' + @primaryKey
                                              +
                      ' is null and poa.ObjectTypeCode = '
                                              +
                                              @otc;

                      PRINT @collectstatement

                      EXEC(@collectstatement)

                      SET @tempRowCountRecreate = @@ROWCOUNT
                      SET @currentCollected =
                      @currentCollected + @tempRowCountRecreate

                      PRINT Cast(@currentCollected AS NVARCHAR(20))
                            + ' records collected for ' + @baseTableName

                      SET @totalCollected = @totalCollected + @currentCollected

                      FETCH next FROM entity_cursor INTO @otc, @baseTableName,
                      @primaryKey
                  END

                CLOSE entity_cursor

                DEALLOCATE entity_cursor

                CREATE UNIQUE NONCLUSTERED INDEX [mainindex]
                  ON [dbo].[ToDeletePoaEntries] ( [objectid] ASC, [otc] ASC )
                  WITH (statistics_norecompute = OFF, sort_in_tempdb = OFF,
                ignore_dup_key
                =
                OFF, drop_existing = OFF, online = OFF, allow_row_locks = ON,
                allow_page_locks = ON) ON [PRIMARY]

                PRINT Cast(@totalCollected AS NVARCHAR(20))
                      + ' total records collected'
            END
      END

    -- We are done! Delete the ToDeletePoaTable and Notify the team
    DROP TABLE [dbo].[todeletepoaentries]

    EXECUTE msdb.dbo.Sp_send_dbmail
      @profile_name = 'SQLNotify Profile',
      @recipients = @recipientList,
      @body = 'All POA Records to be deleted have been deleted.',
      @subject = 'POA Cleanup Complete',
      @importance = 'High'

    -- Reset the @retry value to 0, which will allow the code to exit the WHILE loop
    SET @retry = 0
END try

    BEGIN catch
        PRINT 'Retry ' + CONVERT(NVARCHAR(10), @retry)

        SET @retry = @retry + 1
        -- Hit an error - Notify the team
        SET @bodyText = Error_message();
        SET @subjectText = 'POA Cleanup Progress Email - Error '
                           + CONVERT(NVARCHAR(10), @retry);

        EXECUTE msdb.dbo.Sp_send_dbmail
          @profile_name = 'SQLNotify Profile',
          @recipients = @recipientList,
          @body = @bodyText,
          @subject = @subjectText,
          @importance = 'High'

        -- There was an error so let's reindex
        ALTER INDEX ALL ON dbo.principalobjectaccess reorganize;

        UPDATE STATISTICS dbo.principalobjectaccess;
    END catch
END --END OF THE RETRY LOOP
PRINT 'EXECUTION SUCCEED' 

Script 4: Reset the indexes on the POA table to bring them back to their original condition:

USE [Contoso_MSCRM]

go

IF EXISTS (SELECT *
           FROM   sys.sysindexes si
                  INNER JOIN sys.sysobjects so
                          ON si.id = so.id
           WHERE  so.id = Object_id(N'[dbo].[ToDeletePoaEntries]')
                  AND Objectproperty(so.id, N'IsUserTable') = 1
                  AND si.name LIKE '%mainindex%')
  DROP TABLE [dbo].[todeletepoaentries]

go

USE [Contoso_MSCRM]

go

/****** Object:  Index [IX_CleanupIndex]    Script Date: 12/19/2013 16:02:29 ******/
IF EXISTS (SELECT *
           FROM   sys.indexes
           WHERE  object_id = Object_id(N'[dbo].[PrincipalObjectAccess]')
                  AND name = N'IX_CleanupIndex')
  DROP INDEX [IX_CleanupIndex] ON [dbo].[PrincipalObjectAccess] WITH ( online =
  OFF )

go

/****** Object:  Index [cndx_PrincipalObjectAccess]    Script Date: 12/18/2013 08:52:57 ******/
CREATE CLUSTERED INDEX [cndx_PrincipalObjectAccess]
  ON [dbo].[PrincipalObjectAccess] ( [objectid] ASC, [principalid] ASC )
  WITH (pad_index = OFF, statistics_norecompute = OFF, sort_in_tempdb = OFF,
ignore_dup_key = OFF, drop_existing = OFF, online = OFF, allow_row_locks = ON,
allow_page_locks = ON, FILLFACTOR = 100) ON [PRIMARY]

go

/****** Object:  Index [fndx_Sync_VersionNumber]    Script Date: 12/18/2013 08:53:03 ******/
CREATE UNIQUE NONCLUSTERED INDEX [fndx_Sync_VersionNumber]
  ON [dbo].[PrincipalObjectAccess] ( [versionnumber] ASC )
WHERE ([VersionNumber] IS NOT NULL)
WITH (pad_index = OFF, statistics_norecompute = OFF, sort_in_tempdb = OFF,
ignore_dup_key = OFF, drop_existing = OFF, online = OFF, allow_row_locks = ON,
allow_page_locks = ON, FILLFACTOR = 100) ON [PRIMARY]

go

/****** Object:  Index [ndx_Cover]    Script Date: 12/18/2013 08:53:13 ******/
CREATE NONCLUSTERED INDEX [ndx_Cover]
  ON [dbo].[PrincipalObjectAccess] ( [objecttypecode] ASC, [principalid] ASC,
[accessrightsmask] ASC, [inheritedaccessrightsmask] ASC )
  WITH (pad_index = OFF, statistics_norecompute = OFF, sort_in_tempdb = OFF,
ignore_dup_key = OFF, drop_existing = OFF, online = OFF, allow_row_locks = ON,
allow_page_locks = ON, FILLFACTOR = 80) ON [PRIMARY]

go

/****** Object:  Index [ndx_PrimaryKey_PrincipalObjectAccess]    Script Date: 12/18/2013 08:53:21 ******/
ALTER TABLE [dbo].[principalobjectaccess]
  ADD CONSTRAINT [ndx_PrimaryKey_PrincipalObjectAccess] PRIMARY KEY NONCLUSTERED
  ( [principalobjectaccessid] ASC )WITH (pad_index = OFF, statistics_norecompute
  = OFF, sort_in_tempdb = OFF, ignore_dup_key = OFF, online = OFF,
  allow_row_locks = on, allow_page_locks = on, FILLFACTOR = 100) ON [PRIMARY]

go

/****** Object:  Index [UQ_PrincipalObjectAccess]    Script Date: 12/18/2013 08:53:33 ******/
ALTER TABLE [dbo].[principalobjectaccess]
  ADD CONSTRAINT [UQ_PrincipalObjectAccess] UNIQUE NONCLUSTERED ( [principalid]
  ASC, [objectid] ASC, [objecttypecode] ASC )WITH (pad_index = OFF,
  statistics_norecompute = OFF, sort_in_tempdb = OFF, ignore_dup_key = OFF,
  online = OFF, allow_row_locks = on, allow_page_locks = on, FILLFACTOR = 100)
  ON [PRIMARY]

go 

Monday, September 9, 2013

Pet Peeve #1

Calling ToString() on an object that is already typed as a String.  I see this in all sorts of situations, but this morning it was when accessing a configuration value:
ConfigurationManager.AppSettings["EmailFrom"].ToString();

AppSettings is a NameValueCollection.  When accessing its this[string name] or this[int index] properties, it returns a String.  Don’t give future developers more code that they have to read and subsequently ignore, that doesn’t add to readability.

Tuesday, July 16, 2013

Snippet to Create “C# Like” Collapsible Regions in VS2012 Javascript Files

Ever wanted to create a collapsible region within Javascript? If you have the Web Essentials Extension for VS 2012 you already have that feature:
image
But, the one thing that they are missing in the Web Essentials Extension is a snippet to allow you to automatically insert the region syntax.  Just save this text to “C:\Users\$UserName$\Documents\Visual Studio 2012\Code Snippets\JavaScript\My Code Snippets\regions.snippet” on your local computer, and viola!
<CodeSnippet Format="1.1.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>region</Title>
    <Author>Daryl LaBar</Author>
    <Shortcut>region</Shortcut>
    <Description>Code snippet for region in javascript Using Web Essentials 2012</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
      <SnippetType>SurroundsWith</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>name</ID>
        <ToolTip>Region name</ToolTip>
        <Default>MyRegion</Default>
      </Literal>
    </Declarations>
    <Code Language="JavaScript">
      <![CDATA[//#region $name$
 
 $selected$$end$
 
//#endregion $name$]]>
    </Code>
  </Snippet>
</CodeSnippet>

Wednesday, July 3, 2013

Making FetchXml in Javascript Less SOAPy and XMLy


Whenever I have to request data from CRM within Javascript, my first attempt is always to use an OData call.  The request urls aren’t too difficult to create (On a side note, there are multiple custom tools for this purpose. I prefer LinqPad.) and the data transferred in the request and the response is extremely tiny.  But… it has some limitations, especially within CRM.  So what do you do when you’ve hit one of the limitations?
  1. Search the internet for “CRM FetchXML from JavaScript”
  2. Copy and paste some hard coded SOAP XML from a random post somewhere
  3. Shoehorn your FetchXML into it.
  4. Spend an hour parsing the returned XML with the XML Parser, trying to figure out how many .childNode[i] and .firstChild properties you need to string together to get your actual data.
  5. Feel sorry for the next developer that has to tweak your “ParseResults” code.
Need to do it again 3 months later?  Repeat the process form the top.  It’s one of those processes that makes you amazed there isn’t an easier way.  Well… now there is.

CRM FetchXML Soap Library

In the spirit of “All problems in computer science being solvable by another level of abstraction,” I’ve create a small JavaScript library to abstract away all of the SOAPy, XMLy, uglyness.  Here is an example of it’s use:
// Fetch Xml Call to get all opportunities for TX, with their estimated values
var fetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">' +
'  <entity name="opportunity">' +
'    <attribute name="estimatedvalue" />' +
'    <order attribute="name" descending="false" />' +
'    <link-entity name="account" from="accountid" to="customerid" alias="ae">' +
'      <filter type="and">' +
'        <condition attribute="address1_stateorprovince" operator="eq" value="TX" />' +
'      </filter>' +
'    </link-entity>' +
'    <link-entity name="account" from="accountid" to="parentaccountid" visible="false" link-type="outer" alias="Account">' +
'      <attribute name="address1_stateorprovince" />' +
'    </link-entity>' +
'  </entity>' +
'</fetch>';

var response = Allegient.Core.SoapLib.executeFetchXmlRequest(fetchXml);


Just give the Library FetchXml, and it’ll give you back a collection of javascript objects that are parsed from the result. Here is what the result looks like in the IE debugger:

IE Debugger Window


Here are a couple things to take note of:
  1. The response returned is just an array of entities.
  2. Each entity has a property that maps to a property of the entity returned.  This allows working with the entities in a way that is much easier than XML parsing.  ie to get the first entity’s name: “response[0].name” or to get the the 2nd entity’s currency’s name: “response[1].transactioncurrencyid.Name”.

The Implementation

There is a lot going on under the covers, so we’ll start at the top with executeFetchXmlRequest and work our way down:

executeFetchXmlRequest: function (fetchXml, onSuccess, onError, async) {

     if (async == null) {
         async = false;
     } 
    var request = '<request i:type="b:RetrieveMultipleRequest" xmlns:b="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">'
         + '    <b:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic">'
         + '        <b:KeyValuePairOfstringanyType>'
         + '            <c:key>Query</c:key>'
         + '            <c:value i:type="b:FetchExpression">'
         + '                <b:Query>' + CrmEncodeDecode.CrmXmlEncode(fetchXml)
         + '                </b:Query>'
         + '            </c:value>'
         + '        </b:KeyValuePairOfstringanyType>'
         + '    </b:Parameters>'
         + '    <b:RequestId i:nil="true"/>'
         + '    <b:RequestName>RetrieveMultiple</b:RequestName>'
         + '</request>';
     var response = null;
     var internalOnSuccess;
     if (onSuccess == null) {
         internalOnSuccess = function (r) { response = Allegient.Core.SoapLib._onFetchXmlSuccess(r); };
     } else {
         internalOnSuccess = function (r) {
             var temp = Allegient.Core.SoapLib._onFetchXmlSuccess(r);
             response = onSuccess(temp);
             if (response == null) {
                 response = temp;
             } 
        }; 
    } 
    Allegient.Core.SoapLib.executeRequest(request, internalOnSuccess, onError, async);
     return response;
},


executeFetchXmlRequest just wraps the FetchXml with the RetrieveMultipleRequest request xml, encoding the FetchXml as well.  Then it sets up some default response handlers, allowing for the request to be made asynchronously.  The next step is the executeRequest:

executeRequest: function (requestXml, onSuccess, onError, async) {

     if (async == null) {
         async = false;
     } 
    var soapEnvelope = ""
    + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">"
    + "<s:Body>"
    + "   <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"
    + requestXml
    + "    </Execute>"
    + "  </s:Body>"
    + "</s:Envelope>";
     var req = Allegient.Core.SoapLib.getXMLHttpRequest();
     req.open("POST", Allegient.Core.SoapLib._getServerUrl(), async)
     // Responses will return XML. It isn't possible to return JSON.
     req.setRequestHeader("Accept", "application/xml, text/xml, */*");
     req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
     req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
     req.onreadystatechange = function () { Allegient.Core.SoapLib.ExecuteSOAPResponse(req, onSuccess, onError); };
     req.send(soapEnvelope);
},


It’s primary purpose is to wrap the CRM Request Xml in a Soap Envelope.  It can be used to wrap any SOAP calls to CRM to help keep them DRY (Included in the library is an ExecuteWorkflowRequest to illustrate how another request type would utilize executeRequest).

It utilizes three helper functions.
  1. getXMLHttpRequest - returns an XMLHttpRequestObject in a browser specific safe manner.
  2. _getServerUrl – returns the URL for the SOAP endpoint using the context information available in the form or HTML Web Resource.
  3. ExecuteSOAPResponse – Handles the callback from the request, determining based on the readyState and status if it executed successfully or with an error, calling the appropriate call back.

The default error callback just displays the error in an alert().  The default success callback as defined by executeFetchXmlRequest is _onFetchXmlSuccess:

_onFetchXmlSuccess: function (response) {
     response = Allegient.Core.SoapLib._replaceAll(response, "<ExecuteResponse ", "<a:ExecuteResponse ");
     response = Allegient.Core.SoapLib._replaceAll(response, "<ExecuteResult ", "<a:ExecuteResult ");
     response = response.replace(/<(\/?)([^:>]*:)?([^>]+)>/g, "<$1$3>");
     var doc = Allegient.Core.SoapLib._parseXmlString(response);
     if (Allegient.Core.SoapLib._getElementText(doc.getElementsByTagName("ResponseName")[0]) == "RetrieveMultiple") {
         var elements = doc.getElementsByTagName("Entity");
         var entities = new Array();
         for (var i = 0; i < elements.length; i++) {
             entities[i] = Allegient.Core.SoapLib.XML2jsobj(elements[i]);
         } 
        return entities;
     } else {
         return doc.getElementsByTagName("Results")[0];
     }
},


There is some RegEx magic to remove the namespace prefixes from the XML so XML2jsobj returns valid property names.  Small side note here, the ExecuteResponse and ExecuteResult are the only xml elements in the response that don’t have a namesapce and my current regex doesn’t handle them correctly, hence the manual addition of the namespace prefix to the tag.  _parseXmlString returns a valid XMLDomParser that has loaded the xml passed in.  A quick walk of the XML Dom to see if this is a RetrieveMultiple Response, and if so, each entity is parsed one at a time by XML2jobj.  If it’s not a RetrieveMultiple response, the DOM results from the response are returned.  XML2jobj is based off of a version by Craig Buckler, but specifically modified for reading CRM attribute data:

XML2jsobj: function (node) {
     var data = {};
     var isNull = true;
     // append a value
     function Add(name, value) {
         isNull = false;
         if (data[name]) {
             if (data[name].constructor != Array) {
                 data[name] = [data[name]];
             } 
            data[name][data[name].length] = value;
         } 
        else {
             data[name] = value;
         } 
    }; 
    function AddAttributes(entity, node) {
         for (var i = 0; i < node.childNodes.length; i++) {
             isNull = false;
             //KeyValuePairOfstringanyType
             var valuePair = node.childNodes[i];
             var key = Allegient.Core.SoapLib._getElementText(valuePair.firstChild);
             var value = valuePair.childNodes[1].childNodes;
             if (value.length == 1 && value[0].tagName == "Value") {
                 data[key] = Allegient.Core.SoapLib._getElementText(value[0]);
             } else if (value.length == 1 && value[0].nodeType == 3) {
                 data[key] = value[0].nodeValue;
             } else {
                 data[key] = Allegient.Core.SoapLib.XML2jsobj(valuePair.childNodes[1]);
             } 
        } 
    }; 
    
     var c, cn;

     // child elements
     for (c = 0; cn = node.childNodes[c]; c++) {
         if (cn.nodeType == 1) {
             if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) {
                 // text value
                 Add(cn.nodeName, cn.firstChild.nodeValue);
             } 
            else if (cn.nodeName == "Attributes") {
                 AddAttributes(data, cn)
             } else {
                 // sub-object
                 Add(cn.nodeName, Allegient.Core.SoapLib.XML2jsobj(cn));
             } 
        } 
    } 
    if (isNull) {
         data = null;
     } 
    return data;
},


It loops through the XML DOM, creating a new js object for each node in the xml, with special processing for the attributes collection, resulting in the response looking like the screen shot above. 

Conclusion

The CRM FetchXML SOAP Library is extremely helpful, allowing for just the FetchXML to be passed in (no need to worry about SOAP headers or the wrapping Request XML itself) and a collection of entity JavaScript objects returned.  It should now change your javascript FetchXML steps from what is listed at the top of this article, to this:
  1. Search the internet for “CRM FetchXML from JavaScript”
  2. Download this library
  3. Never repeat steps 1-2 again
  4. Use your FetchXML as is, calling executeFetchXmlRequest
  5. Easily access the data you need in the response
  6. Go home early, and sleep better at night*

*Step 6 is not required but highly likely ;)


Click here to download the source code.


Thursday, April 18, 2013

Programmatically Generating Properties for OptionSet Enums

Generating early bound entity classes for CRM Entities is fairly simple.  Generating the Enums for the OptionSets is fairly simple as well.  Generating the OptionSet Enum properties for entities that are typed to the correct Enum is not so simple, and not currently supported by the CrmSrvUtil.exe.  If you want to be able to use the enums for populating the option set values, you have to continually write code that looks like this:
contact.Address1_AddressTypeCode = new OptionSetValue((int)contact_address1_addresstypecode.Home);


Which I don’t like for three reasons:

No Compile Time Error Checking to Ensure the Correct Enum Type is Used
For my current customer, they have some OptionSets that were created in CRM 4.0, before they had global OptionSets.  Once they upgraded to CRM 2011, they added global versions of these OptionSets as well, so if you’re not paying attention, you could easily be populating a local OptionSetValue on an entity, with the int value of a global OptionSetEnum (which have different int values).

Extra “Boiler Plate” Code Requires More KeyStrokes, and is Less Readable
Any time there is extra code that really isn’t needed, it makes it harder on the human brain to determine exactly what the code is doing because it in essence, has to ignore part of the information.

Just as 
(((x)*2)+1) = 13 
is harder to read than 
x*2+1 = 13 
so is

contact.Address1_AddressTypeCode = new OptionSetValue((int)contact_address1_addresstypecode.Home);

harder to read than

contact.Address1_AddressTypeCodeEnum = contact_address1_addresstypecode.Home;

25% of the text has been eliminated, which results in code that requires less typing, and is more readable.

Inconsistent Mapping of Attribute/Property Name to Enum Type
Determining the correct Enum for a given entity’s OptionSet property is usually pretty straight forward, but sometimes it’s not. i.e. The Enum for FieldPermission.CanCreate is field_security_permission_type and the Enum for Metric.AmountDataType is metric_goaltype.  The only intellisense that’s provided is that it’s an OptionSet, and it is up to the developer to find and choose the correct one.


The Entity OptionSet Enum Mapper Utility to the Rescue!
I have created an EntityOptionSetEnumMapper utility to generate a property for each OptionSetValue with the correct Enum.  For example, it generates these additional properties for the Contact class (CrmEntities is the namespace):

public partial class Contact
{
  public CrmEntities.contact_accountrolecode? AccountRoleCodeEnum { ... }
  public CrmEntities.contact_address1_addresstypecode? Address1_AddressTypeCodeEnum { ... }
  public CrmEntities.contact_address1_freighttermscode? Address1_FreightTermsCodeEnum { ... }
  public CrmEntities.contact_address1_shippingmethodcode? Address1_ShippingMethodCodeEnum { ... }
  public CrmEntities.contact_address2_addresstypecode? Address2_AddressTypeCodeEnum { ... }
  public CrmEntities.contact_address2_freighttermscode? Address2_FreightTermsCodeEnum { ... }
  public CrmEntities.contact_address2_shippingmethodcode? Address2_ShippingMethodCodeEnum { ... }
  public CrmEntities.contact_customersizecode? CustomerSizeCodeEnum { ... }
  public CrmEntities.contact_customertypecode? CustomerTypeCodeEnum { ... }
  public CrmEntities.contact_educationcode? EducationCodeEnum { ... }
  public CrmEntities.contact_familystatuscode? FamilyStatusCodeEnum { ... }
  public CrmEntities.contact_gendercode? GenderCodeEnum { ... }
  public CrmEntities.contact_haschildrencode? HasChildrenCodeEnum { ... }
  public CrmEntities.contact_leadsourcecode? LeadSourceCodeEnum { ... }
  public CrmEntities.contact_paymenttermscode? PaymentTermsCodeEnum { ... }
  public CrmEntities.contact_preferredappointmentdaycode? PreferredAppointmentDayCodeEnum { ... }
  public CrmEntities.contact_preferredappointmenttimecode? PreferredAppointmentTimeCodeEnum { ... }
  public CrmEntities.contact_preferredcontactmethodcode? PreferredContactMethodCodeEnum { ... }
  public CrmEntities.contact_shippingmethodcode? ShippingMethodCodeEnum { ... }
  public CrmEntities.contact_statuscode? StatusCodeEnum { ... }
  public CrmEntities.contact_territorycode? TerritoryCodeEnum { ... }
}

This is a partial class, and so will be combined at compile time with the existing Contact Class.  All of the existing OptionSetValue properties will still exist, but now there will be new ones (appended with “Enum”) that are typed to the correct Enum type.

Each property still uses the OptionSetValue property to store and retrieve the data, so when Address1_AddressTypeCodeEnum is updated, it will also update Address1_AddressTypeCode and visa versa, since they use the Entity.Attributes collection and share the same key.  Here is the Address1_AddressTypeCodeEnum property that is generated:

public CrmEntities.contact_address1_addresstypecode? Address1_AddressTypeCodeEnum
{
     get
     {
         return (CrmEntities.contact_address1_addresstypecode?)EntityOptionSetEnum.GetEnum(this, "address1_addresstypecode");
     }
     set
     {
         Address1_AddressTypeCode = value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value) : null;
     }
}

It makes use of an internal static class that is also in the output file, that retrieves the OptionSet from the Attributes collection as a nullable int:

internal static class EntityOptionSetEnum
{
    public static int? GetEnum(Microsoft.Xrm.Sdk.Entity entity, string attributeLogicalName)
    {
        if(entity.Attributes.ContainsKey(attributeLogicalName))
        {
            return entity.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>(attributeLogicalName).Value;
        }
        else
        {
            return null;
        }
    }
}

The nullable int is then cast to the correct enum type which is then returned. 

Using the Entity OptionSet Enum Mapper Executable
The only thing that the Entity OptionSet Enum Mapper requires is the dll that contains the early bound Entities and Enums created via the CrmSrvcUtil.  It requires no interaction with the CRM server itself.  This creates a standard “which came first, the chicken or the egg” problem.  The Entity and Enum dll must be built first before the utility can be ran, but it must run before the dll is built in order for the generated code to be included in the dll.  This is fixed by adding a pre-build event to the Entities and Enums dll project to build a temporary version of the dll, and then invoking the utility to run and generated the code.      

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe" /target:library /reference:"C:\PathOfSdk\microsoft.xrm.sdk.dll" "$(ProjectDir)Entities.cs" "$(ProjectDir)OptionSets.cs"

This basically says, compile the Entities and OptionSet files, referencing the Microsoft.Xrm.Sdk.  By default this will get compiled to the bin directory of the project, with the name Entities.dll.  A second pre-build event will be needed to call the utility and generate the EntityOptionSetEnum.cs file (which will need to be manually added to the project file the first time).

"C:\PathOfExe\EntityOptionSetEnumMapper.exe" "$(TargetDir)Entities.dll" "$(ProjectDir)EntityOptionSetEnums.cs"

This will run the utility, passing in the path to the Entities.dll to use to generate the EntityOptionSetEnum.cs file, and the path and name of the file to generate.

Both these steps happen before the dll itself get’s built, generating the EntityOptionSetEnum.cs file, which will then be compiled with the actual dll.


Below are separate downloads for the Executable, and the Source Code.  Enjoy!



Entity OptionSet Enum Mapper Executable
Entity OptionSet Enum Mapper Source

Wednesday, March 20, 2013

Make Websites Startup Faster When Debugging

Currently I’m working on an ASP.net website that caches data during the Application_Start event of the Global.asax.cs.  Generally this is a great idea for a website, especially when deploying a website in a load balanced environment, because the penalty of loading cached data can be spent in one page load.  Take the server out of the load balancer, deploy your changes, hit the first page, verify that no errors occurred, and put the server back in the balancer.  This ensures that a user hitting the site, won’t have to pay the penalty of loading the cache data.

But, this is not so much fun when developing/debugging.  90% of the time a developer works on a single page at a time, and if the page uses only a small fraction of the cache, or none at all, they get to pay the cache load penalty each time they restart the website.  Having to wait even 20 seconds each time the website is restarted in Visual Studio is real productivity killer.

Some developers may opt to comment out the cache loading portion of the Application_Start.  But if they accidently commit the change into source control, production could be affected the next time it’s deployed.  And the next time they get latest from source control, they’ll loose their local commented out Application_Start.   So how does one ensure that production will always cache the data on Application_Start, without forcing developers to pay the cache load penalty?

System.Diagnostics.Debugger.IsAttached to the Rescue!

protected void Application_Start(object sender, EventArgs e)
{
     if (System.Diagnostics.Debugger.IsAttached)
     {
         // Speed up the first page load for debugging by not loading all of the Cache
         return;
     }
     PreloadCachedValues();
}
Debugger.IsAttached will check to see if a debugger is currently attached.  Since this will always be the case when developing the website locally, and never be the case in production (assuming there isn’t some catastrophic production event), developers can enjoy the productivity improvements when developing the website, without risking any performance issues in production.

Friday, March 8, 2013

Simplifying Retrieval of Aliased Values in CRM 2011

Aliased values have always annoyed me when performing a QueryExpression, or FetchXML Query.  It requires a lot of boiler plate code each time you attempt to retrieve an aliased value (checking for it to exist, including the entity logical name, casting the aliased value’s value to the correct type, etc).  Due to being a lazy developer who believes if I do something twice, that’s once too many, I created some extension methods to simplify the process.  I’m posting them here today for the world to enjoy.
First the code:  There are 5 methods. 
  1. GetAliasedValue<T> – This is the main method.  It’s an extension method on Entity, so it can be used on any entity, early bound or late.  It accepts the an attributeName which is the name of the aliased attribute.  As long as you don’t have duplicate aliased names (i.e. linking/joining on two different entities, and returning the same attribute name from both),  you don’t have to preappend the the logical name of the entity of the aliased value.  It is also generic, so that it will cast the value of the aliased value to the generic type.
  2. SplitAliasedAttributeEntityName – This helper method splits the attribute name passed in, by a period to determine if an entity logical name has been passed in, or only an attribute name.
  3. IsAttributeAliasedValue – This method determines if a particular aliased value is the aliased value requested by the user
  4. GetAliasedValueOrDefault<T> – By default GetAliasedValue<> will throw an exception if the aliased value wasn’t found, along with a list of the attributes contained in the collection.  This checks to see if the aliased value exists, and gets the default value for the generic type if isn’t doesn’t exist.
  5. HasAliasedAttribute – Used by GetAliasedValueOrDefault<T>.  Also helpful if you want to do some other logic besides getting the default value if it isn’t found
         /// <summary>
         /// Returns the Aliased Value for a column specified in a Linked entity
         /// </summary>
         /// <typeparam name="T">The type of the aliased attribute form the linked entity</typeparam>
         /// <param name="entity"></param>
         /// <param name="attributeName">The aliased attribute from the linked entity.  Can be preappeneded with the
         /// linked entities logical name and a period. ie "Contact.LastName"</param>
         /// <returns></returns>
         public static T GetAliasedValue<T>(this Entity entity, string attributeName)
         {
             string aliasedEntityName = SplitAliasedAttributeEntityName(ref attributeName);
             AliasedValue aliased;
             foreach (var attribute in entity.Attributes.Values)
             {
                 aliased = attribute as AliasedValue;
                 if(entity.IsAttributeAliasedValue(attributeName, aliasedEntityName, aliased))
                 {
                     try
                     {
                         return (T)aliased.Value;
                     }
                     catch (InvalidCastException)
                     {
                         throw new InvalidCastException(
                             String.Format("Unable to cast attribute {0}.{1} from type {2} to type {3}",
                                     aliased.EntityLogicalName, aliased.AttributeLogicalName,
                                     typeof(T).Name, aliased.Value.GetType().Name));
                     }
                 }
             }
             throw new Exception("Aliased value with attribute " + attributeName +
                 " was not found!  Only these attributes were found: " + String.Join(", ", entity.Attributes.Keys));
         }


         /// <summary>
         /// Handles spliting the attributeName if it is formated as "EntityAliasedName.AttributeName",
         /// updating the attribute name and returning the aliased EntityName
         /// </summary>
         /// <param name="attributeName"></param>
         /// <param name="aliasedEntityName"></param>
         private static string SplitAliasedAttributeEntityName(ref string attributeName)
         {
             string aliasedEntityName = null;
             if (attributeName.Contains('.'))
             {
                 var split = attributeName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                 if (split.Length != 2)
                 {
                     throw new Exception("Attribute Name was specified for an Alaised Value with " + split.Length +
                     " split parts, and two were expected.  Attribute Name = " + attributeName);
                 }
                 aliasedEntityName = split[0];
                 attributeName = split[1];
             }
             return aliasedEntityName;
         }


        private static bool IsAttributeAliasedValue(this Entity entity, string attributeName, string aliasedEntityName, AliasedValue aliased)
         {
             bool value =
            (aliased != null &&
                 (aliasedEntityName == null || aliasedEntityName == aliased.EntityLogicalName) &&
                 aliased.AttributeLogicalName == attributeName);

             /// I believe there is a bug in CRM 2011 when dealing with aggregate values of a linked entity in FetchXML.
             /// Even though it is marked with an alias, the AliasedValue in the Attribute collection will use the 
             /// actual CRM name, rather than the aliased one, even though the AttributeCollection's key will correctly
             /// use the aliased name.  So if the aliased Attribute Logical Name doesn't match the assumed attribute name
             /// value, check to see if the entity contains an AliasedValue with that key whose attribute logical name 
             /// doesn't match the key (the assumed bug), and mark it as being the aliased attribute
             if (!value && aliased != null && entity.Contains(attributeName))
             {
                 var aliasedByKey = entity[attributeName] as AliasedValue;
                 if (aliasedByKey != null && aliasedByKey.AttributeLogicalName != attributeName &&
                      Object.ReferenceEquals(aliased, aliasedByKey))
                 {
                     value = true;
                 }
             }
             return value;
         }


         /// <summary>
         /// Returns the Aliased Value for a column specified in a Linked entity, returning the default value for 
         /// the type if it wasn't found
         /// </summary>
         /// <typeparam name="T">The type of the aliased attribute form the linked entity</typeparam>
         /// <param name="entity"></param>
         /// <param name="attributeName">The aliased attribute from the linked entity.  Can be preappeneded with the
         /// linked entities logical name and a period. ie "Contact.LastName"</param>
         /// <returns></returns>
         public static T GetAliasedValueOrDefault<T>(this Entity entity, string attributeName)
         {
             T value;
             if (entity.HasAliasedAttribute(attributeName))
             {
                 value = entity.GetAliasedValue<T>(attributeName);
             }
             else
             {
                 value = default(T);
             }
             return value;
         }


         /// <summary>
         /// Returns the Aliased Value for a column specified in a Linked entity
         /// </summary>
         /// <typeparam name="T">The type of the aliased attribute form the linked entity</typeparam>
         /// <param name="entity"></param>
         /// <param name="attributeName">The aliased attribute from the linked entity.  Can be preappeneded with the
         /// linked entities logical name and a period. ie "Contact.LastName"</param>
         /// <returns></returns>
         public static bool HasAliasedAttribute(this Entity entity, string attributeName)
         {
             string aliasedEntityName = SplitAliasedAttributeEntityName(ref attributeName);
             return entity.Attributes.Values.Any(a =>
                 entity.IsAttributeAliasedValue(attributeName, aliasedEntityName, a as AliasedValue));
         }


Just add these methods to an Extension class and ease the burden aliased values incur:


        public Guid GetBusinessUnit(IOrganizationService service, Guid buildingId)
        {
             var qe = new QueryExpression("new_building");
             qe.ColumnSet.AddColumns("new_buildingid", "new_name");
             qe.Criteria.AddCondition("new_buildingid", ConditionOperator.Equal, buildingId);
             var location = qe.AddLink("new_location", "new_locationid", "new_locationid");
             location.Columns.AddColumn("new businessunitid");
             return service.RetrieveMultiple(qe).Entities.FirstOrDefault().GetAliasedValue<EntityReference>("new_businessunitid").Id;
        }