Archive
Retrieve and Update record with alternate key using Web API – CRM 2016
Alternative Keys are useful to retrieve or update the records without the need of GUID. It avoids the overhead of retrieving record’s GUID while update operation.
In conventional way, to update an Account record from external web application, you would need to get the GUID first and then update.
With alternate key, you can configure any of your field of type (Single Line of Text, Whole Number or Decimal Number) as Alternate key and use instead of GUID to retrieve or update.
We can have up to 5 different alternate keys per entity.
Sample C# code to update record with out GUID:
- I configured “Account Number” as alternate key.
- I have an Account with ‘Account Number’ as ‘Acct123’ and below is the code to update record. Notice that I did not provide the record GUID.
Entity account = new Entity(“account”, “accountnumber”, “Acct123”);
account[“name”] = “Rajeev Modified”;
service.Update(account);
Create an Alternate key
- Go to Customization–> Entity–> Keys –> New
- Click “Ok”
- Wait for few seconds so that the background workflow complete creation of required indexes.
Jscript to retrieve using Alternate key:
- Below is the script to retrieve a record with alternate key using web api.
function getAccountByAlternateKey() {
try {
var clientUrl = Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest();
// Account Number as an ‘Alternate key’
req.open(“GET”, encodeURI(clientUrl + “/api/data/v8.0/accounts(accountnumber=’Acct123′)“), true);
// If multiple keys as ‘Alternate key’
//req.open(“GET”, encodeURI(clientUrl + “/api/data/v8.0/accounts(name=’Rajeev’,emailaddress1=’rajeev@live.com’)”), true);
req.setRequestHeader(“Accept”, “application/json”);
req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
req.setRequestHeader(“OData-MaxVersion”, “4.0”);
req.setRequestHeader(“OData-Version”, “4.0”);
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 200) {
var data = JSON.parse(this.response);
var dat = data.value;
for (var i = 0; i < dat.length; i++) {
var accountId = dat[i].accountid;
Xrm.Utility.alertDialog(“Account Id : ” + accountId);
}
}
else {
var error = JSON.parse(this.response).error;
alert(“Error retrieving Account- ” + error.message);
}
}
};req.send();
} catch (e) {
alert(“Error in getAccountByAlternateKey – ” + e.description);
}
}
JScript to Update Record Using Alternate Key
function updateAccountByAlternateKey() {
try {
var clientUrl = Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest();
// Account Number as an ‘Alternate key’
req.open(“PATCH“, encodeURI(clientUrl + “/api/data/v8.0/accounts(accountnumber=’Acct123′)“), true);
req.setRequestHeader(“Accept”, “application/json”);
req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
req.setRequestHeader(“OData-MaxVersion”, “4.0”);
req.setRequestHeader(“OData-Version”, “4.0”);
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 204) {
var accountUri = this.getResponseHeader(“OData-EntityId”);//get EntityId from ResponseHeader of Created Record
var accountID = accountUri.split(/[()]/);
accountID = accountID[1];Xrm.Utility.alertDialog(“Updated Account ID : ” + accountID);
}
}
};// Set Account Object
var objAccount = {};
objAccount.name = “Rajeev Modified”;
objAccount.revenue = 123456;//convert JSON object to string
var body = JSON.stringify(objAccount);req.send(body);
} catch (e) {
alert(“Error in updateAccountByAlternateKey – ” + e.description);
}
}
Refer article for more details.
🙂
JScript to retrieve and execute view (Predefined Query) using Web API – CRM 2016
Assume you would need to retrieve ‘Active Accounts’ from your script, you can either retrieve by building FetchXML from scratch or simply use Web API to execute existing ‘Active Accounts’ view query with no need of writing Fetch XML.
Using Web API we can retrieve and execute predefined queries (i.e., System view and Personal view queries).
Below are the steps to retrieve and execute ‘System view’ query using CRM WebAPI
- Get the GUID of View by Name.
- Execute the view and fetch the result set. (Columns of the result set would be same as ‘System View’ columns)
Script
function executeView(viewName) {
try {
var clientUrl = Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest();
// Get ‘Active Accounts’ GUID
req.open(“GET”, encodeURI(clientUrl + “/api/data/v8.0/savedqueries?$select=name,savedqueryid&$filter=name eq ‘” + viewName + “‘”), true);
req.setRequestHeader(“Accept”, “application/json”);
req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
req.setRequestHeader(“OData-MaxVersion”, “4.0”);
req.setRequestHeader(“OData-Version”, “4.0”);
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 200) {
var data = JSON.parse(this.response);
var dat = data.value;
for (var i = 0; i < dat.length; i++) {
var viewId = dat[i].savedqueryid;
alert(“View Id : ” + viewId);
if (viewId) {
executeViewQuery(viewId);
}
}
}
else {
var error = JSON.parse(this.response).error;
alert(“Error while fetching view id” + error.message);
}
}};
req.send();
} catch (e) {
alert(“Error in getViewId” + e.description);
}
}
function executeViewQuery(viewId) {
try {
var clientUrl = Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest()
req.open(“GET”, encodeURI(clientUrl + “/api/data/v8.0/accounts?savedQuery=” + viewId + “”), true);
req.setRequestHeader(“Accept”, “application/json”);
req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
req.setRequestHeader(“OData-MaxVersion”, “4.0”);
req.setRequestHeader(“OData-Version”, “4.0”);
// Include this to get Lookup and Optionset text
req.setRequestHeader(“Prefer”, “odata.include-annotations=OData.Community.Display.V1.FormattedValue”);
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 200) {
var data = JSON.parse(this.response);
var dat = data.value;
for (var i = 0; i < dat.length; i++) {
alert(“Account Name – ” + dat[i].name);
// Read Lookup name (i.e.,Primary Contact)
alert(“Primary Contact – ” + dat[i][‘_primarycontactid_value@OData.Community.Display.V1.FormattedValue’]);
}
}
else {
var error = JSON.parse(this.response).error;
alert(“Error while executing view query” + error.message);
}
}
};
req.send();
} catch (e) {
alert(“Error in getViewId” + e.description);
}
}
The result set would look as below.
How Do I call this method:
- Copy and paste above two functions.
- Pass the ‘System View’ name to executeView({View Name}) function.
// To Retrieve and Execute ‘Active Accounts’ view
executeView(“Active Accounts”);
Note: To use “Personal View”, change the “savedqueries” to “userqueries” in Wab API URI.
Refer MSDN Article for more details.
🙂
Build Auto Complete Text Box using Jscript – CRM 2016
In CRM 2016, we got showAutoComplete and hideAutoComplete methods to configure the auto-completion experience in text controls in forms.
In this article, I am going to configure “Auto Complete” feature for my “Locality” text box on my Account form.
JScript:
function suggestLocality() {
// List of sample Locality names to suggest
accounts = [
{ name: ‘AA Street’, code: ‘A01’ },
{ name: ‘AB Street’, code: ‘A02’ },
{ name: ‘AC Street’, code: ‘A03’ },
{ name: ‘Benetten street’, code: ‘A04’ },
{ name: ‘Beverly Hills’, code: ‘A05’ },
{ name: ‘City Street’, code: ‘A06’ },
{ name: ‘City Power & Light’, code: ‘A07’ },
{ name: ‘Aruna Street’, code: ‘A08’ },
{ name: ‘Winery Street’, code: ‘A09’ },
{ name: ‘Coho Vineyard & Winery’, code: ‘A10’ },
{ name: ‘Zeebra Street.’, code: ‘A11’ }
];var localityKeyPress = function (ext) {
try {
var userInput = Xrm.Page.getControl(“raj_locality”).getValue();
resultSet = {
results: new Array(),
commands: {
id: “sp_commands”,
label: “Explore CRM”, // Help link text
action: function () {
window.open(“http://rajeevpentyala.com”); // Help link URL
}
}
};// Read the ‘Text’ entered in Locality field.
var userInputLowerCase = userInput.toLowerCase();
for (i = 0; i < localities.length; i++) {
if (userInputLowerCase === localities[i].name.substring(0, userInputLowerCase.length).toLowerCase()) {
resultSet.results.push({
id: i,
fields: [accounts[i].name]
//, icon:<url> — Its an option field. You can show icon next to the Auto populated text.
});
}
if (resultSet.results.length >= 10) break;
}if (resultSet.results.length > 0) {
// If matches found; Show the Auto complete text area with matched localitites (i.e., Up to 10)
ext.getEventSource().showAutoComplete(resultSet);
} else {
// If no match found; Hide the Auto complete text area.
ext.getEventSource().hideAutoComplete();
}
} catch (e) {
alert(“Error while auto complete – ” + e.description);
}
};// Attach Key Press event to ‘Locality’ text box
Xrm.Page.getControl(“raj_locality”).addOnKeyPress(localityKeyPress);
}
How do I use it:
- Copy the “suggestLocality” function and create a web resource in CRM.
- Register the “suggestLocality” function on onload event of Account form.
- Publish the Customization’s.
- Open an Account and start typing in “Locality” text box.
- You can extend the script by instead of hard coding Localities, you can read from any existing entity and populate the list.
Important Notes on Auto Complete feature:
- “Auto Complete” show up to 10 matching strings in a drop-down list as users press keys to type character in a specific text field.
- These methods aren’t supported for the CRM mobile clients (phones or tablets).
🙂
Task Flow – CRM 2016
- “Task Flow” is a new feature available with CRM 2016 online update and is currently on preview mode.
- Task flows are targeted for phones or tablets.
- You can configure set of steps, where user perform day to day and package that as a ‘Task Flow’.
- “Task Flows” are somewhat similar to Dialog, which helps User with guided navigation of common tasks, but for Phone and Tablets.
In this article I am going to create a simple ‘Task Flow’ to capture Contact’s address along with a ‘Business Rule’.
Enable the preview feature:
- Task flows are a preview feature in CRM Online 2016 Update. So we need to first enable the feature.
- Go to Settings -> Administration -> System Settings -> Preview
- Agree the License terms and select the preview feature.
- After enabling ‘Task Flow’ feature, you will get a new ‘Business Process Type’, if you choose ‘Business Process Flow’.
Create Task Flow
- Go to Settings -> Processes -> New -> ‘Business Process Flow’
- Select “Business Process Type”, “Run process as a task flow (Mobile only)”
- I selected entity as “Contact”
- I named my Task Flow as “Contact Address Capture Task”
Configure your ‘Task Flow’
- As I want to capture my Contact’s Address details, I configured my ‘Task Flow’ with below fields.
Configure ‘Business Rule’
- I want ‘Phone number’ mandatory, if my Contact does not specify ‘City’.
- So I configured the Business Rule as below
Save and Activate.
Check the ‘Task Flow’ on Mobile client
- Open the ‘Dynamics CRM Application’ on Mobile
- You find an Icon on left corner, which shows all the available ‘Task Flows’
- Click on the Icon and choose the “Contact Address Capture Task”.
- Since “Task Flow” was configured on ‘Contact’ entity, I got ‘Contact’ search screen.
- I picked up the Contact which i want to update the Address details.
- It shows up the fields I configured along with ‘Business Rule’ (‘Phone’ become Required since ‘City’ is blank)
- I provided the details and click ‘Done’ to save the details.
🙂
CRM 2016 – Voice of customer’s survey
Capturing customer feedback is crucial in any Service industry to serve Customer better. In Dynamics CRM, Survey feature was the ask from many customers across the world. It has been addressed in the latest release of CRM 2016.
- “Voice of the Customer survey” is a new feature which is in preview mode, currently available on CRM Online 2016 Update 0.1.
- We can create and send out surveys to get feedback from your customers about your products or services.
- We can capture and store the responses in CRM.
- Respondents can take the surveys on a phone, tablet, or computer.
Below are steps to configure and use Survey feature.
Set up ‘Voice of customer’ in your CRM online
- ‘Voice of customer’ feature comes as solution and need to be installed in CRM online instance.
- Open ‘CRM Online Administration Center’ and click on ‘Solutions’
- From the available list choose ‘Voice of the customer’ solution and click ‘INSTALL’.
Accept the terms & conditions
- After the Installation completes, open the CRM instance.
- Open the solution and on configuration page ‘Accept the condition’ to start using Survey feature.
Configure Survey
- After the solution installation, there will be a ‘Voice of the customer’ tab on sitemap.
- To configure a new ‘Survey’ click on ‘Voice of the Customer -> Surveys’
- There is a pre-built ‘Default Survey Template’ available, where you can use or you can create a new Survey.
- “Survey” form has all the details corresponding to the Survey right from Theme,Logo etc…
- Every Survey record has 3 forms
- Survey: Details of the Survey
- Designer: Where we design the survey with question and answers
- Dashboard: Reports
Design Survey
- Open the ‘Default Survey Template’ and select “Designer” form.
- Drag and drop the available controls to create the Survey.
- In my sample, I created a “Diet Survey” with a question of type “Single Response” and “Rating” control.
- Once the design complete, you can preview and Publish the Survey.
Send the Survey
- Once you Publish the survey, CRM gives you a URL (Anonymous Survey), where it can be forwarded to Customers to capture their feedback.
- Copy and open the URL from ‘Anonymous Link’ and complete the survey
Capture the Survey Response
- Once Customer submitted the response, it will be stored as a record in “Survey Response”.
- More details will be captured about survey in the ‘Survey Response ‘ record.
🙂
CRM 2016 Document Generation – Enable Developer Tab and Add repeated rows in word file
Document Generation is a new feature introduced in CRM 2016. Document Generation simplifies converting your CRM data to either Word or Excel documents.
Below are the steps to
- Download Template
- Configure Template
- Upload Template
- Generate Document.
Download the Document Template
- Navigate to ‘Settings -> Templates’
- Choose ‘Document Templates’
- Click ‘New’ button
- Choose the type of document (Excel\Word) and choose entity
- Select the Related entities, if you want to populate your Document with data from related entities too. I chosen ‘Contact’ in this example.
- Once you download the template you can open and create a template by mapping the fields from CRM.
- But what if you don’t find the ‘Developer’ tab?
Steps to enable ‘Developer’ tab
- Open the word document
- Go to File -> Options -> Customize Ribbon
- Select the ‘Developer’ option and click ‘Ok’
- Once you get ‘Developer’ tab on Word document, choose ‘XML Mapping’ pane and choose “urn:microsoft-crm/…../{entity_name}/1/”
Configure Document Template
- In this example, I am going to configure a Document Template with Account details along with all associated Contacts.
- To add Account Name choose ‘Name’ from ‘XML Mapping’ pane and right click and choose ‘Plain Text’.
- If you have to display multiple rows (i.e., Contacts of an Account record) add a table and map fields from ‘Contact’.
Upload Document Template
- Once you are done with content preparation, save the document and upload back to CRM using ‘UPLOAD TEMPLATE’.
- I name my Document Template with ‘Account_Venilla’.
- We are done with configuring ‘Document Template’. Next step is generate the document from the Entity.
- We can also upload ‘Document Template’ through SDK using ‘DocumentTemplate‘ class.
Document Generation
- Open Account record
- Select ‘Word Templates -> {Document_Template_Name}’
- Download the document and open.
- You would see some thing as below
🙂