Monday, 18 April 2016

DEACTIVATE CONTACT IN MS CRM 2013 ONPREMISES

      Contact is Deactivate

a.       If is primary contact of an account – remove  from   the       primary contact field of the account

b. Relationship with account record to remain intact-just not as a primary contact

                       The following plugin:


using System;


using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;

namespace UltimaDisplay2016

{

public class DeactivateContact : IPlugin

{

public void Execute(IServiceProvider serviceProvider)

{

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

try

{

if ((context.InputParameters.Contains("EntityMoniker")) && (context.InputParameters["EntityMoniker"] is EntityReference))

{

var targetEntity = (EntityReference)context.InputParameters["EntityMoniker"];

// throw new InvalidPluginExecutionException(targetEntity.LogicalName.ToString());

var state = (OptionSetValue)context.InputParameters["State"];

 

if (targetEntity.LogicalName != "contact")

{

return;

}

if (state.Value == 1)

{

Guid contactId = targetEntity.Id;

// to fetch account details

EntityCollection entitycollection = getAccountDetails(contactId, service);

foreach (Entity entity in entitycollection.Entities)

{

entity.Attributes["primarycontactid"] = null;

service.Update(entity);

}

}

else

{

return;

}

}

else { return; }

}

catch (Exception)

{

throw;

}

}

// Fetching the record

public EntityCollection getAccountDetails(Guid contactId, IOrganizationService service)

{

try

{

string fetchXML = @"<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>

<entity name='account'>

<attribute name='name'/>

<attribute name='accountid'/>

<filter type='and'>

<condition attribute='primarycontactid' value='{0}' uitype='contact' operator='eq'/>

</filter>

</entity>

</fetch>";

string fetch = string.Format(fetchXML, contactId);

EntityCollection collection = service.RetrieveMultiple(new FetchExpression(fetch));

return collection;

}

catch (Exception)

{

throw;

 

 

 

 

}

}

}

}

 

THE FOLLOWING  ARE PLUGIN REGISTRATION STEPS AS FOLLOWS:

Message : SetStateDynamicEntity
Primary Entity : contact
Secondary Entity : none
Filtering Attributes: Message does not support Filtered Attributes
Event Pipeline of stage execution: Pre-operation
Execution Mode : Synchronous
Deployment: Server

No comments:

Post a Comment

Note: only a member of this blog may post a comment.