OpenThreadToken failed with hr = 1008

23 August 2009 von ckeller Kommentieren »

The crm sdk includes the class CrmImpersonator which allows to execute code with the crm user credentials instead the website credentials.

If you have used this class, you may have come into situations in which the constructor has thrown an InvalidOperationException with the message OpenThreadToken failed with hr = 1008. A little research shows, that the most common reason of this exception is that the CrmImpersonator only works if your website is executed in the context of the crm.

But even if the application runs in the context of crm there is a gotcha which leads to this exception. If you use a generic handler in your application and you are creating a new instance of the CrmImpersonator in the constructor of this handler, it will throw the same exception. See this example for reference

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler1 : IHttpHandler, IDisposable
{
  private CrmImpersonator _impersonator;
 
  public Handler1()
  {
    _impersonator = new CrmImpersonator();
  }
 
  public void ProcessRequest(HttpContext context)
  {
    context.Response.ContentType = "text/plain";
    context.Response.Write("Hello World");
  }
 
  public bool IsReusable
  {
    get{ return false; }
  }
 
  public void Dispose()
  {
    if (_impersonator != null)
    {
       _impersonator.Dispose();
       _impersonator = null;
    }
  }
}

It seems that the thread which processes the request is not properly initialized at this point. The solution of this problem is simple. You have to create the CrmImpersonator in the ProcessRequest method of your handler.

Hinterlasse eine Antwort