Multi Option Set / Picklist in CRM 2011 / 13 / 15 using Javascript

50th Article

Yes it is my 50th Article in WordPress. Hope you all like my articles.

Please provide your valuable comments on my articles to improve further.

Happy New Year to all my blog viewers.

Task: Create a Multi Option Set in contact, for the OptionSet below

OptionSet Values

Solution: Follow the below steps to select multi Option Set / Picklist values in CRM,

Step 1: Create below fields in Contact form,

50 - Field Schema Names

50 - Option Set Field

50 - Option Set Field Values

Step 2: Place the 2 fields on the required place on contact form, and uncheck Visible by default for “Sport Option Set Values” field.

50 - Form Properties - Option Set Field Values

Step 3: Create Javascript Webresource “new_multiPickList”. Open Text Editor, Copy & Paste the below Code

// Method to convert an optionset to multi select OptionSet
function ConvertToMultiSelect(var_sc_optionset, var_sc_optionsetvalue) {
var optionSetObj = Xrm.Page.getAttribute(var_sc_optionset);
if (optionSetObj != null) {
var options = optionSetObj.getOptions();
if (options != null) {
document.getElementById(var_sc_optionset).style.display = “none”;

// Create a DIV container

var addDiv = document.createElement(“div”);
addDiv.id = var_sc_optionsetvalue + “_m”;
addDiv.style.width = “100%”;
addDiv.style.height = “80px”;
addDiv.style.background = “#ffffff”;
addDiv.style.color = “white”;
addDiv.style.overflow = “auto”;
addDiv.style.border = “1px #6699cc solid”;

document.getElementById(var_sc_optionset).parentNode.appendChild(addDiv);

// Declaration of variables will be used in the loop depending upon the browser

var initialValue = 0,
maxValue = 0,
nAgt = navigator.userAgent;

if (nAgt.indexOf(“Firefox”) != -1) { // If the broswer is “Firefox”
initialValue = 1;
maxValue = options.length;
}
else if (nAgt.indexOf(“Chrome”) != -1 || nAgt.indexOf(“IE”) != -1) { // If the browser is Chrome or IE
initialValue = 0;
maxValue = options.length – 1;
}
else if (nAgt.indexOf(“Safari”) != -1) { // If the browser is “Safari”
initialValue = 1;
maxValue = options.length;
}

// Initialize checkbox controls

for (var i = initialValue; i < maxValue; i++) {
var pOption = options[i];
if (!IsChecked(pOption.value, var_sc_optionsetvalue)) {
var addInput = document.createElement(“input”);
addInput.type = “checkbox”;
addInput.style.border = “none”;
addInput.style.width = “25px”;
addInput.style.align = “left”;
addInput.style.color = “#000000”;
addInput.onclick = function() {
OnSave(var_sc_optionset, var_sc_optionsetvalue);
createTable(var_sc_optionsetvalue);
}
} else {
var addInput = document.createElement(“input”);
addInput.type = “checkbox”;
addInput.checked = true;
addInput.setAttribute(“checked”, true);
addInput.checked = “checked”;
addInput.defaultChecked = true;
addInput.style.border = “none”;
addInput.style.width = “25px”;
addInput.style.align = “left”;
addInput.style.color = “#000000”;
addInput.onclick = function() {
OnSave(var_sc_optionset, var_sc_optionsetvalue);
createTable(var_sc_optionsetvalue);
}
}

//Create Label

var addLabel = document.createElement(“label”);
addLabel.style.color = “#000000”;
addLabel.innerHTML = pOption.text;
var addBr = document.createElement(“br”); // it’s a ‘br’ flag

document.getElementById(var_sc_optionset).nextSibling.appendChild(addInput);
document.getElementById(var_sc_optionset).nextSibling.appendChild(addLabel);
document.getElementById(var_sc_optionset).nextSibling.appendChild(addBr);
}
}
}
}

// Check if it is selected function IsChecked(pText, optionSetValue) {

var selectedValue = Xrm.Page.getAttribute(optionSetValue).getValue();
if (selectedValue != “” && selectedValue != null) {
var OSVT = selectedValue.split(“,”);
for (var i = 0; i < OSVT.length; i++) {
if (OSVT[i] == pText)
return true;
}
}
return false;
}

// var_sc_optionsetvalue >> Provide logical-name for field which will

//                         store the multi selected values for Option Set

// optionSet>> Provide logical-name of Option Set field

function OnSave(optionSet, var_sc_optionsetvalue) {
var OS = document.getElementById(optionSet),
options = Xrm.Page.getAttribute(optionSet).getOptions(),
getInput = OS.nextSibling.getElementsByTagName(“input”),
result = “”,
result1 = “”;

var nAgt = navigator.userAgent;

for (var i = 0; i < getInput.length; i++) {
if (getInput[i].checked) {
result += getInput[i].nextSibling.innerHTML + “,”;
if (nAgt.indexOf(“Firefox”) != -1) { //If the broswer is “Firefox”
result1 += options[i + 1].value + “,”;
}
else if (nAgt.indexOf(“Chrome”) != -1 || nAgt.indexOf(“IE”) != -1) { //If the browser is Chrome or IE
result1 += options[i].value + “,”;
}
else if (nAgt.indexOf(“Safari”) != -1) { //If the browser is “Safari”
result1 += options[i + 1].value + “,”;
}
}
}

//save value
Xrm.Page.getAttribute(var_sc_optionsetvalue).setValue(result1);
}

// var_sc_optionsetvalue >> Provide logical-name for field which will
//                         store the multi selected values for Option Set

function createTable(var_sc_optionsetvalue) {    // Get OptionSet value

var OptionValue = Xrm.Page.getAttribute(var_sc_optionsetvalue),
c_OptionValue = Xrm.Page.getControl(var_sc_optionsetvalue),
d_OptionValue = var_sc_optionsetvalue + “_d”;

if (OptionValue.getValue() != null) {

var OptionValueHtml = “<div style=\”overflow-y:auto;width:100%;display: none; min-height: 5em; max-height: 1000px;\”>”,
OptionValueHtml += “<table style=’width:100%;height: 100%;’>”,
OptionValueV = OptionValue.getValue(),
OptionValueT = OptionValueV.split(“,”),
cols = 0;

for (var row = 0; row < OptionValueT.length – 1; row++) {
OptionValueHtml += “<tr style=’height:20px;’>”;
for (var i = cols; i < cols + 3; i++) {
OptionValueHtml += “<td style=’width:33%;’>”;
if (OptionValueT[i] != null || OptionValueT[i] != undefined) {
OptionValueHtml += OptionValueT[i];
}
OptionValueHtml += “</td>”;
}

cols = cols + 3;
OptionValueHtml += “</tr>”;
if (cols >= OptionValueT.length) {
break;
}
}

OptionValueHtml += “</table>”;
OptionValueHtml += “</div>”;
document.getElementById(d_OptionValue).innerHTML = OptionValueHtml;
}
}

Step 4: Open Contact Form -> Form Properties.

Add the webresource “new_multiPickList” on Contact Form.

Select Library “new_multiPickList” and provide the function name “ConvertToMultiSelect” on “OnLoad” Event.

Provide the parameters “new_favouritesport“, “new_sportoptionsetsvalues“.

50 - OnLoad

Step 5: Select Library “new_multiPickList” and provide the function name “OnSave” on OnSave Event.

Provide the parameters “new_favouritesport“, “new_sportoptionsetsvalues“.

50 - OnSave

Step 6: Save & Publish Contact Form. Open any CRM record to see the below Output,

Download JavaScript Code

Sources:

http://slalomdotcom.wordpress.com/2011/05/23/multi-select-option-sets-in-dynamics-crm/

http://mscrmmindfire.wordpress.com/2014/01/30/crm-2013-multi-pick-list-2/

How to setup Unified Service Desk (USD)

CRM Unified Service Desk Startup

Viharayan

Hi everyone, so today ,we are going to discuss ,how to setup USD.:-

1) First of all u should have your on-premise or CRM online trial account.

For Downloading USD agent ,Go to the link http://www.microsoft.com/en-nz/download/details.aspx?id=43110
2) Download the file squared with red color and we have to select either one of green circled file . If your computer is of 32 bit then download i386.exe ,otherwise download amd64.exe for 64 bit machine.

usd

3)Run either i386 or amd64. For this case i am running amd64.exe and got below screen

usd2

4) Make a new folder and click “OK”. Here  I created a folder “usd”.

usd3

5) Now , after finishing this,  start package deployer, tick and continue.

usd4

6) Repeat step 3 and 4

7) click Continue.

usd5

8) Most important step.Select appropriate Deployment type ,for example, if you are using CRM online choose “office 365” . If you have more than one organisation…

View original post 239 more words

Create Email using CRM SDK and C#

Follow the below steps to create a simple Email record in Console application,

Step 1: Open Visual Studio and Create Console Application Project.

Step 2: First we have to establish connection to CRM. Please follow my earlier post Connect to CRM Online or On-premise using C# SDK.

Step 3: Generate Early bound class using Crmsvcutil.exe. Please follow my earlier post Generate Early bound Class using CrmSvcUtil.Exe in CRM.

Step 4: Add EarlyBound.cs to the project.

Step 5: Include the namespace using EarlyBound.cs.

Step 6: Below method will create Email record,

Create Email - Parameter Description

public static void SendEmail(Guid From, Guid To, string ToEntitySchemaName, string Subject, string Description)
{
try
{
// Create 'From' activity party for the email

ActivityParty fromParty = new ActivityParty
{
PartyId = new EntityReference(SystemUser.EntityLogicalName, From)
};

// Create 'To' activity party for the email

ActivityParty toParty = new ActivityParty
{
PartyId = new EntityReference(ToEntitySchemaName, To)
};

// Create an e-mail message

Email email = new Email
{
To = new ActivityParty[] { toParty },
From = new ActivityParty[] { fromParty },
Subject = Subject,
Description = Description,
DirectionCode = true
};

Guid _emailId = _service.Create(email);

SendEmailRequest sendEmailreq = new SendEmailRequest
{
EmailId = _emailId,
TrackingToken = "",
IssueSend = true
};

SendEmailResponse sendEmailresp = (SendEmailResponse)_service.Execute(sendEmailreq);

if (sendEmailresp != null)
{
Console.WriteLine("Email record created successfully");
Console.ReadKey();
}
}
catch(Exception ex)
{
Console.Write("Error " + ex.Message);
Console.ReadKey();
}
}

Step 7: Final Code will be like below,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
using EarlyBound;

namespace LinqToCRM
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
ConnectToMSCRM("arunpotti@XYZOrg.onmicrosoft.com", "password", "https://XYZOrg.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");

Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;

if (userid == Guid.Empty) return;

Contact c = new Contact() //Create Contact Record
{
FirstName = "Arvind Kumar",
LastName = "Shah",
MobilePhone = "9876543210",
EMailAddress1 = "arvindshah@crm2015trial.com"
};

Guid contactGuid = _service.Create(c);

if (contactGuid != Guid.Empty)
{
SendEmail(userid, contactGuid, "contact", "Test Subject", "Test Description");
}
}

public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;
}
catch (Exception ex)
{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();
}
}

public static void SendEmail(Guid From, Guid To, string ToEntitySchemaName, string Subject, string Description)
{
try
{
// Create 'From' activity party for the email

ActivityParty fromParty = new ActivityParty
{
PartyId = new EntityReference(SystemUser.EntityLogicalName, From)
};

// Create 'To' activity party for the email

ActivityParty toParty = new ActivityParty
{
PartyId = new EntityReference(ToEntitySchemaName, To)
};

// Create an e-mail message

Email email = new Email
{
To = new ActivityParty[] { toParty },
From = new ActivityParty[] { fromParty },
Subject = Subject,
Description = Description,
DirectionCode = true
};

Guid _emailId = _service.Create(email);

SendEmailRequest sendEmailreq = new SendEmailRequest
{
EmailId = _emailId,
TrackingToken = "",
IssueSend = true
};

SendEmailResponse sendEmailresp = (SendEmailResponse)_service.Execute(sendEmailreq);

if (sendEmailresp != null)
{
Console.WriteLine("Email record created successfully");
Console.ReadKey();
}
}

catch(Exception ex)
{
Console.Write("Error " + ex.Message);
Console.ReadKey();
}
}
}
}

Step 8: Execute the project for the below output, Open CRM and check for the email record

Create Email - Output

Please provide your valuable comments on this article.

Delete Contact record using Early Bound and LINQ in CRM

Task: Delete Contact record where Full Name = “Arun Potti”

Solution: Follow the below steps,

Step 1: Open Visual Studio and Create Console Application Project.

Step 2: First we have to establish connection to CRM. Please follow my earlier post Connect to CRM Online or On-premise using C# SDK.

Step 3: Generate Early bound class using Crmsvcutil.exe. Please follow my earlier post Generate Early bound Class using CrmSvcUtil.Exe in CRM.

Step 4: Add EarlyBound.cs to the project.

Step 5: Include the namespace using EarlyBound.cs.

Step 6: Below method will delete Contact record,

deleteContactRecord("Arun Potti");
public static void deleteContactRecord(string fullname)
       {
           using (var context = new ServiceContext(_service))
           {
               Contact conRecord = context.ContactSet.FirstOrDefault(c => c.FullName == fullName);
               if (conRecord != null)
               {
                   context.DeleteObject(conRecord);
                   if (context.SaveChanges().Count > 0)
                  {
                       Console.WriteLine("Record deleted Successfully");
                       Console.ReadKey();
                   }
               }
           }
       }

Step 7: Final Code will be like below,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
using EarlyBound;
namespace LinqToCRM
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
ConnectToMSCRM("arunpotti@MyOrg.onmicrosoft.com", "Password", "https://MyOrg.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
if (userid == Guid.Empty) return;
deleteContactRecord("Arun Potti");
}
public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;
}
catch (Exception ex)
{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();
}
}
public static void deleteContactRecord(string fullName)
{
using (var context = new ServiceContext(_service))
{
Contact conRecord = context.ContactSet.FirstOrDefault(c => c.FullName == fullName);
if (conRecord != null)
{
context.DeleteObject(conRecord);
if (context.SaveChanges().Count > 0)
{
Console.WriteLine("Record deleted Successfully");
Console.ReadKey();
}
}
}
}
}
}

Step 8: Execute the project for the below output,

LinqToCrm Delete Output

Please provide your valuable comments on this article.

Update Contact record using Early Bound and LINQ in CRM

Task: Update Mobile Phone for Contact record where Full Name = “Arun Potti”

Solution: Follow the below steps,

Step 1: Open Visual Studio and Create Console Application Project.

Step 2: First we have to establish connection to CRM. Please follow my earlier post Connect to CRM Online or On-premise using C# SDK.

Step 3: Generate Early bound class using Crmsvcutil.exe. Please follow my earlier post Generate Early bound Class using CrmSvcUtil.Exe in CRM.

Step 4: Add EarlyBound.cs to the project.

Step 5: Include the namespace using EarlyBound.cs.

Step 6: Below method will update Contact record,

updateContactRecord("1234567890");
      public static void updateContactRecord(string phoneNumber)
       {
           using (var context = new ServiceContext(_service))
           {
               Contact conRecord = context.ContactSet.FirstOrDefault(c => c.FullName == "Arun Potti");
               if (conRecord != null)
               {
                   conRecord.MobilePhone = phoneNumber;
                   context.UpdateObject(conRecord);
                   if (context.SaveChanges().Count > 0)
                   {
                       Console.WriteLine("Record Updated Successfully");
                       Console.ReadKey();
                   }
               }
           }
       }

Step 7: Final Code will be like below, 

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
using EarlyBound;
namespace LinqToCRM
{
   class Program
   {
       static IOrganizationService _service;
       static void Main(string[] args)
       {
           ConnectToMSCRM("arunpotti@MyOrg.onmicrosoft.com", "Password", "https://MyOrg.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");
           Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
           if (userid == Guid.Empty) return;
           updateContactRecord("1234567890");
       }
       public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
       {
           try
           {
               ClientCredentials credentials = new ClientCredentials();
               credentials.UserName.UserName = UserName;
               credentials.UserName.Password = Password;
               Uri serviceUri = new Uri(SoapOrgServiceUri);
               OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
               proxy.EnableProxyTypes();
               _service = (IOrganizationService)proxy;
           }
           catch (Exception ex)
           {
               Console.WriteLine("Error while connecting to CRM " + ex.Message);
               Console.ReadKey();
           }
       }
       public static void updateContactRecord(string phoneNumber)
       {
           using (var context = new ServiceContext(_service))
           {
               Contact conRecord = context.ContactSet.FirstOrDefault(c => c.FullName == "Arun Potti");
               if (conRecord != null)
               {
                   conRecord.MobilePhone = phoneNumber;
                   context.UpdateObject(conRecord);
                   if (context.SaveChanges().Count > 0)
                   {
                       Console.WriteLine("Record Updated Successfully");
                       Console.ReadKey();
                   }
               }
           }
       }
   }
}

Step 8: Execute the project for the below output,

LinqToCrm Update Output

Please provide your valuable comments on this article.

Create record using Early Bound and LINQ in CRM

Task: Create Contact record

Solution: Follow the below steps,

Step 1: Open Visual Studio and Create Console Application Project.

Step 2: First we have to establish connection to CRM. Please follow my earlier post Connect to CRM Online or On-premise using C# SDK.

Step 3: Generate Early bound class using Crmsvcutil.exe. Please follow my earlier post Generate Early bound Class using CrmSvcUtil.Exe in CRM.

Step 4: Add EarlyBound.cs to the project.

Step 5: Include the namespace using EarlyBound.cs.

Step 6: Below method will create Contact record,

createContactRecord("Arun", "Potti", "9876543210", "arunpotti@xyzorg.com");

public static void createContactRecord(string firstName, string lastName, string mobileNumber, string email)
{
Contact c = new Contact()
{
FirstName = firstName,
LastName =lastName,
MobilePhone = mobileNumber,
EMailAddress1 = email
};
Guid contactGuid = _service.Create(c);
if (contactGuid != Guid.Empty)
Console.WriteLine("Contact record created");
}

Step 7: Final Code will be like below,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
using EarlyBound;
 
namespace LinqToCRM
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
ConnectToMSCRM("arunpotti@MyOrg.onmicrosoft.com", "Password", "https://MyOrg.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;

if (userid == Guid.Empty) return;
createContactRecord("Arun", "Potti", "9876543210", "arunpotti@xyzorg.com");
}

public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;
}
catch (Exception ex)
{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();
}
}

public static void createContactRecord(string firstName, string lastName, string mobileNumber, string email)
{
Contact c = new Contact()
{
FirstName = firstName,
LastName = lastName,
MobilePhone = mobileNumber,
EMailAddress1 = email
};

Guid contactGuid = _service.Create(c);
if (contactGuid != Guid.Empty)
{
Console.WriteLine("Contact record created");
Console.ReadKey();
}
}
}
}

Step 8: Execute the project for the below output,

LinqToCrm Create Output

Please provide your valuable comments on this article.