Business flows not switching by Workflow/Plugin

The problem is when you want to have a Business Process Flow (BPF) that changes automatically when a user changes a field, but that process flow is only changing to that user and not to the others.

For example:

When user1 changes the field, he can see the BPF changing after the reload of the form. When user2 looks at the same record, he can’t see the BPF changed.

This happens because the BPF’s in Dynamics 365  allows multiple processes to run concurrently against the same record and the process that is running for a user might not be the same to the other user.

To have a workaround that works, it is necessary to implement a JScript OnLoad calling that will set the active process in the record to the one that the user wants, for that it can be used Xrm.Page.data.process.setActiveProcess/setActiveProcessInstance.

If you want to know more about the new BPF and how it works, take a look at this post.

Hope this helps.

Advertisements

Debugging Javascript with Dev Tools

When we are developing in Javascript, sometimes we need to debug the code when we found an error. You can easily do debug with the Dev Tools of the browser.
If you press F12 on your browser you have access to a window like shown below and move to the debugger tab and your code you have a debugger; condition in your code, when you execute the action you will get the debug active and you can start moving on your code to see where the problem is.

debugging-javascript-with-dev-tools

You can also search for the web resource file name and make a breakpoint on the DevTools instead if you don’t want to have the debugger; written in your code.

crm-diagnostics1

Hope this helps

Duplicate Record

Have you ever had a client that needed a functionality like this and the Dynamics CRM still doesn’t do it?

You can accomplish this with a simple code that you can put in a button in the ribbon.

You can accomplish this with a ASP.NET (if you are On-premise) page or a HTML web resource (Online). For this example I’m using the ASP.NET.

protected void Page_Load(object sender, EventArgs e)
{
	try
	{
		CopyEntity copy = new CopyEntity();
		string newEntityID = copy.CopyEntity(base.Request.QueryString["Id"].ToString(), base.Request.QueryString["user"].ToString());
		string str = ConfigurationManager.AppSettings["Server"].ToString() + @"/" + base.Request.QueryString["org"].ToString() + "/main.aspx?etc=" + ConfigurationManager.AppSettings["EntityType"].ToString() + "&id=%7b" + newEntityID + "%7d&newWindow=true&pagetype=entityrecord";
		base.Response.Write("window.location.replace('" + str + "')");
	}
	catch (Exception ex)
	{
		throw new Exception(ex.Message);
	}
}

When you do copy.CopyEntity, you have a class that you implement the logic to copy the record (query the selected record to get the data of the fields and create a new one) that is selected in the Homepagegrid or Form.

You can have this in a button, that invokes a Javascript that will call this page for example.

function callCopyEntity() {
	var userid = Xrm.Page.context.getUserId();
	var guid = Xrm.Page.data.entity.getId();
	var url = "connection";
	var address = url + guid + '&user=' + userid;
	window.open(address, 'DuplicateEntity', 'menubar=no,resizable=yes,toolbar=yes,location=yes');
}

This is an easy implementation that will allow the user to copy the records easily, which would have to create manually, having to change only the information that finds necessary.

Hope this helps.

Hide +New button in the Customer field

The other day it was necessary to hide the “+new” button that exists in the Customer field in the Opportunity/Quote, because that button when clicked opens the windows for a new Contact.

I tried to use some javascript code to change the option, instead of, open the Contact, opens the Account, but didn’t work.

So this is a way that can be used to hide that button:

document.getElementById("customerid_i").attributes[19].value = "account:true,contact:false";

Changing the “contact:true” to “contact:false”, does the work.

Hope this helps.

Create Entity with Javascript

If you need to create an Entity using Javascript, here is a way to do it:

if (typeof (SDK) == "undefined")
   { SDK = { __namespace: true }; }

       SDK.SAMPLES = {
           _getServerUrl: function () {

               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;
               }, 
           CreateEntityRequest: 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:CreateEntityRequest\" 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 i:nil=\"true\" />";
               requestMain += "              <c:ActivityTypeMask i:nil=\"true\" />";
               requestMain += "              <c:Attributes i:nil=\"true\" />";
               requestMain += "              <c:AutoRouteToOwnerQueue i:nil=\"true\" />";
               requestMain += "              <c:CanBeInManyToMany i:nil=\"true\" />";
               requestMain += "              <c:CanBePrimaryEntityInRelationship i:nil=\"true\" />";
               requestMain += "              <c:CanBeRelatedEntityInRelationship i:nil=\"true\" />";
               requestMain += "              <c:CanCreateAttributes i:nil=\"true\" />";
               requestMain += "              <c:CanCreateCharts i:nil=\"true\" />";
               requestMain += "              <c:CanCreateForms i:nil=\"true\" />";
               requestMain += "              <c:CanCreateViews i:nil=\"true\" />";
               requestMain += "              <c:CanModifyAdditionalSettings i:nil=\"true\" />";
               requestMain += "              <c:CanTriggerWorkflow i:nil=\"true\" />";
               requestMain += "              <c:Description>";
               requestMain += "                <a:LocalizedLabels>";
               requestMain += "                  <a:LocalizedLabel>";
               requestMain += "                    <a:IsManaged i:nil=\"true\" />";
               requestMain += "                    <a:Label>An entity to store information about custom robots</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 i:nil=\"true\" />";
               requestMain += "                    <a:Label>Custom Robots3</a:Label>";
               requestMain += "                    <a:LanguageCode>1033</a:LanguageCode>";
               requestMain += "                  </a:LocalizedLabel>";
               requestMain += "                </a:LocalizedLabels>";
               requestMain += "                <a:UserLocalizedLabel i:nil=\"true\" />";
               requestMain += "              </c:DisplayCollectionName>";
               requestMain += "              <c:DisplayName>";
               requestMain += "                <a:LocalizedLabels>";
               requestMain += "                  <a:LocalizedLabel>";
               requestMain += "                    <a:IsManaged i:nil=\"true\" />";
               requestMain += "                    <a:Label>Custom Robot3 </a:Label>";
               requestMain += "                    <a:LanguageCode>1033</a:LanguageCode>";
               requestMain += "                  </a:LocalizedLabel>";
               requestMain += "                </a:LocalizedLabels>";
               requestMain += "                <a:UserLocalizedLabel i:nil=\"true\" />";
               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 i:nil=\"true\" />";
               requestMain += "              <c:IsAuditEnabled i:nil=\"true\" />";
               requestMain += "              <c:IsAvailableOffline i:nil=\"true\" />";
               requestMain += "              <c:IsChildEntity i:nil=\"true\" />";
               requestMain += "              <c:IsConnectionsEnabled i:nil=\"true\" />";
               requestMain += "              <c:IsCustomEntity i:nil=\"true\" />";
               requestMain += "              <c:IsCustomizable i:nil=\"true\" />";
               requestMain += "              <c:IsDocumentManagementEnabled i:nil=\"true\" />";
               requestMain += "              <c:IsDuplicateDetectionEnabled i:nil=\"true\" />";
               requestMain += "              <c:IsEnabledForCharts i:nil=\"true\" />";
               requestMain += "              <c:IsImportable i:nil=\"true\" />";
               requestMain += "              <c:IsIntersect i:nil=\"true\" />";
               requestMain += "              <c:IsMailMergeEnabled i:nil=\"true\" />";
               requestMain += "              <c:IsManaged i:nil=\"true\" />";
               requestMain += "              <c:IsMappable i:nil=\"true\" />";
               requestMain += "              <c:IsReadingPaneEnabled i:nil=\"true\" />";
               requestMain += "              <c:IsRenameable i:nil=\"true\" />";
               requestMain += "              <c:IsValidForAdvancedFind i:nil=\"true\" />";
               requestMain += "              <c:IsValidForQueue i:nil=\"true\" />";
               requestMain += "              <c:IsVisibleInMobile i:nil=\"true\" />";
               requestMain += "              <c:LogicalName i:nil=\"true\" />";
               requestMain += "              <c:ManyToManyRelationships i:nil=\"true\" />";
               requestMain += "              <c:ManyToOneRelationships i:nil=\"true\" />";
               requestMain += "              <c:ObjectTypeCode i:nil=\"true\" />";
               requestMain += "              <c:OneToManyRelationships i:nil=\"true\" />";
               requestMain += "              <c:OwnershipType>UserOwned</c:OwnershipType>";
               requestMain += "              <c:PrimaryIdAttribute i:nil=\"true\" />";
               requestMain += "              <c:PrimaryNameAttribute i:nil=\"true\" />";
               requestMain += "              <c:Privileges i:nil=\"true\" />";
               requestMain += "              <c:RecurrenceBaseEntityLogicalName i:nil=\"true\" />";
               requestMain += "              <c:ReportViewName i:nil=\"true\" />";
               requestMain += "              <c:SchemaName>new_customrobot3</c:SchemaName>";
               requestMain += "            </b:value>";
               requestMain += "          </a:KeyValuePairOfstringanyType>";
               requestMain += "          <a:KeyValuePairOfstringanyType>";
               requestMain += "            <b:key>HasActivities</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:KeyValuePairOfstringanyType>";
               requestMain += "            <b:key>HasNotes</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:KeyValuePairOfstringanyType>";
               requestMain += "            <b:key>PrimaryAttribute</b:key>";
               requestMain += "            <b:value i:type=\"c:StringAttributeMetadata\" xmlns:c=\"http://schemas.microsoft.com/xrm/2011/Metadata\">";
               requestMain += "              <c:MetadataId i:nil=\"true\" />";
               requestMain += "              <c:AttributeOf i:nil=\"true\" />";
               requestMain += "              <c:AttributeType>String</c:AttributeType>";
               requestMain += "              <c:CanBeSecuredForCreate i:nil=\"true\" />";
               requestMain += "              <c:CanBeSecuredForRead i:nil=\"true\" />";
               requestMain += "              <c:CanBeSecuredForUpdate i:nil=\"true\" />";
               requestMain += "              <c:CanModifyAdditionalSettings i:nil=\"true\" />";
               requestMain += "              <c:ColumnNumber i:nil=\"true\" />";
               requestMain += "              <c:DeprecatedVersion i:nil=\"true\" />";
               requestMain += "              <c:Description>";
               requestMain += "                <a:LocalizedLabels>";
               requestMain += "                  <a:LocalizedLabel>";
               requestMain += "                    <a:IsManaged i:nil=\"true\" />";
               requestMain += "                    <a:Label>The primary attribute for the custom robot entity.</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:DisplayName>";
               requestMain += "                <a:LocalizedLabels>";
               requestMain += "                  <a:LocalizedLabel>";
               requestMain += "                    <a:IsManaged i:nil=\"true\" />";
               requestMain += "                    <a:Label>Robot Name</a:Label>";
               requestMain += "                    <a:LanguageCode>1033</a:LanguageCode>";
               requestMain += "                  </a:LocalizedLabel>";
               requestMain += "                </a:LocalizedLabels>";
               requestMain += "                <a:UserLocalizedLabel i:nil=\"true\" />";
               requestMain += "              </c:DisplayName>";
               requestMain += "              <c:EntityLogicalName i:nil=\"true\" />";
               requestMain += "              <c:IsAuditEnabled i:nil=\"true\" />";
               requestMain += "              <c:IsCustomAttribute i:nil=\"true\" />";
               requestMain += "              <c:IsCustomizable i:nil=\"true\" />";
               requestMain += "              <c:IsManaged i:nil=\"true\" />";
               requestMain += "              <c:IsPrimaryId i:nil=\"true\" />";
               requestMain += "              <c:IsPrimaryName i:nil=\"true\" />";
               requestMain += "              <c:IsRenameable i:nil=\"true\" />";
               requestMain += "              <c:IsSecured i:nil=\"true\" />";
               requestMain += "              <c:IsValidForAdvancedFind i:nil=\"true\" />";
               requestMain += "              <c:IsValidForCreate i:nil=\"true\" />";
               requestMain += "              <c:IsValidForRead i:nil=\"true\" />";
               requestMain += "              <c:IsValidForUpdate i:nil=\"true\" />";
               requestMain += "              <c:LinkedAttributeId i:nil=\"true\" />";
               requestMain += "              <c:LogicalName i:nil=\"true\" />";
               requestMain += "              <c:RequiredLevel>";
               requestMain += "                <a:CanBeChanged>true</a:CanBeChanged>";
               requestMain += "                <a:ManagedPropertyLogicalName i:nil=\"true\" />";
               requestMain += "                <a:Value>None</a:Value>";
               requestMain += "              </c:RequiredLevel>";
               requestMain += "              <c:SchemaName>new_robotname</c:SchemaName>";
               requestMain += "              <c:Format>Text</c:Format>";
               requestMain += "              <c:ImeMode i:nil=\"true\" />";
               requestMain += "              <c:MaxLength>100</c:MaxLength>";
               requestMain += "              <c:YomiOf i:nil=\"true\" />";
               requestMain += "            </b:value>";
               requestMain += "          </a:KeyValuePairOfstringanyType>";
               requestMain += "        </a:Parameters>";
               requestMain += "        <a:RequestId i:nil=\"true\" />";
               requestMain += "        <a:RequestName>CreateEntity</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.CreateEntityResponse(req, successCallback, errorCallback); };
               req.send(requestMain);
           },
       CreateEntityResponse: function (req, successCallback, errorCallback) {
               
               if (req.readyState == 4) {
               if (req.status == 200) {
               if (successCallback != null)
               { successCallback(); }
               }
               else {
                   errorCallback(SDK.SAMPLES._getError(req.responseXML));
               }
           }
       },
       _getError: function (faultXml) {
           
           var errorMessage = "Unknown Error (Unable to parse the fault)";
           if (typeof faultXml == "object") {
               try {
                   var bodyNode = faultXml.firstChild.firstChild;

                   for (var i = 0; i < bodyNode.childNodes.length; i++) {
                       var node = bodyNode.childNodes[i];

                       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
};

XrmServiceToolKit – Associate, Disassociate, Fetch, etc

Well, sometimes we need to do some code in Javascript instead of Plugins C#.

So here is a way to Associate a relationship, in my case it was a N:N between quote and opportunity.

First of all I will search if the relation already exists and after I’ll create the relation (if doesn’t exists).

Associate:

var fetch =
“<fetch mapping=’logical’>” +
“<entity name=’RelationshipName’>” +
“<all-attributes />” +
“<filter>” +
“<condition attribute=’opportunityid’ operator=’eq’ value='” + opportunityId + “‘ />” +
“<condition attribute=’quoteid’ operator=’eq’ value='” + quoteId + “‘ />” +
“</filter>” +
“</entity>” +
“</fetch>”;

var retrieve = XrmServiceToolkit.Soap.Fetch(fetch);
if (retrieve.length == 0)
{
var quote = new XrmServiceToolkit.Soap.BusinessEntity(“quote”, quoteId);
var relatedQuotes = new Array();
relatedQuotes[0] = quote;
var response = XrmServiceToolkit.Soap.Associate(“RelationshipName”, “opportunity”, opportunityId, “quote”, relatedQuotes);
}

The same logic can be applied for the Disassociate, search for the record first to see if exists, and if exists (retrieve.length > 0) disassoaciate it.

Disassociate:

var account = new XrmServiceToolkit.Soap.BusinessEntity(“account”, accountId);
var relatedAccounts = new Array();
relatedAccounts[0] = account;
var response = XrmServiceToolkit.Soap.Disassociate(“RelationshipName”, “contact”, contactId, “account”, relatedAccounts);

Fetch:

var fetch =
“<fetch mapping=’logical’>” +
“<entity name=’contact’>” +
“<all-attributes />” +
“<filter>” +
“<condition attribute=’contactid’ operator=’eq’ value='” + contactId + “‘ />” +
“</filter>” +
“</entity>” +
“</fetch>”;

var retrieve = XrmServiceToolkit.Soap.Fetch(fetch);

if(retrieve.length > 0)

{

var contactName = retrieve[0].attributes.fullname.value; //String

var account = retrieve[0].attributes.accountid.id //Lookup

}

Delete:

var deleteResponse = XrmServiceToolkit.Soap.Delete(“contact”, contactId);

SetState:

var response = XrmServiceToolkit.Soap.SetState(“contact”, contactId, 1, 2);

QueryByAttribute:

I prefer to query with fetch.

var queryOptions = {
entityName: “contact”,
attributes: [“firstname”, “middlename”, “lastname”],
values: [“John”, “<&>”, “Snow”],
columnSet: [“firstname”, “lastname”, “middlename”, “familystatuscode”, “ownerid”, “creditlimit”, “birthdate”, “donotemail”, “donotphone”],
orderby: [“firstname”, “lastname”] // Order by firstname and then lastname even though we are only getting one record back
};

var fetchedContacts = XrmServiceToolkit.Soap.QueryByAttribute(queryOptions);

Change Lookup Text – Originating Lead field

Some clients like to have other text shown on the lookup fields, that’s the example on the Originating Lead field that links a Lead to an Opportunity (and Accounts and Contacts), because the lookup field in the Opportunity shows the Contact name (if the contact field is filled in the Lead), if not, then the lookup field appears to be empty.

So this is a code that will allow you to change the text to anything that you want/need. In our case it was the name of the Lead (subject field).

function ChangeLookUpDisplayValue()
{
 var lookupData = new Array();
 var lookupItem= new Object(); 
 
 if(Xrm.Page.getAttribute("originatingleadid") != null)
 {
   var lookup = Xrm.Page.getAttribute("originatingleadid").getValue(); 
 
   if (lookup != null)
   {
     lookupItem.id = lookup[0].id; 
     lookupItem.typename = lookup[0].typename;
     var displayvalue='';
 
     var fetchXml =
       "<fetch mapping='logical'>" +
        "<entity name='lead'>" +
         "<attribute name='subject'/>" +
        "<filter>" +
         "<condition attribute='leadid' operator='eq' value='" + lookupItem.id + "' />" +
        "</filter>" +
        "</entity>" +
       "</fetch>";

     var retrievedLead = XrmServiceToolkit.Soap.Fetch(fetchXml);
 
     if(retrievedLead != null)
     {
       if (retrievedLead.length == 1)
       {
          displayvalue = retrievedLead[0].attributes['subject'].value;
          lookupItem.name = displayvalue;
          lookupData[0] = lookupItem;
 
          Xrm.Page.getAttribute("originatingleadid").setValue(lookupData);
       }
     }
   }
  }
 }

Hope this helps.

Show/Hide Ribbon Button using Enable Rule

If you want to show/hide a ribbon button, but you are having problems because of the load/save events that sometimes makes the show/hide not work correctly, this is the best way I found to get the job done.

Just need to add this bit of code in the RibbonDiffXml in the extracted solution of the entity you want to add (or already have) the button, in the customization.xml file.

<CommandDefinitions>
 <CommandDefinition Id="Mscrm.Form.entity.name"> <!--button id-->
 <EnableRule Id="entity.functionName.EnableRule" />
 <DisplayRules />
 <Actions>
 <JavaScriptFunction FunctionName="markopportunityasgo" Library="$Webresource:cst_Opportunity2013" />
 </Actions>
 </CommandDefinition>
 </CommandDefinitions>

<EnableRules>
 <EnableRule Id="entity.functionName.EnableRule">
 <CustomRule FunctionName="javascriptFunction" Library="$webresource:javascriptFileName">
 <CrmParameter Value="PrimaryItemIds" /> <!--get entity id-->
 </CustomRule>
 </EnableRule>
 </EnableRules>
//Javascript function that get the entity id. If gives error, you can remove it from the funtion
function javascriptFunction(id)
{
 //Logic
 return true; //shows button
}

Create/Update Entity records using XrmServiceToolKit.Soap

If you want to create or update a record using the XrmServiceToolKit Soap and don’t know how to do it for all the field types, here is some code that might help you.

//Create Entity
var entity = new XrmServiceToolkit.Soap.BusinessEntity("EntityName");
//String
entity.attributes["fieldName"] = Xrm.Page.getAttribute("fieldName").getValue();

//Lookup
entity.attributes['fieldName'] = { id : Xrm.Page.getAttribute('fieldName').getValue()[0].id, logicalName : Xrm.Page.getAttribute('fieldName').getValue()[0].entityType, type : 'EntityReference' };

//Bool
entity.attributes["fieldName"] = Xrm.Page.getAttribute("fieldName").getValue();

//OptionSetValue
entity.attributes["fieldName"] = { value: Xrm.Page.getAttribute("fieldName").getValue(), type: "OptionSetValue" };

//Currency
entity.attributes["fieldName"] = { Value: Xrm.Page.data.entity.attributes.get("fieldName").getValue() };

//Decimal
entity.attributes["fieldName"] = { Value: parseFloat(eval(Xrm.Page.data.entity.attributes.get("fieldName").getValue())) };

entity.attributes["fieldName"] = { Value: 2, type: "int"}; 

entity.attributes["fieldName"] = { Value: 1.5617, type: "double" }; 

var quoteId;
quoteId = XrmServiceToolkit.Soap.Create(entity);

//Update Entity
var updateEntity = new XrmServiceToolkit.Soap.BusinessEntity("EntityName", entityGuid);
//Lookup to update
updateEntity.attributes["fieldName"] = { id : entityGuid, logicalName : 'entityName', type : 'EntityReference' };
//OptionSet
updateEntity.attributes["fieldName"] = { value : Value, type : 'OptionSetValue' };
//Currency
updateEntity.attributes["fieldName"] = { value : Value, type : 'Money' };
//Boolean
updateEntity.attributes["fieldName"] = { value : true/false, type: 'boolean' };
//String
updateEntity.attributes["fieldName"] = "Value";

updateEntity.attributes["fieldName"] = { Value: 2, type: "int"}; 

updateEntity.attributes["fieldName"] = { Value: 1.5617, type: "double" }; 

</pre>
<pre>var updateResponse = XrmServiceToolkit.Soap.Update(updateEntity ); 

Run a Workflow from a Button in the Ribbon

The other day a colleague asked me if I could help because it was necessary to run a CRM worflow from a button. So after a little bit of search on the web, with some test of some scripts, I’ve got the solution that worked for our case.

You will only need to set the guid of the Workflow that you want to run (workflowGuid) and entityId on which the Workflow was created and make the javascript to run from the button or event on the form.

Hope this helps!

function TriggerWorkflow(entityId, workflowGuid) {
var url = Xrm.Page.context.getServerUrl();
var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
url = url + OrgServicePath;
var request;

request = "xmlns:s=\'http://schemas.xmlsoap.org/soap/envelope/\'>" +
"<s:Body>" +
"xmlns=\'http://schemas.microsoft.com/xrm/2011/Contracts/Services\' xmlns:i=\'http://www.w3.org/2001/XMLSchema-instance\'>" +
"i:type=\'b:ExecuteWorkflowRequest\' xmlns:a=\'http://schemas.microsoft.com/xrm/2011/Contracts\' xmlns:b=\'http://schemas.microsoft.com/crm/2011/Contracts\'>" +
"xmlns:c=\"<a href="http://schemas.datacontract.org/2004/07/System.Collections.Generic/">http://schemas.datacontract.org/2004/07/System.Collections.Generic\</a>">" +
"<a:KeyValuePairOfstringanyType>" +
"<c:key>EntityId</c:key>" +
"i:type=\'d:guid\' xmlns:d=\'http://schemas.microsoft.com/2003/10/Serialization/\'>" + <strong>entityId</strong> + "</c:value>" +
"</a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType>" +
"<c:key>WorkflowId</c:key>" +
"i:type=\'d:guid\' xmlns:d=\'http://schemas.microsoft.com/2003/10/Serialization/\'>" + <strong>workflowGuid</strong> + "</c:value>" +
"</a:KeyValuePairOfstringanyType>" +
"</a:Parameters>" +
"<a:RequestId i:nil=\'true\' />" +
"<a:RequestName>ExecuteWorkflow</a:RequestName>" +
"</request>" +
"</Execute>" +
"</s:Body>" +
"</s:Envelope>";

var req = new XMLHttpRequest();
req.open("POST", url, false)

// 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", "<a href="http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute">http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute</a>");

req.onreadystatechange = function () { assignResponse(req); }; //Alert to validate if the workflow ran. Method bellow.

req.send(request);
}

function assignResponse(req) {
if (req.readyState == 4)
{
  if (req.status == 200)
  {
    alert('successfully executed the workflow');
  }
  else
  {
     alert(req.status);
  }
}
}