CRM Plugins: Retrieve children during Delete

Tip of the day!

If you want to write a plugin that needs to read children of a record being deleted – this must be done in the Pre Validation stage.

Why is that?

For 1:N relations with Delete Behavior: Remove Link, the lookup to the parent being deleted is set to null somewhere between stage 10 (Pre Validation) and 20 (Pre Operation), but inside the transaction of the primary record deletion. RemoveLink So if trying to retrieve the children in any stage after Pre Validation you will not get any results, as they all have a not-yet-committed update transaction where the relation is nulled.

Why on earth should I care?

You might agree with me that the constraints regarding cascade behavior on relationships do not quite fulfill the needs that are quite common when creating manual N:N relations. I will publish some tricks to generically cascade delete from several parents to a manual intersect entity in an article soon to come. Stay tuned! Unfamiliar with native / manual N:N relations? See Richard Knudson’s excellent article on this topic.

Automatically Set Regarding on New Activities

Summary

Missing functionality in the MS CRM 2011 OOB functionality:

  • Activities created from menu File – New Activity on entity forms do not get the Regarding field populated.
  • When creating new activities from the associated view on the entity form, the Regarding field is mapped properly.

FileNewActivityIn this post, I will demonstrate a javascript example of a generic way to populate the Regarding field on activities, where the OOB CRM functionality fails to do this.TaskWORegarding

Objective

Whenever possible, the activity form shall to try to find which record that should be set as regarding. While doing this, also provide an opportunity to specify which entities that shall be allowed as regarding for each type of activity entity.

Method

  1. As the activity form is not opened with any parameters indicating “where it came from”, I investigate window.parent.opener to find information of its origin.
  2. Metadata requests are used to find additional information of the source, to be able to map between ObjectTypeCode and LogicalName, as well as to dynamically find which attribute on the source that is the primary attribute (i.e. the “name” attribute”).
  3. I perform a REST request to find the name of the source record, instead of e.g. trying to walk through the source form’s DOM to find information about it.

Code samples

Function to verify and populate the Regarding field:

Cinteros.Xrm.Activity = {
      _verifyRegarding: function (regardingEntities) {
        try {
            // First check if we have a valid mapped regardingobject
            var regardingObjectId = Xrm.Page.getAttribute("regardingobjectid").getValue();
            if (regardingObjectId && regardingObjectId[0].entityType) {
                // We have a regarding object through mapping, verify it is from an allowed entity
                if (!regardingEntities || !regardingEntities.length) {
                    return true;
                }
                for (var i = 0; i < regardingEntities.length; i++) {
                    if (regardingObjectId[0].entityType === regardingEntities[i]) {
                        return true;
                    }
                }
                return false;
            }
            // No regarding object was set - now examine opener to see where we came from
            if (window && window.parent && window.parent.opener && window.parent.opener.location && window.parent.opener.location.href) {
                var href = window.parent.opener.location.href;
                // Extract parent etc from its href
                var parentEtc = Cinteros.Xrm.SDK.getParameter(href, "etc") || Cinteros.Xrm.SDK.getParameter(href, "oType");
                // Get metadata for parent entitytype
                var regardingEntityMeta;
                var entityMetadataCollection;
                if (!regardingEntities || !regardingEntities.length) {
                    // No allowed entities specified, load metadata for all entities
                    entityMetadataCollection = Cinteros.Xrm.SDK.RetrieveAllEntities();
                }
                else {
                    // Load metadata only for allowed entities
                    entityMetadataCollection = [];
                    for (var i = 0; i < regardingEntities.length; i++) {
                        entityMetadataCollection.push(Cinteros.Xrm.SDK.RetrieveEntity(regardingEntities[i]));
                    }
                }
                // Get the metadata for correct parent entity, based on etc/otc
                for (var i = 0; i < entityMetadataCollection.length; i++) {
                    if (entityMetadataCollection[i].ObjectTypeCode == parentEtc) {
                        regardingEntityMeta = entityMetadataCollection[i];
                        break;
                    }
                }
                if (regardingEntityMeta && regardingEntityMeta.ObjectTypeCode == parentEtc) {
                    // Extract parent id from its href
                    var parentId = Cinteros.Xrm.SDK.getParameter(href, "id") || Cinteros.Xrm.SDK.getParameter(href, "oId");
                    if (parentId) {
                        parentId = unescape(parentId);
                        var attributeMeta = Cinteros.Xrm.SDK.RetrieveAttribute(regardingEntityMeta.LogicalName, regardingEntityMeta.PrimaryNameAttribute);
                        // Retrieve the regarding entity, to be able to find its primary name
                        var regardingObject = Cinteros.Xrm.REST.Retrieve(regardingEntityMeta.SchemaName, parentId, "?$select=" + attributeMeta.SchemaName);
                        if (regardingObject) {
                            // Found regarding record, create lookup object
                            var regardingLkp = [{ "id": parentId, "entityType": regardingEntityMeta.LogicalName, "name": regardingObject[attributeMeta.SchemaName]}];
                            Xrm.Page.getAttribute("regardingobjectid").setValue(regardingLkp);
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        catch (e) {
            window.alert("Error in verifyRegarding:nn" + e.description);
        }
    }
}

Note: The javascript-functions in namespace Cinteros.Xrm are part of our internally developed tools, but the names should be quite self-explanatory.
REST functionality can be replaced by similar functionality in the CrmRestKit, see http://crmrestkit.codeplex.com/, or by other custom made code.
MetaData functionality can be replaced by functionality in the MS CRM SDK, see Sample: Retrieve Entity Metadata Using JScript.
Feel free to contact me if you have any questions.

Function to register for the formLoad event on each activity entity that shall have this functionality:

Cinteros.Xrm.Activity = {
    formLoad: function () {
        try {
            // Only do this when creating new activities
            if (Xrm.Page.ui.getFormType() === 1) {
                // For this example - four entities are allowed to be set as regarding
                var allowedEntities = ["contact", "lead", "opportunity", "jr_my_custom_entity"];
                if (this._verifyRegarding(allowedEntities) === false) {
                    window.alert("Activity must be created from a valid regarding record.n(" + allowedEntities.toString() + ")");
                    Xrm.Page.ui.close();
                }
            }
        }
        catch (e) {
            window.alert("Error during formLoad:nn" + e.description);
        }
    }
}

It is possible to call the _verifyRegarding function without any parameter, thus allowing any entity as regarding object. This will however read all entity metadata from the database, which typically takes a few seconds. So specifying the allowed set of regarding entity types is recommended.
Exclude the if-clause when calling the _verifyRegarding function to ignore it’s return value. Then the function will simply populate the regarding field when possible, without any verification that the field must be populated, or that it must be populated by a specific entity type.
Note that this solution uses window references and url parameters to interpret the caller. This is probably not supported according to MS CRM SDK, but it is not unsupported either, as it does not alter the DOM or use undocumented javascript methods, and it includes quite good error handling.

Xrm.Utility methods in MS Dynamics CRM UR8

  • Have you ever used the unsupported javascript-function openObj to open a form in Microsoft Dynamics CRM 2011?
  • Have you ever cursed out loud over getting correct paths and parameters for URL Addressable Forms?
  • Have you ever implemented your own functionality to open a Microsoft Dynamics CRM 2011 webresource in a new window?

Stop that. Now. At last, in UR8 Microsoft has included supported javascript-functions for those actions, providing a better user experience as well as nicer code than using the functionality of URL Addressable Forms and Views. No new SDK version has been released yet, so you cannot read about it or find any examples there, it was just recently announced in The Microsoft Dynamics CRM Blog.

Basic description

There is a javascript library called Xrm.Utility which is available “everywhere” as long as you have a CRM context.

Xrm.Utility.openEntityForm(name, id, parameters)
Xrm.Utility.openWebResource(webResourceName, webResourceData, width, height)

Both functions return the window object that is created which allows you to e.g. move and resize the window.
The parameters parameter can be used to set default values when creating a new record and to specify which form to display.
One of the best things though – is that the openEntityForm function takes the LogicalName of the entity instead of forcing us to make a metadata request to get the ObjectTypeCode…!

Usage examples

openEntityForm
  • Open a record from a custom html or Silverlight displaying CRM data
  • Open a new record form from a custom ribbon button populating with default data
  • Create a new record in javascript and then opening that new record
openWebResource
  • Open a webresource from a custom ribbon button (e.g. html page with Bing map integration)
  • Prompt user for confirmation using your own nicely styled Confirm dialog (instead of ugly styled window.confirm(…))

Thank’s Markus for enlightening me about this news!

Save & Publish Button for Forms and WebResources

While working with customizations and UI development in CRM 2011 – have you ever been looking for that “Save and Publish” button? Have you ever not been looking for it? We all wonder why it is not there and there is a case on Microsoft Connect requesting it.
But relax, it is quite easy to get it in there right now.

Annoying facts:

SaveAndPublish32It seems to me that someone just forgot to implement this function. There is a button icon /CRMWEB/_imgs/ribbon/SaveAndPublish32.png (and corresponding 16 pix icon). The javascript function being called when clicking the existing Publish button in form customization is called SaveAndPublish(). It just does not do what the name indicates.

Solution:

To get a Save & Publish button:

  • Create a javascript webresource that first calls the Save function and then the Publish function
  • Create the button in the RibbonDiffXml section of customizations.xml, using existing icon files and calling the function created in step 1
  • Import the ribbon customizations SnP
    Javascript:
    Cinteros.Xrm.Customization = {
        SaveAndPublishForm: function () {
            try {
                SaveForm(false);
            }
            catch (e) { }
            try {
                SaveAndPublish();
            }
            catch (e) { }
        },
        SaveAndPublishWebResource: function () {
            try {
                SaveForm(false);
            }
            catch (e) { }
            try {
                PublishWebResource();
            }
            catch (e) { }
        }
    }
    RibbonDiffXml:
      <RibbonDiffXml>
        <CustomActions>
          <CustomAction Id="Cint.Mscrm.FormEditorTab.SaveButtons.Controls" Location="Mscrm.FormEditorTab.SaveButtons.Controls._children" Sequence="1">
            <CommandUIDefinition>
              <Button Command="Cint.Mscrm.FormEditorTab.SaveButtons.Controls.Button.SaveAndPublish" CommandType="General" Id="Cint.Mscrm.FormEditorTab.SaveButtons.Controls.Button.SaveAndPublish.Id" Image16by16="/_imgs/ribbon/SaveAndPublish16.png" Image32by32="/_imgs/ribbon/SaveAndPublish32.png" TemplateAlias="o1" LabelText="$LocLabels:Cint.Mscrm.FormEditorTab.SaveAndPublish.LabelText" ToolTipTitle="$LocLabels:Cint.Mscrm.FormEditorTab.SaveAndPublish.ToolTip" ToolTipDescription="$LocLabels:Cint.Mscrm.FormEditorTab.SaveAndPublish.ToolTipDescription" />
            </CommandUIDefinition>
          </CustomAction>
          <CustomAction Id="Cint.Mscrm.WebResourceEditTab.Save.Controls" Location="Mscrm.WebResourceEditTab.Save.Controls._children" Sequence="1">
            <CommandUIDefinition>
              <Button Command="Cint.Mscrm.WebResourceEditTab.Save.Controls.Button.SaveAndPublish" CommandType="General" Id="Cint.Mscrm.WebResourceEditTab.Save.Controls.Button.SaveAndPublish.Id" Image16by16="/_imgs/ribbon/SaveAndPublish16.png" Image32by32="/_imgs/ribbon/SaveAndPublish32.png" TemplateAlias="o1" LabelText="$LocLabels:Cint.Mscrm.FormEditorTab.SaveAndPublish.LabelText" ToolTipTitle="$LocLabels:Cint.Mscrm.FormEditorTab.SaveAndPublish.ToolTip" ToolTipDescription="$LocLabels:Cint.Mscrm.FormEditorTab.SaveAndPublish.ToolTipDescription" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>
        <Templates>
          <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
        </Templates>
        <CommandDefinitions>
          <CommandDefinition Id="Cint.Mscrm.FormEditorTab.SaveButtons.Controls.Button.SaveAndPublish">
            <EnableRules>
              <EnableRule Id="Mscrm.Enable.IsCustomizableManagedPropertyRule" />
            </EnableRules>
            <DisplayRules />
            <Actions>
              <JavaScriptFunction FunctionName="Cinteros.Xrm.Customization.SaveAndPublish" Library="$webresource:cint_/scripts/utils_support.js" />
            </Actions>
          </CommandDefinition>
          <CommandDefinition Id="Cint.Mscrm.WebResourceEditTab.Save.Controls.Button.SaveAndPublish">
            <EnableRules>
              <EnableRule Id="Mscrm.Enable.IsWebResourceCustomizableRule" />
            </EnableRules>
            <DisplayRules />
            <Actions>
              <JavaScriptFunction FunctionName="Cinteros.Xrm.Customization.SaveAndPublishWebResource" Library="$webresource:cint_/scripts/utils_support.js" />
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>
        <RuleDefinitions>
          <TabDisplayRules />
          <DisplayRules />
          <EnableRules />
        </RuleDefinitions>
        <LocLabels>
          <LocLabel Id="Cint.Mscrm.FormEditorTab.SaveAndPublish.LabelText">
            <Titles>
              <Title languagecode="1033" description="Save and Publish" />
              <Title languagecode="1053" description="Spara och Publicera" />
            </Titles>
          </LocLabel>
          <LocLabel Id="Cint.Mscrm.FormEditorTab.SaveAndPublish.ToolTip">
            <Titles>
              <Title languagecode="1033" description="Save and Publish" />
              <Title languagecode="1053" description="Spara och Publicera" />
            </Titles>
          </LocLabel>
          <LocLabel Id="Cint.Mscrm.FormEditorTab.SaveAndPublish.ToolTipDescription">
            <Titles>
              <Title languagecode="1033" description="Saves and publishes the form" />
              <Title languagecode="1053" description="Sparar och publicerar formuläret" />
            </Titles>
          </LocLabel>
        </LocLabels>
      </RibbonDiffXml>
    

    Shortcut:

    If you don’t want to do this manually, you can download a solution with just this content HERE.

  • Execute Server-Side Code from Javascript

    Background:

    General business rules shall be implemented in server-side code to ensure its execution regardless of the origin of data changes; CRM UI, workflow, integration or any other application consuming the CRM web services. But on some occasions it would be handy to be able to execute this code from JavaScript to improve the user’s experience of the application.

    Scenario:

    When creating or updating an Account, there is a plugin registered Pre Validation Create/Update to verify that the given VAT number is in a correct format. If not, the plugin throws an exception instructing the user to enter a correct VAT number.

    VATincorrect

    Another plugin is registered Pre Operation Create/Update to look up city/state/county from given zip-code to ensure correct data for the account. This function consumes an external service from a third party accessible as a web service.

    Account Cinteros zip

    Challenge

    To improve user experience, the customer requires immediate verification of the VAT no and lookup of geographic information for the zip-code.

    Solution 1 (bad):

    Required functionality can of course be implemented entirely in JavaScript. Rules for VAT numbers and calls to external web services can be coded in client side code. Calling external services may be a problem, depending on firewall configuration, local browser settings etc. but usually it is possible to find a way around these problems. Composing and parsing SOAP-messages in javascript is neither intuitive nor fun, but of course it can be done. This solution however would duplicate the same code in two entirely different environments and languages. Duplicated code is, and I think everyone agrees to this, NOT something we want. Right?! Especially not from a maintenance perspective.

    Solution 2 (good:)

    Create a custom entity jr_serverfunction with one text field jr_parameter and one text field jr_result.

    ServerFunction blank

    Server-side

    • Extract logic from the two plugins mentioned to methods in an isolated C# class
    • Rewrite the plugins to consume this class (to preserve existing functionality invoked on create/update)
    • Create a plugin triggering Post Operation RetrieveMultiple on jr_serverfunction. This plugin shall investigate the incoming query to extract it’s condition for field jr_parameter and use this condition to execute desired server-side code
    • When the result of the function is determined, an instance of entity jr_serverfunction is created (in code, not saved to the database), resulting data/information placed in field jr_result, and the entity placed in the EntityCollection that is to be returned in the query response

    ServerFunction registration Note that the custom entity will actually never hold any records in the CRM database. This is why I also trigger the Create message and immediately throw an error. ServerFunction assembly Plugin code:

    public class ServerSideExecution : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            if (context.MessageName == "Create")
                throw new InvalidPluginExecutionException("Server Function entity cannot be instantiated");
    
            if (context.MessageName == "RetrieveMultiple" &&
                context.Stage == 40 &&      // Post Operation
                context.PrimaryEntityName == "jr_serverfunction" &&
                context.InputParameters.Contains("Query") &&
                context.InputParameters["Query"] is QueryExpression)
            {
                ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                tracer.Trace("Initialize service etc");
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                QueryExpression query = (QueryExpression)context.InputParameters["Query"];
                tracer.Trace("Extract condition from query");
                ConditionExpression parameterCondition = MyFunctions.GetFilterConditionByAttribute(query.Criteria, "jr_parameter");
                if (parameterCondition != null && parameterCondition.Values.Count == 1)
                {
                    string parameter = parameterCondition.Values[0].ToString().Trim('%');
                    tracer.Trace("Parameter is: {0}", parameter);
                    string command = parameter.Split(';')[0];
                    string result = null;
                    switch (command)
                    {
                        case "VerifyVAT":
                            tracer.Trace("Check if VAT number is correct");
                            string vat = parameter.Split(';')[1];
                            if (MyFunctions.VerifyVAT(vat))
                                result = "ok";
                            else
                                result = "not ok";
                            break;
                        case "LookupZIP":
                            tracer.Trace("Lookup city etc from ZIP code");
                            string zip = parameter.Split(';')[1];
                            // Returns a semi-colon separated string with city;state;country
                            result = MyFunctions.GetZipInfo(zip);
                            break;
                        // **************************************
                        // ** Add more functions here as needed
                        // **************************************
                    }
                    if (result != null)
                    {
                        tracer.Trace("Create resulting serverfunction entity with result: {0}", result);
                        Entity serverfunction = new Entity("jr_serverfunction");
                        Guid id = new Guid();
                        serverfunction.Id = id;
                        serverfunction.Attributes.Add("jr_serverfunctionid", id);
                        serverfunction.Attributes.Add("jr_parameter", parameter);
                        serverfunction.Attributes.Add("jr_result", result);
                        tracer.Trace("Replace contents of resulting entitycollection");
                        EntityCollection resultCollection = (EntityCollection)context.OutputParameters["BusinessEntityCollection"];
                        resultCollection.Entities.Clear();
                        resultCollection.Entities.Add(serverfunction);
                        context.OutputParameters["BusinessEntityCollection"] = resultCollection;
                    }
                }
            }
        }
    }

    Note: The function MyFunctions.GetFilterConditionByAttribute is part of internally developed tools. Please contact me if you are interested in how we find specific conditions in a query.
    The plugin can easily be tested by making an Advanced Find query on the Server Function entity in the CRM.
    TestVAT TestZIP

    Client-side

    In the client-side JavaScript a method is registered for the onChange event of the VAT no field. The function will use the REST endpoint to query CRM for records of jr_serverfunction where jr_parameter equals “VerifyVAT;1234567890” (where the numbers should be the number entered on the form).
    The result will contain one record, and the jr_result field will contain “ok” or “not ok”, which the JavaScript can use to immediately instruct the user to correct the number.

    Cinteros.Xrm.AccountServerFunction = {
        jr_vat_onChange: function () {
            try {
                var vatNo = Xrm.Page.getAttribute("jr_vat").getValue();
                if (vatNo != null) {
                    var parameter = "VerifyVAT;" + vatNo;
                    var result = this.ExecuteServerFunction(parameter);
                    if (result === "not ok") {
                        window.alert("VAT number is not in a correct format");
                    }
                }
            }
            catch (e) {
                alert("Error in jr_vat_onChange:nn" + e.description);
            }
        },
    
        ExecuteServerFunction: function (parameter) {
            var result = null;
            var serverFunctionResult = Cinteros.Xrm.REST.RetrieveMultiple("jr_serverfunction",
                    "?$select=jr_result" +
                    "&$filter=jr_parameter eq '" + parameter + "'");
    
            if (serverFunctionResult && serverFunctionResult.length === 1) {
                result = serverFunctionResult[0].jr_result;
            }
            return result;
        }
    }

    Note: The javascript-function Cinteros.Xrm.REST.RetrieveMultiple is part of our internally developed tools, it may well be replaced by similar functionality in the CrmRestKit (http://crmrestkit.codeplex.com/) or by other custom made code.
    Registering this function as the onchange event of the VAT number field immediately executes the server-side functionality for validating a VAT number when the user changes the field in the CRM client.

    VATeventhandler VATincorrectJS

    Corresponding onChange event for the zip-code field can be implemented to get geographic information and automatically populate city/state etc. on the form.

    address1_postalcode_onChange: function () {
        try {
            var zipCode = Xrm.Page.getAttribute("address1_postalcode").getValue();
            if (zipCode != null) {
                var parameter = "LookupZIP;" + zipCode;
                var result = this.ExecuteServerFunction(parameter);
                if (result) {
                    var city = result.split(';')[0];
                    var state = result.split(';')[1];
                    var country = result.split(';')[2];
                    Xrm.Page.getAttribute("address1_city").setValue(city);
                    Xrm.Page.getAttribute("address1_stateorprovince").setValue(state);
                    Xrm.Page.getAttribute("address1_country").setValue(country);
                } 
            }
        }
        catch (e) {
            alert("Error in address1_postalcode_onChange:nn" + e.description);
        }
    }
    

    Adding Duplicates in N:N-Relations

    The possibility to use many-to-many relations in Microsoft Dynamics CRM 2011 is very handy for various scenarios.

    However, it’s implementation is not very forgiving when you try to add a relation which already exists.
     
    There is no way to configure the relationship or functionality of the “Add existing…” ribbon button to prevent this “ugly” message – so I decided to create a plugin which smooths things out, so that adding a relation which already exists only makes sure the relationship is there, but does not complain if it already was.
     
    Scenario
    We have a N:N-relation between Account and Product, to indicate which products are interesting to which accounts.
     
    Clicking the Add Existing Product button brings up the lookup dialog for products.
    When I now want to add a number of products, I do not want to have recall or check which products were already added. I just want to select all products (we can really sell anything to this company 😉 click OK and be done with it.
     
    Solution
    We can create a plugin before main operation that verifies if the added relation already exists. But if it exists, we cannot prevent the relation from being created in any other way than throwing an exception, which will then result in a similar “ugly” message to the user, except it will contain the text we throw.

    So we have to get around the implementation in the main operation (CRM core) some other way.
    My choice was to simply delete the existing relation, so adding the new one will not be a problem.
    Naturally, this causes extra transactions, but in normal circumstances this will not have any greater impact.
     
     
    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Metadata;
    using Microsoft.Xrm.Sdk.Query;
    
    namespace Cinteros.Xrm
    {
        public class AssociateAllower : IPlugin
        {
            public void Execute(IServiceProvider serviceProvider)
            {
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    
                if (context.MessageName == "Associate" &&
                    context.Stage == 20 &&      // Before, inside transaction
                    context.Mode == 0 &&        // Synchronous
                    context.InputParameters.Contains("Target") &&
                    context.InputParameters["Target"] is EntityReference &&
                    context.InputParameters.Contains("Relationship") &&
                    context.InputParameters["Relationship"] is Relationship &&
                    context.InputParameters.Contains("RelatedEntities") &&
                    context.InputParameters["RelatedEntities"] is EntityReferenceCollection)
                {
                    try
                    {
                        ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    
                        Trace(tracer, "Get the name of the intersect table and related entities from the context");
                        Relationship relationship = ((Relationship)context.InputParameters["Relationship"]);
                        Trace(tracer, "Intersect: {0}", relationship);
                        EntityReference entity1ref = (EntityReference)context.InputParameters["Target"];
                        Trace(tracer, "Entity1: {0} {1}", entity1ref.LogicalName, entity1ref.Id);
                        EntityReferenceCollection entity2refs = (EntityReferenceCollection)context.InputParameters["RelatedEntities"];
                        Trace(tracer, "Entity2 count: {0}", entity2refs.Count);
    
                        Trace(tracer, "Get metadata for intersect relation: {0}", relationship);
                        RetrieveRelationshipResponse relationshipmetadata = (RetrieveRelationshipResponse)service.Execute(new RetrieveRelationshipRequest() { Name = relationship.SchemaName });
                        if (relationshipmetadata != null && relationshipmetadata.RelationshipMetadata is ManyToManyRelationshipMetadata)
                        {
                            ManyToManyRelationshipMetadata mmrel = (ManyToManyRelationshipMetadata)relationshipmetadata.RelationshipMetadata;
                            Trace(tracer, "Get intersect attribute names (we cannot know which entity is entity1 and which is entity2)");
                            string entity1idattribute = mmrel.Entity1LogicalName == entity1ref.LogicalName ? mmrel.Entity1IntersectAttribute : mmrel.Entity2IntersectAttribute;
                            string entity2idattribute = mmrel.Entity1LogicalName == entity1ref.LogicalName ? mmrel.Entity2IntersectAttribute : mmrel.Entity1IntersectAttribute;
                            Trace(tracer, "Entiy1id: {0} Entity2id: {1}", entity1idattribute, entity2idattribute);
    
                            Trace(tracer, "Verify if any of the new relations already exist");
                            foreach (EntityReference entity2ref in entity2refs)
                            {
                                QueryByAttribute qba = new QueryByAttribute(relationship.SchemaName);
                                qba.AddAttributeValue(entity1idattribute, entity1ref.Id);
                                qba.AddAttributeValue(entity2idattribute, entity2ref.Id);
                                EntityCollection existingAssociations = service.RetrieveMultiple(qba);
                                Trace(tracer, "Found {0} existing relations", existingAssociations.Entities.Count);
                                if (existingAssociations.Entities.Count > 0)
                                {
                                    EntityReferenceCollection deleteRefs = new EntityReferenceCollection();
                                    deleteRefs.Add(entity2ref);
                                    Trace(tracer, "Disassociating entities");
                                    service.Execute(new DisassociateRequest()
                                    {
                                        Target = entity1ref,
                                        RelatedEntities = deleteRefs,
                                        Relationship = relationship
                                    });
                                    Trace(tracer, "Disassociated");
                                }
                            }
                        }
                        else
                        {
                            throw new InvalidPluginExecutionException("Metadata for relation " + relationship + " is not of type ManyToManyRelationshipMetadata");
                        }
                        Trace(tracer, "Done!");
                    }
                    catch (FaultException<OrganizationServiceFault> ex)
                    {
                        throw new InvalidPluginExecutionException(
                            String.Format("An error occurred in plug-in {0}. {1}: {2}", this, ex, ex.Detail.Message));
                    }
                }
            }
    
            private void Trace(ITracingService tracer, string format, params object[] args)
            {
                tracer.Trace(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + format, args);
            }
        }
    }
    
    

    The Welcome Post

    There must be a Welcome Post.
    So this is it.

    Welcome to my blog about development on the Microsoft Dynamics CRM platform!

    The blog will focus on plugin development in C# and UI development in javascript, but in the words of mama Gump – Ya never know what’ya gonna get.