views:

528

answers:

1

I have this code that works in a unit test but doesn't work when executed in the context of a plugin. What the code does is try to create a lead by calling the crm4 webservice.

When the plugin executes I get the following exception: "HTTP status 401: Unauthorized"

This is the code that initialises an instance of the webservice

CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = GetConfig("crm.organisation_name");
_crmService = new CrmService(GetConfig("webservice.crm"));

_crmService.CrmAuthenticationTokenValue = token;
_crmService.UseDefaultCredentials = false;      
_crmService.PreAuthenticate = false;
_crmService.Credentials = new NetworkCredential(GetConfig("crm.user_username"),
                                                GetConfig("crm.user_password"), 
                                                GetConfig("crm.user_domain"));

Anyone have advice on what I can try next? The lead is created when the test runs, and the configuration information is the same in the unit test as it is when the app is executing the plugin.

A: 

Hi Zahir.

Rather than instantiating the CrmService by yourself, alternatively you can obtain the CrmService by obtaining the reference of the IPluginExecutionContext and invoke the CreateCrmService method

Please refer to this link regarding creating the CrmService from IPluginExecutionContext

Here is some code snippet

public void Execute(IPluginExecutionContext context)
{
  // the below code means, the CrmService will be created 
  // by referring to the user account who is registered to 
  // run the CRM Application Pool
  ICrmService crmService = context.CreateCrmService(false);

  // the below code means, the CrmService will be created
  // by taking account the user account who login and run
  // the current plugin
  ICrmService crmService = context.CreateCrmService(true);

  // the below code means, the CrmService will be created
  // by impersonating a valid user
  ICrmService crmService = context.CreateCrmService(new Guid("3F2504E0-4F89-11D3-9A0C-0305E82C3301"));
}

Regards,

hadi

hadi teo
Thanks Hadi. If only my code was /that/ sort of plugin. The plugin I was referring to is executed in the context of a messagebus. Someone had rolled back the mb's configuration so it started loading an older cache'd version of my plugin -- which just happened to be pointing to an older instance of crm. I'll make you up though :)
Zahir