Enable Audience Targeting Programmatically
I've seen the question if it is possible to enable Audience Targetting on a SharePoint document library or list trough code, but I've never found an answer to it. But this weekend Ryan Ramcharan posted a solution in one of the SharePoint Forums posts. It looks like you can enable Audience Targeting programatically by adding the Target Audiences field as XML, here is a small code snippet:
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Shared Documents"];
XmlElement fldElement = new XmlDocument().CreateElement("Field");
fldElement.SetAttribute("ID", "61cbb965-1e04-4273-b658-eedaa662f48d");
fldElement.SetAttribute("Type", "TargetTo");
fldElement.SetAttribute("Name", "TargetTo");
fldElement.SetAttribute("DisplayName", "Target Audiences");
fldElement.SetAttribute("Required", "FALSE");
list.Fields.AddFieldAsXml(fldElement.OuterXml);
list.Update();
}
}
The strange thing is that this seems to only way to add the field, you can't get a hold of the Target Audiences field through the Object Model. Thanks Ryan for posting this solution! And if you know a nicer way to accomplish this, feel free to drop a comment. :-)