Wednesday, August 11, 2010

The following uses dynamic entity to update a Lookup field on a related contact:


using System;
//using System.Collections.Generic;
using System.Collections;

using System.Text;
using Microsoft.Win32;

// Microsoft Dynamics CRM namespaces
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.SdkTypeProxy.Metadata;

using System.IO;
using System.Configuration;
using System.Net.Mail;

namespace CTCA.Crm.Plugins
{
public class EmbraceCaregiver : IPlugin
{

// Related SDK topic: Writing a Plug-in
public void Execute(IPluginExecutionContext context)
{
Guid currentQualifier;
Guid previousQualifier;
Int32 PatientCaregiver;

ICrmService crmService = context.CreateCrmService(true);

DynamicEntity preTask = (DynamicEntity)context.PreEntityImages["contpre"];
DynamicEntity postTask = (DynamicEntity)context.PostEntityImages["contpost"];

if (preTask.Properties.Contains("ctca_isqualifierownerid") && postTask.Properties.Contains("ctca_isqualifierownerid"))
{

previousQualifier = ((Microsoft.Crm.Sdk.Lookup)preTask.Properties["ctca_isqualifierownerid"]).Value;
currentQualifier = ((Microsoft.Crm.Sdk.Lookup)postTask.Properties["ctca_isqualifierownerid"]).Value;
PatientCaregiver = ((Microsoft.Crm.Sdk.Picklist)preTask.Properties["ctca_contacttype"]).Value;
//RelatedCaregiver = ((Microsoft.Crm.Sdk.Lookup)preTask.Properties["ctca_relatedcaregiverid"]).Value;

//if the qualifierownerid field has been changed
if (previousQualifier != currentQualifier && currentQualifier != null && preTask.Properties.Contains("ctca_relatedcaregiverid"))
{
if (PatientCaregiver == 2)
{
Guid patientId = ((Key)preTask.Properties["contactid"]).Value;
//Guid relatedId = ((Lookup)patientId.Properties["ctca_relatedcaregiverid"]).Value;

if (patientId != null)
{
try
{
//Get the related contact
TargetRetrieveDynamic target = new TargetRetrieveDynamic();
target.EntityId = patientId;
target.EntityName = EntityName.contact.ToString();

RetrieveRequest retrieve = new RetrieveRequest();
retrieve.ColumnSet = new Microsoft.Crm.Sdk.Query.AllColumns();
retrieve.ReturnDynamicEntities = true;
retrieve.Target = target;

RetrieveResponse response = (RetrieveResponse)crmService.Execute(retrieve);
DynamicEntity contact = (DynamicEntity)response.BusinessEntity;

Guid isQualifierownerId = ((Lookup)contact.Properties["ctca_isqualifierownerid"]).Value;
Guid relatedContact = ((Lookup)contact.Properties["parentcustomerid"]).Value;

//Get the related contact
TargetRetrieveDynamic target2 = new TargetRetrieveDynamic();
target2.EntityId = relatedContact;
target2.EntityName = EntityName.contact.ToString();

RetrieveRequest retrieve2 = new RetrieveRequest();
retrieve2.ColumnSet = new Microsoft.Crm.Sdk.Query.AllColumns();
retrieve2.ReturnDynamicEntities = true;
retrieve2.Target = target2;

RetrieveResponse response2 = (RetrieveResponse)crmService.Execute(retrieve2);
DynamicEntity contact2 = (DynamicEntity)response2.BusinessEntity;

ArrayList arrProps = new ArrayList();

Property qualifier = new LookupProperty();
((LookupProperty)qualifier).Name = "ctca_isqualifierownerid";
((LookupProperty)qualifier).Value = new Lookup();
((LookupProperty)qualifier).Value.type = "contact";
((LookupProperty)qualifier).Value.Value = new Guid(isQualifierownerId.ToString());
arrProps.Add(qualifier);

contact2.Properties.AddRange((Property[])arrProps.ToArray(typeof(Property)));

TargetUpdateDynamic updateDynamic = new TargetUpdateDynamic();
updateDynamic.Entity = contact2;
UpdateRequest updateReq = new UpdateRequest();
updateReq.Target = updateDynamic;
UpdateResponse updatedRes = (UpdateResponse)crmService.Execute(updateReq);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
throw new InvalidPluginExecutionException("An error occurred in the Update plug-in.", ex);
}


//crmService.Update(contact2);
}

}
}
}
}

#region Private methods
///
/// Creates a CrmService proxy for plug-ins that execute in the child pipeline.
///

/// The execution context that was passed to the plug-ins Execute method.
/// Set to True to use impersontation.
/// A CrmServce instance.
private CrmService CreateCrmService(IPluginExecutionContext context, Boolean flag)
{
CrmAuthenticationToken authToken = new CrmAuthenticationToken();
authToken.AuthenticationType = 0;
authToken.OrganizationName = context.OrganizationName;

// Include support for impersonation.
if (flag)
authToken.CallerId = context.UserId;
else
authToken.CallerId = context.InitiatingUserId;

CrmService service = new CrmService();
service.CrmAuthenticationTokenValue = authToken;
service.UseDefaultCredentials = true;

// Include support for infinite loop detection.
CorrelationToken corToken = new CorrelationToken();
corToken.CorrelationId = context.CorrelationId;
corToken.CorrelationUpdatedTime = context.CorrelationUpdatedTime;
corToken.Depth = context.Depth;

RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");

service.Url = String.Concat(regkey.GetValue("ServerUrl").ToString(), "/2007/crmservice.asmx");
service.CorrelationTokenValue = corToken;

return service;
}

///
/// Creates a MetadataService proxy for plug-ins that execute in the child pipeline.
///

/// The execution context that was passed to the plug-ins Execute method.
/// Set to True to use impersontation.
/// A MetadataServce instance.
private MetadataService CreateMetadataService(IPluginExecutionContext context, Boolean flag)
{
CrmAuthenticationToken authToken = new CrmAuthenticationToken();
authToken.AuthenticationType = 0;
authToken.OrganizationName = context.OrganizationName;

// Include support for impersonation.
if (flag)
authToken.CallerId = context.UserId;
else
authToken.CallerId = context.InitiatingUserId;

MetadataService service = new MetadataService();
service.CrmAuthenticationTokenValue = authToken;
service.UseDefaultCredentials = true;

RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");

service.Url = String.Concat(regkey.GetValue("ServerUrl").ToString(), "/2007/metadataservice.asmx");

return service;
}

#endregion Private Methods
}
}