Create a follow up Task on create of Contact. The task should be completed in 2 days from the contact created on date.
Register the Plugin on:
- Message = Create
- Primary Entity = contact
- Pipeline Event = PostOperation
using System;
using Microsoft.Xrm.Sdk;
namespace HelloPlugin
{
public class CreateTask: IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// Get a reference to the Organization service.
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
//Obtain the target entity from the input parameter
Entity contact = (Entity)context.InputParameters["Target"];
try{
//Implement Plugin Business Logic inside try block
Entity taskRecord = new Entity("task"); //Creating object taskRecord of task entity.
//Single line of text(String fields)Append Follow Up on Task entity Subject field
taskRecord.Attributes.Add("subject", "Follow Up");
//Append Need to follow up with contact statement on Task entity description field
taskRecord.Attributes.Add("description", "Need to follow up with contact");
//Set value in Date field
taskRecord.Attributes.Add("scheduledend", DateTime.Now.AddDays(2)); //Added 2 days from the Contact creation date.
//Set value in Optionset field (use Optionset value not lable)
taskRecord.Attributes.Add("prioritycode", new OptionSetValue(2));
//Set Parent Record to Task record.
//taskRecord.Attributes.Add("regardingobjectid", new EntityReference("contact", contact.Id)); //Old Methodology
taskRecord.Attributes.Add("regardingobjectid", contact.ToEntityReference());//New Methodology -- Link to Contact Record.
//Create a task record
Guid taskGuid = service.Create(taskRecord);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
}

