SaguiItay

My blog has moved!

You should be automatically redirected in 4 seconds. If not, visit:
http://itaysagui.wordpress.com
and update your bookmarks.

Thursday, September 15, 2011

SharePoint Client Object Model: Adding a Site Column only if it does not already exist

Before creating a new Site Column, you should make sure that the column doesn't already exist. At the very least, make sure that the ID you are using isn't already taken. The sample below uses the FindField method from a previous post:

public static Field EnsureField(this ClientContext clientContext, Web web, Guid id, string name, string schema)
{
	var field = FindField(clientContext, web, f => f.Id == id);
	if (field != null)
		return field;

	var newField = web.Fields.AddFieldAsXml(schema, false,
		AddFieldOptions.AddToNoContentType | AddFieldOptions.AddFieldInternalNameHint);
	clientContext.ExecuteQuery();
	return newField;
}

Labels: , ,

Wednesday, September 14, 2011

SharePoint Client Object Model: Verifying if a Field is part of a Content Type

Before adding a field to a ContentType, it is important to check that the field is not already part of the Content Type. Here's an extension method to ClientContext that does just that:

public static bool ExistInContentType( this ClientContext clientContext, ContentType contentType, Field field)
{
	var fieldLinks = contentType.FieldLinks;
	var existingFields = clientContext.LoadQuery(fieldLinks.Where(fl => fl.Id == field.Id));
	clientContext.ExecuteQuery();
	var existingField = existingFields.FirstOrDefault();
	if (existingField != null)
		return true;
	return false;
}

Labels: , ,

Tuesday, September 13, 2011

SharePoint Client Object Model: Finding a field in a list

When working with the SharePoint Client Object Model, it is useful to find a field in a list, or a site column in the web. Below are some extension methods to ClientContext, to facilitate these:

public static class FieldClientContextExtensions
{
    public static Field FindField(this ClientContext clientContext, List list,                                       
        Expression<Func<Field, bool>> predicate)
    {
        var webFields = list.Fields;
        var matchingFields = clientContext.LoadQuery(webFields.Where(predicate));
        clientContext.ExecuteQuery();

        Field field = matchingFields.FirstOrDefault();
        return field;
    }

    public static Field FindField(this ClientContext clientContext, Web web, Expression<Func<Field, bool>> predicate)
    {
        var webFields = web.Fields;
        var allFields = web.AvailableFields;
        var matchingWebFields = clientContext.LoadQuery(webFields.Where(predicate));
        var matchingAllFields = clientContext.LoadQuery(allFields.Where(predicate));

        clientContext.ExecuteQuery();
        Field field = matchingWebFields.FirstOrDefault() ?? matchingAllFields.FirstOrDefault();
        return field;
    }
}

Labels: , ,