SharePoint 2010 Client OM: Type Casting Field instances to Field Type instances

If you are using Client Object Model to create Fields, you will be working with the Field class:

private static void AddFieldsToProjectsList()
{
    String fldDescriptionXml = String.Format(FieldXml,
                                            "<guid>",
                                            "Text",
                                            "Description",
                                            "Description",
                                            "TRUE",
                                            "TRUE",
                                            "TRUE",
                                            "TRUE");
            
    String fldDueDateXml = String.Format(FieldXml,
                "<guid>",
                "DateTime",
                "DueDate",
                "Due Date",
                "TRUE",
                "TRUE",
                "TRUE",
                "TRUE");


    using (ClientContext spContext = new ClientContext(_siteUrl))
    {
        spWeb = spContext.Web;                

        List lstProjects = spWeb.Lists.GetByTitle("Projects");

        Field fldDescription = lstProjects
            .Fields
            .AddFieldAsXml(fldDescriptionXml, 
                            true, 
                            AddFieldOptions.AddToDefaultContentType);               
 
        Field fldDueDate = lstProjects
            .Fields
            .AddFieldAsXml(fldDueDateXml, 
                            true, 
                            AddFieldOptions.AddToDefaultContentType);
                
        spContext.ExecuteQuery();
    }
}

As you can see in the above code sample, I am adding a DateTime field. So, what if I have to change the field’s DisplayFormat to Date only?

If you try to cast the Field object to FieldDateTime object, you will get an error:

Unable to cast object of type ‘Microsoft.SharePoint.Client.Field’ to type ‘Microsoft.SharePoint.Client.<field-type>’

image

So, how do we cast then?

You should use SPContext.CastTo method to cast a specified client object to its derived type.

Below is the right way to cast a Field object to FieldDateTime object:

FieldDateTime fldDateField = spContext.CastTo<FieldDateTime>(fldDueDate);
fldDateField.DisplayFormat = DateTimeFieldFormatType.DateOnly;
fldDateField.UpdateAndPushChanges(true);

SharePoint 2010 EcmaScript(JavaScript) IntelliSense in VS2010

If you are using JavaScript Client OM for building SharePoint 2010 solutions, especially manipulating the Ribbon, building modal dialog boxes etc., , you might be wondering how I can get IntelliSense working for my JavaScript code.

 

It is actually very simple. At the top of your .js file, you need to add the following:

 

/// <reference name="MicrosoftAjax.js" />
/// <reference path="file://C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.core.debug.js" />
/// <reference path="file://C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.debug.js" />

 

Depending on your needs, the .js files may change, but you have to include MicrosoftAjax.js.

 

After saving the .js file, press Ctrl + Shift + J  to update the JavaScript IntelliSense.

 

Tip: Sometimes, you might have to press Ctrl + Shift + J for each .js file referenced.

 

After this, I now get the intellisense:

 

JavaScript IntelliSense

 

You can find more options here: http://msdn.microsoft.com/en-us/library/ff798328.aspx

SharePoint 2010: Asynchronous Query Pattern for Client Object Model

In the SharePoint 2010: Getting Started With Client Object Model blog post, we built a simple SharePoint console application using Client OM. We queried synchronously which is good for simple operations, but you would like to query asynchronously too if you intend to have more queries to the SharePoint server. Below are simple yet easy steps to query asynchronously.

Step 1 – Create a new class for our Asynchronous operations

Create a new class ClientOMAsync

Step 2 – Create a delegate for our Query

public class ClientOMAsync
{
delegate void ExecuteAyncQuery();
}

Add the required variables you want to use

Step 3 – Declare our variables

public class ClientOMAsync
{
delegate void ExecuteAyncQuery();

    Web site;
ClientContext context;
}

Step 4 – Create the Run method

public void Run()
{
context =
new ClientContext(http://<your-site>);
site = context.Web;
context.Load(site, s => s.Title);
ExecuteAyncQuery executeQueryAsync = new ExecuteAyncQuery(context.ExecuteQuery);
executeQueryAsync.BeginInvoke(callback, null);
}
Pretty basic Asynchronous programming model and notice again that we are fetching only the Title property.
Step 5 – Create our Callback method
void callback(IAsyncResult arg)
{
Console.WriteLine("Aync Callback!");


Console.WriteLine("Title before changing: {0}",site.Title);
site.Title = site.Title + " Async";
site.Update();


context.ExecuteQuery();


Console.WriteLine("Title after the change: {0}",site.Title);
Console.WriteLine("Query completed!");
}
Step 6 – Perform the Asynchronous Client OM

Below is the code block that starts this asynchronous query operation from the Main method in the console application

static void Main(string[] args)
{
ClientOMAsync clientOMAsync = new ClientOMAsync();
clientOMAsync.Run();


Console.WriteLine("This is end of the Main program");

Console.Read();
}
And here is our Output:
 
image
 
Below is the full code for ClientOMAsync class:
 
public class ClientOMAsync
{
delegate void ExecuteAyncQuery();

Web site;
ClientContext context;

public void Run()
{
context =
new ClientContext("http://demo2010a");
site = context.Web;
context.Load(site, osite => osite.Title);
ExecuteAyncQuery executeQueryAsync = new ExecuteAyncQuery(context.ExecuteQuery);
executeQueryAsync.BeginInvoke(callback, null);
}

void callback(IAsyncResult arg)
{
Console.WriteLine("Aync Callback!");

Console.WriteLine("Title before changing: {0}",site.Title);
site.Title = site.Title + " Async";
site.Update();

context.ExecuteQuery();

Console.WriteLine("Title after the change: {0}",site.Title);
Console.WriteLine("Query completed!");
}
}

SharePoint 2010: Getting Started With Client Object Model

Along with the Server Object Model, SharePoint 2010 introduces new set of API called Client Object Model

Refer to my blog post SharePoint 2010: Introducing the Client Object Model to get to know more about Client Object Model.

The Client Object Model (OM) is a new programming interface for SharePoint 2010 where code runs on a user’s client machine against a local object model and interacts with data on the SharePoint Server.

Lets get started on our ‘Hello Word’ Client Object Model console application.

Step 1 – Reference the Client Object Model

You need to reference two dlls which are available at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI

1. Microsoft.SharePoint.Client

2. Microsoft.SharePoint.Client.Runtime

image

Add the using namespace for Microsoft.SharePoint.Client

using Microsoft.SharePoint.Client;

Step 2 – Create the Client Context

[ We will use the Main function to write our piece of code ]

You need to first create a context to the SharePoint site:

ClientContext context = 
new ClientContext(http://<your-site>);
Step 3 – Create Your Query

Here is the next block of code, explanations will follow below:

Web site = context.Web;
context.Load(site, s => s.Title);

As you can see, we are querying for what we require and nothing else will be returned. In our code, we pass the site to the context, but say we want to query only the property Title.

Step 4 – Execute Your Query

Below is the code to execute the query:

context.ExecuteQuery();

The ExecuteQuery() method is a synchronous method call.

Step 5 – The Output

Below is the output:

image

Another Query Example

ListCollection lists = site.Lists;
IEnumerable<SP.List> listsCollection =
context.LoadQuery(lists.Include(
l => l.Title,
l => l.Id));

The above code queries all the Lists in the site, but only returns the Title and the Id properties.

In the next post, we will see how we can query asynchronously.

SharePoint 2010: Introducing the Client Object Model

SharePoint 2010

 

Today

If you want to access SharePoint Server 2007 Data today, you have two ways of doing it (based on your needs):

  1. Writing a Server Application
    • This application resides in server
  2. Writing a Client Application
    • This client application can run from any other server or a desktop

How are we building these Server and Client applications today?

Server Application

SharePoint Server Application

We interact with the Server Object Model, which are nothing but SharePoint APIs and build applications.

For example:

List<Announcement> announcements = new List<Announcement>();
SPSite site = SPContext.GetContext(HttpContext.Current).Site;
using (SPWeb curWeb = site.OpenWeb())
{
      SPList lstAnnouncements = curWeb.Lists[new Guid(LibraryName)];
 
      //rest of the code
}

Client Application

SharePoint Client Application

We use the SharePoint Web Services which then interacts with the SharePoint API. Usually, developers either build their own set of web services which exposes only certain methods/functions they want to expose to the application or consume the default out of the box SharePoint web services. This becomes difficult if you are going write rich client applications such as Silverlight, or Javascript applications and most of the time accessing SharePoint data via web services is complicated. That is why, I am not going to show you an example code!

The Future of SharePoint Client Applications

SharePoint 2010 introduces the new Client Object Model. From the sneak peak videos:

“The Client Object Model (OM) is a new programming interface for SharePoint 2010 where code runs on a user’s client machine against a local object model and interacts with data on the SharePoint Server. Client OM methods can be called from JavaScript, .NET code or Silverlight code and makes building rich client applications for SharePoint easy.”

So, how things are going to change?

Shareoint Client Application

One API to rule them all – Yep, whether its WPF or Windows Forms or Silverlight or Javascript – your code uses Client Object Model to interact with the SharePoint site to access the data. Now, there is something common that everybody can use instead of creating their own wrapper services to access SharePoint data!

Any code sample?

The only source of information available for now is the Developer Sneak Peak Video.

In the video, a Silverlight application is built using the Client Object Model.

The assemblies added to the project are:

Client Object Model

  • Microsoft.SharePoint.Client.Silverlight.dll
  • Microsoft.SharePoint.Client.Silverlight.Runtime.dll

And also there is a using statement added in the code behind:

Client Object Model

using Microsoft.SharePoint.Client;

And the code showcasing this new Client Object Model:

Client Object Model Code

You can explore the Microsoft.SharePoint.Client namespace in the SharePoint 2010 Technical Preview Documentation

Microsoft.SharePoint.Client namespace

Lets hope this Client Object Model simplifies accessing SharePoint data from client applications :)


Creative Commons License
Chaks' Corner Blog by Chakkaradeep Chandran is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
Based on a work at www.chakkaradeep.com.
Permissions beyond the scope of this license may be available at http://www.chakkaradeep.com.