Friday, February 22, 2013

SharePoint 2013 - How to get HostWeb Info from App

First create SharePoint Hosted App using Visual Studio 2012 and add below given html control in default.aspx page

< div>
        < p id="message1">
            < !-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        < /p>
    < /div>
    < div>
        < p id="percentHTML">
            < !-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing..................
        < /p>
    < /div>
    < p id="hostWebURL">< /p>
    < p id="appWebURL">< /p>

    < div id="message">
    < /div>
    < p id="currentWebText">< /p>
    < ul id="listTree">
    < /ul>

    < div id="addItemPanel" style='display: none'>
        Item Title:
        < input type="text" name="itemTitle" title="Item Title" id="itemTitle" />
        < a href="javascript:createListItem()">Create List Item< /a>
    < /div>


Replace App.js file as given below

var context;
var web;
var hostWeb;
var user;

var hostweburl;
var appweburl;
var appContextSite;
var list;
var collList;
var appContextSite;

function getUrl() {
    hostweburl = getQueryStringParameter("SPHostUrl");
    appweburl = getQueryStringParameter("SPAppWebUrl");
    hostweburl = decodeURIComponent(hostweburl);
    appweburl = decodeURIComponent(appweburl);
    $("#hostWebURL").text("Host Web URL: " + hostweburl);
    $("#appWebURL").text("App Web URL: " + appweburl);
}

function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}


// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    context = SP.ClientContext.get_current();
    web = context.get_web();

    //getUserName();
    getUrl();
    //getHostweb();
    retrieveWebSiteProperties();

});

function getHostweb() {
    var appContextSite = new SP.AppContextSite(
        context,
        hostweburl
    );
    hostWeb = appContextSite.get_web();
    context.load(hostWeb);
    context.executeQueryAsync(onSuccess, onFail);

}
function onSuccess() {
    $('#hostWebInfo').text("Host web title through api " + hostWeb.get_title());
}

// This function is executed if the above call fails
function onFail(sender, args) {
    alert(args.get_message());
}


// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    user = web.get_currentUser();
    context.load(web, 'Title');
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above OM call is successful
// It replaces the contents of the 'helloString' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
    $('#currentWebText').text("Current Web Context: " + web.get_title());

}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}


function retrieveWebSiteProperties() {

    appContextSite = new SP.AppContextSite(
        context,
        hostweburl
    );
    hostWeb = appContextSite.get_web();
    context.load(hostWeb, 'Title', 'Created');

    collList = hostWeb.get_lists();
    context.load(collList, 'Include(Title, Id)');

    context.executeQueryAsync(
        Function.createDelegate(this, onQuerySucceeded),
        Function.createDelegate(this, onQueryFailed)
    );
}

function onQuerySucceeded(sender, args) {
    var message = 'Title: ' + hostWeb.get_title() +
        ' Created: ' + hostWeb.get_created();

    document.getElementById("message").innerText = message;

    //display lists
    var listEnumerator = collList.getEnumerator();
    var listTree = document.getElementById("listTree");
    while (listEnumerator.moveNext()) {
        var oList = listEnumerator.get_current();
        var listTitle = oList.get_title();
        var li = document.createElement("li");
        li.id = listTitle;
        li.appendChild(document.createTextNode(listTitle));
        listTree.appendChild(li);
        if (listTitle == "CustomList1") {
            getListItems();
        }
    }
}

function getListItems() {
    //alert('getting list items');
    //var oList = clientContext.get_web().get_lists().getByTitle('CustomList1');
    var oList = appContextSite.get_web().get_lists().getByTitle('CustomList1');
    var camlQuery = new SP.CamlQuery();
 

camlQuery.set_viewXml(
        '< View>< Query>< Where>< Geq>< FieldRef Name=\'ID\'/>' +
        '< Value Type=\'Number\'>1< /Value>< /Geq>< /Where>< /Query>' +
        '< RowLimit>25< /RowLimit>< /View>'
    );
    this.collListItem = oList.getItems(camlQuery);

    context.load(collListItem);
    context.executeQueryAsync(
        Function.createDelegate(this, onItemsGetQuerySucceeded),
        Function.createDelegate(this, onQueryFailed)
    );

}

function onQueryFailed(sender, args) {
    console.log('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}


function createListItem() {

    //var oList = clientContext.get_web().get_lists().getByTitle('CustomList1');
    var oList = appContextSite.get_web().get_lists().getByTitle('CustomList1');

    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', document.getElementById("itemTitle").value);
    oListItem.update();

    context.load(oListItem);
    context.executeQueryAsync(
        Function.createDelegate(this, this.onItemCreateQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}


function onItemsGetQuerySucceeded() {
    var listItemEnumerator = collListItem.getEnumerator();

    var cl = document.getElementById("CustomList1");
    while (cl.childNodes.length > 0) {
        cl.removeChild(cl.childNodes[0]);

    }
    cl.textContent = cl.id;
    var ul = document.createElement("ul");;
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var li = document.createElement("li");
        li.appendChild(document.createTextNode("Title:" + oListItem.get_item('Title') + " Title: " + oListItem.get_item('Title')));
        ul.appendChild(li);
    }
    cl.appendChild(ul);
    var div = document.createElement("div");
    div.innerHTML = document.getElementById("addItemPanel").innerHTML;
    cl.appendChild(div);
}

function onItemCreateQuerySucceeded() {
    //alert('Item created: ' + oListItem.get_id());
    getListItems();
}


No comments:

Post a Comment