I’m currently learning about Dynamics and trying to update a contact’s Preferred Contact Method field using only the emailaddress1 and telephone1 fields. When I select one of those options and fill in the corresponding field, the contact should be updated. However, I only get the exception message when I try to update the contact, otherwise, it should pop the exception message. Can you help me understand what might be causing the problem?
I done the next code, taking the value fo the field that im updating in the Preferred Contact Mtehod, and i don´t know where i´m i doing wrong:
using System;
using Microsoft.Xrm.Sdk;
namespace BasicPluginTwo
{
public class ContactUpdatePlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// The InputParameters collection contains all the data passed in the 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"];
// Verify that the entity represents a contact.
if (entity.LogicalName != "contact") return;
// Check if Preferred Contact Method, Email or Phone fields
int preferredContactMethodOption = entity.GetAttributeValue<OptionSetValue>("preferredcontactmethodcode").Value;
string email = entity.Contains("emailaddress1") ? entity.GetAttributeValue<string>("emailaddress1") : string.Empty;
string phone = entity.Contains("telephone1") ? entity.GetAttributeValue<string>("telephone1") : string.Empty;
// Validate fields based on Preferred Contact Method
if ((preferredContactMethodOption == 2 && string.IsNullOrEmpty(email)) || (preferredContactMethodOption == 3 && string.IsNullOrEmpty(phone)))
{
throw new InvalidPluginExecutionException("Preferred Contact Method requires a corresponding non-empty contact detail.");
}
}
}
}
}