The following code can be used to retrieve the record and find the GUID of the lookup field.
using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
namespace XMA_UpdateOppotunityAccOwner.XMA_UpdateOpportunityAccOwner
{
public class PostOperationaccountUpdate: IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
//Initializing Service Context.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
try
{
//Defining Entity Object.
Entity eTarget = null;
if (context.MessageName == "Update")
{
eTarget = (context.InputParameters.Contains("Target") && context.InputParameters["Target"] != null) ?
context.InputParameters["Target"] as Entity : null;
Guid accountIdGuid = eTarget.GetAttributeValue<Guid>("accountid");
RetrieveRequest request = new RetrieveRequest()
{
ColumnSet = new ColumnSet("ownerid"),
Target = new EntityReference("account", accountIdGuid)
};
var response = (RetrieveResponse)service.Execute(request);
Entity entity = response.Entity;
Guid ownerId = ((EntityReference)entity.Attributes["ownerid"]).Id;//Find Guid from a lookup
RetrieveRequest requestUer = new RetrieveRequest()
{
ColumnSet = new ColumnSet("fullname"),
Target = new EntityReference("systemuser", ownerId)
};
response = (RetrieveResponse)service.Execute(requestUer);
entity = response.Entity;
var ownerName = entity["fullname"];
QueryExpression query = new QueryExpression();
query.EntityName = "opportunity";
query.ColumnSet = new ColumnSet("opportunityid", "parentaccountid", "name");
FilterExpression filter = new FilterExpression(LogicalOperator.And);
filter.AddCondition("parentaccountid", ConditionOperator.Equal, accountIdGuid);
query.Criteria.AddFilter(filter);
EntityCollection entityCollection = service.RetrieveMultiple(query);
if (entityCollection.Entities.Count > 0)
{
int TotalAccountCount = entityCollection.Entities.Count;
foreach (var accountEntity in entityCollection.Entities)
{
//Stage 6.
Entity opportunity = new Entity("opportunity");
opportunity.Id = accountEntity.Id;
opportunity["fieldName"] = ownerName;
service.Update(opportunity);
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
Regards,
Arun S Keerthi
No comments:
Post a Comment