Quantcast
Viewing all articles
Browse latest Browse all 2

Simplify reading and writing field values of type SPFieldUser, SPFieldUrl and SPFieldLookup using extension methods

To read or write values to fields of type SPFieldUser or SPFielLookup is an annoying task because you have to create field value objects bevore you can write your values into a field. The following post descripes how you can encapsulate those tasks to extension methods and slim your code to make it more readable.

SPFieldUser

The following code displays a couple of extension methods extending the SPListItem class for simple reading and writing access to fields of type SPFieldUser.

using System;
using System.Collections.Generic;
using Microsoft.SharePoint;

namespace ExtensionMethods
{
    public static class SPListItemExtensions
    {
        /// 
        /// Returns the login name of an User-Field.
        /// 
        public static string GetFieldValueUserLogin(this SPListItem item,
          string fieldName)
        {
            if (item != null)
            {
                SPFieldUserValue userValue =
                  new SPFieldUserValue(
                    item.Web, item[fieldName] as string);
                return userValue.User.LoginName;
            }
            else
            {
                return string.Empty;
            }
        }

        /// 
        /// Sets the value of a User-Field to a login name.
        /// 
        public static void SetFieldValueUser(this SPListItem item,
          string fieldName, string loginName)
        {
            if (item != null)
            {
                item[fieldName] = item.Web.EnsureUser(loginName);
            }
        }

        /// 
        /// Sets the value of a User-Field to an SPPrincipal
        /// (SPGroup or SPUser).
        /// 
        public static void SetFieldValueUser(this SPListItem item,
          string fieldName, SPPrincipal principal)
        {
            if (item != null)
            {
                item[fieldName] = principal;
            }
        }

        public static void SetFieldValueUser(this SPListItem item,
          string fieldName, IEnumerable principals)
        {
            if (item != null)
            {
                SPFieldUserValueCollection fieldValues =
                  new SPFieldUserValueCollection();

                foreach (SPPrincipal principal in principals)
                {
                    fieldValues.Add(
                      new SPFieldUserValue(
                        item.Web, principal.ID, principal.Name));
                }
                item[fieldName] = fieldValues;
            }
        }

        /// 
        /// Sets the value of a multivalue User-Field to
        /// a list of user names.
        /// 
        public static void SetFieldValueUser(this SPListItem item,
          string fieldName, IEnumerable loginNames)
        {
            if (item != null)
            {
                SPFieldUserValueCollection fieldValues =
                  new SPFieldUserValueCollection();

                foreach (string loginName in loginNames)
                {
                    SPUser user = item.Web.EnsureUser(loginName);
                    fieldValues.Add(
                      new SPFieldUserValue(
                        item.Web, user.ID, user.Name));
                }

                item[fieldName] = fieldValues;
            }
        }
    }
}

The following lines of code demonstrate how these extension methods can be used.

using ExtensionMethods;

SPList list = web.Lists["MyList"];
SPListItem item = list.Items[0];

// Get a user login of a SPFieldUser field
string userLogin = item.GetFieldValueUserLogin("Author");

// Set a SPFieldUser field to a user using the login
item.SetFieldValueUser("Person", "alexander.bruett");

// Set a SPFieldUser field that allows multiple values to a list of users
string[] persons = { "alexander.bruett", "paul.panzer" };
item.SetFieldValueUser("Mehrere Personen", persons);

// Set a SPFieldUser field to a SPUser
SPUser user = web.Users[1];
item.SetFieldValueUser("Person", user);

// Set a SPFieldUser field to a list of SPPrincipal
SPGroup group = web.Groups[0];
SPUser user = web.Users[0];
SPUser user2 = web.EnsureUser("alexander.bruett");
SPUser user3 = web.EnsureUser("Domain Users"); ;
SPPrincipal[] principals = { group, user, user2, user3 };
item.SetFieldValueUser("AssignedTo", principals);

Especially setting fields that allow multiple values now needs only a couple of code lines.

SPFieldLookup

The SPFieldLookup field is a little bit more complicated if you want to set the field only by the lookup string. You have to query the ID of the lookup value before you can set the field value. The following extension methods simplify this task.

/// 
/// Returns the value of a Lookup Field.
/// 
private static string GetFieldValueLookup(this SPListItem item,
    string fieldName)
{
    if (item != null)
    {
        SPFieldLookupValue lookupValue =
            new SPFieldLookupValue(item[fieldName] as string);
        return lookupValue.LookupValue;
    }
    else
    {
        return string.Empty;
    }
}

/// 
/// Returns the value of a Lookup-Field with multiple values.
/// 
public static IEnumerable GetFieldValueLookupCollection(
    this SPListItem item, string fieldName)
{
    List result = new List();
    if (item != null)
    {
        SPFieldLookupValueCollection values =
            item[fieldName] as SPFieldLookupValueCollection;

        foreach (SPFieldLookupValue value in values)
        {
            result.Add(value.LookupValue);
        }
    }
    return result;
}

/// 
/// Returns the SPFieldLookupValue instance of a lookup value.
/// The ID value will be obtained using SPQuery.
/// 
private static SPFieldLookupValue GetLookupValue(
    SPWeb web, SPFieldLookup field, string lookupValue)
{
    string queryFormat =
        @"
            
                
                {1}
            
          ";

    string queryText =
        string.Format(queryFormat, field.LookupField, lookupValue);
    SPList lookupList = web.Lists[new Guid(field.LookupList)];

    SPListItemCollection lookupItems =
        lookupList.GetItems(new SPQuery() { Query = queryText });

    if (lookupItems.Count > 0)
    {
        int lookupId =
            Convert.ToInt32(lookupItems[0][SPBuiltInFieldId.ID]);

        return new SPFieldLookupValue(lookupId, lookupValue);
    }
    else
    {
        return null;
    }
}

/// 
/// Sets the value of a Lookup-Field.
/// 
public static void SetFieldValueLookup(
    this SPListItem item, string fieldName, string lookupValue)
{
    if (item != null)
    {
        SPFieldLookup field =
            item.Fields.GetField(fieldName) as SPFieldLookup;
        item[fieldName] = GetLookupValue(item.Web, field, lookupValue);
    }
    else
    {
        item[fieldName] = null;
    }
}

/// 
/// Set the values of a Lookup-Field with multiple values allowed.
/// 
public static void SetFieldValueLookup(this SPListItem item,
    string fieldName, IEnumerable lookupValues)
{
    if (item != null)
    {
        SPFieldLookup field =
            item.Fields.GetField(fieldName) as SPFieldLookup;

        SPFieldLookupValueCollection fieldValues =
            new SPFieldLookupValueCollection();

        foreach (string lookupValue in lookupValues)
        {
            fieldValues.Add(
                GetLookupValue(item.Web, field, lookupValue));
        }
        item[fieldName] = fieldValues;
    }
}

That’s been a lot of code but take a look at the following lines of code. Especially the setting task becomes very easy now.

// Reads the value of a SPFieldLookup field
string value = item.GetFieldValueLookup("LookupFieldName");

// Read lookup values of a SPFieldLookup field
// with multiple values allowed
IEnumerable values =
  item.GetFieldValueLookupCollection("MultiLookupFieldName");

// Set the value of a SPFieldLookup field
item.SetFieldValueLookup("LookupFieldName", "LookupValue");

//Set the value of a SPFieldLookup field with multiple values allowed
string[] values = {"Hamburg", "London" };
item.SetFieldValueLookup("MultiLookupFieldName", values);

SPFieldUrl

Setting and getting SPFieldUrl field values is very simple:

/// 
/// Returns the value of an Url-Field.
/// 
public static string GetFieldValueUrl(
    this SPListItem item, string fieldName)
{
    if (item != null)
    {
        SPFieldUrlValue urlValue =
            new SPFieldUrlValue(item[fieldName] as string);
        return urlValue.Url;
    }
    else
    {
        return string.Empty;
    }
}

/// 
/// Sets the value of an URL-Field.
/// 
public static void SetFieldValueUrl(this SPListItem item,
    string fieldName, string url, string description)
{
    if (item != null)
    {
        item[fieldName] =
            new SPFieldUrlValue()
                {
                    Description = description,
                    Url = url
                };
    }
}

The following lines of code show how to get and set values of the SPFieldUrl field using the extension methods above:

// Get the url of a SPFieldUrl field
string url = item.GetFieldValueUrl("URL");

// Set the url and description of a SPFieldUrl field
item.SetFieldValueUrl("URL", "http://www.alexbruett.net", "Alex' Blog");

Conclusion

Using extension methods to simplify the access to complex and SharePoint list fields makes your code more readable and reduces the lines of code.

You could also use helper classes instead of extension methods but you will have to write more code to call a helper method instead of calling a extension method.


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 2

Trending Articles