Monday, June 7, 2010

Create a CrmService proxy for plug-ins that execute in the child pipeline.

We always come across creating a CrmService Proxy for plug-ins that execute in the child pipeline. In a Child pipeline, you must instantiate the CrmService or MetadataService manually. We just need to check the InvocationSource Property (Child = 1, Parent = 0) of the IPluginExecutionContext. Pass the InvocationSource Property value to the below method.

Below is very simple code which creates a proxy.
[C#]
/// The execution context that was passed to the plug-in's Execute method.
/// Set to True to use impersonation.
/// 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;
}

No comments: