Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 Microsoft.Xrm.Sdk.Metadata;
namespace Validation.Plugin.CoreLib
{
public class ValidationPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(null);
var entity = GetEntityFromContext(context);
var allRequredAttributes = GetAllRequiredAttributes(service, entity);
foreach (var attribute in allRequredAttributes)
{
var errorMessage = $"Attribute {attribute.LogicalName} is required. Please specify value for this attribute before saving record.";
if (!entity.Contains(attribute.LogicalName))
{
throw new InvalidPluginExecutionException(errorMessage);
}
else
{
var value = entity[attribute.LogicalName];
if (value == null)
{
throw new InvalidPluginExecutionException(errorMessage);
}
else if (value is string && string.IsNullOrEmpty(value as string))
{
throw new InvalidPluginExecutionException(errorMessage);
}
}
}
}
private Entity GetEntityFromContext(IPluginExecutionContext localContext)
{
var target = localContext.InputParameters["Target"] as Entity;
var entity = new Entity(target.LogicalName);
if (localContext.PreEntityImages.ContainsKey("PreImage"))
{
var preImage = localContext.PreEntityImages["PreImage"];
foreach (var preImageAttribute in preImage.Attributes)
{
entity[preImageAttribute.Key] = target.Contains(preImageAttribute.Key) ? target[preImageAttribute.Key] : preImageAttribute;
}
}
foreach (var targetAttribute in target.Attributes)
{
entity[targetAttribute.Key] = targetAttribute.Value;
}
return entity;
}
private IEnumerable<AttributeMetadata> GetAllRequiredAttributes(IOrganizationService service, Entity entity)
{
var metadataRequest = new RetrieveEntityRequest()
{
LogicalName = entity.LogicalName,
EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes
};
var metadata = (RetrieveEntityResponse)service.Execute(metadataRequest);
var attributeMetadataCollection = metadata.EntityMetadata.Attributes;
var allRequredAttributes = attributeMetadataCollection.Where(am => am.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired);
return allRequredAttributes;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.