Using the SharePoint ‘Person or Group’ field in code

The following code is a simple example of a Console Application which accepts a semi-colon delimited list of aliases (i.e. domain\user;domain\user;domain\user) and then adds them to a ‘Person or Group’ field called ‘MyPersonField’ in a list.
Console.WriteLine("Enter a ; delimited list of domain\alias that need to be added:");


string sAliases = Console.ReadLine(); //captures whatever the user entered

string sValueToAddToFieldInSP = ""; //used to build the full string needed for the person field



string sAllContacts = "";



using (SPSite site = new SPSite(“http://sites/site/yoursite”))

{

site.AllowUnsafeUpdates = true;

using (SPWeb web = site.RootWeb)

{

web.AllowUnsafeUpdates = true;

string[] aAliases = sAliases.Split(';');

foreach (string sAlias in aAliases)

{

SPUser user = web.EnsureUser(sAlias);

sAllContacts += user.ID.ToString() + ";#" + user.LoginName.ToString() + ";#";

}

web.Update();

}

}



if (sAllContacts.EndsWith(";#"))

{

sAllContacts = sAllContacts.Substring(0, sAllContacts.Length - 2);

}





//add the list item

SPList l = web.Lists[""];

SPListItem li= l.Items.Add();

li["Title"] = sAllContacts ;

li["MyPerson"] = sAllContacts ;

li.Update();

Console.WriteLine("Done");
 
 
 
Note :The UserID relates to the ID of the user within the site collection. This is fine but the chances are that not all users are members of the site collection. To address this, the SharePoint OM has a handy little method called SPWeb.EnsureUser() which accepts a Login Name of a user as a string and first checks if the user exists in the site collection, if it does not then it adds the user and returns an SPUser object. Please be aware that you may need to set SPWeb.AllowUnsafeUpdates = True for this to work.

Comments

Popular posts from this blog

ContextSwitchDeadlock was detected

Visual Studio setup and deployment projects

Using SvcUtil.exe to generate the proxy class and config file