Tuesday, May 28, 2013

Set and Get property bag values in SharePoint 2013 apps using CSOM

Property bags are a place to store metadata or properties of SharePoint 2013 site. A Property bag is a key value pair, that can be used in Farm, Web Application, Site and Web level.
Following example shows how to write and read the property bag values of host web.
Following code shows how to write value in property bag. Here I am writing value for “Directory Tagged” key.

function tag() {
    var hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    var appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    var clientContext = new SP.ClientContext.get_current();
    var hostContext = new SP.AppContextSite(clientContext, hostweburl);
    var web = hostContext.get_web();
    clientContext.load(web);
    var webProperties = web.get_allProperties();
    clientContext.load(webProperties);
    webProperties.set_item("DirectoryTagged", true);
    web.update();
    clientContext.executeQueryAsync(TaggedSuccess, TaggedFail);
}

function TaggedSuccess(sender, args) {
    $("#results").text("Tagged your site.");
}

function TaggedFail(sender, args) {
    $("#results").text("Tagging failed");
}

In the following code Iam reading the value of “Directory Tagged” key value and the value is ‘True’ Iam disabling the button

function checkIfTagged() {
    var hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    var appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    var clientContext = new SP.ClientContext.get_current();
    var hostContext = new SP.AppContextSite(clientContext, hostweburl);   
    var web = hostContext.get_web();
    clientContext.load(web);

    //get all web properties
    webProperties = web.get_allProperties();
    clientContext.load(webProperties);   
    clientContext.executeQueryAsync(getWebPropertiesSucceeded, getWebPropertiesFailed);
}

function getWebPropertiesSucceeded() {

    //Get all property fields
    var allProps = webProperties.get_fieldValues();
    var customProp = "";

    //Check property exists or not
    if (webProperties.get_fieldValues().DirectoryTagged != undefined) {
        var customProp = webProperties.get_fieldValues().DirectoryTagged;
    }   

    if (customProp == "TRUE")
    {
        //property value is true                       
        $("#results").text("Site tag is true.");
        $("#btnTag").attr("disabled", "disabled");
        return;
    }
    //property value is false
    $("#btnTag").bind("click", tag);
    $("#messageText").text("Site is tag is false.");
}

function getWebPropertiesFailed(args, sender) {
//log error message

Share this