For my plugins I usually use this "utils".
I have an Plugin Utils folder where I add these 3 classes:
EntityPlugin.cs
namespace Plugins
{
public abstract class EntityPlugin<T> where T : Entity
{
private static bool LogInit = false;
public void Execute(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
var utils = new PluginUtils(serviceProvider);
var entity = utils.PluginContext.InputParameters["Target"] as Entity;
if (entity == null)
{
//if Post Delete dont take entity entityReference
if (utils.PluginContext.MessageName.ToLower() != "delete" || utils.PluginContext.Stage != 40)
{
var entityReference = utils.PluginContext.InputParameters["Target"] as EntityReference;
entity = utils.Service.Retrieve(entityReference.LogicalName, entityReference.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
T target = entity.ToEntity<T>();
Execute(utils, target);
}
//in case of Post Delete
else
{
T target = null;
Execute(utils, target);
}
}
else
{
T target = entity.ToEntity<T>();
Execute(utils, target);
}
}
protected abstract void Execute(IPluginUtils utils, T target);
}
}
IPluginUtils.cs
namespace Plugins.Interfaces
{
public interface IPluginUtils
{
CrmDataContext CrmDataContext { get; }
IPluginExecutionContext PluginContext { get; }
IOrganizationService Service { get; }
}
}
PluginUtils .cs
namespace Plugins
{
public class PluginUtils : IPluginUtils
{
public PluginUtils(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
PluginContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
Service = serviceFactory.CreateOrganizationService(PluginContext.UserId);
CrmDataContext = new CrmDataContext(Service);
}
public IPluginExecutionContext PluginContext { get; private set; }
public IOrganizationService Service { get; private set; }
public CrmDataContext CrmDataContext { get; private set; }
}
}
In my plugins the code will look something like this:
namespace Plugins.Account
{
public class PostCreate_AccountDoSomething : EntityPlugin<EntityMappings.Account>, IPlugin
{
protected override void Execute(Interfaces.IPluginUtils utils, EntityMappings.Account target)
{
//do code
utils.Service.Execute(somerequest);
}
}
}
No comments:
Post a Comment