0
votes

I need to create plugin for Dynamics CRM Online wich randomly change company name after editing the contact's fields. As i know i need to change parentcustomerid field, but i dont know how to get all customer IDs аnd assign one of them in plugin's code.

My code:

public class ContactPlugin: IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

        if (context.InputParameters.Contains("Target") &&
            context.InputParameters["Target"] is Entity)
        {
            Entity entity = (Entity)context.InputParameters["Target"];

            if (entity.LogicalName == "contact") 
            {
                //entity.Attributes.Add("parentcustomerid", GetNewParentCustomerId());              
            }
        }
    }
}

How can i do that?

1

1 Answers

3
votes

First, write a function to retrieve all accounts from CRM:

static List<Entity> GetAllAccounts(IOrganizationService service)
{
    var query = new QueryExpression { EntityName = "account", ColumnSet = new ColumnSet(false) };
    var accounts = service.RetrieveMultiple(query).Entities.ToList();

   return accounts;
}

Then store an instance of Random class at the top of your plugin class:

static Random random  = new Random();

Then write a function which can retrieve a random item from a list:

static Entity GetRandomItemFromList(List<Entity> list)
{
    var r = random.Next(list.Count);
    return list[r];
}

Call the functions to first get all of your accounts and then to select one at random:

var accounts = GetAllAccounts(service);
var randomAccount = GetRandomItemFromList(accounts);

Then convert the randomAccount Entity to an EntityReference and assign the value to your contact's parentcustomerid attribute:

entity.Attributes.Add("parentcustomerid", new randomAccount.ToEntityReference());

To update the contact and insert the value into the database, use service.Update(entity). However, if you plan to call Update straight away in your code, I'd suggest reinstantiating your contact so that only the parentcustomerid attribute is updated in the database:

var updatedContact = new Entity { Id = entity.Id, LogicalName = entity.LogicalName };
updatedContact.Attributes.Add("parentcustomerid", new randomAccount.ToEntityReference());