Plugin profiler

  1. Plug-in Profiler (rus)
  2. CRM 2015 – Understanding the plugin profiler and a puzzling error (with some useful links)
  3.  Step by Step: Working with CRM2011 plugin profiler
Advertisements

From the Microsoft Dynamics CRM Blogs

Корисні джерела

 http://blogs.office.com/ 

http://www.microsoftblog.com.ua/ 

http://blogs.technet.com/b/tasush/ 

http://roadmap.office.com/en-us 

http://blogs.windows.com/ 

http://azure.microsoft.com/blog/  

https://community.dynamics.com/crm/b/default.aspx 

 

 

From the Microsoft Dynamics CRM Blogs: Avoiding form reload; Routing rules; Calculated fields; Casting error

  • Avoiding Form Reload When Switching CRM Forms Based on a Field;
  • Using Routing Rule Set in Microsoft Dynamics CRM 2013;
  • Calculated Fields in Dynamics CRM 2015;
  • CRM 2011/CRM2013 – Investigating a Casting Error with ActivityParty

Avoiding Form Reload When Switching CRM Forms Based on a Field

This post comes to us from Gonzalo Ruiz’ Dynamics CRM blog, offering a solution for avoiding a certain kind of double form load scenario.

Ruiz says quite often you define different forms for a given entity and you do a form switch based on a field rather than based on the security role of the user.

The problem with this approach is that there is often a double form load because when the wrong form loads, then the record re-loads using the appropriate form.

“The effect is bad user experience because the form loads twice so it doubles the form load time,” he explains.

You can find out what the solution is here.

Using Routing Rules in Microsoft Dynamics CRM 2013

On the Himbap blog, Microsoft MVP Mahendar Pal talks about a new feature introduced in Microsoft Dynamics CRM 2013 SP1 and Microsoft Dynamics CRM Online Spring ’14 that allows users define case routing rules.

Users can set up different queues based on different business scenarios and then define case routing rules to route cases to these queues, he explains.

To learn where to go to define routing rules, as well as which users can create and modify routing rules, check out the post here.

Calculated Fields in Dynamics CRM 2015

On the PowerObjects Dynamics CRM blog, Joe CRM says that often it’s necessary to have calculated fields on a form. For example, you may have a few fields and you also want to have the total on the form. Before Dynamics CRM 2013, you’d have to do calculations via JavaScript. Then 2013 introduced Business Rules, which can be used to place a calculated value in a field. The author explains:

“Let’s take a hypothetical example, where we have a few fields and we need to display the calculated total. So we have the actual item cost, the assemble cost and optional accessory cost. We want to have a field for the total cost of the assembled item.”

You can read more about calculated fields in CRM 2015 here.

CRM 2011/CRM2013 – Investigating a Casting Error with ActivityParty

On Hosk’s Dynamics CRM Blog, Hosk, aka Ben Hosking, says he was getting an odd error while he was casting an ActivityParty to an Entity.

Here’s the casting error: error in getproduct Unable to cast object of type “Microsoft.Xrm.Sdk.Entity” to type “Hosk.Dynamics.Entities.ActivityParty.”

He explains:

“What I was trying to do, is when the user updated the ServiceAppointment Entity, I would check the resources (which can either be a user or equipment). If it’s equipment, I can then look up the value of a product and show a few product details on the ServiceAppointment record. I was using early bound records but when I tried to get the ServiceAppointment.Resources I got a casting error.

Hosk knew the problem wasn’t that the Resources field was empty because he was checking it and it definitely had a value – the only problem was he got an error every time he tried to get it.

You can read about how he tracked down the error here.

CRM – General Qs

1) Buying Behavior Customer?

Gerente KRITER SOFTWARE. Presidente ASEITEC Top Contributor

So Long As You can see I try to Get the Facts Related Account Record With buying behavior, facilitate cross-selling and upselling. Examples
For Accounts
– Annual Purchases Account
– Hot Products purchased For An Account .
– Products not purchased at UN A Period Of Account
– Number of Annual bills.
– Annual Number of Cases
– Number of Annual Opportunities .
– Last invoice date
– Date of Last Case

For Organization.
– Best Products Purchased
– Customers who have not purchased a product in a period
– Sales of Product .

It is strange that they are not reflected these issues.
Excuse for my English and, thank you for your time

Lock CRM records

1)Need help to Prevent two user open same lead form.

2)  What is the best way of locking a Record or a Form in a Record while a user is working on it in CRM 2011

3)   Concurrency Control in CRM 2011

Note: In the web resource code the value of the “aSync” parameter passed to the retrieveRecord method is extremely crucial. Rest calls using Ajax are asynchronous by default. But in this scenario we require a synchronous call as the system needs to wait for the result before proceeding with the “Save” event. So we pass the value “false” for this parameter thus forcing it to ne a synchronous call.

CRM with Excel

Playing With CRM Data In Excel (Source)

 Connecting CRM to Excel

OData Connections

Out of the Box Excel OData Connections

etc.

<More> in Leon Tribe’s  blog

MS CRM JScript functions list

Source

Here’s a quick reference guide covering Microsoft CRM syntax for common jscript requirements

Most of the examples are provided as functions that you can easily test in the OnLoad/OnChange event of the Account form to see a working example

1. Get the GUID value of a lookup field:
Note: this example reads and pops the GUID of the primary contact on the Account form
function AlertGUID() {
var primaryContactGUID = Xrm.Page.data.entity.attributes.get(“primarycontactid”).getValue()[0].id;
alert(primaryContactGUID);
}
2. Get the Text value of a lookup field:
Note: this example reads and pops the name of the primary contact on the Account form
function AlertText() {
var primaryContactName = Xrm.Page.data.entity.attributes.get(“primarycontactid”).getValue()[0].name;
alert(primaryContactName);
}
3. Get the value of a text field:
Note: this example reads and pops the value of the Main Phone (telephone1) field on the Account form
function AlertTextField() {
var MainPhone = Xrm.Page.data.entity.attributes.get(“telephone1”).getValue();
alert(MainPhone);
}
4. Get the database value of an Option Set field:
Note: this example reads and pops the value of the Address Type (address1_addresstypecode) field on the Account form
function AlertOptionSetDatabaseValue() {
var AddressTypeDBValue = Xrm.Page.data.entity.attributes.get(“address1_addresstypecode”).getValue();
if (AddressTypeDBValue != null) {
alert(AddressTypeDBValue);
}
}
5. Get the text value of an Option Set field:
Note: this example reads and pops the value of the Address Type (address1_addresstypecode) field on the Account form
function AlertOptionSetDisplayValue() {
var AddressTypeDisplayValue = Xrm.Page.data.entity.attributes.get(“address1_addresstypecode”).getText();
if (AddressTypeDisplayValue != null) {
alert(AddressTypeDisplayValue);
}
}
6. Get the database value of a Bit field:
// example GetBitValue(“telephone1”);
function GetBitValue(fieldname) {
return Xrm.Page.data.entity.attributes.get(fieldname).getValue();
}
7. Get the value of a Date field:
returns a value like: Wed Nov 30 17:04:06 UTC+0800 2011
and reflects the users time zone set under personal options
// example GetDate(“createdon”);
function GetDate(fieldname) {
return Xrm.Page.data.entity.attributes.get(fieldname).getValue();
}
8. Get the day, month and year parts from a Date field:
// This function takes the fieldname of a date field as input and returns a DD-MM-YYYY value
// Note: the day, month and year variables are numbers
function FormatDate(fieldname) {
var d = Xrm.Page.data.entity.attributes.get(fieldname).getValue();
if (d != null) {
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++; // getMonth() considers Jan month 0, need to add 1
var curr_year = d.getFullYear();
return curr_date + “-” + curr_month + “-” + curr_year;
}
else return null;
}

// An example where the above function is called
alert(FormatDate(“new_date2”));
9. Set the value of a string field:
Note: this example sets the Account Name field on the Account Form to “ABC”
function SetStringField() {
var Name = Xrm.Page.data.entity.attributes.get(“name”);
Name.setValue(“ABC”);
}
10. Set the value of an Option Set (pick list) field:
Note: this example sets the Address Type field on the Account Form to “Bill To”, which corresponds to a database value of “1”
function SetOptionSetField() {
var AddressType = Xrm.Page.data.entity.attributes.get(“address1_addresstypecode”);
AddressType.setValue(1);
}
11. Set a Date field / Default a Date field to Today:
//set date field to now (works on date and date time fields)
Xrm.Page.data.entity.attributes.get(“new_date1”).setValue(new Date());
12. Set a Date field to 7 days from now:
function SetDateField() {
var today = new Date();
var futureDate = new Date(today.setDate(today.getDate() + 7));
Xrm.Page.data.entity.attributes.get(“new_date2”).setValue(futureDate);
Xrm.Page.data.entity.attributes.get(“new_date2”).setSubmitMode(“always”); // Save the Disabled Field
}
13. Set the Time portion of a Date Field:
// This is a function you can call to set the time portion of a date field
function SetTime(attributeName, hour, minute) {
var attribute = Xrm.Page.getAttribute(attributeName);
if (attribute.getValue() == null) {
attribute.setValue(new Date());
}
attribute.setValue(attribute.getValue().setHours(hour, minute, 0));
}

// Here’s an example where I use the function to default the time to 8:30am
SetTime(‘new_date2’, 8, 30);
14. Set the value of a Lookup field:
Note: here I am providing a reusable function…
// Set the value of a lookup field
function SetLookupValue(fieldName, id, name, entityType) {
if (fieldName != null) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = id;
lookupValue[0].name = name;
lookupValue[0].entityType = entityType;
Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
}
}
Here’s an example of how to call the function (I retrieve the details of one lookup field and then call the above function to populate another lookup field):
var ExistingCase = Xrm.Page.data.entity.attributes.get(“new_existingcase”);
if (ExistingCase.getValue() != null) {
var ExistingCaseGUID = ExistingCase.getValue()[0].id;
var ExistingCaseName = ExistingCase.getValue()[0].name;
SetLookupValue(“regardingobjectid”, ExistingCaseGUID, ExistingCaseName, “incident”);
}
15. Split a Full Name into First Name and Last Name fields:
function PopulateNameFields() {
var ContactName = Xrm.Page.data.entity.attributes.get(“customerid”).getValue()[0].name;
var mySplitResult = ContactName.split(” “);
var fName = mySplitResult[0];
var lName = mySplitResult[1];
Xrm.Page.data.entity.attributes.get(“firstname”).setValue(fName);
Xrm.Page.data.entity.attributes.get(“lastname”).setValue(lName);
}
16. Set the Requirement Level of a Field:
Note: this example sets the requirement level of the Address Type field on the Account form to Required.
Note: setRequiredLevel(“none”) would make the field optional again.
function SetRequirementLevel() {
var AddressType = Xrm.Page.data.entity.attributes.get(“address1_addresstypecode”);
AddressType.setRequiredLevel(“required”);
}
17. Disable a field:
function SetEnabledState() {
var AddressType = Xrm.Page.ui.controls.get(“address1_addresstypecode”);
AddressType.setDisabled(true);
}
18. Force Submit the Save of a Disabled Field:
// Save the Disabled Field
Xrm.Page.data.entity.attributes.get(“new_date1”).setSubmitMode(“always”);
19. Show/Hide a field:
function hideName() {
var name = Xrm.Page.ui.controls.get(“name”);
name.setVisible(false);
}
20. Show/Hide a field based on a Bit field
function DisableExistingCustomerLookup() {
var ExistingCustomerBit = Xrm.Page.data.entity.attributes.get(“new_existingcustomer”).getValue();
if (ExistingCustomerBit == false) {
Xrm.Page.ui.controls.get(“customerid”).setVisible(false);
}
else {
Xrm.Page.ui.controls.get(“customerid”).setVisible(true);
}
}
21. Show/Hide a nav item:
Note: you need to refer to the nav id of the link, use F12 developer tools in IE to determine this
function hideContacts() {
var objNavItem = Xrm.Page.ui.navigation.items.get(“navContacts”);
objNavItem.setVisible(false);
}
22. Show/Hide a Section:
Note: Here I provide a function you can use. Below the function is a sample.
function HideShowSection(tabName, sectionName, visible) {
try {
Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(visible);
}
catch (err) { }
}

HideShowSection(“general”, “address”, false); // “false” = invisible
23. Show/Hide a Tab:
Note: Here I provide a function you can use. Below the function is a sample.
function HideShowTab(tabName, visible) {
try {
Xrm.Page.ui.tabs.get(tabName).setVisible(visible);
}
catch (err) { }
}

HideShowTab(“general”, false); // “false” = invisible
24. Save the form:
function SaveAndClose() {
Xrm.Page.data.entity.save();
}
25. Save and close the form:
function SaveAndClose() {
Xrm.Page.data.entity.save(“saveandclose”);
}
26. Close the form:
Note: the user will be prompted for confirmation if unsaved changes exist
function Close() {
Xrm.Page.ui.close();
}
27. Determine which fields on the form are dirty:
var attributes = Xrm.Page.data.entity.attributes.get()
for (var i in attributes)
{
var attribute = attributes[i];
if (attribute.getIsDirty())
{
alert(“attribute dirty: ” + attribute.getName());
}
}
28. Determine the Form Type:
Note: Form type codes: Create (1), Update (2), Read Only (3), Disabled (4), Bulk Edit (6)
function AlertFormType() {
var FormType = Xrm.Page.ui.getFormType();
if (FormType != null) {
alert(FormType);
}
}
29. Get the GUID of the current record:
function AlertGUID() {
var GUIDvalue = Xrm.Page.data.entity.getId();
if (GUIDvalue != null) {
alert(GUIDvalue);
}
}
30. Get the GUID of the current user:
function AlertGUIDofCurrentUser() {
var UserGUID = Xrm.Page.context.getUserId();
if (UserGUID != null) {
alert(UserGUID);
}
}
31. Get the Security Roles of the current user:
(returns an array of GUIDs, note: my example reveals the first value in the array only)
function AlertRoles() {
alert(Xrm.Page.context.getUserRoles());
}
32. Determine the CRM server URL:
// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length – 1);
}
33. Refresh a Sub-Grid:
var targetgird = Xrm.Page.ui.controls.get(“target_grid”);
targetgird.refresh();
34. Change the default entity in the lookup window of a Customer or Regarding field:
Note: I am setting the customerid field’s lookup window to offer Contacts (entityid 2) by default (rather than Accounts). I have also hardcoded the GUID of the default view I wish displayed in the lookup window.
function ChangeLookup() {
document.getElementById(“customerid”).setAttribute(“defaulttype”, “2”);
var ViewGUID= “A2D479C5-53E3-4C69-ADDD-802327E67A0D”;
Xrm.Page.getControl(“customerid”).setDefaultView(ViewGUID);
}
35. Pop an existing CRM record (new approach):
function PopContact() {
//get PrimaryContact GUID
var primaryContactGUID = Xrm.Page.data.entity.attributes.get(“primarycontactid”).getValue()[0].id;
if (primaryContactGUID != null) {
//open Contact form
Xrm.Utility.openEntityForm(“contact”, primaryContactGUID)
}
}
36. Pop an existing CRM record (old approach):
Note: this example pops an existing Case record. The GUID of the record has already been established and is stored in the variable IncidentId.
//Set features for how the window will appear
var features = “location=no,menubar=no,status=no,toolbar=no”;

// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length – 1);
}

window.open(serverUrl + “/main.aspx?etn=incident&pagetype=entityrecord&id=” + encodeURIComponent(IncidentId), “_blank”, features, false);
37. Pop a blank CRM form (new approach):
function PopNewCase() {
Xrm.Utility.openEntityForm(“incident”)
}
38. Pop a new CRM record with default values (new approach):
function CreateIncident() {
//get Account GUID and Name
var AccountGUID = Xrm.Page.data.entity.getId();
var AccountName = Xrm.Page.data.entity.attributes.get(“name”).getValue();
//define default values for new Incident record
var parameters = {};
parameters[“title”] = “New customer support request”;
parameters[“casetypecode”] = “3”;
parameters[“customerid”] = AccountGUID;
parameters[“customeridname”] = AccountName;
parameters[“customeridtype”] = “account”;
//pop incident form with default values
Xrm.Utility.openEntityForm(“incident”, null, parameters);
}
39. Pop a new CRM record with default values (old approach):
Note: this example pops the Case form from the Phone Call form, defaulting the Case’s CustomerID based on the Phone Call’s SenderID and defaulting the Case Title to “New Case”
//Collect values from the existing CRM form that you want to default onto the new record
var CallerGUID = Xrm.Page.data.entity.attributes.get(“from”).getValue()[0].id;
var CallerName = Xrm.Page.data.entity.attributes.get(“from”).getValue()[0].name;

//Set the parameter values
var extraqs = “&title=New Case”;
extraqs += “&customerid=” + CallerGUID;
extraqs += “&customeridname=” + CallerName;
extraqs += “&customeridtype=contact”;

//Set features for how the window will appear
var features = “location=no,menubar=no,status=no,toolbar=no”;

// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length – 1);
}

//Pop the window
window.open(serverUrl + “/main.aspx?etn=incident&pagetype=entityrecord&extraqs=” + encodeURIComponent(extraqs), “_blank”, features, false);
40. Pop a Dialog from a ribbon button
Note: this example has the Dialog GUID and CRM Server URL hardcoded, which you should avoid. A simple function is included which centres the Dialog when launched.
function LaunchDialog(sLeadID) {
var DialogGUID = “128CEEDC-2763-4FA9-AB89-35BBB7D5517D”;
var serverUrl = “https://avanademarchdemo.crm5.dynamics.com/&#8221;;
serverUrl = serverUrl + “cs/dialog/rundialog.aspx?DialogId=” + “{” + DialogGUID + “}” + “&EntityName=lead&ObjectId=” + sLeadID;
PopupCenter(serverUrl, “mywindow”, 400, 400);
window.location.reload(true);
}

function PopupCenter(pageURL, title, w, h) {
var left = (screen.width / 2) – (w / 2);
var top = (screen.height / 2) – (h / 2);
var targetWin = window.showModalDialog(pageURL, title, ‘toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=’ + w + ‘, height=’ + h + ‘, top=’ + top + ‘, left=’ + left);
}
41. Pop a URL from a ribbon button
Great info on the window parameters you can set here: http://javascript-array.com/scripts/window_open/
function LaunchSite() {
// read URL from CRM field
var SiteURL = Xrm.Page.data.entity.attributes.get(“new_sharepointurl”).getValue();
// execute function to launch the URL
LaunchFullScreen(SiteURL);
}

function LaunchFullScreen(url) {
// set the window parameters
params = ‘width=’+screen.width;
params += ‘, height=’+screen.height;
params += ‘, top=0, left=0’;
params += ‘, fullscreen=yes’;
params += ‘, resizable=yes’;
params += ‘, scrollbars=yes’;
params += ‘, location=yes’;

newwin=window.open(url,’windowname4′, params);
if (window.focus) {
newwin.focus()
}
return false;
}
42. Pop the lookup window associated to a Lookup field:
window.document.getElementById(‘new_existingcase’).click();
43. Pop a Web Resource (new approach):
function PopWebResource() {
Xrm.Utility.openWebResource(“new_Hello”);
}
44. Using a SWITCH statement
function GetFormType() {
var FormType = Xrm.Page.ui.getFormType();
if (FormType != null) {
switch (FormType) {
case 1:
return “create”;
break;
case 2:
return “update”;
break;
case 3:
return “readonly”;
break;
case 4:
return “disabled”;
break;
case 6:
return “bulkedit”;
break;
default:
return null;
}
}
}
45. Pop an Ok/Cancel Dialog
function SetApproval() {
if (confirm(“Are you sure?”)) {
// Actions to perform when ‘Ok’ is selected:
var Approval = Xrm.Page.data.entity.attributes.get(“new_phaseapproval”);
Approval.setValue(1);
alert(“Approval has been granted – click Ok to update CRM”);
Xrm.Page.data.entity.save();
}
else {
// Actions to perform when ‘Cancel’ is selected:
alert(“Action cancelled”);
}
}

Here is a little more info that will help you get your head around the general design of all this…

Depending upon what you want to do you will interact with one of the following:

Xrm.Page.data.entity.attributes – The data fields represented by fields on the form

Xrm.Page.ui.controls – The user interface controls on the form

Xrm.Page.ui.navigation.items – The navigation items on the form

Xrm.Utility – A container of helpful functions

– – – – – –

2) Source – balarajann.blogspot.com/2013/03/microsoft-dynamics-crm-2011-javascript.html

Microsoft Dynamics CRM 2011 Javascript

         Below are the few useful properties, commands in Microsoft Dynamics CRM 2011 Javascript. You can work with them on form event say OnLoad.

Click on the item below to go through the description about that.

Get the string value of a Text field:

Returns the string value in the text field.
var fieldValue = Xrm.Page.data.entity.attributes.get("fieldName").getValue();

Set the string value of a Text field:

Set the string value for Text field.

Xrm.Page.data.entity.attributes.get("fieldName").setValue("New Value");

Retrieve Optionset Value/Text:

Returns the Value/Text of Optionset.

var optionSet = Xrm.Page.data.entity.attributes.get("optionSetName");
var optionSetText = optionSet.getText();
var optionSetValue = optionSet.getValue();

Get the label name of the field:

Get the Label of the specified field.

var fieldLabel = Xrm.Page.ui.controls.get("fieldName").getLabel();

Get the Lookup field value:

Get the value in given Lookup field.

var lookupValue=Xrm.Page.data.entity.attributes.get("lookupFieldName").getValue()[0].name;

Get the Lookup field ID:

Returns the ID of the record to which the lookup pointing to.

var lookupFieldId=Xrm.Page.data.entity.attributes.get("lookupFieldName").getValue()[0].id;

Get current entity name:

Returns the logical name of the current entity.

var entityName = Xrm.Page.data.entity.getEntityName();

Get Type Code of lookup:

Returns the code type with respect to an entity the lookup pointing to.

var objectTypeCode = Xrm.Page.getAttribute("lookupFieldName").getValue()[0].type;

Get reference entity name of lookup:

Returns the logical name of an entity the lookup pointing to.

var entityName = Xrm.Page.getAttribute("lookupField").getValue()[0].entityType;

Check for Dirty:

Returns a Boolean value indicating if any fields in the form have been modified.

var formChanged = Xrm.Page.data.entity.getIsDirty();

Set Lookup field:

Set the lookup field value.

var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = newId;
lookupValue[0].name = newName;
lookupValue[0].entityType = entityType;
Xrm.Page.getAttribute("lookupName").setValue(lookupValue);

Get event generated field value:

Returns the value of the field which generates the event.

function fieldValue_onchange(obj) {
  var attribute = obj.getEventSource();
  alert(attribute .getValue());
  alert(Xrm.Page.ui.getCurrentControl().getAttribute().getValue());
}

Get Organization Name:

Returns the unique name of logged-in organization.

var orgName = Xrm.Page.context.getOrgUniqueName();

Get Organization Language Code:

Returns organization’s language code(LCID).
var orgLanguage = Xrm.Page.context.getUserLcid();

Get Server URL:

Returns the base server URL.

var orgName = Xrm.Page.context.getServerUrl();

Get GUID of current record:

Returns GUID for the record.

var guid = Xrm.Page.data.entity.getId();

Whether the field is disabled or not:

Returns a Boolean value indicating whether the control is disabled.

var fieldDisabled = Xrm.Page.ui.controls.get("fieldName").getDisabled();

Get form type:

Returns an integer value, indicates the form type: 1-Create, 2-Update

var FormType = Xrm.Page.ui.getFormType();

Get required fields in the form:

Returns required field names in the form:

Xrm.Page.data.entity.attributes.forEach( function (attribute, index) { 
 if (attribute.getRequiredLevel() == "required" ) {
  requiredFields += attribute.getName()+"\n";
 }
} );

Form Save:

Save the current form.

Xrm.Page.data.entity.save();

Form Save and Close:

Save and Close the form.

Xrm.Page.data.entity.save("saveandclose");

Set Focus:

Set focus on the control.
Xrm.Page.ui.controls.get("fieldName").setFocus();

Hide a field:

Hide the specified control.

Xrm.Page.ui.controls.get("fieldName").setVisible(false);

Disable and Enable a field:

Set field as Read only.

Xrm.Page.ui.controls.get("fieldName").setDisabled(true);

Set field as editable(Enable).

Xrm.Page.ui.controls.get("fieldName").setDisabled(false);

Close window:

Close the current opened window.

Xrm.Page.ui.close();

Open New window:

Open a new browser window with specified URL.

window.open("http://google.com", 
  'name', 
  'width=900,height=800,toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,modal=yes');

Get Logged-in User ID:

Get the Logged-in User ID.

var userID = Xrm.Page.context.getUserId();

Attach Event to Control:

As CRM 2011 does not supports some events like onclick and ondblclick, we can attach a particular event to the control on form load.

function onload_method() {
    var control = document.getElementById("fieldName");
    if (control) {
        control.attachEvent("onclick", control_clicked);
        control.attachEvent("oncdbllick", control_dblclicked);
    }
}

function control_clicked(){
    //This function fires on field click
    //onclick logic goes here
}

function control_dblclicked(){
   //This function fires on field double click
   //ondblclick logic goes here
}

Set Description field in E-mail entity:

The Description field in E-mail entity is inside an IFrame and since its made for text decoration, text inside this field is enclosed with html tags. So, we can’t directly set the field value. Below is the solution to set this field OnLoad of the form.

function onload_method() {
    var descriptionFrame = document.getElementById('descriptionIFrame');
    descriptionFrame.attachEvent('onreadystatechange', setValue);
}

function setValue () {
    var descriptionFrame = document.getElementById('descriptionIFrame'); 
    if (descriptionFrame.readyState != 'complete')
        return; 
    var htmlTag = "<:html> Value for Description field...<:/html>";
    var descriptionWindow = document.frames['descriptionIFrame'];
    descriptionWindow.document.body.innerHTML = htmlTag; 
}

Set IFrame URL:

To change the URL of IFrame and can also pass values in query string.

function setIFrameURL() {
    var IFrame = Xrm.Page.ui.controls.get("IFRAME_GoogleMap");
    var countryName = Xrm.Page.data.entity.attributes.get("address1_country").getValue();
    var newTarget= "http://maps.google.com/maps?q="+countryName;
    IFrame.setSrc(newTarget);
}

Get Schema Names of the Attributes:

To get the Schema Names of all the attributes in given entity.

getSchemaNamesList = function (entityName) {
 var request = "<Request xsi:type='RetrieveEntityRequest'>"+
               "<MetadataId>00000000-0000-0000-0000-000000000000<:/MetadataId>"+
               "<EntityItems>IncludeAttributes<:/EntityItems>"+
               "<LogicalName>" + entityName + "<:/LogicalName>"+
               "<IsCustomizable>1<:/IsCustomizable>"+
               "<RetrieveAsIfPublished>true<:/RetrieveAsIfPublished>"+
               "</Request>";

 var result = queryMetadataService(request);
 var schemaNames = result.selectNodes("//EntityMetadata/Attributes/Attribute/SchemaName");
        var namesList = "";
        for (var i = 0; i < schemaNames.length; i++) {
  namesList += schemaNames[i];
        }
        alert("Schema Names: "+namesList)
}

queryMetadataService = function (request) {
 var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 xmlhttp.open("POST", '/mscrmservices/2007/MetadataService.asmx', false);
 xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
 xmlhttp.setRequestHeader("SOAPAction", 'http://schemas.microsoft.com/crm/2007/WebServices/Execute');

 var soapMessage = "<?xml version='1.0' encoding='utf-8'?>" +
 "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
 "xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
 "<soap:Header>" +
 "<CrmAuthenticationToken xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
 "<AuthenticationType xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>" + AUTHENTICATION_TYPE +
 "</AuthenticationType>" +
 "<OrganizationName xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>" + ORG_UNIQUE_NAME +
 "</OrganizationName>" +
 "<CallerId xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>00000000-0000-0000-0000-000000000000" +
 "</CallerId>"+
 "</CrmAuthenticationToken>" +
 "</soap:Header>" +
 "<soap:Body><:Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" + request +
 "</Execute><:/soap:Body>" +
 "</soap:Envelope>";

 xmlhttp.send(soapMessage);
 return xmlhttp.responseXML;
}

Get Teams of User:

Get all the Teams User belongs to.

var xml = "" +
 "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
 "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
 GenerateAuthenticationHeader() +
 " <soap:Body>" +
 " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
 " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
 " <q1:EntityName>team</q1:EntityName>" +
 " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
 " <q1:Attributes>" +
 " <q1:Attribute>name</q1:Attribute>" +
 " </q1:Attributes>" +
 " </q1:ColumnSet>" +
 " <q1:Distinct>false</q1:Distinct>" +
 " <q1:LinkEntities>" +
 " <q1:LinkEntity>" +
 " <q1:LinkFromAttributeName>teamid</q1:LinkFromAttributeName>" +
 " <q1:LinkFromEntityName>team</q1:LinkFromEntityName>" +
 " <q1:LinkToEntityName>teammembership</q1:LinkToEntityName>" +
 " <q1:LinkToAttributeName>teamid</q1:LinkToAttributeName>" +
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +
 " <q1:LinkCriteria>" +
 " <q1:FilterOperator>And</q1:FilterOperator>" +
 " <q1:Conditions>" +
 " <q1:Condition>" +
 " <q1:AttributeName>systemuserid</q1:AttributeName>" +
 " <q1:Operator>EqualUserId</q1:Operator>" +
 " </q1:Condition>" +
 " </q1:Conditions>" +
 " </q1:LinkCriteria>" +
 " </q1:LinkEntity>" +
 " </q1:LinkEntities>" +
 " </query>" +
 " </RetrieveMultiple>" +
 " </soap:Body>" +
 "</soap:Envelope>";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
//alert(resultXml.xml);

// Save all entity nodes in an array.
var entityNodes = resultXml.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

var teamnames = new Array();
var teamids = new Array();

for (var i = 0; i < entityNodes.length; i++) {

 var entityNode = entityNodes[i];
 var teamidNode = entityNode.selectSingleNode("q1:teamid");
 var teamNode = entityNode.selectSingleNode("q1:name");
 var teamid = (teamidNode == null) ? null : teamidNode.text;
 var team = (teamNode == null) ? null : teamNode.text;

 teamnames[i] = team;
 teamids[i] = teamid;
}

Filtered Lookup:

Filter the lookup view based the value selected in another lookup.

You can get fetchXml value from your CRM system by following the steps below.
Open Dynamics CRM à Click Advanced Find on ribbon à Select Target(say) in “Look for:” list à Select Owning Team(Team) in list below à Select Team under Owning Team(Team) à Leave Equals as default filter à In Enter Value lookup select one record à Click Download Fetch XML on ribbon. You will get fetch XML string and put that code in variable ‘fetchXml’ in below code and replace GUID from ‘value’ property in <condition> tag with dynamic variable, here it is _teamId.

function changeCustomView() {
//new_targetvalue is a lookup to new_target entity which we are filtering present on new_test entity form
//new_team is a lookup to Team on new_test entity form by which new_targetvalue lookup filtering
//new_targetid is a primary key attribute in new_target entity
//teamid is a lookup to Team on new_target entity form
 
   var entityName = "new_target"; //Filtering lookup entity name
   var _team = Xrm.Page.data.entity.attributes.get("new_team"); //Team on which filtering depends on
   var viewDisplayName = "CustomTargetFilteredView";

   // If new_team contains a value, then filter the new_targetvalue lookup based on new_team selected
   if (_team.getValue() != null) {
      var _teamId = _team.getValue()[0].id;
      var viewId = "{1DFB2B35-B07C-44D1-868D-258DEEAB88E2}"; // Unique viewID
      var fetchXml = "<?xml version='1.0'?>" +
        "<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>" +
        "<entity name='new_target'> <attribute name='new_targetid'/>" +
        "<attribute name='new_name'/>" +
        "<attribute name='createdon'/>" +
        "<order descending='false' attribute='new_name'/>" +
        "<link-entity name='team' alias='aa' to='owningteam' from='teamid'>" +
        "<filter type='and'>"+ 
        "<condition attribute='teamid' value='" + _teamId + "' uitype='team' operator='eq'/>" +
        "</filter> " +
        "</link-entity> " +
        "</entity> " +
        "</fetch>";

      var layoutXml = "<grid name='resultset' " +
        "object='1' " +
        "jump='new_name' " +
        "select='1' " +
        "icon='1' " +
        "preview='1'>" +
        "<row name='result' " +
        "id='new_targetid'>" +
        "<cell name='new_name'/>" +
        "width='100' />" +
        "</row>" +
        "</grid>";

      var lookup = Xrm.Page.ui.controls.get("new_targetvalue");
      lookup.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
      lookup.setDefaultView(viewId);
      document.getElementById("new_targetvalue").setAttribute("disableViewPicker", "1");   
   }
}

Trigger the Workflow:

Trigger the workflow(process) using javascript.

Steps to be followed to implement javascript to trigger workflow:
à Download JQuery here.
à Crate one JScript webresource and upload this downloaded JQuery.
à Create one JScript webresource for the below code and register to the CRM form where you want to run this script.

function TriggerWorkflow() {

 // Get the Workflow ID
 var workflowId = GetProcessId();
 if (workflowId[0].results.length > 0) {
  var xml = "" +
  "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
  "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
  GenerateAuthenticationHeader() +
  "<soap:Body>" +
  "<Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
  "<Request xsi:type=\"ExecuteWorkflowRequest\">" +
  "<EntityId>" + Xrm.Page.data.entity.getId() + "</EntityId>" +
  "<WorkflowId>" + workflowId[0].results[0].WorkflowId + "</WorkflowId>" +
  "</Request>" +
  "</Execute>" +
  "  </soap:Body>" +
  "</soap:Envelope>" +
  "";
  var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
  xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", true);
  xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
  xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
  xmlHttpRequest.send(xml);
 }
}

function GetProcessId() {
 // Pass the workflow name manually to get the Id of the workflow
 var processName = "My Workflow Name";

 // Get the server URL
 var serverUrl = Xrm.Page.context.getServerUrl();
 var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/WorkflowSet?$select=WorkflowId&$filter=Name eq '" + processName + "' and ActiveWorkflowId/Id ne null";
 var jSonArray = new Array();

 jQuery.ajax({
  type: "GET",
  contentType: "application/json; charset=utf-8",
  datatype: "json",
  url: oDataUri,
  async: false,
  beforeSend: function (XMLHttpRequest) {
   XMLHttpRequest.setRequestHeader("Accept", "application/json");
  },
  success: function (data, textStatus, XmlHttpRequest) {
   if (data && data.d != null) {
    jSonArray.push(data.d);
   }
  },
  error: function (XmlHttpRequest, textStatus, errorThrown) {
   alert("Error :  has occured during retrieval of the workflowId");
  }
 });
 return jSonArray;
}

Set field value using query string parameter:

When we click on some ribbon button or on some event, the new Account window will open with setting the Account Name field by passing that value in query string parameter.

function openAccountWindow(value) {
 var windowProperties = 'width=900,height=800,toolbar=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,modal=yes';
 var encodedParam = encodeURIComponent("name = New Test Account");
 window.open("http://serverName/OrgName/main.aspx?etc=1&extraqs="+ encodedParam +"&pagetype=entityrecord",
'accountWindow',
windowProperties);
}

Easy to use JavaScript Retrieve and RetrieveMultiple functions

Source

These functions are built around SOAP implementations of the Retrieve and RetrieveMultiple messages. I haven’t annotated my code, so forgive any obvious lack of description of what the code is doing. I’ll try to briefly summarize here:
MischiefMayhemSOAP
Parameters:
xmlSoapBody – (string) XML containing the body of the SOAP call
soapActionHeader – (string) The ‘SOAPAction’ specifying the type of SOAP call
Purpose:
Serves as a generic XMLHTTP interface to CRM’s SOAP functions.
Returns:
(string) XML result from the CRM server.
RetrieveRecord
Parameters:
entityName – (string) The CRM-platform name of the desired entity
entityId – (string) The GUID of the record to retrieve
attrArray – (string[]) An Array of attributes to retrieve for the record
Purpose:
Easily retrieves a single record from CRM.
Returns:
(string[] or null) An Array of values from CRM, index-matching the attributes provided in attrArray. Returns null if there is an error with, or invalid return from, the SOAP call.
RetrieveMultiple
Parameters:
entityName – (string) The CRM-platform name of the desired entity
attrArray – (string[]) An Array of attributes to retrieve for the records
distinct – (string:”true” or “false”) Directs CRM to return with or without duplicate records
criteriaXml – (string) XML containing any combination of Criteria or LinkEntities elements pertaining to the “RetrieveMultiple” SOAP message
Purpose:
Easily retrieves multiple records from CRM which match the rules defined in the criteriaXml.
Returns:
(string[n][] or null) An Array, with n matching-record elements, of an array of values from CRM, index-matching the attributes provided in attrArray. Returns null if there is an error with, or invalid return from, the SOAP call.

function ret_mobile()
{

function MischiefMayhemSOAP(xmlSoapBody, soapActionHeader) {
var xmlReq = “”
+ ” + ” xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance'&#8221;
+ ” xmlns:xsd=’http://www.w3.org/2001/XMLSchema’>&#8221;
+ Xrm.Page.context.getAuthenticationHeader()
+ ” ”
+ xmlSoapBody
+ ” ”
+ “”;

var httpObj = new ActiveXObject(“Msxml2.XMLHTTP”);

httpObj.open(‘POST’, ‘/mscrmservices/2007/crmservice.asmx’, false);

httpObj.setRequestHeader(‘SOAPAction’, soapActionHeader);
httpObj.setRequestHeader(‘Content-Type’, ‘text/xml; charset=utf-8’);
httpObj.setRequestHeader(‘Content-Length’, xmlReq.length);

httpObj.send(xmlReq);

var resultXml = httpObj.responseXML;

var errorCount = resultXml.selectNodes(‘//error’).length;
if (errorCount != 0) {
var msg = resultXml.selectSingleNode(‘//description’).nodeTypedValue;
alert(“The following error was encountered: ” + msg);
return null;
} else {
return resultXml;
}
}

function RetrieveRecord(entityName, entityId, attrArray) {
var xmlSoapBody = “”
+ ” ”
+ ” ” + entityName + “”
+ ” ” + entityId + “”
+ ” ”
+ ” “;

for (index in attrArray) {
xmlSoapBody += ” ” + attrArray[index] + “”;
}

xmlSoapBody += “”
+ ” ”
+ ” ”
+ ” “;

var resultXml = MischiefMayhemSOAP(xmlSoapBody, ‘http://schemas.microsoft.com/crm/2007/WebServices/Retrieve&#8217;);

if (resultXml != null) {
var resultArray = new Array();

for (index in attrArray) {
if (resultXml.selectSingleNode(“//q1:” + attrArray[index]) != null) {
resultArray[index] = resultXml.selectSingleNode(“//q1:” + attrArray[index]).nodeTypedValue;
} else {
resultArray[index] = null;
}
}

return resultArray;
} else {
return null;
}
}

function RetrieveMultiple(entityName, attrArray, distinct, criteriaXml) {
var xmlSoapBody = “”
+ ” ”
+ ” ”
+ ” ” + entityName + “”
+ ” ”
+ ” “;

for (index in attrArray) {
xmlSoapBody += ” ” + attrArray[index] + “”;
}

xmlSoapBody += “”
+ ” ”
+ ” ”
+ ” ” + distinct + “”
+ criteriaXml
+ ” ”
+ ” “;

var resultXml = MischiefMayhemSOAP(xmlSoapBody, ‘http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple&#8217;);

if (resultXml != null) {
var resultArray = new Array();
var entityNodes = resultXml.selectNodes(“//RetrieveMultipleResult/BusinessEntities/BusinessEntity”);

if (entityNodes.length > 0) {
for (var index = 0; index < entityNodes.length; index++) {
var entityNode = entityNodes[index];
resultArray[index] = new Array();

for (attrIndex in attrArray) {
if (entityNode.selectSingleNode(“q1:” + attrArray[attrIndex]) != null) {
resultArray[index][attrIndex] = entityNode.selectSingleNode(“q1:” + attrArray[attrIndex]).nodeTypedValue;
} else {
resultArray[index][attrIndex] = null;
}
}
}

return resultArray;
} else {
return null;
}
} else {
return null;
}
}

var mobile=””;
mobile=RetrieveRecord(‘contact’, Xrm.Page.getAttribute(“new_contact”).getValue()[0].id, new Array(“mobilephone”));
Xrm.Page.getAttribute(“new_mobile”).setValue(String(mobile));
}

Previous Older Entries