Get the mail address from a FieldUserValue Client Side vs Server Side

In SharePoint are two ways to code by using an object model. The one way is the Client-Side Object Modell (CSOM) and the other side is the Server-Side Object Model (SSOM). At the first look they both look the same the only difference is how the objects are looking for example the is the 'Site'-object (client side) is called 'SPSite' on server side. A good way to demonstrate the difference is to get the mailaddress of a userfield. That sounds easy, but needs more lines that I thought at first. So let's say you got a SharePoint 2013 and want to read the mailaddress on client side. That would look like this:

1
2
3
4
5
6
7
8
9
// get the userfield of the item e.q. Author
FieldUserValue Author = (FieldUserValue)currentItem["Author"];
// ask the web to find a user with the id in the field (only works if the user visited the site)
var user = web.SiteUsers.GetById(Author.LookupId);
// load the data with the context
context.Load(user);
context.ExecuteQuery();
// read the address
Console.WriteLine(user.Email);


If you are using a SharePoint 2010 it would look like this:

1
2
3
4
5
6
7
8
9
// get the userfield of the item e.q. Author
FieldUserValue Author = (FieldUserValue)currentItem["Author"];
// ensure the user exists with the web in case the user exist you get the data
var user = web.EnsureUser(Author.LookupValue);
// load the data with the context               
context.Load(user);
context.ExecuteQuery();
// read the address
Console.WriteLine(user.Email);

That is the Client Side. The difference to the Server Side code is not only that you need add SP to the object names. The biggest point is that the context is not necessary. So the Server Side code looks like this:

1
2
3
4
5
6
// get the value of the column
SPFieldUser UserColumn = (SPFieldUser)item.Fields.GetField("Author");
// get the value out of the column
SPFieldUserValue fieldValue = UserColumn.GetFieldValue(item["Author"].ToString()) as SPFieldUserValue;
// read the address
Console.WriteLine(fieldValue.User.Email);

This works also on SharePoint 2010.
So the big thing is that you do not need to ask for the information you are looking for, the server got them instant.

Comments

Popular posts from this blog

How to support multiple languages in WPF