The long long wait is over… Have you ever had a CRM installation that can be accessed using different URLs, e.g. one to be used inside a corporate network, and one to be used for external access?
Have you also written some javascript to make calls to the OData endpoint or to open a new entity form? Then you have realized that the context.getServerUrl method returns the URL that was assigned the server during the installation of CRM, and not the URL currently used to access CRM. Why is that a problem? Well, authenticating the user to one URL, and then having javascript making calls to the OData endpoint on another URL, will just give the user a “too bad, you are not authorized to do anything on this URL”. Now, at last, in Microsoft Dynamics CRM Software Development Kit version 5.0.13 the context.getClientUrl method is introduced, which returns the base URL currently used by the user to access the CRM application.
The getServerUrl method is still there, but deprecated and should not be used in the future. Documentation can be found here. Happy javascripting!
CRM 2011: Multiple Cascade Delete – part 2
In my previous post CRM 2011: Multiple Cascade Delete – part 1 I discussed the limitations in relationship behavior configuration for manual intersect entities, and proposed a solution with a plugin and a configuration entity.
In this post I will go into the details of the plugin and how it is registered.
I will not go into the basics of writing a plugin, there are tons of examples out there.
You need to be somewhat familiar with the event execution pipeline in Microsoft Dynamics CRM 2011 and the SDK classes used when developing plugins using late binding.
Objective
Consider the following entity model:

Role records should be deleted if either the associated contact or account is deleted, but only one of the relations can be configured with cascade delete. Responsibility records should be deleted if associated Role is deleted. The goal is to accomplish this through a generic plugin that is configured using a dedicated CRM entity.
Plugin overview
The plugin will contain three main blocks
- Configuration cache being loaded on demand and cleared whenever a Cascade Delete rule is being changed.
- Pre Validation step to retrieve all child records that should be deleted prior to the parent record being deleted.
- Pre Operation step to perform the deletion of retrieved child records.
The reason for separating block 2 and 3 is described in more detail in the previous post.
Continue reading “CRM 2011: Multiple Cascade Delete – part 2”CRM 2011: Multiple Cascade Delete – part 1
As I have recently mentioned, the possibilities of defining cascade deletes in Microsoft Dynamics CRM 2011 are quite limited. Only one parent entity can have the relationship behavior set to Cascade Delete. When you create a manual intersect entity to connect two or more other entities, this constraint is simply not acceptable for the end users.
Scenario
Consider this classic scenario: Instead of just associating contacts with a parent account, you want to be able to define a more dynamic model.
This could be accomplished using Connections and Connection Roles, but that too has a number of pros and cons, which I will not go into in this article. When creating the relations to the Role entity, only one of them (i.e. either the relation to Account, Contact or Function) can be defined with cascade delete. What you would like here is to specify Cascade for both Account and Contact, and Remove Link for Function.
When using a manual intersect entity as in this example, the Role object will loose all meaning if either the associated Contact or the associated Account is deleted, thus the Role should of course be deleted in both cases.
To solve this, I will create a plugin which can be configured to perform the cascade behavior where it is not possible to do it by customizations only.
Relationship Behavior
First a few notes about the different types of relationship behavior during delete. The Restrict behavior verifies if there are any existing associating records before stage 20 (Pre Operation). So this behavior cannot be used, as we want to perform our configured plugin delete within the triggering transaction to ensure proper rollback behavior. The Cascade behavior can only be defined for one relationship, which in this case will be to the Contact entity. The Remove Link behavior will leave the child records in CRM, which is possible as the relationship attribute will be nulled by CRM between stage 10 and 20. Using this behavior alone would leave Roles defining e.g. that “Jonas has function Consultant at company null” when deleting accounts.
Objective and Configuration
A plugin shall delete children of a parent record that is being deleted. To specify which relationships that shall invoke this function, I use a configuration entity in CRM.
It is also possible to pass the configuration as parameters to the plugin constructor, but then you have to enter the configuration in the step registrations, which is not very user friendly to the sysadmin. The operation shall be performed in stage 20 (Pre Operation) as it will then be within the transaction of the triggering delete, and the children will be deleted before the parent record is actually removed from the database. As the lookup attributes are nulled before stage 20 of the event execution pipeline, the plugin will retrieve a list of the children to delete in stage 10. This list is passed to the plugin triggered in stage 20 within the context’s SharedVariables. To improve performance, a cache of Cascade Delete configurations is maintained in the plugin class. If a configuration record is created, updated or deleted, the cache will be cleared.
In the next post I demonstrate and explain the code in the plugin, and also provide a complete solution for deploying multiple cascade delete in your Microsoft Dynamics CRM. Stay tuned!
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.
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.
CRM 2011 Quick Reference for Form Scripting
Big thumbs up to Jim Daly who composed this Form Scripting Quick Reference for Microsoft Dynamics CRM 2011. Very good, short, intuitive examples and really easy to find what you are looking for.
http://msdn.microsoft.com/en-us/library/jj602964.aspx
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.
In 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.
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
- 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.
- 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”).
- 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:
It 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:
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.
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.
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.
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
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.
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.
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.
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.
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);
}
}
}





