Thursday, February 3, 2011

SharePoint 2010 - Object Model Code on External List - BDC Exception Solution


When you're working with the Object Model Code on an external list in SharePoint 2010 you might stumble upon the following problem:
Microsoft.BusinessData.Infrastructure.BdcException: The shim execution failed unexpectedly - Proxy creation failed. Default context not found..
---> Microsoft.Office.SecureStoreService.Server.SecureStoreServiceException: Proxy creation failed. Default context not found.
This is caused by the fact that there is no default SPServiceContext, meaning SPServiceContext.Current is always null. The problem is that, for example, when you are working with methods like listitems.getdatatable() you need a current context, since the underlying code will use SPServiceContext.Current
To solve this issue you can create a code block that will fill the current SPServiceContext:












using (var site = new SPSite("http://localhost"))
{
// Get context for the site.
var context = SPServiceContext.GetContext(site);
// Assign context in SPServiceContext.Current
using (var scope = new SPServiceContextScope(context))
{
...
listitems.getdatatable()
}
}
After closing the using codeblock your current SPServiceContext will be empty again.