Recently in our projects, we are using a lot of Property Bag Values. But in some specific requirement, we were trying to Search the Property Bag from the SharePoint Keyword Query. To do that, we want the Property Bag Key to be Indexed as Queryable. That, we need to do programmatically as part of our Provisioning. Let us see, how to do that. The code is very straight forward.
Basically, we are updating a Property Bag called vti_indexedpropertykeys with the values Encoded.
namespace Console.Office365
{
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core;
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
AuthenticationManager authManager = new AuthenticationManager();
var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant("https://***.sharepoint.com/sites/CommunitySite/", "Sathish@******.com", "**********");
Web web = clientContext.Web;
clientContext.Load(clientContext.Web);
clientContext.Load(clientContext.Site);
clientContext.Load(clientContext.Site.RootWeb);
PropertyValues properties = clientContext.Web.AllProperties;
clientContext.Load(properties);
clientContext.ExecuteQuery();
// Get the Existing Property Bag Values from the Indexxed Property Keys
var oldPropertyBagValue = clientContext.Web.PropertyBagContainsKey("vti_indexedpropertykeys") ? Convert.ToString(properties["vti_indexedpropertykeys"]) : string.Empty;
string[] O365Properties = new string[] { "PropertyBagKey1", "PropertyBagKey2", "PropertyBagKey3"};
string newPropertyBagValue = string.Empty;
// Get the New Property Bag Values. In our case, it is propertybagkey1, propertybagkey2 etc.,
foreach (var propertiesString in O365Properties)
{
newPropertyBagValue += Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(propertiesString)) + "|";
}
// Add the new values to the existing ones.
newPropertyBagValue = oldPropertyBagValue + newPropertyBagValue;
// take the Unique Items. There could be changes that a key can be repeated. So always using Distinct.
var distinctNewPropertyBagValue = newPropertyBagValue.Split('|').Distinct().ToArray();
// Update the Property Bag Key
properties["vti_indexedpropertykeys"] = string.Join("|", distinctNewPropertyBagValue).Trim();
web.Update();
clientContext.Load(web.AllProperties);
clientContext.ExecuteQuery();
}
}
}
Happy Coding,
Sathish Nadarajan.
Leave a comment