Thursday, 13 February 2014

Sandbox add To Property Bag

You can't add to the property bag in a sandbox solution as you would in a farm solution; In a farm solution you would access the AllProperties or Properties collections, but in a sandbox solution you have to use the functions exposed on the SPWeb class.

// Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    var web = properties.Feature.Parent as SPWeb;

    AddValueToPropertyBag(web, "language_en_location", "/sites/ApprovalsPortal/SiteAssets/Navigation_en.xml");
}

private void AddValueToPropertyBag(SPWeb web, string key, string value)
{
    if (web != null)
    {
        web.SetProperty(key, value);

        web.AllowUnsafeUpdates = true;
        web.Update();

        web.AllowUnsafeUpdates = false;
    }
}

// Uncomment the method below to handle the event raised before a feature is deactivated.
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    var web = properties.Feature.Parent as SPWeb;

    RemoveValueFromPropertyBag(web, "language_en_location");
}

private void RemoveValueFromPropertyBag(SPWeb web, object key)
{
    if (web != null && web.AllProperties.ContainsKey(key))
    {
        web.AllowUnsafeUpdates = true;

        web.DeleteProperty(key);
        web.Update();

        web.AllowUnsafeUpdates = false;
    }
}