Creating a Plugin
The
code snippet given below shows how the owner field of the newly created record
is being set but one thing, which we need to know is this process can be done
only during the pre-creation stage. If we are trying to update the owner field
of a record, which is already created, then we may need to use AssignRequest,
as shown in section 2.
Section:1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Query;
using System.Runtime.Serialization;
namespace projectname.fieldmappings {
public class FieldMappings: IPlugin {
//Main function of the plugin
public void Execute(IServiceProvider serviceProvider) {
//Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService = (ITracingService) serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory) serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService orgService = serviceFactory.CreateOrganizationService(context.UserId);
// The Input Parameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) {
// Obtain the target entity from the input parameters.
Entity entity = (Entity) context.InputParameters["Target"];
//Create record in Contact Entity
Entity ContactDetails = new Entity("Contact");
// To assign the owner id of Contact Details
EntityReference owner = new EntityReference();
owner.Id = ((EntityReference)(entity.Attributes["primarycontactid"])).Id; // Taking id from current entity and assigning it to contact’s owner
owner.LogicalName = ((EntityReference)(entity.Attributes["primarycontactid"])).LogicalName; // Taking id from current entity and assigning it to contact’s owner
ContactDetails["ownerid"] = owner;
orgSvc.Create(ContactDetails);
}
}
}
}
Please refer to this link to
register and debug the plugin.
Section 2
To update the owner field of the existing record, use the
code given below.
// Create the Request Object and Set the Request Object's Properties
AssignRequest assignowner = new AssignRequest {
Assignee = new EntityReference(SystemUser.EntityLogicalName, _otherUserId),
Target = new EntityReference(Account.EntityLogicalName, _accountId)
};
// Execute the Request
orgService.execute(assignowner);
No comments:
Post a Comment