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 (SPSite site = new SPSite(http://mysite/))
{
    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. :-)

2 Comments

  • I was able to get a reference to the field by calling SPWeb.Fields.GetField() or SPWeb.Fields.GetFieldByInternalName().

    Oddly, it seems that trying to get a reference using the Guid throws an exception.

  • We were able to do it with the following code:

    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Publishing;
    ...

    SPField audienceField = site.RootWeb.Fields[FieldId.AudienceTargeting];
    if (
    (audienceField != null)
    && (!list.Fields.ContainsField(audienceField.InternalName))
    )
    {
    list.Fields.Add(audienceField);
    list.Update();
    }

Comments have been disabled for this content.