Wednesday 13 February 2019

Party List Fields in Dynamics 365





















In Dynamics 365, an activity (phonecall, task, email, appointment) can either be associated with a single person or a group of person which represent the Activity Party. An activity can have multiple activity parties.

For Example, an email can either be sent to CRM Contacts or CRM User or Queue. So there must be such type of field available in CRM which can refer to multiple entities as Lookup can only be associated to only single entity. Hence Party List comes into picture.

When you add any Party List type of field on the CRM form, you may notice that these fields look like Lookup fields but may function a little different. For example the Email's From and To fields let you select multiple records of the same or different type.




























  • CRM Activity Party List field is a special type of lookup field which refers to multiple entities. To hold or store these multiple entities references, Microsoft has provided one special type of entity named Activity Party.
  • Activity Party, has one special field called Party Id. which has the capability to store multiple entities references like user, contact, account, lead etc.
  • Hence, if we have to get/set value in Party List Field, we have to interact with Activity Party Party Id field.
  • So, we just have to remember, while getting or setting value in party list fields (to, from cc, bcc, regarding etc). We have to use Activity Party Entity and Party Id field. We can understand it better through code also.

Get value from Party List Fields using C#

public static void Main(string[] args)
{
  // Pass the email record guid
  getPartyList("C4723A9F-592F-E911-A979-000D3AF24324");
}
public static void getPartyList(string emailRecordId)
{

// Retrieve email record
//Here service is your IOrganisation Service Object
Entity email = 
service.Retrieve("email",new Guid(emailRecordId),new ColumnSet("from", "to"));


// get value from partylist - 'FROM' field
EntityCollection from = email.GetAttributeValue<EntityCollection>("from"); if (from != null && from.Entities.Count > 0) { foreach (var item in from.Entities) {
  EntityReference partyId = item.GetAttributeValue<EntityReference>("partyid");

  string addressUsed = item.GetAttributeValue<string>("addressused");

  Console.WriteLine("Email Send From: " + partyId.Name + "," + addressUsed);

  }
 }

Console.WriteLine("------------------------------------------------------------------");

// get value from partylist - 'TO' field
EntityCollection to = email.GetAttributeValue<EntityCollection>("to"); if (to != null && to.Entities.Count > 0) { foreach (var item in to.Entities) { EntityReference partyId = item.GetAttributeValue<EntityReference>("partyid"); string addressUsed = item.GetAttributeValue<string>("addressused"); Console.WriteLine("Email Send To: " + partyId.Name + "," + addressUsed); } } Console.ReadKey();

}


Output


























Set value in Party List Fields using C# (Single Recipient)

public static void Main(string[] args)
{
  // call the function in Main
SetPartyList_SingleRecipient();
}

public static void SetPartyList_SingleRecipient()
{          
  // declare party list entity to set value in FROM field
  Entity from = new Entity("activityparty");
  // declare party list entity to set value in TO field
  Entity to = new Entity("activityparty");
           
  // set value in FROM field
  from["partyid"] = 
new EntityReference("systemuser", new Guid("D72D8D9E-FCEC-4C6B-8340-A2CB9FAA88D5"));

  // set value in TO field
  to["partyid"] = 
new EntityReference("account", new Guid("475B158C-541C-E511-80D3-3863BB347BA8"));

  // declare party list entity to set value in FROM field
  Entity email = new Entity("email");

  // insert value in email FROM field
  email["from"] = new Entity[] { from };
  // insert value in email TO field
  email["to"] = new Entity[] { to };

  //Set regarding object property (i.e. The entity record, which u want this email associated with)
  EntityReference regardingObject = 
new EntityReference("contact", new Guid("49A0E5B9-88DF-E311-B8E5-6C3BE5A8B200"));
  
  email.Attributes.Add("regardingobjectid", regardingObject);

  //Set subject & body properties
  email.Attributes.Add("subject", "Email created from Console for Single recipients");
  email.Attributes.Add("description", "Email created from Console for Single recipients");

  //Create email activity
  //Here service is your IOrganisation Service Object
Guid emailID = service.Create(email); Console.WriteLine("Email created successfully"); Console.Read();
}


Output
























Set value in Party List Fields using C# (Multiple Recipient)

public static void Main(string[] args)
{
  // call the function in Main
SetPartyList_MutipleRecipient();
}

public static void SetPartyList_MutipleRecipient()
{
 // set value in FROM party list field
 Entity from1 = new Entity("activityparty");

 // two accounts inside the TO field
 Entity to1 = new Entity("activityparty");
 Entity to2 = new Entity("activityparty");
 // two contacts inside the TO field
 Entity to3 = new Entity("activityparty");
 Entity to4 = new Entity("activityparty");

 // set value in FROM field
 from1["partyid"] = 
new EntityReference("systemuser", new Guid("D72D8D9E-FCEC-4C6B-8340-A2CB9FAA88D5"));

 // set multiple values in TO field
 to1["partyid"] = 
new EntityReference("account", new Guid("475B158C-541C-E511-80D3-3863BB347BA8"));
 to2["partyid"] = 
new EntityReference("account", new Guid("A8A19CDD-88DF-E311-B8E5-6C3BE5A8B200"));
 to3["partyid"] = 
new EntityReference("contact", new Guid("25A17064-1AE7-E611-80F4-E0071B661F01"));
 to4["partyid"] = 
new EntityReference("contact", new Guid("49A0E5B9-88DF-E311-B8E5-6C3BE5A8B200"));
 Entity email = new Entity("email");

 //Set regarding object property (i.e. The entity record, which u want this email associated with)
 EntityReference regardingObject = 
new EntityReference("contact", new Guid("49A0E5B9-88DF-E311-B8E5-6C3BE5A8B200"));

 email.Attributes.Add("regardingobjectid", regardingObject);

  // Insert value in FROM field
   email["from"] = new Entity[] { from1 };
  // Insert value in TO field
   email["to"] = new Entity[] { to1, to2, to3, to4 };

  //Set subject & body properties
   email.Attributes.Add("subject", "Email created from Console for Multiple recipients");
   email.Attributes.Add("description", "Email created from Console or Multiple recipients");

   //Create email activity
   //Here service is your IOrganisation Service Object
Guid emailID = service.Create(email); Console.WriteLine("Email created successfully"); Console.Read();
}

Output















In the above code,

To get the value from Party List TO and FROM fields:

We are retrieving the value from Party Id field of Activity Party entity, which holds the record’s Guids which was selected in Email’s FROM and TO fields.

To set the value in Party List TO and FROM fields:

We are first passing the value in Party Id field of Activity Party entity and then setting it’s Entity reference to partylist FROM and TO fields.


Note: 

  • For demonstration, I have hard-coded the record Guids. However, in real time you'll have to pick these values dynamically based upon your requirement.
  • For demonstration, I have taken the example of Email Activity Entity and it's To and From party list fields. Same code/logic can also be used for other activities and party list fields.


Thanks for your time. Please do share your valuable feedback. It means a lot for me.

Cheers

Friday 1 February 2019

Move queue item from one queue to another programmatically in Dynamics 365

This article shows how to add a record from one queue to another.

AddToQueueRequest routeRequest = new AddToQueueRequest
{
        SourceQueueId = queueId.Id,
        Target = new EntityReference(obj.LogicalName, obj.Id),
        DestinationQueueId = userQueueId

};
orgService.Execute(routeRequest);


Sample Code

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

namespace CRMCodeHelper
{
class Program
{
private static IOrganizationService service = null;

static void Main(string[] args)
{       

service = ConnectToCRM();

Guid sourceQueueId = new Guid("9b2296-bacb-e811-a962-000d3ab4998c");

Guid destinationQueueId = new Guid("4f7cd6-54c5-e811-a95d-000d3ab49476");

EntityReference Target = 
new EntityReference("phonecall",new Guid("8d408d-c255-4587-9e34-596d496e6738"));

MoveQueueItem(sourceQueueId, destinationQueueId, Target);

}

public static IOrganizationService ConnectToCRM()
{

IOrganizationService organizationService = null;
try
{

   ClientCredentials clientCredentials = new ClientCredentials();

   clientCredentials.UserName.UserName = "<UserName>";

   clientCredentials.UserName.Password = "<Password>";

   ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

   organizationService = 
new OrganizationServiceProxy(new Uri("<CRM Organisation Service URL>"), null, clientCredentials, null);

   return organizationService;

  }

catch (Exception ex)
{

 Console.WriteLine("Exception caught - " + ex.Message);

 return organizationService;

}

}

public static void MoveQueueItem(Guid SourceQueueGuId, Guid DestinationQueueGuid, EntityReference ItemToMove)
{

 AddToQueueRequest routeRequest = new AddToQueueRequest
 {

    SourceQueueId = SourceQueueGuId,

    Target = ItemToMove,

    DestinationQueueId = DestinationQueueGuid

 };

   service.Execute(routeRequest);

}
}

}

Call Global Custom Action using JavaScript in Dynamics 365

Sometimes there are scenarios you need to create Global Actions where you don't specify an entity in particularly. When you create such global action and if you need to call that action from your JavaScript code or on Button Click. Here is the way to do that.

Example of calling Global Action Without Parameters:

Create a Global Action





























Add Steps and Copy Action Unique Name (My Custom Action)






















JavaScript to call Action

//Execute the created global action using Web API.
function CallGlobalCustomAction() {
    
    //get the current organization name
    var serverURL = Xrm.Page.context.getClientUrl();

    //query to send the request to the global Action 
    var actionName = "new_MyCustomAction"; // Global Action Unique Name

    //Pass the input parameters of action
    var data = {};

    //Create the HttpRequestObject to send WEB API Request 
    var req = new XMLHttpRequest();
    //Post the WEB API Request 
    req.open("POST", serverURL + "/api/data/v8.0/" + actionName, 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 || this.status == 204)
            {
                alert("Action Executed Successfully...");
               
            }
            else
            {
                var error = JSON.parse(this.response).error;
                alert("Error in Action: "+error.message);
            }
        }
    };
    //Execute request passing the input parameter of the action 
    req.send(window.JSON.stringify(data));
}




Example of calling Global Action with Parameters:























JavaScript to call Action

//Execute the created global action using Web API.
function CallGlobalCustomAction() {
    
    //get the current organization name
    var serverURL = Xrm.Page.context.getClientUrl();

    //query to send the request to the global Action 
    var actionName = "new_MyCustomAction"; // Global Action Unique Name

    //set the current loggedin userid in to _inputParameter of the 
    var InputParameterValue = Xrm.Page.context.getUserId();
 
    //Pass the input parameters of action
    var data = {
    "MyInputParameter": InputParameterValue
    };
//Create the HttpRequestObject to send WEB API Request var req = new XMLHttpRequest(); //Post the WEB API Request req.open("POST", serverURL + "/api/data/v8.0/" + actionName, 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 || this.status == 204) { alert("Action Executed Successfully...");

               //You can get the output parameter of the action with name as given below
               result = JSON.parse(this.response);
               alert(result.MyOutputParameter);
} else { var error = JSON.parse(this.response).error; alert("Error in Action: "+error.message); } } }; //Execute request passing the input parameter of the action req.send(window.JSON.stringify(data)); }




Blogger Widgets