# What is the best practice to create property in propertybag (+ indexed for search)

I would like to create a new property to the propertybag. And it needs to be indexed by search. I try this but it is not working:

private void CreatePropertyBagItem(Web web, string key,  string value)
{

//Execute query
web.Context.ExecuteQuery();

//set property bag
web.AllProperties[key] = value;

//Update and write back to web
web.Update();
web.Context.ExecuteQuery();
}


When I remove the row with "AddIndexedPropertyBagKey" it creates successfully a new property in the propertybag, but it is not indexed.

ps. I try to do this in CSOM code.

Vesa Juvonen has methods here.

• This methode (AddIndexedPropertyBagKey) exist. It is an extension method of the [OfficeDevPnP.Core] (github.com/OfficeDev/PnP/tree/…). But you are right, to do that (without OfficeDevPnP) you have to ADD you property in property bag, and after add your new property in the vti_indexedpropertykeys – Nico Oct 28 '16 at 14:56
• Why is my example not working with the pnp solution? – Ola Oct 30 '16 at 9:04

Based on the your comments and my investigation, it looks like there is some issue with the PnP code. Use it as below:

public void UpdateMetadata(ClientContext clientContext, string key)
{
var props = clientContext.Web.AllProperties;
clientContext.ExecuteQuery();

// Confirm that property bag values are indexed by search
List<string> keys = new List<string>();
SetPropertyValue(clientContext, props, "vti_indexedpropertykeys", GetEncodedValueForSearchIndexProperty(keys));
}

public static string GetEncodedValueForSearchIndexProperty(List<string> keys)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (string current in keys)
{
stringBuilder.Append(Convert.ToBase64String(Encoding.Unicode.GetBytes(current)));
stringBuilder.Append('|');
}
return stringBuilder.ToString();
}

public void SetPropertyValue(ClientContext clientContext, PropertyValues props, string key, string value)
{
props[key] = value;
clientContext.Web.Update();
clientContext.ExecuteQuery();
}

• I already using the office dev pnp dll from nuget. But why is my code example not working? What I am doing wrong. The solution is building, but there is nog property in the propertybag. – Ola Oct 30 '16 at 9:03
• have updated the answer. Please check. – Gautam Sheth Oct 30 '16 at 13:03