Querying
The only major difference between the
Windows Phone CSOM and the Managed CSOM that you will not be familiar
with from previous releases is in how you set up authentication. This
step is required prior to making any CSOM calls. To do it you first
pick the authentication option that your SharePoint site uses. You
create a ClientContext object and then set up the Credentials property on it. In the following example the Credentials property is set to authenticate using Office 365:
ClientContext context = new ClientContext("https://contoso.sharepoint.com/");
Authenticator auth = new Authenticator();
auth.AuthenticationMode = ClientAuthenticationMode.MicrosoftOnline;
context.Credentials = auth;
NOTE
The Windows Phone CSOM library assists your authenticating with
SharePoint Online by opening a Sign In window that allows the user to
sign in to the SharePoint site, as shown in Figure 2. Providing a username and password and circumventing this user interaction are not possible at this time.
Alternatively, if your SharePoint Server uses forms authentication, then you can supply a username and password as follows:
auth.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
auth.UserName = "Your_UserName";
auth.Password = "Password";
After you indicate your authentication options
you are ready to start making CSOM calls to SharePoint. The code is
almost the same as what you would use with the JavaScript or Managed
CSOM; however, because Windows Phone Silverlight requires all network
calls to be made asynchronously, you must cater callbacks in that
manner for when your CSOM call succeeds or fails. To illustrate this
process the following code makes a CSOM call to retrieve a list from
the SharePoint Server:
List list = context.Web.Lists.GetByTitle("My Custom List");
// Load the query and execute the request to fetch data.
context.Load(list);
context.ExecuteQueryAsync((object obj, ClientRequestSucceededEventArgs args) =>
{
// success
var SiteId = list.Id;
},
(object obj, ClientRequestFailedEventArgs args) =>
{
// query failed.
});
As you can see the code defines a success and a
failure function inline using a lambda expression. In your success
function you can query and use the now “full” objects you asked for in
your CSOM query.
The Windows Phone Silverlight
Client-Side Object Model provides a great set of functionality to
quickly get you up and running querying and interacting with
SharePoint. You must take into account some differences with
authentication and some runtime subtleties such as asynchronous
callbacks. However, for the most part you can use the CSOM the same way
you use the Managed CSOM.