To communicate with the SharePoint server in Silverlight context we need to give two client SharePoint DLL references to the silver light project.
DLL's Needed: Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll. They can be found at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin".
OK, we understand the concept and we will create a project and implement code for better understanding on how it works.
- Open Visual Studio 2010.
- File -> New -> Project -> Visual C# -> Silverlight -> Select Silverlight Application project template as shown below.
- Give some name to the project. In my example, I have given some meaningful name like "SP2010Silverlight_HelloWorld" and create the project.
- Now, you see the below screen.
- What this meaning is "Do you want to create an ASP.NET web site and host the XAP file generated to the web site". For our example, it's really not needed. But, there is no problem by using that.
- Now next step is getting the SharePoint Silverlight Client Dll's reference to our project. So, for this get the SharePoint dll's to the client machine [Where we created project] and paste the DLL's in some safe location. I copied them to C:\SP2010_ClientDLL\.
- Now, go to Visual Studio 2010 project right click on project -> select References and browse to location where client dll's copied and select both dll's and hit ok as shown in below figure.
- After you added all references the references folder should look like this.
- Now we are ready with all prerequisites and part left is with writing code. I will show you simple code on how to write the code for getting web site title and description using Silverlight Client OM.
- Before start coding, we need to add reference to the namespace in page by declaring using keyword as shown below.
using Microsoft.SharePoint.Client;
- This is the code to get data from a SharePoint server, in this example we are retrieving Title and Description of a web site.
MainPage.Xaml.cs file code:
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.SharePoint.Client; namespace SP2010Silverlight_HelloWorld{ public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private ClientContext context = null; private Web web = null; private delegate void UpdateUIMethod(); private void btnLoadSite_Click(object sender, RoutedEventArgs e) { context = ClientContext.Current; web = context.Web; context.Load(web, w => w.Title, w => w.Description, w => w.ServerRelativeUrl); context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure); } private void OnSiteLoadSuccess(object sender, ClientRequestSucceededEventArgs e) { UpdateUIMethod updateUI = LoadSiteData; this.Dispatcher.BeginInvoke(updateUI); } private void OnSiteLoadFailure(object sender, ClientRequestFailedEventArgs e) { MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace); } private void LoadSiteData() { canvasLabels.Visibility = System.Windows.Visibility.Visible; label2.Content = web.Title; label4.Content = web.ServerRelativeUrl; label6.Content = web.Description; } } }
Place all the code above given in the both files of your project.
Till now, what we have done is, writing and complete code for loading the site data. But, we need to understand the above code.
In the above code, there is a callback function used. Which is asynchronous and loads data. But, you may confuse at the line delegate UpdateUIMethod(). I copied the below text from MSDN to better understand about the delegate and why it's needed.
"Because query execution is asynchronous when you use the SharePoint Foundation Silverlight object model, you must pass delegates for callback methods as parameters in the ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) method, similarly to query execution in the ECMAScript object model. However, to run code that makes changes in the user interface (UI) through the Silverlight object model, you must delegate this work to the Dispatcher object of the thread that created the UI by calling BeginInvoke()". So, we should use the delegate to make changes on the UI.
Deploy and Test
We have two ways to deploy the XAP file in SharePoint environment.
One is, We can use SharePoint default location [\Templates\Layouts\ClientBin] and deploy the file there. Refer this location from the Silverlight web part.
Second is, We can use a SharePoint document library and deploy the file there. Refer this document library location file path while adding the silverlight web part. In this post, we will use the default location to deploy and test.
- To deploy and test the code in SharePoint 2010 we need to use the SharePoint Silverlight web part [New web part added in this version].
- The silverlight web part default location is "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin". So, all the XAP files should be deployed to this location to use them in the silverlight web part.
- To make this process easier, we need to do below.
- Right click on Silverlight project -> propertiese -> Build -> change the output path to "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin" as shown below.
- Build the solution and see the XAP generated in the ClientBin location.
- Now, navigate to SharePoint site where you want to see the silverlight data, Edit page.
- Add silverlight web part to the page.
- It will prompt you for the XAP file location: Type the url: "/_layouts/ClientBin/SP2010Silverlight_HelloWorld.xap".
- Now click on OK and you can see the silverlight web part on the page.
Wow, This is the one of the great and excellent posts I like these days. The way you have written is very explanatory and easily understanding. I appreciate the work you are allocating for writing posts sharing knowledge. With this example, I am also one of the dev who created Silverlight app in SharePoint 2010. Awesome. Happy. :)
ReplyDeleteHi,
ReplyDeleteGreat post.
Microsoft Playground
Thanks for the Excellent Post. Is Visual Studio 2010 required for developing solutions with Silverlight Client Object Model ? Is Sharepoint Designer of any value for working with Client Object Model ?
ReplyDeleteSilverlight Client Object Model is nothing but Silverlight programming and accessing objects. So, you can't do that with SharePoint designer. You should need Visual Studio 2010 to get this job done. Any way it's in BETA, I believe no problems to install it.
ReplyDeleteHi,
ReplyDeleteI cannot seem to get it deployed to the sharepoint site. When i enter the URL /_layouts/ClientBin/TEST.xap
i get the error "Could not download the Silverlight application or the Silverlight Plugin did not load.
To re-configure the Web Part or to provide a different Silverlight application (.xap), open the tool pane and then click Configure."
Nice post..
ReplyDeleteHi Fzzzz,
ReplyDeleteSeems like you have given wrong url in deploying the XAP file from application. Check once the deploy location of the build and test. Let me know, if you need to any help on this.
Hi there... im sort of a noob in this SP COM can you explain to me where should I must change the site url more precisely and how? I know it's a lame question but i have no idea. thanks
ReplyDeleteHi Art-Uhr,
ReplyDeleteI have changed the code few days back and forgot to update the site url related information. Now the note section in the post is strike out.... So, no url and nothing to be changed. Just copy and paste directly...
Thanks any way/
Tahnk's to you! I thought I was missing somthing. lol, gorgeous tutorial, btw just added u to gtalk hope it's ok
ReplyDeleteHi Guys,
ReplyDeleteGreat post indeed. I am at client side (meaning out of dev environment) and there is some discussion going at if SP2010 + Silverlight can be used as an application development tool which will be different from typical SharePoint look and feel. Can you please suggest any sites which were developed using above mentioned tools? I just want to give demo about the power of this combo.
Much obliged.
Naveed
I am trying to get the Description label to word wrap over more then one line.
ReplyDeleteAlso how do I use Textbox or other controls instead of just Label. If I try to use a text box or any other control I get "control was not found"
<datainput:Textbox
I've also tried draging and droping the control onto the canvas, but get the same error.
When using datainput name I only have access to Label, ValidationSummary, DescritionViewer.
Hmm... Very great and awesome article. I really like it. You save my live.. hehe...
ReplyDeleteYou can go with ASPHostPortal (http://www.asphostportal.com). This provider offer sharepoint only with $ 9.99/month. I have tried it and until now everyhing works great. Just recommendation
Awesome post. Thanks for all the good work you are doing. It really helps to beginners like me. Keep up the good work. :)
ReplyDeleteHi,
ReplyDeletei used your code to generate a silverlight application but i'm facing problem since last three to four days. the problem is that "OnSiteLoadSuccess" and "OnSiteLoadFailed" are never being called. i tried different ways but useless. kindly help..
Mubeen Iqbal
Hi,
ReplyDeletei used your code to generate a silverlight application but i'm facing problem since last three to four days. the problem is that "OnSiteLoadSuccess" and "OnSiteLoadFailed" are never being called. i tried different ways but useless. kindly help..
Mubeen Iqbal
Hi Iqbal,
ReplyDeletePlease try to debug line by line and see whether the code is getting called at least. Put a break point in btnLoadSite_Click() first line and see the code is getting called.
Hi Praveen,
ReplyDeleteyes i checked and event "btnLoadSite_Click()" gets called but "OnSiteLoadSuccess" and "OnSiteLoadFailed" are never being called. what could be the reason for this? any configuration am i missing or any other problem?
Regards,
Mubeen
.xaml code is not visible. there is some error.
ReplyDeleteCould you check once your browser settings? I am able to see the XAML code without any issues.
ReplyDelete-Praveen
It always goes to OnSiteLoadFailure method . please help
ReplyDeleteTIA
This is the error i got:
ReplyDeleteUnhandled Error in Silverlight Application Invalid cross-thread access. at MS.Internal.XcpImports.CheckThread()
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet)
at System.Windows.Controls.ContentControl.set_Content(Object value)
at COMSilverlight.MainPage.OnSiteLoadSuccess(Object sender, ClientRequestSucceededEventArgs e)
at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryGetResponseAsyncCallback(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassd.b__b(Object state2)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() default.aspx, line 1 character 1
I beleive you are using the same code as is and you are deploying the code to a SharePoint server and using in a sharepoint site. Please find the full code here:
ReplyDeletehttp://praveenbattula.blogspot.com/2010/05/silverlight-client-object-model-samples.html
thanks
-Praveen.
Thanx, this was indeed awesome
ReplyDeleteWhy am I getting this error:
ReplyDeleteSilverlight Application The query expression is not supported at Microsoft.SharePoint.Client.DataRetrieval.ProcessMemberAccessQueryExpression
I have deployed my XAP into documents library and approved it. It renders correctly but when I click on button it is giving above error.
Venky,
ReplyDeleteThe error should not come. This is the first time I am seeing this kind of error. I believe as you are deployed with your credentials, I don't think this is not a permissions issue. And the document library you deployed is also in the same site site as you are using silverlight web part. And please get the complete code here and try:
http://praveenbattula.blogspot.com/2010/05/silverlight-client-object-model-samples.html
thanks
-Praveen
Hi, I am new in silverlight
ReplyDeleteI don't find the .dll files which should be located at Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS\ClientBin.
I don't even have this folders. It ends at \14 and then there is nothing
Can I download those dlls somewhere?
Thank you in advance
I believe you can download it from here:
ReplyDeletehttp://www.microsoft.com/downloads/en/details.aspx?FamilyID=b4579045-b183-4ed4-bf61-dc2f0deabe47
Regards
WS