client object model labaz12722.vo.msecnd.net/sp2010devtrainingcourse2-0/... · 3. launch visual...
TRANSCRIPT
Hands-On Lab
Lab: Client Object Model
Lab version: 1.0.0
Last updated: 2/23/2011
CONTENTS
OVERVIEW .................................................................................................................................................. 3
EXERCISE 1: RETRIEVING LISTS............................................................................................................. 4
EXERCISE 2: PRINTING A LIST ................................................................................................................ 8
EXERCISE 3: USING ADO.NET DATA SERVICES .................................................................................. 13
Overview
Lab Time: 45 minutes
Lab Folder: C:\Student\Labs\06_ClientOM
Lab Overview: The Client Object Model extends the familiar server-side object model to the client. The
Client Object Model comes in three flavors: .NET, JavaScript and Silverlight. The .NET model can be used
with console applications and Windows applications, while the Silverlight client object model can be
used from within Silverlight applications. The JavaScript model is used in client scripting. In this lab,
you’ll make use of the different Client Object Models to build different applications.
Note: Lab Setup Requirements
This lab requires the OpenXML 2.0 SDK to be installed. This should already be installed on your
student VM.
Before you begin this lab, you must run the batch file named SetupLab06.bat. This batch file
creates a new SharePoint site collection at the location
http://intranet.contoso.com/sites/Lab06.
Exercise 1: Retrieving Lists
In this exercise you will create the first part of a Windows application for printing SharePoint lists as
Word documents. You will retrieve the available lists from a SharePoint site using the .NET Client Object
model.
1. If you haven’t already done so, run the batch file named SetupLab06.bat, found in the
c:\Student\Labs\06_ClientOM\ folder, to create the new site collection that will be used to test
and debug the code you will be writing in this lab. This batch file creates a new site collection at
an URL of http://intranet.contoso.com/sites/Lab06.
2. Launch Internet Explorer and navigate to the top-level site at
http://intranet.contoso.com/sites/Lab06. Take a moment to inspect the site and make sure it
behaves as expected. Note that the setup script creates a new site collection with a Blank site
as its top-level site.
3. Launch Visual Studio 2010.
4. In Visual Studio, start a new project by selecting File » New » Project.
5. In the New Project dialog, expand the nodes Visual C#/Visual Basic » Windows and select
Windows Forms Application. Make sure that Framework 3.5 is selected.
6. Name the new project ListPrinter and click the OK button.
7. Add a reference to the Client Object Model by selecting Project » Add Reference from the
Visual Studio main menu. In the References dialog, on the .NET tab select both the
Microsoft.SharePoint.Client and Micorosoft.SharePoint.Client.Runtime compontents. Click
OK.
Note: if you cannot find these in the .Net tab, Browse to C:\Program Files\Common
Files\Microsoft Shared\web server extensions\14\ISAPI and select the following assemblies,
then click OK to add the references to the project:
C#
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll
8. Drag a TextBox control onto Form1. You’ll use this TextBox to specify the Url for the site where
you want to access list data. Set the Name property to UrlTextBox.
9. Drag a ListBox control onto Form1. You’ll use this to show the lists available from the site. Set
the Name property to ListsListBox.
10. Drag a Button control onto Form1. You’ll use this button to connect with the site and fill the
ListBox. Change the Text property of this button to Show Lists and the Name property to
ShowButton.
11. Set the Form1 Text property to Client Object Model.
12. You can optionally drag additional labels onto the form to make it look like the following:
Figure 1
Design the user interface of the form
13. Double-click the Button control to open the code window. To avoid ambiguous references
between the Client Object Model and the Windows Forms namespace, add the following
statement to the top of the code module.
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ClientOM = Microsoft.SharePoint.Client;
VB.NET
Imports ClientOM = Microsoft.SharePoint.Client
14. Enter the following code in the ShowButton_Click event to retrieve the available lists from the
target site.
C#
private void ShowButton_Click(object sender, EventArgs e)
{
//Show the hourglass wait cursor
this.Cursor = Cursors.WaitCursor;
ListsListBox.Items.Clear();
//Get a context
using (ClientOM.ClientContext ctx =
new ClientOM.ClientContext(UrlTextBox.Text))
{
//Get the site
ClientOM.Web site = ctx.Web;
ctx.Load(site);
//Get Lists
ctx.Load(site.Lists);
//Query
ctx.ExecuteQuery();
//Fill List
foreach (ClientOM.List list in site.Lists)
{
ListsListBox.Items.Add(list.Title);
}
//Return the cursor to normal
this.Cursor = Cursors.Default;
}
}
VB.NET
Private Sub ShowButton_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles ShowButton.Click
'Show the hourglass wait cursor
Me.Cursor = Cursors.WaitCursor
ListsListBox.Items.Clear()
'Get a context
Using ctx As New ClientOM.ClientContext(UrlTextBox.Text)
'Get the site
Dim site As ClientOM.Web = ctx.Web
ctx.Load(site)
'Get Lists
ctx.Load(site.Lists)
'Query
ctx.ExecuteQuery()
'Fill List
For Each list As ClientOM.List In site.Lists
ListsListBox.Items.Add(list.Title)
Next
'Return the cursor to normal
Me.Cursor = Cursors.[Default]
End Using
End Sub
15. Run your project, enter http://intranet.contoso.com/sites/Lab06 in the TextBox control and
click the Show Lists button. Verify that you are returning lists from the site.
Note: If you get an error when the ClientContext calls ExecuteQuery(), try navigating to the
site in the browser first, then rerun the code.
Figure 2
The .NET Client object model in action
16. Stop the project and return to Visual Studio.
Note: In this exercise you created a Windows Forms application that used the SharePoint
Client Object Model to query a SharePoint site for all the lists in the site and display them in a
listbox.
Exercise 2: Printing a List
In this exercise you will finish the application by using a combination of the Client Object model and the
Open XML 2.0 SDK for Office to create a Word document that contains list items from a selected list.
This exercise requires that the OpenXML 2.0 SDK is installed.
1. Using the same Windows Form application from the previous exercise, drag a new Button
control to Form1. This second button will be used to create a Word document from the items in
a selected list.
2. Change the Text property for the Button to Print List. Change the Name property to
PrintButton
3. Add a reference to the OpenXML SDK 2.0 API by selecting Project » Add Reference from the
Visual Studio main menu.
a. In the References dialog, set a reference to DocumentFormat.OpenXML. If this does not
show up on the .Net references tab, you will have to browse to the C:\Program Files
(x86)\OpenXML SDK\v2.0\lib directory.
b. Add another reference to WindowsBase.dll assembly by following the same steps.
Again, if this does not show up on the .Net references Tab, browse to C:\Program
Files\Reference Assemblies\Microsoft\Framework\v3.0 and select to set a reference
to WindowsBase.dll.
4. When Form1 open in Design mode, double click the Print List button to open the code window.
5. Add the following statements to the top of the code module to use the Open XML 2.0 API.
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ClientOM = Microsoft.SharePoint.Client;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
Visual Basic
Imports ClientOM = Microsoft.SharePoint.Client
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing
6. Add the following code to the Click event of the Print List button to retrieve the columns and
list items that you will need to build the document.
C#
private void PrintButton_Click(object sender, EventArgs e)
{
if (ListsListBox.SelectedIndex > -1)
{
//Context
using (ClientOM.ClientContext ctx = new
ClientOM.ClientContext(UrlTextBox.Text))
{
//Get selected list
string listTitle = ListsListBox.SelectedItem.ToString();
ClientOM.Web site = ctx.Web;
ctx.Load(site,s => s.Lists.Where(l => l.Title ==
listTitle));
ctx.ExecuteQuery();
ClientOM.List list = site.Lists[0];
//Get fields for this list
ctx.Load(list,l => l.Fields.Where(f => f.Hidden == false &&
(f.CanBeDeleted == true || f.InternalName == "Title")));
ctx.ExecuteQuery();
//Get items for the list
ClientOM.ListItemCollection listItems =
list.GetItems(ClientOM.CamlQuery.CreateAllItemsQuery());
ctx.Load(listItems);
ctx.ExecuteQuery();
// DOCUMENT CREATION CODE GOES HERE
}
MessageBox.Show("Document Created!");
}
}
Visual Basic
Private Sub PrintButton_Click(ByVal sender As Object, ByVal e As
EventArgs) _
Handles PrintButton.Click
If ListsListBox.SelectedIndex > -1 Then
'Context
Using ctx As New ClientOM.ClientContext(UrlTextBox.Text)
'Get selected list
Dim listTitle As String =
ListsListBox.SelectedItem.ToString()
Dim site As ClientOM.Web = ctx.Web
ctx.Load(site, Function(s) s.Lists.Where(Function(l)
l.Title = listTitle))
ctx.ExecuteQuery()
Dim list As ClientOM.List = site.Lists(0)
'Get fields for this list
ctx.Load(list, Function(l)l.Fields.Where(Function(f)
f.Hidden = False _
AndAlso (f.CanBeDeleted = True _ OrElse f.InternalName =
"Title")))
ctx.ExecuteQuery()
'Get items for the list
Dim listItems As ClientOM.ListItemCollection
=list.GetItems(ClientOM.CamlQuery.CreateAllItemsQuery())
ctx.Load(listItems)
ctx.ExecuteQuery()
' DOCUMENT CREATION CODE GOES HERE
End Using
MessageBox.Show("Document Created!")
End If
End Sub
Note: The Open XML formats use a set of XML documents to represent all of the components
of an Office 2007 document. These components are referred to as “parts”. Parts are
designated through content type URI’s (not to be confused with SharePoint content types!).
So, the process of creating a Word document involves the proper creation and packaging of
the required “parts”. The OpenXML 2.0 SDK makes it easier to create these parts because it
provides strongly-types objects from which you can build a document. The document you will
create will contain a table with columns for each field in the list.
7. Add the following code into your project to build the document.
C#
private void PrintButton_Click(object sender, EventArgs e)
{
...
ctx.Load(list.Items);
ctx.ExecuteQuery();
//Create the document
using (WordprocessingDocument package =
WordprocessingDocument.Create("c:\\" +
istsListBox.SelectedItem.ToString() + ".docx",
WordprocessingDocumentType.Document))
{
Body body = new Body();
Table table = new Table();
//Columns
TableRow colRow = new TableRow();
foreach (ClientOM.Field field in list.Fields)
{
TableCell colCell = new TableCell();
colCell.Append(new Paragraph(new Run(new
Text(field.Title))));
colRow.Append(colCell);
}
table.Append(colRow);
//Rows
foreach (ClientOM.ListItem item in listItems)
{
TableRow dataRow = new TableRow();
foreach(ClientOM.Field field in list.Fields)
{
TableCell dataCell = new TableCell();
string dataVal = string.Empty;
try
{
dataVal
=item[field.InternalName].ToString();
}
catch{ dataVal = "-"; }
dataCell.Append(new Paragraph(new Run(new
Text(dataVal))));
dataRow.Append(dataCell);
}
table.Append(dataRow);
}
body.Append(table);
//Build document package
package.AddMainDocumentPart();
package.MainDocumentPart.Document = new Document(body);
package.MainDocumentPart.Document.Save();
package.Close();
}
}
MessageBox.Show("Document Created!");
}
}
Visual Basic
Private Sub PrintButton_Click(ByVal sender As Object, ByVal e As
EventArgs)
Handles PrintButton.Click
ctx.Load(list.Items)
ctx.ExecuteQuery()
' DOCUMENT CREATION CODE GOES HERE
'Create the document
Using package As WordprocessingDocument =
WordprocessingDocument.Create("c:\" +
ListsListBox.SelectedItem.ToString()
& ".docx", WordprocessingDocumentType.Document)
Dim body As New Body()
Dim table As New Table()
'Columns
Dim colRow As New TableRow()
For Each field As ClientOM.Field In list.Fields
Dim colCell As New TableCell()
colCell.Append(New Paragraph(New Run(New
Text(field.Title))))
colRow.Append(colCell)
Next
table.Append(colRow)
'Rows
For Each item As ClientOM.ListItem In listItems
Dim dataRow As New TableRow()
For Each field As ClientOM.Field In list.Fields
Dim dataCell As New TableCell()
Dim dataVal As String = String.Empty
Try
dataVal =
item(field.InternalName).ToString()
Catch
dataVal = "-"
End Try
dataCell.Append(New Paragraph(New Run(New
Text(dataVal))))
dataRow.Append(dataCell)
Next
table.Append(dataRow)
Next
body.Append(table)
'Build document package
package.AddMainDocumentPart()
package.MainDocumentPart.Document = New
Document(body)
package.MainDocumentPart.Document.Save()
package.Close()
End Using
End Using
MessageBox.Show("Document Created!")
End If
End Sub
8. Once you have finished coding, verify that the project compiles and starts it in Visual Studio by
building and running it [Ctrl] + [F5]. You should be able to enter a URL for a site and retrieve the
lists for the site. Then select a list from the site and print it. A new Word document will appear
in the root of the C:\ drive having a name that is the title of the selected list.
(Note: as we do not have much data on this site, the documents created will likewise not have
much data in them. One list that has a couple of entries on it is the Web Part Gallery, if you
wish to see some data in your word document try selecting this one to Print)
Note: In this exercise you added code to the existing Windows Forms application that prints
the contents of a SharePoint list to a Word document using the OpenXML 2.0 SDK.
Exercise 3: Using ADO.NET Data Services
In this exercise you will create an application using ADO.NET Data Services. This exercise requires the
installation of ADO.NET Data Services version 1.5 (CTP2). You should also have completed Lab 5 LINQ to
SharePoint because you will reuse the lists from that lab in this exercise.
1. In Visual Studio 2010, create a new project by selecting File » New » Project.
2. In the New Project dialog, expand the nodes Visual C#/Visual Basic » Windows and select
Windows Form Application. Pay attention that the Framework 3.5 is selected.
3. Name the new project ProjectManagers and click the OK button.
4. When the new project opens, right-click the References node in the Solution Explorer and
select Add Service Reference.
5. In the Add Service Reference dialog, enter the URL for the ListData Web Service. This service is
available through the ListData.svc endpoint. You can create a URL for the service by appending
_vti_bin/ListData.svc to the URL for the site you created in a previous lab (e.g.,
http://intranet.contoso.com/sites/Lab05/_vti_bin/ListData.svc).
6. Once you have located the ListData service, change the namespace in the Add Service
Reference to MyDataService. Then click the OK button.
Note: When Visual Studio makes the service reference, it uses the functionality found in
System.Data.Service.Client. However, you need to replace this reference with a reference to
Microsoft.Data.Services.Client, which is part of the ADO.NET Data Services 1.5 CTP2.
Figure 3
The System.Data.Services.Client reference
7. Right click the System.Data.Services.Client reference in the Solution Explorer and select
Remove from the menu.
8. Right click the References node in the Solution Explorer and select Add Reference.
9. In the Add Reference dialog, click the Browse tab. Navigate to C:\Program Files (x86)\ADO.NET
Data Services V1.5 CTP2\bin. Add a reference to Microsoft.Data.Services.Client.dll.
Figure 4
Add a reference to the Microsoft.Data.Services.Client
Note: In addition to replacing the client-side assembly, you must also make new proxy classes
for your project. This is because Visual Studio does not use the proxy creation capability found
in ADO.NET Data Services 1.5 CTP2. You can make the new proxies using a command-line
utility.
10. Open a command window and change the directory to C:\Program Files (x86)\ADO.NET Data
Services V1.5 CTP2\bin.
11. At the command prompt, type the following to generate new proxy classes:
C#
DataSvcUtil.exe
/uri:http://intranet.contoso.com/sites/Lab05/_vti_bin/ListData.svc
/language:CSharp /out:Reference.cs
Visual Basic
DataSvcUtil.exe
/uri:http://intranet.contoso.com/sites/Lab05/_vti_bin/ListData.svc
/language:VB /out:Reference.vb
12. Copy the new file Reference.cs (found in the same directory where the DataSvcUtil.exe was
executed) over existing file with the same name in the MyDataService folder of your project.
Your project is now all set to use the new ADO.NET Data Services.
13. In Visual Studio open the Data Sources window by selecting Data » Show Data Sources from
the menu. In this window, you should see the lists available on the SharePoint site.
Figure 5
The Data Sources window
Note: If you don’t see data sources listed in the Data Sources window, right-click the
MyDataService reference in the Solution Explorer and select Update Service Reference. If you
do this, make sure you go back and remove the reference to System.Data.Services.Client that
was re-added by Visual Studio.
14. In the Data Sources window, click the Add New Data Source button (left-most button).
15. In the Data Source Configuration Wizard, select Object and click the Next button.
16. On the Select Data Objects screen, expand the ProjectManagers treeview. Select
EmployeesItem and ProjectsItem and click the Finish button.
Figure 6
The Data Source Configuration Wizard
17. Drag the ProjectsItem data source from the Data Sources window and drop it on the Windows
form. This action will create a grid on the form.
Figure 7
Drag and drop the ProjectItems data source
18. Right click the grid and select Edit Columns from the context menu. Remove all of the columns
except for Title, and Description. Then click the OK button.
19. To work with LINQ in SharePoint, you need to add a reference to a new assembly. Do this with
the following steps:
a. Select Project » Add Reference from the Visual Studio main menu.
20. In the Add Reference dialog, on the .NET tab select Microsoft.SharePoint.Linq and click the OK
button.
(Note: if you cannot find it here, Browse to c:\Program Files\Common Files\Microsoft
Shared\web server extensions\14\ISAPI and select Microsoft.SharePoint.Linq.dll. Then click
the OK button.
21. Open the code window for the form and add the following statements to the top of the code
module.
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint.Linq;
using System.Net;
Visual Basic
Imports Microsoft.SharePoint.Linq
Imports System.Net
22. Add code to create a context object so that your project matches the following.
C#
namespace ProjectManagers
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Context
MyDataService.Lab5UsingLINQToSharePointDataContext ctx =
new MyDataService.Lab5UsingLINQToSharePointDataContext(new Uri(
"http://intranet.contoso.com/sites/Lab05/_vti_bin/ListData.svc"));
}
Visual Basic
Public Class Form1
'Context
Private ctx As New
MyDataService.Lab5UsingLINQToSharePointDataContext(New
Uri("http://intranet.contoso.com/sites/Lab05/_vti_bin/ListData.svc"))
End Class
Note: If you encounter an error after having typed in MyDataService, remove the complete
statement and type Lab5UsingLINQToSharePointDataContext. Right-click this and choose
Resolve. Click on the suggested using statement.
23. In the Form1_Load event, add the following code to bind the list items to the grid. If the
Form1_Load event doesn’t exist, go back to the Design and double-click the form to create it.
C#
private void Form1_Load(object sender, EventArgs e)
{
ctx.Credentials = CredentialCache.DefaultCredentials;
var q = from p in ctx.Projects select p;
this.projectsItemBindingSource.DataSource = q;
}
Visual Basic
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
ctx.Credentials = CredentialCache.DefaultCredentials
Dim q = From p In ctx.Projects _
Select p
Me.projectsItemBindingSource.DataSource = q
End Sub
24. Run the project now and you should see some results in the grid.
25. Return to Visual Studio. Open Form1 in Design view and right-click the save icon on the form
and select Enabled from the context menu.
Figure 8
Configure the data source
26. Now add the following code to your project to enable saving the changes you make in the grid.
C#
private void projectsItemBindingNavigatorSaveItem_Click(object sender,
EventArgs e)
{
ctx.SaveChanges();
}
private void projectsItemBindingSource_CurrentChanged(object sender,
EventArgs e)
{
ctx.UpdateObject(this.projectsItemBindingSource.Current);
}
Visual Basic
Private Sub projectsItemBindingNavigatorSaveItem_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
ctx.SaveChanges()
End Sub
Private Sub projectsItemBindingSource_CurrentChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs)
ctx.UpdateObject(Me.projectsItemBindingSource.Current)
End Sub
27. Go back to the Design view, right click the Save button and select Properties. This will open the
Properties tool window. In the Click event, select
projectsItemBindingNavigatorSaveItem_Click.
Figure 9
Bind the click event to the SaveItem event handler
28. In the drop down at the top of the Properties tool window, change the selection from
projectsItemBindingNavigatorSaveItem to projectsItemBindingSource. In the CurrentChanged
event, select projectsItemBindingSource_CurrentChanged.
Figure 10
Bind the CurrentChanged event to the event handler
29. Run the project again and make a few changes to the existing items clicking the Save button
when finished (make sure you change the focus so the control knows there are changes to a
specific item). Now open the browser and go find the item you just changed to see if in fact
your changes were persisted.
Note: In this exercise you utilized ADO.NET Services to retrieve and update items within a
SharePoint list.