Quantcast
Viewing latest article 7
Browse Latest Browse All 12

Applying SharePoint Retention Labels Programmatically

So you’ve created and published Retention Labels in Office 365 and now you want to apply labels by CSOM code. It’s not very well documented. The following (crude) code should help you get started applying labels to both individual items and to set as default for the whole library:

First some boilerplate initialization…

using Microsoft.SharePoint.Client.CompliancePolicy;
...
var ctx = GetAppOnlyClientContext("https://mytenant.sharepoint.com/sites/myaswesomesite");
var rootWeb = ctx.Site.RootWeb;
var list = rootWeb.Lists.GetByTitle("My List");
var listRootFolder = list.RootFolder;
ctx.Load(rootWeb);
ctx.Load(list);
ctx.Load(listRootFolder);
await ctx.ExecuteQueryAsync();

Get all labels available on the site:

var availableLabels = SPPolicyStoreProxy.GetAvailableTagsForSite(ctx, "https://mytenant.sharepoint.com/sites/myawesomesite");
await ctx.ExecuteQueryAsync();

Console.WriteLine("All available Retention Labels:");
foreach (var label in availableLabels)
{
    Console.WriteLine("\t" + label.TagName);
}

Get the default label for a list:

var currentLabelApplied = SPPolicyStoreProxy.GetListComplianceTag(ctx, listRootFolder.ServerRelativeUrl);
await ctx.ExecuteQueryAsync();
if(currentLabelApplied.Value != null)
{
    Console.WriteLine("List Default Label: " + currentLabelApplied.Value.TagName);
}

Get labels for all items in a list:

for(var i=1; i<=list.ItemCount; i++)
{
    var item = list.GetItemById(i);
    ctx.Load(item);
    await ctx.ExecuteQueryAsync();
    Console.WriteLine($"Item '{item.FieldValues["Title"]}' has label '{item.FieldValues["_ComplianceTag"]}'");
}

Write label to a list item:

var itemToLabel = list.GetItemById(1);
ctx.Load(itemToLabel);
await ctx.ExecuteQueryAsync();
itemToLabel.SetComplianceTag("My retention Label", false, false, false, false);
itemToLabel.Update();
await ctx.ExecuteQueryAsync();

Set the default label for a list:

var applyToExistingItems = true;
SPPolicyStoreProxy.SetListComplianceTag(ctx, listRootFolder.ServerRelativeUrl, "My Label", false, false, applyToExistingItems);
await ctx.ExecuteQueryAsync();

SetComplianceTag and SetListComplianceTag have parameters (isTagPolicyHold, isTagPolicyRecord and isEventBasedTag) that are not documented what they actually do. Above I have set them to false. If you know what they do, please leave a comment!


Viewing latest article 7
Browse Latest Browse All 12

Trending Articles