Wednesday, July 27, 2011

Update Entity Metadata Using Jscript or .NET in Microsoft Dynamics CRM 2011 with UpdateEntityRequest

This illustration shows how to update an entities metadata in Microsoft Dynamics CRM 2011 in code with the UpdateEntityRequest.   This example will be given in Jscript (SOAP) and in C# (.NET).

Ok, here is what the code looks like!
First in C#:

//first retrieve entity metadata you want to update
RetrieveEntityRequest req = new RetrieveEntityRequest();
req.LogicalName = "account";
RetrieveEntityResponse resp = (RetrieveEntityResponse)slos.Execute(req);

EntityMetadata entity = resp.EntityMetadata;

//change properties
entity.Description = new Label("my test description", 1033);

//Now update the entity
UpdateEntityRequest updatereq = new UpdateEntityRequest();
updatereq.Entity = entity;

UpdateEntityResponse updateresp = (UpdateEntityResponse)slos.Execute(updatereq);

If you need help instantiating a service object in .NET within a plugin check out this post:
http://mileyja.blogspot.com/2011/04/instantiating-service-object-within.html

Now here is the Jscript nicely formatted by the CRM 2011 SOAP formatter. Available at: http://crm2011soap.codeplex.com/

Now in Jscript


This example is asynchronous, if you want to learn how to make JScript SOAP calls synchronously please visit this posthttp://mileyja.blogspot.com/2011/07/using-jscript-to-access-soap-web.html

if (typeof (SDK) == "undefined")
   { SDK = { __namespace: true }; }
       //This will establish a more unique namespace for functions in this library. This will reduce the 
       // potential for functions to be overwritten due to a duplicate name when the library is loaded.
       SDK.SAMPLES = {
           _getServerUrl: function () {
               ///<summary>
               /// Returns the URL for the SOAP endpoint using the context information available in the form
               /// or HTML Web resource.
               ///</summary>
               var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
               var serverUrl = "";
               if (typeof GetGlobalContext == "function") {
                   var context = GetGlobalContext();
                   serverUrl = context.getServerUrl();
               }
               else {
                   if (typeof Xrm.Page.context == "object") {
                         serverUrl = Xrm.Page.context.getServerUrl();
                   }
                   else
                   { throw new Error("Unable to access the server URL"); }
                   }
                  if (serverUrl.match(/\/$/)) {
                       serverUrl = serverUrl.substring(0, serverUrl.length - 1);
                   } 
                   return serverUrl + OrgServicePath;
               }, 
           UpdateEntityRequest: function () {
               var requestMain = ""
               requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
               requestMain += "  <s:Body>";
               requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
               requestMain += "      <request i:type=\"a:UpdateEntityRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
               requestMain += "        <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
               requestMain += "          <a:KeyValuePairOfstringanyType>";
               requestMain += "            <b:key>Entity</b:key>";
               requestMain += "            <b:value i:type=\"c:EntityMetadata\" xmlns:c=\"http://schemas.microsoft.com/xrm/2011/Metadata\">";
               requestMain += "              <c:MetadataId>70816501-edb9-4740-a16c-6a5efbc05d84</c:MetadataId>";
               requestMain += "              <c:ActivityTypeMask>1</c:ActivityTypeMask>";
               requestMain += "              <c:Attributes i:nil=\"true\" />";
               requestMain += "              <c:AutoRouteToOwnerQueue>false</c:AutoRouteToOwnerQueue>";
               requestMain += "              <c:CanBeInManyToMany>";
               requestMain += "                <a:CanBeChanged>false</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>canbeinmanytomany</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:CanBeInManyToMany>";
               requestMain += "              <c:CanBePrimaryEntityInRelationship>";
               requestMain += "                <a:CanBeChanged>false</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>canbeprimaryentityinrelationship</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:CanBePrimaryEntityInRelationship>";
               requestMain += "              <c:CanBeRelatedEntityInRelationship>";
               requestMain += "                <a:CanBeChanged>false</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>canberelatedentityinrelationship</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:CanBeRelatedEntityInRelationship>";
               requestMain += "              <c:CanCreateAttributes>";
               requestMain += "                <a:CanBeChanged>false</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>cancreateattributes</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:CanCreateAttributes>";
               requestMain += "              <c:CanCreateCharts>";
               requestMain += "                <a:CanBeChanged>false</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>cancreatecharts</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:CanCreateCharts>";
               requestMain += "              <c:CanCreateForms>";
               requestMain += "                <a:CanBeChanged>false</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>cancreateforms</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:CanCreateForms>";
               requestMain += "              <c:CanCreateViews>";
               requestMain += "                <a:CanBeChanged>false</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>cancreateviews</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:CanCreateViews>";
               requestMain += "              <c:CanModifyAdditionalSettings>";
               requestMain += "                <a:CanBeChanged>true</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>canmodifyadditionalsettings</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:CanModifyAdditionalSettings>";
               requestMain += "              <c:CanTriggerWorkflow>true</c:CanTriggerWorkflow>";
               requestMain += "              <c:Description>";
               requestMain += "                <a:LocalizedLabels>";
               requestMain += "                  <a:LocalizedLabel>";
               requestMain += "                    <a:IsManaged i:nil=\"true\" />";
               requestMain += "                    <a:Label>my test description</a:Label>";
               requestMain += "                    <a:LanguageCode>1033</a:LanguageCode>";
               requestMain += "                  </a:LocalizedLabel>";
               requestMain += "                </a:LocalizedLabels>";
               requestMain += "                <a:UserLocalizedLabel i:nil=\"true\" />";
               requestMain += "              </c:Description>";
               requestMain += "              <c:DisplayCollectionName>";
               requestMain += "                <a:LocalizedLabels>";
               requestMain += "                  <a:LocalizedLabel>";
               requestMain += "                    <a:IsManaged>true</a:IsManaged>";
               requestMain += "                    <a:Label>Accounts</a:Label>";
               requestMain += "                    <a:LanguageCode>1033</a:LanguageCode>";
               requestMain += "                  </a:LocalizedLabel>";
               requestMain += "                </a:LocalizedLabels>";
               requestMain += "                <a:UserLocalizedLabel>";
               requestMain += "                  <a:IsManaged>true</a:IsManaged>";
               requestMain += "                  <a:Label>Accounts</a:Label>";
               requestMain += "                  <a:LanguageCode>1033</a:LanguageCode>";
               requestMain += "                </a:UserLocalizedLabel>";
               requestMain += "              </c:DisplayCollectionName>";
               requestMain += "              <c:DisplayName>";
               requestMain += "                <a:LocalizedLabels>";
               requestMain += "                  <a:LocalizedLabel>";
               requestMain += "                    <a:IsManaged>true</a:IsManaged>";
               requestMain += "                    <a:Label>Account</a:Label>";
               requestMain += "                    <a:LanguageCode>1033</a:LanguageCode>";
               requestMain += "                  </a:LocalizedLabel>";
               requestMain += "                </a:LocalizedLabels>";
               requestMain += "                <a:UserLocalizedLabel>";
               requestMain += "                  <a:IsManaged>true</a:IsManaged>";
               requestMain += "                  <a:Label>Account</a:Label>";
               requestMain += "                  <a:LanguageCode>1033</a:LanguageCode>";
               requestMain += "                </a:UserLocalizedLabel>";
               requestMain += "              </c:DisplayName>";
               requestMain += "              <c:IconLargeName i:nil=\"true\" />";
               requestMain += "              <c:IconMediumName i:nil=\"true\" />";
               requestMain += "              <c:IconSmallName i:nil=\"true\" />";
               requestMain += "              <c:IsActivity>false</c:IsActivity>";
               requestMain += "              <c:IsActivityParty>true</c:IsActivityParty>";
               requestMain += "              <c:IsAuditEnabled>";
               requestMain += "                <a:CanBeChanged>true</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>canmodifyauditsettings</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>false</a:Value>";
               requestMain += "              </c:IsAuditEnabled>";
               requestMain += "              <c:IsAvailableOffline>true</c:IsAvailableOffline>";
               requestMain += "              <c:IsChildEntity>false</c:IsChildEntity>";
               requestMain += "              <c:IsConnectionsEnabled>";
               requestMain += "                <a:CanBeChanged>true</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>canmodifyconnectionsettings</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:IsConnectionsEnabled>";
               requestMain += "              <c:IsCustomEntity>false</c:IsCustomEntity>";
               requestMain += "              <c:IsCustomizable>";
               requestMain += "                <a:CanBeChanged>false</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>iscustomizable</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:IsCustomizable>";
               requestMain += "              <c:IsDocumentManagementEnabled>true</c:IsDocumentManagementEnabled>";
               requestMain += "              <c:IsDuplicateDetectionEnabled>";
               requestMain += "                <a:CanBeChanged>true</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>canmodifyduplicatedetectionsettings</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:IsDuplicateDetectionEnabled>";
               requestMain += "              <c:IsEnabledForCharts>true</c:IsEnabledForCharts>";
               requestMain += "              <c:IsImportable>true</c:IsImportable>";
               requestMain += "              <c:IsIntersect>false</c:IsIntersect>";
               requestMain += "              <c:IsMailMergeEnabled>";
               requestMain += "                <a:CanBeChanged>true</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>canmodifymailmergesettings</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:IsMailMergeEnabled>";
               requestMain += "              <c:IsManaged>true</c:IsManaged>";
               requestMain += "              <c:IsMappable>";
               requestMain += "                <a:CanBeChanged>false</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>ismappable</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:IsMappable>";
               requestMain += "              <c:IsReadingPaneEnabled>true</c:IsReadingPaneEnabled>";
               requestMain += "              <c:IsRenameable>";
               requestMain += "                <a:CanBeChanged>false</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>isrenameable</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:IsRenameable>";
               requestMain += "              <c:IsValidForAdvancedFind>true</c:IsValidForAdvancedFind>";
               requestMain += "              <c:IsValidForQueue>";
               requestMain += "                <a:CanBeChanged>true</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>canmodifyqueuesettings</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>false</a:Value>";
               requestMain += "              </c:IsValidForQueue>";
               requestMain += "              <c:IsVisibleInMobile>";
               requestMain += "                <a:CanBeChanged>true</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName>canmodifymobilevisibility</a:ManagedPropertyLogicalName>";
               requestMain += "                <a:Value>true</a:Value>";
               requestMain += "              </c:IsVisibleInMobile>";
               requestMain += "              <c:LogicalName>account</c:LogicalName>";
               requestMain += "              <c:ManyToManyRelationships i:nil=\"true\" />";
               requestMain += "              <c:ManyToOneRelationships i:nil=\"true\" />";
               requestMain += "              <c:ObjectTypeCode>1</c:ObjectTypeCode>";
               requestMain += "              <c:OneToManyRelationships i:nil=\"true\" />";
               requestMain += "              <c:OwnershipType>UserOwned</c:OwnershipType>";
               requestMain += "              <c:PrimaryIdAttribute>accountid</c:PrimaryIdAttribute>";
               requestMain += "              <c:PrimaryNameAttribute>name</c:PrimaryNameAttribute>";
               requestMain += "              <c:Privileges i:nil=\"true\" />";
               requestMain += "              <c:RecurrenceBaseEntityLogicalName i:nil=\"true\" />";
               requestMain += "              <c:ReportViewName>FilteredAccount</c:ReportViewName>";
               requestMain += "              <c:SchemaName>Account</c:SchemaName>";
               requestMain += "            </b:value>";
               requestMain += "          </a:KeyValuePairOfstringanyType>";
               requestMain += "          <a:KeyValuePairOfstringanyType>";
               requestMain += "            <b:key>MergeLabels</b:key>";
               requestMain += "            <b:value i:type=\"c:boolean\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">false</b:value>";
               requestMain += "          </a:KeyValuePairOfstringanyType>";
               requestMain += "        </a:Parameters>";
               requestMain += "        <a:RequestId i:nil=\"true\" />";
               requestMain += "        <a:RequestName>UpdateEntity</a:RequestName>";
               requestMain += "      </request>";
               requestMain += "    </Execute>";
               requestMain += "  </s:Body>";
               requestMain += "</s:Envelope>";
               var req = new XMLHttpRequest();
               req.open("POST", SDK.SAMPLES._getServerUrl(), true)
               // 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");
               var successCallback = null;
               var errorCallback = null;
               req.onreadystatechange = function () { SDK.SAMPLES.UpdateEntityResponse(req, successCallback, errorCallback); };
               req.send(requestMain);
           },
       UpdateEntityResponse: function (req, successCallback, errorCallback) {
               ///<summary>
               /// Recieves the assign response
               ///</summary>
               ///<param name="req" Type="XMLHttpRequest">
               /// The XMLHttpRequest response
               ///</param>
               ///<param name="successCallback" Type="Function">
               /// The function to perform when an successfult response is returned.
               /// For this message no data is returned so a success callback is not really necessary.
               ///</param>
               ///<param name="errorCallback" Type="Function">
               /// The function to perform when an error is returned.
               /// This function accepts a JScript error returned by the _getError function
               ///</param>
               if (req.readyState == 4) {
               if (req.status == 200) {
               if (successCallback != null)
               { successCallback(); }
               }
               else {
                   errorCallback(SDK.SAMPLES._getError(req.responseXML));
               }
           }
       },
       _getError: function (faultXml) {
           ///<summary>
           /// Parses the WCF fault returned in the event of an error.
           ///</summary>
           ///<param name="faultXml" Type="XML">
           /// The responseXML property of the XMLHttpRequest response.
           ///</param>
           var errorMessage = "Unknown Error (Unable to parse the fault)";
           if (typeof faultXml == "object") {
               try {
                   var bodyNode = faultXml.firstChild.firstChild;
                   //Retrieve the fault node
                   for (var i = 0; i < bodyNode.childNodes.length; i++) {
                       var node = bodyNode.childNodes[i];
                       //NOTE: This comparison does not handle the case where the XML namespace changes
                       if ("s:Fault" == node.nodeName) {
                       for (var j = 0; j < node.childNodes.length; j++) {
                           var faultStringNode = node.childNodes[j];
                           if ("faultstring" == faultStringNode.nodeName) {
                               errorMessage = faultStringNode.text;
                               break;
                           }
                       }
                       break;
                   }
               }
           }
           catch (e) { };
        }
        return new Error(errorMessage);
     },
 __namespace: true
};




To understand how to parse the response please review my post on using the DOM parser.
Now you can call the SDK.SAMPLES.UpdateEntityRequest function from your form jscript handler.
Thats all there is to it!

I hope this helps!

1 comment:

  1. Hi, I am new in CRM..
    I want to update some entity metadata..
    Can you please guide me how can i use above javascript to update entity metadata....

    My requirement is that there are some system entities like Task,Email,Campaign Activity etc. these are showing as Activity Type... I need to set "IsActivity=false" of these entities... :)

    ReplyDelete