Saturday 27 August 2011

Operation is not valid due to the current state of the object

When your perfectly good SharePoint web service or elevated delegate throws this error it could ruin your day. The cause of the error lies deep inside the SharePoint object model which uses the current SharePoint context assuming all is well with it. I have got around this issue in the past by temporarily wiping the HTTP context after which all is well:

   1:  HttpContext ctx = HttpContext.Current;
   2:  HttpContext.Current = null;
   3:   
   4:  try
   5:  {
   6:      // TODO:your code
   7:  }
   8:  finally
   9:  {
  10:      HttpContext.Current = ctx;
  11:  }

This has always worked for me although recently I spied another approach on Kristian Kjær blog which also works well; the choice is yours.

No comments:

Post a Comment