Enable or Disable Audience targeting of a list in SharePoint

  • Posted by: Softree Technology

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();

            }

        }

    }

}

Author: Softree Technology

Leave a Reply

1 Comment