Enable or Disable Audience targeting of a list in SharePoint

Below code describes how to enable or Disable Audience targeting of a list in sharepoint using client side object model

  1. Add reference “Microsoft.sharepoint.client.dll” and “Microsoft.sharepoint.client.Runtime.dll”.
  2. Write Below Code.

 

using Microsoft.SharePoint.Client;

namespace ConsoleApplication

{  

    class Program

    {

        static void Main(string[] args)

        {

            using (ClientContext ctx=new ClientContext(“SiteUrl”))

            {

                //Apply Credential

                ctx.Credentials = new System.Net.NetworkCredential(“UserName”, “Password”);

                Web web = ctx.Web;

                ctx.Load(web,w=>w.Lists);

                List list = web.Lists.GetByTitle(“New List”);//Load list

                ctx.Load(list, l => l.Fields);

                ctx.ExecuteQuery();

                //Enable Audience Targetting

                try

                {

                    Guid guid = new Guid(“61cbb965-1e04-4273-b658-eedaa662f48d”);

                    Field field = list.Fields.GetById(guid);

                    ctx.Load(field);

                    ctx.ExecuteQuery(); //if field is not present then it will give exception

                }

                catch (Exception ex)

                {

                    string fieldSchema = “<Field ID=”61cbb965-1e04-4273-b658-eedaa662f48d” Type=”TargetTo”     DisplayName=”Target Audiences” Name=”TargetTo” Required=”True” />”;

                    list.Fields.AddFieldAsXml(fieldSchema, true, AddFieldOptions.AddToDefaultContentType);

                    list.Update();

                    ctx.ExecuteQuery();

                }

                //Disable Audience Targetting

                Guid newGuid = new Guid(“61cbb965-1e04-4273-b658-eedaa662f48d”);

                Field fields = list.Fields.GetById(newGuid);

                fields.DeleteObject();

                ctx.ExecuteQuery();

            }

        }

    }

}

Tags: , , , , , , ,

1 thought on “Enable or Disable Audience targeting of a list in SharePoint

Leave a Reply

Your email address will not be published. Required fields are marked *