Second Life of a Hungarian SharePoint Geek

May 26, 2010

A more convenient way of creating fields using the managed client object model.

Filed under: Managed Client OM, SP 2010 — Tags: , — Peter Holpar @ 15:58

If you are just start learning the usage of the new managed client object model feature of SharePoint Foundation 2010, one of the first article you might have read is Using the SharePoint Foundation 2010 Managed Client Object Model.

If you read the article, you may be surprised how complicated creation of new list fields is. As you can see, the fields are created using their XML schema, that is not really user (developer) friendly way of work. It’s even more strange if you know that there are specific field type in the client OM as well, like FieldNumber or FieldChoice.

Another article (How to: Create, Update, and Delete Lists, see the Adding a field to a list section) demonstrates a better approach, manipulates field property using their own field type class, but it still creates the fields from the schema XML.

If you check the methods of the FieldCollection class, there is an Add method having a Field parameter. So we can try to create a field from scratch using the constructor, and add it to the collection. The Field constructor has two parameters, ClientRuntimeContext and ObjectPath type. We have the first one in our code, but how to get the second one?

To tell the truth, that is the problematic part of the task. In the client OM each object derived from the ClientObject class has the public Path property of type ObjectPath. When working from Visual Studio 2010, IntelliSense does not show up this property, since it is “reserved for internal use and is not intended to be used directly from your code” and decorated with the [EditorBrowsable(EditorBrowsableState.Never)] attribute, but if you simply type the name of the property instead of relying on IntelliSense, the code will be compiled without any error.

I found that you could use the ObjectPath for your own purposes to do some really great tricks in the client OM, but it is a long story and I will write about that hopefully soon. The bad news is that for this specific case I was not able to create a Field object using this technique.

To hide loading the schema XML I created two extension methods for the FieldCollection class as shown below:

  1. public static class Extensions
  2. {
  3.     public static Field Add(this FieldCollection fields, FieldType fieldType, String displayName, bool addToDefaultView)
  4.     {
  5.         return fields.AddFieldAsXml(String.Format("<Field DisplayName='{0}' Type='{1}' />", displayName, fieldType), addToDefaultView, AddFieldOptions.DefaultValue);
  6.     }
  7.  
  8.     public static Field Add(this FieldCollection fields, FieldType fieldType, String displayName, String[] choices, bool addToDefaultView)
  9.     {
  10.         return fields.AddFieldAsXml(
  11.             String.Format("<Field DisplayName='{0}' Type='{1}'><CHOICES>{2}</CHOICES></Field>",
  12.                 displayName,
  13.                 fieldType,
  14.                 String.Concat(Array.ConvertAll<String, String>(choices, choice => String.Format("<CHOICE>{0}</CHOICE>", choice)))),
  15.             addToDefaultView, AddFieldOptions.DefaultValue);
  16.     }
  17. }

Using these methods it is pretty simple to create the fields for your list:

  1. ClientContext clientContext = new ClientContext("http://sp2010&quot;);
  2. Web web = clientContext.Web;
  3.  
  4. List list = web.Lists.GetByTitle("YourList");
  5. FieldCollection fields = list.Fields;
  6.  
  7. String[] choices = new String[]   
  8.         {
  9.             "Specification",
  10.             "Development",
  11.             "Test",
  12.             "Documentation"
  13.         };
  14.  
  15. FieldChoice fieldChoice = clientContext.CastTo<FieldChoice>(list.Fields.Add(FieldType.Choice, "ChoiceField", choices, true));
  16. fieldChoice.DefaultValue = "Specification";
  17. fieldChoice.EditFormat = ChoiceFormatType.Dropdown;
  18. fieldChoice.Description = "Our choice field";
  19. fieldChoice.Required = true;
  20. fieldChoice.Update();
  21.  
  22. FieldNumber fieldNumber = clientContext.CastTo<FieldNumber>(list.Fields.Add(FieldType.Number, "NumberField", true));
  23. fieldNumber.DefaultValue = "3";
  24. fieldNumber.MinimumValue = 1;
  25. fieldNumber.MaximumValue = 5;
  26. fieldNumber.Description = "Our number field";
  27. fieldNumber.Update();

You can verify the result on the user interface or use the following code snippet to list the choices of the new field from code:

  1. ClientContext clientContext = new ClientContext("http://sp2010&quot;);
  2. Web web = clientContext.Web;
  3.  
  4. List list = web.Lists.GetByTitle("YourList");
  5. FieldChoice field1 = clientContext.CastTo<FieldChoice>(list.Fields.GetByInternalNameOrTitle("ChoiceField"));
  6.  
  7. clientContext.Load(field1,
  8.     field => field.Choices);
  9.  
  10. clientContext.ExecuteQuery();
  11.  
  12. foreach (String choice in field1.Choices)
  13. {
  14.     Console.WriteLine(choice);
  15. }

It’s rather easy to delete the field you have just created using the same managed client OM:

  1. ClientContext clientContext = new ClientContext("http://sp2010&quot;);
  2. Web web = clientContext.Web;
  3.  
  4. List list = web.Lists.GetByTitle("YourList");
  5. Field field1 = list.Fields.GetByInternalNameOrTitle("YourField");
  6.  
  7. field1.DeleteObject();
  8.  
  9. clientContext.ExecuteQuery();

Advertisements

2 Comments »

  1. Hey,

    Good Article,
    This article helped me a lot

    Thanks,
    – Codename “Santosh”

    Comment by Santosh — July 31, 2010 @ 13:03

  2. Awesome. Thank you for this article. This is exactly what I need to do, and thanks for sharing your extension methods. They’ll come in very handy.

    Comment by Adam Collings — February 9, 2012 @ 03:25


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: