Archive
Create record using OData and JQuery in CRM 2011
Hi,
Below is the code snippet to create a record (i.e., Account) using OData & JQuery.
//Prepare ‘Account’ object and call create function
function createAccount() {
//Create an object to represent an Account record and set properties
var account = new Object();
// Set text field
account.Name = “Rajeev Pentyala”;
// Set Lookup field (Contact should exists in the system)
var primaryContact = new Object();
primaryContact.ContactId = “”;
primaryContact.FullName = “”;
// if (primaryContact != null) {
// account.PrimaryContactId = { Id: primaryContact.ContactId, LogicalName: “contact”, Name: primaryContact.FullName };
// }
//Set a picklist value
account.PreferredContactMethodCode = { Value: 2 };
// Set a money value (i.e., Annual Revenue)
account.Revenue = { Value: “2000000.00” };
// Set a Decimal field (Here ‘new_DecimalField’ is my custom Account field)
account.new_DecimalField = 200.00.toString();
// Set a Boolean value
account.DoNotPhone = true;
// Set Date field (Here ‘new_DateField’ is my custom Account field)
var myDate = new Date();
myDate.setFullYear(1980, 12, 29);
account.new_DateField= myDate;
// Call create method by passing
// (i) Entity Object (i.e.,account in this case)
//(ii) Entity Set
//(iii)SuccessCallback function
// (iv) Error callback function
createRecord(account, “AccountSet”, createAccountCompleted, null);
}
// This callback method executes on succesful account creation
function createAccountCompleted(data, textStatus, XmlHttpRequest) {
var account = data;
alert(“Account created; Id: ” + account.AccountId.toString());
}
// This function creates record by making OData call
function createRecord(entityObject, odataSetName, successCallback, errorCallback) {
//Parse the entity object into JSON
var jsonEntity = window.JSON.stringify(entityObject);
// Get Server URL
var serverUrl = Xrm.Page.context.getServerUrl();
//The OData end-point
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
//Asynchronous AJAX function to Create a CRM record using OData
$.ajax({
type: “POST”,
contentType: “application/json; charset=utf-8”,
datatype: “json”,
url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
},
success: function (data, textStatus, XmlHttpRequest) {
if (successCallback) {
successCallback(data.d, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
alert(“Error on the creation of record; Error – “+errorThrown);
}
});
}
How do I call this method :-
- Create a new .jscript file (i.e., “account.js”)
- Copy & Paste above code
- Add “account.js” as a webresource in CRM
- Add “Json2.js” & “jquery1.4.1.min.js” helper script files as webresources
- You can get the helper files from CRM 2011 SDk under path “\sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts”
- Add “createAccount” function to form load method (Refer below)
- Save & Publish
- Open any account record and on loading of record our script fires and it creates new account name “Rajeev Pentyala”
Hope it helps 🙂
Reading Querystring using Jscript
Hi,
Below is the Jscript function to parse query string (i.e., In to Parameter & Value pair)
// Read querystring and returns Parameter & Value pair Array
function fetchQueryStringParams() {
var qrStr = window.location.search;
var spQrStr = qrStr.substring(1);
var arrQrStr = new Array();
// splits each of pair
var arr = spQrStr.split(‘&’);
for (var i = 0; i < arr.length; i++) {
// splits each of field-value pair
var index = arr[i].indexOf(‘=’);
var key = arr[i].substring(0, index);
var val = arr[i].substring(index + 1);
// saves each of field-value pair in an array variable
arrQrStr[key] = val;
}
return arrQrStr;
}
How do I call this method?
- Suppose you have URl with 2 query string parameters (fname & lname)
- Call the above method in Page “Onload()” Jscript event.
function onload() {
var arrQrStr = fetchQueryStringParams();
alert(“First Name” + arrQrStr[‘fname’]);
alert(“Last Name” + arrQrStr[‘lname’]);
}
Hope it helps 🙂
You must use the Role Management Tool to install .Net Framework Exception
Hi,
Today I got below error screen when I try to install .Net 3.5 Framework SP1 on my WIN 2008 R2 server .
Reason :-
- Windows 2008 R2 natively ships with the .NET 3.5 SP1 framework.
- So, it wont allow us to run the .Net 3.5 framework setup file.
Workaround :-
- As Windows 2008 R2 ships with the .NET 3.5 SP1, We just need to enable the feature from “Server Manager“.
Steps to enable feature on Server Manager :-
- Click on “Start” button and type keyword “Server”
- Double click on “Server Manager” link
- On the “Server Manager” window, Choose “Features -> Add Features”
- Check the “Dotnet Frameowrk 3.5.1 Features” check box
- Restart the server
Hope it helps 🙂
Fetching user security roles using Linq in CRM 2011 Plug-in’s
Hi,
Below is the sample code to fetch the User’s security roles based on the “User Id” in the Plug-in’s using Linq
/// <summary>
/// Returns the list of User security role names
/// </summary>
private List<string> GetUserRoles(IOrganizationService service, Guid userId) {
// Create Query Expression to fetch Role Entity
var query = new QueryExpression
{
// Setting the link entity condition and filter condition criteria/
LinkEntities =
{
new LinkEntity
{
LinkFromEntityName = “role”,
LinkFromAttributeName = “roleid”,
LinkToEntityName = “systemuserroles”,
LinkToAttributeName = “roleid”,
LinkCriteria = new FilterExpression
{
FilterOperator =
LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = “systemuserid”,
Operator = ConditionOperator.Equal,
Values =
{
userId
}
}
}
}
}
},
ColumnSet = new ColumnSet(true),
EntityName = “role”
};
// Obtain results from the query expression.
var userRoles = service.RetrieveMultiple(query);
// Get the usre role names collection
var roleNames = new List<string>();
if (userRoles != null) {
roleNames.AddRange(
from entrole in userRoles.Entities
select entrole as Role
into role
where role != null && role.RoleId != null
select role.Name);
}
return roleNames;
}
How do I call this method :-
- In your plug-in, pass the service and User Id as parameters to this method
public void Execute(IServiceProvider serviceProvider) {
context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(context.UserId);
// Get the current users Security Roles Name’s
Var roleNames = GetUserRoles(service, this.context.UserId);
}
Hope it helps 🙂
Setting default view using Plug-in’s in CRM 2011
Hi,
We often get the requirement to set a default view based on some criteria (Ex – Could be based on logged in user role, etc…). We can achieve this using a Plug-in.
Little insight :-
- When you click on an entity (i.e., ‘Contacts’ in my sample) in CRM application, In the background a “RetreieveMultiple” method call happens on “savedquery” entity.
- “savedquery” is a system entity in CRM which stores the meta data of all the views in the system
Plug-in Logic :-
- We register a Plug-in for the RetreieveMultiple message on the savedquery entity to be executed in the post stage
- From “Outputparameters” fetch the “BusinessEntityCollection” (i.e., Views of particular entity)
- Loop through the views and set “isdefault” property to “true” for the desired view
– Below is the sample code
public void Execute(IServiceProvider serviceProvider)
{
this.context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(this.context.UserId);
if (this.context.InputParameters.Contains(“Query”) && this.context.InputParameters[“Query”] is QueryExpression && this.context.Stage == 40){
var qe = (QueryExpression)this.context.InputParameters[“Query”];
if (qe.Criteria != null) {
var condition = (ConditionExpression)qe.Criteria.Conditions[1];
// “Type code” of entity you want default views ( Object type code of ‘contact’ is 2)
// Refer Useful article on how to get “Object Type Code”
if (condition.Values[0].Equals(2)) {
// Name of the view you want to set as Default
string ourDefaultView = “My custom view – Contacts”;
if (!string.IsNullOrEmpty(ourDefaultView)){
var collection = (EntityCollection)this.context.OutputParameters[“BusinessEntityCollection”];
collection = ChangeViewCollection(ourDefaultView, collection);
this.context.OutputParameters[“BusinessEntityCollection”] = collection;
}
}
}}}
/// <summary>
/// Setting IsDefault property of views
/// </summary>
private EntityCollection ChangeViewCollection(string ourDefaultViewName, EntityCollection records){
foreach (Entity record in records.Entities){
string viewName = (string)record[“name”];
if (viewName.Equals(ourDefaultViewName)){
record[“isdefault”] = new bool();
record[“isdefault”] = true;
}
else {
record[“isdefault”] = new bool();
record[“isdefault”] = false;
}
}
return records;
}
Plug-in Registration Steps :-
Message Name – RetrieveMultiple
Entity – SavedQuery
Stage – post
- Register the assembly & Refresh the CRM application
@@ 🙂 Here goes my 50th article. Thanks for all your visits and valuable comments 🙂 @@
How to Debug Plug-Ins in CRM
Hi,
Sometimes you might get wonder (even frustrated) why the debugger is not hitting the break point in your Plug-In code file.
Below are the Checklist to perform prior to start the debugging of your Plug-in assembly.
- Ensure that your plug-in assembly is signed (See)
- Rebuild the plug-in assembly
- Reset the IIS (i.e. Open command prompt and run ‘iisreset’ command)
- Restart CRM Asynchronous Service on CRM server (Only in case of asynchronous plug-in or Custom workflow )
- Copy the .pdb file and your .dll file to server’s assembly (i.e., ..\Program Files\Microsoft Dynamics CRM\Server\bin\assembly)
- Open the Plug-in Registration Tool (Download)
- Browse the dll from your Plug-Ins projects “bin\debug” folder
- In Plug-in Registration Tool , Choose “Specify the location where assembly should be stored” option as “Disk”
- Register the step
- Register the image(s) if any
- Attach the process by opening the Plug-in project in the Visual Studio and then
- From menu choose “Debug -> Attach to Process…” ( or Click ‘Alt + Ctrl + P’)
- Select w3wp.exe (i.e.,Worker Process), if plug-in is Synchronous
- Select CRMAsyncService.exe, if Plug-in is asynchronous or Custom workflow.
- You are all set by now and put a break point (Click F9) on relevant code line.
In case of Remote Debugger :-
- If your CRM server machine is different from your development machine
- Install “Visual Studio Remote Debugger” (Download) on CRM server machine
- Run it as “Administrator”
- Follow the same steps above except while attaching Process, in the “Attach to Process” window, set “Qualifier” as “CRM server machine”
Debug plug-in in outlook offline mode
- Clean and rebuild the plug-in solution on your machine using visual studio
- Register the plugin on the server
- Synchronize the organization with the outlook
- Go Offline
- Attach the debugger to the process “Microsoft.Crm.Application.Hoster.exe”
- Place a breakpoint in the code.
- Run the scenario
Hope it helps 🙂
Auto numbering logic in CRM 2011
Hi,
Auto numbering feature is one of the most frequently asked requirement in CRM projects and below is the sample.
In my sample, I am going to generate an auto number to the each ‘Contact’ that create under a particular ‘Account’. The auto number format will be “Contact – 001, Contact – 002,….”.
To achieve the above requirement, I am going to
- Create a Plug-In on “Pre – Create” event of the contact
- Use the CRM early bound
Steps :-
- Generate “Organization Service Context Class” using the Code Generation Tool (CrmSvcUtil.exe). (See)
- You will get a “ServiceContext.cs” file with all entity wrapper classes.
- Create a new Plug-In project and add the generated “ServiceContext.cs” file
- Add a new class “ContactAutoNumber.cs” to the project and paste below code
public class ContactAutoNumber: IPlugin {
private Entity dynEntity;
private contact objContact;
public void Execute(IServiceProvider serviceProvider) {
this.context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(this.context.UserId);
if (this.context.InputParameters.Contains(“Target”) && this.context.InputParameters[“Target”] isEntity) {
// Obtain the target entity from the input parmameters.
this.dynEntity = (Entity)this.context.InputParameters[“Target”];
// Cast “Dynamic Entity” to “Contact”
this.objContact = this.dynEntity.ToEntity<contact>();
}
// Instantiate “Service Context” (i.e., The name of ‘Organization Service Context Class’)
var svcContext = new ServiceContext(service);
// Get the “Contact” list under parent ‘Account’ by “AccountId”
var contacts = svcContext.ContactSet.Where(
ns => (ns.AccountId.Id ==this.objContact.AccountId.Id));
// Get the count of the contacts
var cntContacts= Enumerable.Count(contacts);
// Increment the suffix count
var strFormat = (cntContacts + 1).ToString();
// Logic to prepare format “001,002,…..”
if (strFormat.Length < 3){
strFormat = (strFormat.Length == 1) ?
“00” + strFormat : “0” + strFormat;
}
// Set the auto number to your attribute
this.objContact.{Attribute_Name}= “contact – “ + strFormat;
}
}
}
Plug – In Registration step :-
Message : Create
Entity : contact
Statge : Pre
- Register the Plug -in as above mentioned
Hope it helps 🙂
Entities display area not getting set on Solution Import in CRM 2011
Hi,
Please observe below scenario
- In my CRM organization “ORG – A
- I Created a new custom entity “new_city” and I set “Area to display” as “Workplace”.
- I created a new “Managed” solution “Sol – I” having the custom entity “new_city”
- Now In my Organization “ORG – B”, I imported the solution “Sol – I” successfully.
Issue I Faced :-
- After solution import, to my surprise I don’t see entity “new_city” under “Workplace” area
- To dig more, When I open “new_city” entitie’s customization form , all the options under “Area to display” are unchecked.
- Since the solution was “Managed” I can’t select the “Area to display” option manually.
Fix :-
- While making the solution, Include “Sitemap component” under Client extensions
Hope it helps 🙂
Bulk Updating or Inserting records from Excel using CRM Data Import
Hi,
In CRM, you may come across scenarios where you need to Update/Insert a very large number of records very quickly. In these cases, opening each record’s form to make the change can be time-consuming.
We can handle this better by using CRM Data Import feature by which we can make bulk Update/Insert very quickly.
Below are the steps to achieve this. I am using ‘Contact’ entity for this article.
Steps :-
- Navigate to ‘Contact’ entity
- Click on “Export to Excel” button in the Ribbon menu
- In the “Export Data to Excel” dialog box which comes up, Select “Static worksheet with records” and check the “Make this data available…” check box.
- Save the file
- Open the Excel file and it looks as below
Important Points :-
* This Excel file has some unique characteristics which simplifies the data entry and re-import process.
* As you click on each cell, you will notice a pop-up that tells you format of the data and whether the field is required or not.
* Required fields are not enforced in Excel (i.e., Excel won’t validate even if you miss the value in required cell).
* If you miss a value in required field cell, the record wont be updated in the import process.
* You can enter “Lookup” values also, but the values must match with parent record.
For example, In this Excel “Parent Customer” cell is a lookup to the “Account” entity. So i need to give “Account” full name in the cell.
* If any wrong data entry in the lookup cell, the record will not be updated on import
- In the imported Excel (Above screen), If you observe, I don’t have “Middle Name” for any of my contacts. So I am giving middle name as “Updated” (Below screen)
- Next, I want to insert a new record “Rajeev Pentyala” to my contacts.
Important Point :-
– We can create new records by entering them in the bottom of Excel. (***Be sure to fill all required fields ***).
- So, In my last row of Excel, I enter “First Name”,”Last Name” ,”Email”,”Parent Customer” (i.e.,Valid full name of existing Account)
- Save the Excel file. (Ignore the warning and continue saving)
- In the CRM, Click on “Import Data” button in the Ribbon
- In the dialog window browse the saved file
- Click “Next” button
- In the next window, click on “Submit” button
- Refresh the CRM application
- Now you can see the newly inserted contact “Rajeev Pentyala” with the given values in Excel
- You can also verify the remaining contacts with the updated “Middle Name”
- This is how we handle “Data import” process
Tip :-
- To verify your import finished successfully or any problems with it.
- Navigate to “Settings -> Data Management -> Imports”
This article provides you a basic knowledge about Data import from Excel.
Hope it helps 🙂
“The context is not currently tracking the entity” exception in CRM 2011
Hi,
You may come across below exception when you are trying to Create/Update child record in the Parent record context of Plug-in using XRM Linq
Scenario :-
- Imagine you have registered a “Post Update” Plug-in on ‘Account’ entity which Updates an associated ‘Contact’ entity
- Here the Plug-in runs under Parent Entity Context (i.e., Account)
- When you try to update child record (i.e.,Contact) it throws out exception, since the context knows nothing about ‘Contact’
Fix :-
- The solution is call the context.Attach() method; Call this method before calling the Update method (Refer below code)
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
var ServiceContext=
new
XrmServiceContext(service);
Guid contactGUID= (from c in xrm.ContactSet where c.FullName == “Farest Chand” select c.Id).FirstOrDefault();
ServiceContext.Contact objContact= new ServiceContext.Contact { Id = contactGUID, FullName= ‘Rajeev’};
ServiceContext.ClearChanges();
ServiceContext.Attach(objContact);
ServiceContext.UpdateObject(objContact);
ServiceContext.SaveChanges();
Hope it Helps 🙂