Thursday, August 12, 2010 4:35 PM Jan Tielens

"Object reference not set to an instance of an object" when using SharePoint's ClientContext.Current in Silverlight

SharePoint 2010 and Silverlight is a fantastic combination, especially when you use the Client Object Model for Silverlight to access SharePoint data. But maybe you’ve encountered the following situation: your Silverlight application works great when it’s hosted in the out-of-the-box Silverlight Web Part, but when you build your own custom Web Part to show the Silverlight Application it just doesn’t work anymore: the browser tells you there is an Error on page. The details of the error are: Unhandled Error in Silverlight Application Object reference not set to an instance of an object.

When you debug your Silverlight code, you’ll notice that the issue is that the ClientContext.Current is a Null Reference. To solution for this problem is that fact that if you want to use the Current ClientContext you need to add the MS.SP.url parameter to the initParams in the HTML object that loads the XAP. This MS.SP.url parameter needs to contain the URL of the site in which the Silverlight Application is currently being displayed. The code of your Silverlight Web Part could look as follows:

public class SLWebPartDemo : WebPart
{
  protected override void RenderContents(HtmlTextWriter writer)
  {
    writer.Write(string.Format(
      @"<object data='data:application/x-silverlight-2,' type='application/x-silverlight-2' width='100%' height='100%'>
         <param name='source' value='{1}XAPs/SLWebPartDemoControl.xap'/>
         <param name='initParams' value='MS.SP.url={0}/{1}'/>
         <param name='onError' value='onSilverlightError' />
         <param name='background' value='white' />
         <param name='minRuntimeVersion' value='3.0.40818.0' />
         <param name='autoUpgrade' value='true' />
         <a href='http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40818.0' style='text-decoration:none'>
          <img src='http://go.microsoft.com/fwlink/?LinkId=161376' alt='Get Microsoft Silverlight' style='border-style:none'/>
         </a>
        </object>", SPContext.Current.Site.Url,
                    SPContext.Current.Web.ServerRelativeUrl));
  }
}

Filed under:

Comments

# re: "Object reference not set to an instance of an object" when using SharePoint's ClientContext.Current in Silverlight

Thursday, October 7, 2010 4:28 AM by rakesj

tel me about object refernce not set why tel me