Thursday, September 12, 2013

How to get list of sub accounts in CRM plugin ?

public void Execute(IServiceProvider serviceProvider)
  {
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];
                if (entity.LogicalName == "account") 
                {
                    // Obtain the organization service reference.
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                    //Get current account id (accountid)
                    var currentAccountid = entity["accountid"];
                    Microsoft.Xrm.Sdk.Query.QueryByAttribute querybyattribute = new Microsoft.Xrm.Sdk.Query.QueryByAttribute("account");
                    querybyattribute.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("accountnumber", "accountid", "emailaddress1");

                    querybyattribute.Attributes.AddRange("parentaccountid");
                    querybyattribute.Values.AddRange(currentAccountid);

                    EntityCollection retrieved = service.RetrieveMultiple(querybyattribute);
                    int count = 0;
                    foreach (var en in retrieved.Entities)
                    {
                        count += 1;
                        en.Attributes["accountnumber"] = count.ToString();
                        service.Update(en);
                    }
               }  
 
  }


No comments:

Post a Comment