Tuesday, February 14, 2012

MS CRM 2011: How to find Syntax to read different values

MS CRM 2011 syntax for common basic Jscript functions are following:
for more information read the blog

1) Get the GUID value of a lookup field:
function GetGUID() {
var primaryContactGUID = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].id;
alert(primaryContactGUID);
}

2) Get the Text value of a lookup field:
function GetText() {
var primaryContactName = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].name;
alert(primaryContactName);
}

3) Get the string value of a text field:
function GetTextField() {
var MainPhone = Xrm.Page.data.entity.attributes.get("telephone1").getValue();
alert(MainPhone);
}

4) Get the database value (i.e. the integer value) of an Option Set (pick list) field:
function GetOptionSetDatabaseValue() {
var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
AddressTypeDisplayValue = AddressType.getValue();
if (AddressTypeDisplayValue != null) {
alert(AddressTypeDisplayValue);
}
}

5) Get the display value (i.e. the text displayed in the drop down) of an Option Set (pick list) field:

function GetOptionSetDisplayValue() {
var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
AddressTypeDisplayValue = AddressType.getText();
if (AddressTypeDisplayValue != null) {
alert(AddressTypeDisplayValue);
}
}

6) Set the value of a string field:

function SetStringField() {
var Name = Xrm.Page.data.entity.attributes.get("name");
Name.setValue("ABC");
}

7) Set the value of an Option Set (pick list) field:

function SetOptionSetField() {
var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
AddressType.setValue(1);
}

8) Set the value of a Date field:

function SetDateField() {
var BirthDate = Xrm.Page.data.entity.attributes.get("birthdate");
var today = new Date();
var futureDate = new Date(today.setDate(today.getDate() + 1));
BirthDate.setValue(futureDate);
}

9) Set the value of a Lookup field:

// 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);
}
}

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");
}

10) Set the Requirement Level of a Field:

function SetRequirementLevel() {
var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
AddressType.setRequiredLevel("required");
}


11) Disable a field:
function SetEnabledState() {
var AddressType = Xrm.Page.ui.controls.get("address1_addresstypecode");
AddressType.setDisabled(true);
}

12) Hide a field:
function hideName() {
var name = Xrm.Page.ui.controls.get("name");
name.setVisible(false);
}

13) 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);
}

14) Hide a Section:
function HideShowSection(tabName, sectionName, visible) {
Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(visible);
}

HideShowSection("tab_5", "tab_5_section_4", true);


15) Save the form:
function SaveAndClose() {
Xrm.Page.data.entity.save();
}

16) Save and close the form:
function SaveAndClose() {
Xrm.Page.data.entity.save("saveandclose");
}

17) Close the form:
Note: the user will be prompted for confirmation if unsaved changes exist

function Close() {
Xrm.Page.ui.close();
}

18) 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);
}
}

19) Determine the GUID of the current record:

function AlertGUID() {
var GUIDvalue = Xrm.Page.data.entity.getId();
if (GUIDvalue != null) {
alert(GUIDvalue);
}
}

20) Determine the GUID of the current user:

function AlertGUIDofCurrentUser() {
var UserGUID = Xrm.Page.context.getUserId();
if (UserGUID != null) {
alert(UserGUID);
}
}

21) 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);
}

22) Refresh a Sub-Grid:

var targetgird = Xrm.Page.ui.controls.get("target_grid");
targetgird.refresh();

23) Pop the lookup window associated to a Lookup field:

window.document.getElementById('new_existingcase').click();

24) Change the default entity in the lookup window of a Customer or Regarding field:

Note: this approach utilises my configuration data framework as described here. You will need to create the supporting configuration data entity and add a configuration record to house the GUID of the default view you wish displayed in the lookup window

function ChangeLookup() {
document.getElementById("from").setAttribute("defaulttype", "2");
var ConfigValue = GetConfigValue("ActiveContactsViewGUID");
Xrm.Page.getControl("from").setDefaultView(ConfigValue);
}



function GetConfigValue(ConfigParamName) {

// 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);
}

// Specify the ODATA end point (this is the same for all CRM 2011 implementations)
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

// Specify the ODATA entity collection (this needs to be specific to your entity)
var ODATA_EntityCollection = "/new_configurationSet";

// Specify the ODATA filter
var ODATA_Query = "?$select=new_Value&$filter=new_name%20eq%20\'" + ConfigParamName + "\'&$top=1";

// Build the URL
var ODATA_Final_url = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + ODATA_Query;

//Calls the REST endpoint
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODATA_Final_url,
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) {
//This function will trigger asynchronously if the Retrieve was successful
return (data.d.results[0].new_Value);
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
//This function will trigger asynchronously if the Retrieve returned an error
//alert("ajax call failed");
}
});
}

25) Pop an existing CRM record:
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);

26) Force Submit value
Sets whether data from the attribute will be submitted when the record is saved.
function submitAllOptionsetData()
{
var attributes = Xrm.Page.data.entity.attributes.get(SDK.AttributeSamples.isOptionSet);
for (var i in attributes)
{
attributes[i].setSubmitMode("always");
}

alert(Xrm.Page.data.entity.getDataXml());
}

or

Xrm.Page.getAttribute("attribute Id").setSubmitMode("always");


27) Pop the Create form of a CRM record type:

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

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

28) SetFocus on MS CRM 2011 for tab, navigation and controls
To set the focus on tab, navigation or on fields afetr doing some validations.

Set Focus for Tab
Xrm.Page.ui.tabs.get('TabName').setFous();

Set Focus for Navigation
Xrm.Page.ui.navigation.items.get(0).set Focus();

Set Focus for Fields (Controls)
(Xrm.Page.ui.controls.get("attributeName")).setFocus();


for more information read the blog

MS CRM 2011: How to colorize grid rows based on some conditions

In CRM 2011, I found a way to add color to entities grids using the ribbon, even if there are still two limitations:

1) This is still not supported (as I browse and change DOM as you will see below) but does not required access to the filesystem
2) Ribbon element that helps me to colorize the grid view can’t be hidden and it is useful just to add color, it should then not be visible…

To accomplish this you need to perform three tasks
1) Add Ribbon Button

This button is added in the HomePageGrid of an case entity (but could also be added to SubGrid). It has an Enable rule that perform the grid colorization and returns always false to be deactivated. This is the last remaining difficulty, the SDK doesn’t allow to use a customRule to manage DisplayRule, so we can just deactivate the button.

<RibbonDiffXml>
<CustomActions>
<CustomAction Id="Mscrm.HomepageGrid.incident.MainTab.Actions" Location="Mscrm.HomepageGrid.incident.MainTab.Actions.Controls._children" Sequence="20">
<CommandUIDefinition>
<Button Id="Mscrm.HomepageGrid.incident.Colorization.Button" Command="Mscrm.HomepageGrid.incident.Colorization.Button.Command" CommandType="General" Image32by32="/_imgs/Ribbon/Actions_32.png" LabelText="Colorize" Sequence="22" TemplateAlias="o1" />
</CommandUIDefinition>
</CustomAction>
</CustomActions>
<Templates>
<RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
</Templates>
<CommandDefinitions>
<CommandDefinition Id="Mscrm.HomepageGrid.incident.Colorization.Button.Command">
<EnableRules>
<EnableRule Id="ColorizeRule" />
</EnableRules>
<DisplayRules />
<Actions />
</CommandDefinition>
</CommandDefinitions>
<RuleDefinitions>
<TabDisplayRules />
<DisplayRules>
<DisplayRule Id="testRule">
<CrmClientTypeRule
Default="false"
InvertResult="false"
Type="Outlook" />
</DisplayRule>
</DisplayRules>
<EnableRules>
<EnableRule Id="ColorizeRule">
<CustomRule
Default="true"
InvertResult="false"
FunctionName="load"
Library="$webresource:mctools_/ColorView/jQuery_1_7_1.js" />
<CustomRule Default="true" InvertResult="false" FunctionName="load" Library="$webresource:new_jQuery_1_7_1" />
<CustomRule Default="false" InvertResult="false" FunctionName="load" Library="$webresource:new_case_colour_enabled">
<CrmParameter Value="SelectedControlAllItemReferences" />
<CrmParameter Value="SelectedControl" />
</CustomRule>
</EnableRule>
</EnableRules>
</RuleDefinitions>
<LocLabels />
</RibbonDiffXml>

2) jQuery library

Download the latest version from jQuery web site and add a new function to permit load of this script file from ribbon. jQuery will help us writing faster code…

3) A custom library

The custom library has a unique function with two parameters:
A list of entityReference that contains the grid elements displayed
The grid control itself

Script File we are using is

function load(items,grid)
{
try
{
if(items)
{
var index = $("#gridBodyTable").find("col[name=gendercode]").index();
/*//to colour a specific cell of grid row
var a = document.all['crmGrid'].InnerGrid.AllRecords;
alert(a);
alert(a.length);
for (var i=0; i <a.length; i++)
{
alert(a[i][a[i].length-1].cells[3].innerText);

if(a[i][a[i].length-1].cells[3].innerText=='Homme')
{
a[i][a[i].length-1].cells[3].style.backgroundColor='CCFF33';
}
if(a[i][a[i].length-1].cells[3].innerText=='Femme')
{
a[i][a[i].length-1].cells[3].style.backgroundColor='FF9966';
}

}*/

/*
$('table tr :nth-child(3)').css('background-color', 'red');
$('table tr :nth-child(3)').innerHtml();
var myValue = $(this).parents('tr:first').find('td:eq(4)').text();

*/
//To colour a grid row
for(var i=0;i<items.length;i++)
{
var id = items[i].Id;

$(grid._element).find("tr[oid='" + id + "']").each(function()
{
var theTr = $(this);

//alert(theTr);
//alert(theTr.find("td:nth-child(4)")[0].innerText);
//theTr.find("td:nth-child(" + (index/1 + 1/1) + ")")[0].innerText

if(theTr.find("td:nth-child(5)")[0].innerText.indexOf("Normal") >= 0)
{
theTr.find("td").css("background-color","lightblue");
}
else if(theTr.find("td:nth-child(5)")[0].innerText.indexOf("Low") >= 0)
{
theTr.find("td").css("background-color","pink");
}
else if(theTr.find("td:nth-child(5)")[0].innerText.indexOf("High") >= 0)
{
theTr.find("td").css("background-color","red");
}
});
}
}
}
catch(e)
{
alert(e.description);
}
}


5) Screenshot



For More Information please read the mscrmtools blog

Monday, February 6, 2012

MS CRM 2011: how to assign a case to queue in Javascript using SOAP Endpoint?

Use the following line of code to move a case or incident from one assigned queue to another queue

It's a fully tested code just copy and paste after change the record. source and destination Guid

//Move case from 1 queue to another queue
var recordid="8B1A6B37-5451-E111-B17D-00155D00A500";
var sourceQueueid="d9192f47-b650-e111-b17d-00155d00a500";
var destinationQueueid="da192f47-b650-e111-b17d-00155d00a500";

var header = Xrm.Page.context.getAuthenticationHeader();

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\">" +
header +
" <soap:Body>" +
" <Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <Request xsi:type=\"RouteRequest\">" +
" <Target xsi:type=\"TargetQueuedIncident\">" +
" <EntityId>" + recordid + "</EntityId>" +
" </Target>" +
" <SourceQueueId>" + sourceQueueid + "</SourceQueueId>" +
" <RouteType>Queue</RouteType>" +
" <EndpointId>" + destinationQueueid + "</EndpointId>" +
" </Request>" +
" </Execute>" +
" </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/Execute");
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);

}

MS CRM 2011: How to read the value from Lookup?

Many times we required to read lookup value and Guid of Lookup for this use the following line of code:

function movecase() {

var lookupObject = Xrm.Page.getAttribute("LookupFieldId");

if (lookupObject != null)
{

var lookUpObjectValue = lookupObject.getValue();

if ((lookUpObjectValue != null))
{

var lookuptextvalue = lookUpObjectValue[0].name;
alert(lookuptextvalue);
var lookupid = lookUpObjectValue[0].id;
alert(lookupid);
}

}

Saturday, February 4, 2012

Add Custom Button, Custom Group and Custom Tab in Custom Entity or system Entity

Here you can find the complete code to add Custom Button, Custom Group and Custom Tab in Custom Entity.

Steps:
1 Export the entity
2 Edit the customizations.xml in Visual Studio editor
3 Copy the below code and replace it with RibbonDiffXml
4 Import and Publish the Solution
5 Test and Verify the Requirements
6 Note: If you required to open intelisense in customizations.xml then
1 go in XML menu in VS
2 click on Schema
3 Click on Add
4 select the path \sdk\schemas of CRM 2011
5 Select Customizationssolution.xsd, ribboncore.xsd, ribbontypes.xsd and ribbonwss.xsd files
6 Click open
7 Now check Intelisense

<RibbonDiffXml>
<CustomActions>
<CustomAction Id="Sample.Form.new_test.CustomTab.CustomAction" Location="Mscrm.Tabs._children" Sequence="40">
<CommandUIDefinition>
<Tab Id="Sample.Form.new_test.CustomTab" Command="Sample.Form.new_test.CustomTab" Title="My First Custom Tab" Description="Finally managed to put my first custom tab" Sequence="40">
<Scaling Id="Sample.Form.new_test.CustomTab.Scaling">
<MaxSize Id="Sample.Form.new_test.CustomTab.FirstGroup.MaxSize" GroupId="Sample.Form.new_test.CustomTab.FirstGroup" Sequence="10" Size="LargeMedium" />
</Scaling>
<Groups Id="Sample.Form.new_test.CustomTab.Groups">
<Group Id="Sample.Form.new_test.CustomTab.FirstGroup" Command="Sample.Form.new_test.FirstGroup" Sequence="10" Title="Custom Group" Template="Mscrm.Templates.3.3">
<Controls Id="Sample.Grid.new_test.CustomTab.FirstGroup.Controls">
<Button Id="Sample.Form.new_test.CustomTab.FirstGroup.FirstButton" ToolTipTitle="My First Button Tool Tip" ToolTipDescription="My First Button Tool Tip Description" Command="Sample.Form.new_test.FirstButton" Sequence="10" LabelText="First Button" Alt="Alt First Button" TemplateAlias="o1" />
</Controls>
</Group>
</Groups>
</Tab>
</CommandUIDefinition>
</CustomAction>
<CustomAction Id="Sample.new_test.form.Save.CustomAction" Location="Mscrm.Form.new_test.MainTab.Save.Controls._children" Sequence="80">
<CommandUIDefinition>
<Button Id="Sample.new_test.form.Save.Button" Command="Sample.new_test.form.Save.Command" LabelText="Button" ToolTipTitle="Button ToolTip" ToolTipDescription="Button Description" TemplateAlias="o1" Image16by16="/_imgs/ribbon/AddEmail_16.png" Image32by32="/_imgs/ribbon/Email_32.png" />
</CommandUIDefinition>
</CustomAction>
<CustomAction Id="Mscrm.Form.new_test.CustomGroup.CustomAction" Location="Mscrm.Form.new_test.MainTab.Groups._children" Sequence="81">
<CommandUIDefinition>
<Group Id="Mscrm.Form.new_test.CustomGroup.Group" Command="Mscrm.Form.new_test.CustomGroup.Command" Title="HKG Group" Sequence="11" Template="Mscrm.Templates.3.3">
<Controls Id="Mscrm.Form.new_test.CustomGroup.Controls">
<Button Id="Mscrm.Form.new_test.CustomGroup.Button.HK" Sequence="10" Command="Mscrm.Form.new_test.CustomGroup.Button.HK.Command" LabelText="HK" ToolTipTitle="Button ToolTip(HK)" ToolTipDescription="Button Description(HK)" TemplateAlias="o1" Image16by16="/_imgs/ribbon/AddEmail_16.png" Image32by32="/_imgs/ribbon/Email_32.png" />
</Controls>
</Group>
</CommandUIDefinition>
</CustomAction>
<CustomAction Id="Mscrm.Form.new_test.CustomGroup.MaxSize.CustomAction"
Location="Mscrm.Form.new_test.MainTab.Scaling._children"
Sequence="120">
<CommandUIDefinition>
<MaxSize Id="Mscrm.Form.new_test.CustomGroup.MaxSize"
GroupId="Mscrm.Form.new_test.CustomGroup.Group"
Sequence="21"
Size="LargeLarge" />
</CommandUIDefinition>
</CustomAction>
</CustomActions>
<Templates>
<RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
</Templates>
<CommandDefinitions>
<CommandDefinition Id="Sample.Form.new_test.CustomTab">
<EnableRules>
<EnableRule Id="Mscrm.Enabled " />
</EnableRules>
<DisplayRules></DisplayRules>
<Actions />
</CommandDefinition>
<CommandDefinition Id="Sample.Form.new_test.FirstButton">
<EnableRules>
<EnableRule Id="Mscrm.Enabled " />
</EnableRules>
<DisplayRules>
<DisplayRule Id="Sample.new_test.form.FormStateNotNew.DisplayRule"></DisplayRule>
</DisplayRules>
<Actions></Actions>
</CommandDefinition>
<CommandDefinition Id="Sample.Form.new_test.FirstGroup">
<EnableRules>
<EnableRule Id="Mscrm.Enabled " />
</EnableRules>
<DisplayRules></DisplayRules>
<Actions />
</CommandDefinition>
<CommandDefinition Id="Sample.new_test.form.Save.Command">
<EnableRules />
<DisplayRules />
<Actions>
<JavaScriptFunction Library="$webresource:new_JS_Common_Library" FunctionName="show">
<StringParameter Value="A" />
</JavaScriptFunction>
</Actions>
</CommandDefinition>
<CommandDefinition Id="Mscrm.Form.new_test.CustomGroup.Button.HK.Command">
<EnableRules />
<DisplayRules />
<Actions>
<Url Address="http://www.google.com" />
</Actions>
</CommandDefinition>
<CommandDefinition Id="Mscrm.Form.new_test.CustomGroup.Command">
<EnableRules>
<EnableRule Id="Mscrm.NotOffline"/>
</EnableRules>
<DisplayRules>
<DisplayRule Id="Mscrm.NotOffline"/>
</DisplayRules>
<Actions />
</CommandDefinition>
</CommandDefinitions>
<RuleDefinitions>
<TabDisplayRules>
<TabDisplayRule TabCommand="Sample.Form.new_test.CustomTab">
<EntityRule EntityName="new_test" Context="Form" AppliesTo="PrimaryEntity" />
</TabDisplayRule>
</TabDisplayRules>
<DisplayRules>
<DisplayRule Id="Sample.new_test.form.FormStateNotNew.DisplayRule">
<FormStateRule State="Create" InvertResult="true" />
</DisplayRule>
</DisplayRules>
<EnableRules />
</RuleDefinitions>
<LocLabels>
<LocLabel Id="Sample.new_test.form.Save.LabelText">
<Titles>
<Title languagecode="1033" description="Custom Button1" />
</Titles>
</LocLabel>
<LocLabel Id="Sample.new_test.form.Save.ToolTip">
<Titles>
<Title languagecode="1033" description="Custom Button1" />
</Titles>
</LocLabel>
</LocLabels>
</RibbonDiffXml>

CRM 2011: Reopen or reactivate a closed task / activity with SDK

Use the following line of code to Reopen the closed task in CRM 2011

// Re-open the Task to update it
SetStateRequest ssr = new SetStateRequest();
ssr.EntityMoniker = t.ToEntityReference();
ssr.State = new OptionSetValue(0);
ssr.Status = new OptionSetValue(2);

SetStateResponse resp1 = (SetStateResponse)xrmConnection.Execute(ssr);


Use the following line of code to close task in CRM 2011
// close the task again.
SetStateRequest Closed = new SetStateRequest();
Closed.EntityMoniker = new EntityReference(t.LogicalName, t.Id);
Closed.State = new OptionSetValue(TaskClosedState);
Closed.Status = new OptionSetValue(TaskClosedStatus);

SetStateResponse resp2 = (SetStateResponse)xrmConnection.Execute(Closed);

CRM 4.0: Reopen or reactivate a closed task / activity with SDK

Once a time Some tasks and opportunities closed wrongly in CRM4.0, so I need to reopen all these tasks and opportunity, to do this you will follow some steps:


Task: loop through for all the selected tasks
foreach (BusinessEntity TaskEntity in result.BusinessEntities)
{
try
{
task objtaskEntity = (task)TaskEntity;
task objtaskEntity1 = (task)TaskEntity;

//Create the request of the Task for State
SetStateTaskRequest objtask = new SetStateTaskRequest();
objtask.EntityId = new Guid(objtaskEntity.activityid.Value.ToString());
objtask.TaskState = 0;
objtask.TaskStatus = 2;
//Execute the request
SetStateTaskResponse res = (SetStateTaskResponse)service.Execute(objtask);


//You need to update the attribute of task entity then use the following line of code
objtaskEntity1.category = string.Empty;
service.Update(objtaskEntity1);
break;
}
catch(Exception ex)
{
continue;
}
}

Opportunity: to update or reopen Opportunity you will follow the following line of code

Picklist plSalesStage = new Picklist();
lSalesStage.Value = 1;
RenOpp.salesstagecode = plSalesStage;

OpportunityStateInfo objstateinfo = new OpportunityStateInfo();
objstateinfo.Value = OpportunityState.Open;
RenOpp.statecode = objstateinfo;
service.Update(RenOpp);

Split the String values with a special character in MS Flow to convert this into Array

 Many times we have a requirement to prepare the Mailing address for some of the documents, suppose there are Address Line1, Address Line2, ...