Tuesday, 5 April 2016

ACTIVATE AND DEACTIVATE THE CONTACT RECORD IN MS CRM 2013

ACTIVATE AND DEACTIVATE THE CONTACT AND DEACTIVATE/ACTIVATE FROM ITS PRIMARY ACCOUNT IN MS CRM 2013









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"];

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

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

if(targetEntity.LogicalName != "contact")



{
return;



}
if(state.Value == 1)



{
Guid contactId = targetEntity.Id;

Entity account = new Entity("account");

// to fetch account details

EntityCollection entitycollection = getAccountDetails(contactId, service);




foreach(Entity entity in entitycollection.Entities)



{
entity.Attributes["primarycontactid"] = null;



service.Update(entity);

}

}
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;



}

}

}

}









No comments:

Post a Comment