I am very new to CRM technology as well as to .NET framework. This is one of my first programs I'm trying to execute. I am getting this error when I'm trying to run my Plugin. I am trying to auto populate the credit limit field in my Account entity as soon as user provides the countrycode while creating a record in account. Build was successful and I have registered my plugin. Please give your comments on the error as well as guide me if there are other issues in the program. Since this exception error was the first one I'm not sure if any more errors are there or not.
Here is the code:
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Xrm.Sdk
{
namespace PSPlugins
{
public class SetDefaultCreditLimitPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
//check if pre-operation stage
if (context.Stage != 20)
throw new InvalidPluginExecutionException("Must run as pre operation stage 20");
if (context.MessageName != "Create")
throw new InvalidPluginExecutionException("Registered for " + context.MessageName + " only create is supported");
if (context.PrimaryEntityName != "Account")
throw new InvalidPluginExecutionException("Registered for " + context.PrimaryEntityName + " entity and only account is supported");
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
tracingService.Trace("Hello from the plug-in");
Entity account = context.InputParameters["Target"] as Entity;
tracingService.Trace("Check if credit limit is set");
if (account.Contains("creditlimit"))
return;
tracingService.Trace("Get Country code from account");
string countrycode = string.Empty;
if (account.Contains("address1_country"))
countrycode = account.GetAttributeValue<string>("address1_country");
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(null);
QueryExpression query = new QueryExpression()
{
EntityName = "m3_defaultcreditlimit",
ColumnSet = new ColumnSet("m3_creditlimit")
};
query.Criteria = new FilterExpression();
query.Criteria.AddCondition("m3_countrycode", ConditionOperator.Equal, countrycode);
var queryResults = service.RetrieveMultiple(query);
tracingService.Trace("Query Completed Found " + queryResults.Entities.Count);
if (queryResults.Entities.Count == 0)
throw new InvalidPluginExecutionException("Default for country " + countrycode + " is not configured");
tracingService.Trace("Setting default value on account");
var defaultLimitEntity = queryResults.Entities[0];
account["creditlimit"] = defaultLimitEntity.GetAttributeValue<Money>("m3_creditlimit");
}
}
}
}
Thanks!