Monday, August 9, 2010

Current Web Url in Silverlight

Scenario:
Client Object Model and Silverlight is best combo which I use often and always get this question on how to get the Current SharePoint Web Url from within Silverlight without passing it from initparam's manually.

Answer is simple

Steps:
1. Open App.xaml.cs and add the following using statements to the top of the file

using Microsoft.SharePoint.Client;
using System.Threading;
2. Add the following code to the beginning of the Application_Startup method.
ApplicationContext.Init(e.InitParams, SynchronizationContext.Current);
3. Open MainPage.xaml.cs and add the following using statement to the top of the file
using Microsoft.SharePoint.Client;
4. Use the following code to get the client context for current web
ClientContext context = new ClientContext(ApplicationContext.Current.Url);
context.Load(context.Web);

List listSharedDocuments = context.Web.Lists.GetByTitle("Shared Documents");
context.Load(listSharedDocuments);

5 comments:

Ham Home June 7, 2011 at 8:02 AM  

I did follow by your step but "ApplicationContext.Current.Url" return null so it throw exception error.

Please help me

Sandeep K Nahta June 7, 2011 at 10:08 AM  

My best guess is you are missing ASPNet compatibility

http://blogs.msdn.com/b/wenlong/archive/2006/01/23/516041.aspx#_Toc125716003

Robin July 14, 2011 at 8:33 AM  

i tried using your solution but having same exception...

Kay October 27, 2011 at 4:02 PM  

No need to go to the trouble of hacking the ASP.NET application context from it.

Use

ClientContext ctx = ClientContext.Current;

or

ClientContext ctx = new ClientContext(url);

Absolute worst case scenario regex the current url