Archive

Archive for February, 2012

Using Regular Expression and JScript to validate phone no format

February 27, 2012 Leave a comment

Hi,

I got a requirement to validate a CRM field with “Indian Telephone Number” format (i.e., 040-1234567).

I opted to use regular expression and Jscript for format validation.

Below is the JScript function

function businessPhoneOnChange() {

var telephone = Xrm.Page.data.entity.attributes.get(“telephone1”);

// Regular expression with Indian Telephone format

var regExp= /^[0-9]\d{2,4}-\d{6,8}$/;

if (telephone) {

var phoneNumber = telephone.getValue();

if (phoneNumber.search(regExp) == -1) {

alert(“Invalid Phone number format”);

// Clear the field value

phoneNumber.setValue(“”);

}

}

}

  • Add a webresource with this function to CRM
  • Register “onchange” event of field with the above method
  • Save & Publish

Hope it helps 🙂

Advertisement

Creating OrganizationServiceProxy in CRM2011 custom applications

February 26, 2012 7 comments

Hi,

Below are the steps to instantiate “Organization Service Proxy” which can be used to consume CRM service and perform operations in a  custom application

– Refer “Microsoft.Xrm.Sdk & Microsoft.Xrm.Sdk.Client” .dll’s to your custom application

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Client;

using System.Net.Security;

using System.ServiceModel.Description;

using System.Security.Cryptography.X509Certificates;

private Uri homeRealmUri = null;

private ClientCredentials credentials;

private Uri organizationUri;

private IOrganizationService service;

private OrganizationServiceProxy serviceProxy;

 credentials = new ClientCredentials();

// If CRM On-Premise

// To use custom credentials pass user credentials

credentials.Windows.ClientCredential = new NetworkCredential( {userId},{ password},{ domain} );

// To use Default Credentials; Uncomment below line and comment above

// credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;

// If CRM Online

credentials.UserName.UserName = “Office 365 ID”; // i.e.,  name@domain.onmicrosoft.com

credentials.UserName.Password = “Office 365 Password”;

// Use “https” if CRM is SSL configured

string orgUrl= “http://ServerName/OrganizationName/XRMServices/2011/Organization.svc”;

// Add this line if URL has “https” (i.e.,CRM is SSL configured)

if (!string.IsNullOrEmpty(orgUrl) && orgUrl.Contains(“https”)) {

ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors) { return true; };

}

organizationUri = new Uri(orgUrl);

using (

serviceProxy =

new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null))

{

// To impersonate set the GUID of CRM user here

serviceProxy.CallerId = {GUID of CRM User};

serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

service = serviceProxy;

}

Hope it helps 🙂

Reading Language Code (LCID) in CRM 2011

February 24, 2012 Leave a comment

Hi,

Here is the JScript to get the LCID (Locale Id) of User & Organization Base Language

 

var currUserLcid = Xrm.Page.context.getUserLcid();

var orgLcid= Xrm.Page.context. getOrgLcid();

 

Below is the MSDN link contains list of LCID (Locale Id’s) of CRM 2011

CRM 2011 LCID Chart

 

Hope it helps 🙂

 

Deleting a record using OData & JQuery in CRM 2011

February 20, 2012 Leave a comment

Hi,

Below is the script to delete record using OData & JScript

 

function deleteRecord(id, odataSetName) {

// Get Server URL

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

//The OData end-point

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

//Asynchronous AJAX function to Delete a CRM record using OData

$.ajax({

type: “POST”,

contentType: “application/json; charset=utf-8”,

datatype: “json”,

url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “(guid'” + id + “‘)”,

beforeSend: function (XMLHttpRequest) {

//Specifying this header ensures that the results will be returned as JSON.

XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);

//Specify the HTTP method DELETE to perform a delete operation.

XMLHttpRequest.setRequestHeader(“X-HTTP-Method”, “DELETE”);

},

success: function (data, textStatus, XmlHttpRequest) {

alert(“Record deleted successfully!!!!”);

},

error: function (XmlHttpRequest, textStatus, errorThrown) {

alert(“Error while deletion – “+errorThrown);

}

});

}

 

How Do I call this method :-

    • To delete a “Account” record  set account id & Odata set name and call the above method

var accountId = {}; //Set Account GUID

var odataSeName = “AccountSet”;

deleteRecord(accountId, odataSeName);

 

Hope it helps 🙂

Sending Email using Email Template in CRM 2011

February 19, 2012 2 comments

Hi,

Here is the sample code to send an Email using Email template name.

Before start below are few keywords

  • Template Name   (i.e., Name of the Template)
  • Regarding Id        (i.e., GUID of the entity record which template associated with)
  • Regarding Type   (i.e., Logical name of the entity which template associated with)
  • ActivityParty[]     (i.e., Sender & Receivers Can be Users/Contacts/Accounts/Leads)
  • IOrganizationService crmService

 public void SendEmailUsingTemplate(IOrganizationService crmService,

ActivityParty[] fromParty,  ActivityParty[] toParty,

string templateName,

Guid regardingId, string regardingType)

{

try

{

// Create e-mail message.

var email = new Email

{

To = toParty,

From = fromParty,

DirectionCode = true

};

if (!string.IsNullOrEmpty(templateName))

{

Guid templateId = Guid.Empty;

// Get Template Id by Name

Entity template = GetTemplateByName(crmService, templateName);

if (template != null && template.Id != null)

{

var emailUsingTemplateReq = new SendEmailFromTemplateRequest

{

Target = email.ToEntity<Entity>(),

TemplateId = template.Id,

RegardingId = regardingId,

RegardingType = regardingType

};

var emailUsingTemplateResp = (SendEmailFromTemplateResponse)crmService.Execute(emailUsingTemplateReq);

}

else

{

// “****No email template exists with the given name ****”);

}

}

}

catch (Exception ex)

{

throw;

}

}

     private Entity GetTemplateByName(string title, IOrganizationService crmService)

{

var query = new QueryExpression();

query.EntityName = “template”;

var filter = new FilterExpression();

var condition1 = new ConditionExpression(“title”, ConditionOperator.Equal, new object[] { title });

filter.AddCondition(condition1);

query.Criteria = filter;

EntityCollection allTemplates = crmService.RetrieveMultiple(query);

Entity emailTemplate = null;

if (allTemplates.Entities.Count > 0)            {

emailTemplate = allTemplates.Entities[0];

}

return emailTemplate;

}

How Do I call this method

  • Prepare From and To Users/Contacts/Accounts
  • Pass Service,Template Name,Regarding details

// Prepare “From” activity parties

var from = new ActivityParty

{

PartyId = new EntityReference(SystemUser.EntityLogicalName, {GUID of User})

};

var fromParty = new[] { from };

// Prepare “To” activity parties

var to = new ActivityParty

{

PartyId = new EntityReference(SystemUser.EntityLogicalName, {GUID of User})

};

var toParty = new[] { to };

var orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);

IOrganizationService orgnaizationService = orgProxy;

Guid regardingntityId={GUID of record} // Ex – Guid of contact

string regardingEntityName = “contact” // Logical name ‘contact’

SendEmailUsingTemplate(orgnaizationService , fromParty, toParty, “templateName”, regardingntityId, regardingEntityName);

Hope it helps 🙂

Retrieve record using OData and JQuery in CRM 2011

February 12, 2012 11 comments

Hi,

Below is the script to read a record using OData & JQuery

function retrieveRecord(id, odataSetName) {

// Get Server URL

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

//The OData end-point

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

//Asynchronous AJAX function to Retrieve a CRM record using OData

$.ajax({

type: “GET”,

contentType: “application/json; charset=utf-8”,

datatype: “json”,

url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “(guid'” + id + “‘)”,

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) {

readRecord(data, textStatus, XmlHttpRequest)

},

error: function (XmlHttpRequest, textStatus, errorThrown) {

alert(“Error – ” + errorThrown)

}

});

}

function readRecord(data, textStatus, XmlHttpRequest) {

alert(“Record read successfully!!”);

var account = data;

alert(“Name – ” + account.d.Name);

alert(“Id – ” + account.d.AccountId);

}

How do I call this method :-

  • Below is the sample function to read Account

var accountId = “”; // Assign account GUID

var odataSetName = “AccountSet”;

retrieveRecord(accountId,odataSetName );

Hope it helps 🙂

Reading the GUID of record from CRM form URL

February 9, 2012 2 comments

Hi,

Below are the steps to get the GUID of record from CRM form URL.

  • In the form ribbon, click on Copy a Link button in the Collaborate group.
Copy Link

Copy Link

  • Paste the URL on notepad.
  • The ‘id’ parameter in the copied URL contains the encoded id value for the record.
  • The brackets in the actual GUID “{” and “}” will be substituted with “%7B” and “%7D”, respectively.
    • (i.e., Guid “{899D4FCF-F4D3-E011-9D26-00155DBA3819}”, comes as id=%7b 899D4FCF-F4D3-E011-9D26-00155DBA3819 %7d)

For example, in the below copied URL

http://mycrm/myOrg/main.aspx?etc=4&id=%7b899D4FCF-F4D3-E011-9D26-00155DBA3819%7d&pagetype=entityrecord.

The GUID is-  899D4FCF-F4D3-E011-9D26-00155DBA3819.

Hope it helps 🙂

Using JQuery and Json in Ribbon button’s function handler

February 6, 2012 3 comments

Hi,

  • In one of my CRM 2011 requirement, I had to update a record using ribbon button placed on CRM grid.
  • I had written an update script which calls OData service using Json & JQuery. (link)
  • But when I execute the function, I got “$ undefined” exception.
  • I wondered since I already had “Json.js” & “JQuery.js” web resources added to my entity.
  • After digging deeper, I came to know that, “JQuery.js” web resource is not getting loaded when my ribbon button’s function handler fired.

Fix :-

  • I fixed the problem by loading “JQuery.js” web resource dynamically, before I call my update method.
  • Below is the script to load the web resource’s

    var JScriptWebResourceUrl = “../WebResources/new_JQuery”;

var xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);

xmlHttp.open(“GET”, JScriptWebResourceUrl, false);

xmlHttp.send();

eval(xmlHttp.responseText);

Hope it helps 🙂

Assign record using JScript in CRM 2011

February 4, 2012 7 comments

Hi,

Below is the Jscript to assign a record to particular User using SOAP.

function AssignRecord(Assignee, Target, entityName) {

var request = “<s:Envelope xmlns:s=\”http://schemas.xmlsoap.org/soap/envelope/\”>”;

request += “<s:Body>”;

request += “<Execute xmlns=\”http://schemas.microsoft.com/xrm/2011/Contracts/Services\””;

request += ” xmlns:i=\”http://www.w3.org/2001/XMLSchema-instance\”>”;

request += “<request i:type=\”b:AssignRequest\””;

request += ” xmlns:a=\”http://schemas.microsoft.com/xrm/2011/Contracts\””;

request += ” xmlns:b=\”http://schemas.microsoft.com/crm/2011/Contracts\”>”;

request += “<a:Parameters xmlns:c=\”http://schemas.datacontract.org/2004/07/System.Collections.Generic\”>”;

request += “<a:KeyValuePairOfstringanyType>”;

request += “<c:key>Target</c:key>”;

request += “<c:value i:type=\”a:EntityReference\”>”;

request += “<a:Id>” + Target + “</a:Id>”;

request += “<a:LogicalName>” + entityName + “</a:LogicalName>”;

request += “<a:Name i:nil=\”true\” />”;

request += “</c:value>”;

request += “</a:KeyValuePairOfstringanyType>”;

request += “<a:KeyValuePairOfstringanyType>”;

request += “<c:key>Assignee</c:key>”;

request += “<c:value i:type=\”a:EntityReference\”>”;

request += “<a:Id>” + Assignee + “</a:Id>”;

request += “<a:LogicalName>systemuser</a:LogicalName>”;

request += “<a:Name i:nil=\”true\” />”;

request += “</c:value>”;

request += “</a:KeyValuePairOfstringanyType>”;

request += “</a:Parameters>”;

request += “<a:RequestId i:nil=\”true\” />”;

request += “<a:RequestName>Assign</a:RequestName>”;

request += “</request>”;

request += “</Execute>”;

request += “</s:Body>”;

request += “</s:Envelope>”;

// Get server URL

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

var req = new XMLHttpRequest();

req.open(“POST”, serverUrl, 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&#8221;);

req.onreadystatechange = function () { assignResponse(req); };

req.send(request);

}

// This function gets called after the execution

function assignResponse(req) {

if (req.readyState == 4) {

if (req.status == 200) {

alert(“Success !!!”);

}

else {

alert(“Error – ” + req.responseXML);

}

}

}

How Do I Call this function :-

  • Pass User Id, Record Id and Entity name to the function

var userId = “”      // GUID of user whome to assign the record

var recordId = “”      // GUID of record you want to assign

var entityName = “”  // Entity name the record

AssignRecord(userId,recordId,entityName);

Hope it helps 🙂