Thursday, 27 August 2015

Get User Profile using REST in SharePoint hosted App (JSOM)

We can get current user Profile like Display name , Email ,Picture Url etc using REST.
REST :
$.ajax({
  url: "http://<site url>/_api/sp.userprofiles.peoplemanager
    /getmyproperties",
  type: "GET",
  headers: { "accept": "application/json;odata=verbose" },
  success: successHandler,
  error: errorHandler
});


Refer msdn Link

Html code in ContentPlaceHolderID of my .aspx page

Before go further, kindly ensure "SP.UserProfiles.js" should load.

 <script type="text/javascript" src="/_layouts/15/SP.UserProfiles.js"></script> 

<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

    <div>
        <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        </p>
         <p id="Email"></p>       
        <img id="profileimg" alt="profile image"/>
    </div>

</asp:Content>


App.JS

//'use strict';

var hostweburl;
var appweburl;

// Get the URLs for the add-in web the host web URL from the query string.
$(document).ready(function () {
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    alert(hostweburl);
    var scriptbase = hostweburl + "/_layouts/15/";
    SP.SOD.executeOrDelayUntilScriptLoaded(testfunction, 'SP.UserProfiles.js');

});

function testfunction() {
    $.ajax({
        url: appweburl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",
        // url: hostweburl + "/_api/sp.userprofiles.peoplemanager/getmyproperties",
        type: "GET",
        headers: { "accept": "application/json;odata=verbose" },
        success: successHandler,
        error: errorHandler
    });

}


function successHandler(data) {
    var pictureURL = data.d.PictureUrl;
   // alert(pictureURL);
    $('#message').text('Name:'  + data.d.DisplayName);
    $('#Email').text('Email:' + data.d.Email);
    $('#profileimg').attr('src', data.d.PictureUrl);
}

function errorHandler(data, ajaxOptions, thrownError) {
    alert('Failed');
}

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];
    }
}


OutPut :


FAQ Sample logic in SharePoint Hosted App (JSOM)

Here I am going to perform FAQ operation with SharePoint hosted app (JSOM) .

We need two list
1] FAQ Category
2]FAQ Bank

1] FAQ Category :


From this list , we will bind items to drop down.


2]FAQ Bank:

In this list , we will submit questions on click of submit button.
As well , will  fetch  question and answers based on selected FAQ category from drop down.



FAQ Functionality :

Employee can submit questions : select category from dropdown (binding category from list) and enter question . Question will be submitted click on submit button.

Employee can view FAQs : Select FAQ category from Dropdown. Click on search FAQs, able to view respective FAQs against selected FAQ category.


Html code in ContentPlaceHolderID of default.aspx page .

<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

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

        <select id="Category">
 </select>
        <br />
        <br />
        <input type="text" name="Question" id="Question" placeholder="Enter Question"/><br/> <br />
<input type="submit" value="Submit" id="subtn" onclick="btnSubmit_OnClientClick(); return false;"/>
        <br />
        <br />

        <input type="submit" value="Search FAQ" id="searchfaq" onclick="btnSearchFAQ_OnClientClick(); return false;"/>
        <br />
        <br />
        
        <table id="tblFAQ">
         
        </table>
    </div>

</asp:Content>


App.JS Code

'use strict';

function manageQueryStringParameter(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];
        }
    }
}


var hostWebUrl;
var appWebUrl;
var list1;
var allItems;
var web;
// 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 () {
    hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
    appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
    getUserName();
});

// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    var context = new SP.ClientContext(appWebUrl);
    var appCtxSite = new SP.AppContextSite(context, hostWebUrl);
    web = appCtxSite.get_web();
    list1 = web.get_lists().getByTitle("FAQ Category");

    //context.load(list);
    //context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
    
    var myquery = new SP.CamlQuery.createAllItemsQuery();
    allItems = list1.getItems(myquery);
    context.load(allItems);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}


// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + 'Anup Ghume');
    var test;
    var ListEnumerator = allItems.getEnumerator();
    while (ListEnumerator.moveNext()) {
        var currentItem = ListEnumerator.get_current();
        test = currentItem.get_item('Category');
        //alert(test);
        //fillDropDown();
        var ddlCategory = document.getElementById('Category');          
        Category.options[Category.options.length] = new Option(currentItem.get_item('Category'), currentItem.get_item('ID'));

    }
}

function fillDropDown() {
    var ddlCategory = document.getElementById('Category');
    if (ddlCategory != null) {
        alert("ookk");
    }
}

function btnSubmit_OnClientClick() {
    //var categoryValue = document.getElementById('Category').value;
    
    var e = document.getElementById("Category");
    var categoryValue = e.options[e.selectedIndex].text;
    alert(categoryValue);
    var QuestionValue = document.getElementById("Question").value;
    alert(QuestionValue);
    //var list = web.get_lists().getByTitle("FAQ Bank");
    var context = new SP.ClientContext(appWebUrl);
    var appCtxSite = new SP.AppContextSite(context, hostWebUrl);
    web = appCtxSite.get_web();
    var list = web.get_lists().getByTitle("FAQ Bank");

    var listItemCreationInfo = new SP.ListItemCreationInformation();
    var item = list.addItem(listItemCreationInfo);

    item.set_item("FAQCategory", categoryValue);
    item.set_item("Question", QuestionValue);
    item.update();

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

    function SaveEmployeeSuccess() {
        document.getElementById("Question").value = "";
        document.getElementById("Category").selectedIndex = 0;
    }

    function SaveEmployeeFailure() {
        alert('item not save');
    }

    function btnSearchFAQ_OnClientClick() {
        var e = document.getElementById("Category");
        var categoryValueOnSearch = e.options[e.selectedIndex].text;
        alert(categoryValueOnSearch);

        var context = new SP.ClientContext(appWebUrl);
        var appCtxSite = new SP.AppContextSite(context, hostWebUrl);
        web = appCtxSite.get_web();
        var list = web.get_lists().getByTitle("FAQ Bank");

        var query = new SP.CamlQuery();
        //query.set_viewXml('<Where><Eq><FieldRef Name=\'FAQCategory\' /><Value Type=\'Text\'>UI</Value></Eq></Where>');
        query.set_viewXml("<View><Query><Where><Eq><FieldRef Name='FAQCategory' /><Value Type='Text'>" + categoryValueOnSearch + "</Value></Eq></Where></Query></View>");


        var items = list.getItems(query);
        context.load(list);
        context.load(items);

        var table = $("#tblFAQ");
        var innerHtml = "<tr><td>Questions</td><td>Answers</td></tr>";

        context.executeQueryAsync(
        Function.createDelegate(this, function () {
            //var itemInfo = '';
            var enumerator = items.getEnumerator();
            while (enumerator.moveNext()) {
                var currentListItem = enumerator.get_current();
                //alert(currentListItem.get_item('Question'));
                innerHtml += "<tr><td>" + currentListItem.get_item('Question') + "</td><td>" + currentListItem.get_item('Answer') + "</td></tr>";

            }
            table.html(innerHtml);
        }),
        Function.createDelegate(this, fail)
        );
    }
        function fail() {
            alert("Fail all");
        }

        
    

Wednesday, 19 August 2015

CRUD operation with SharePoint Hosted App - Part 2

Create a list "StudentList" in Visual Studio with column in snap below.



Refer some basic links: List Operations on Sharepoint Apps: using ECMAScript
                                      Check whether the list exists or not using ECMAScript
                                       Create fields in sharepoint list using ECMAScript
                                     

Add below HTML in "PlaceHolderMain"section of  .aspx page

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

    <script src="../JS/jquery-1.11.1.js"></script>
    <script src="../JS/AddToList.js"></script>
    <link href="../CSS/RefClass.css" rel="stylesheet" />
    <div>
        <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        </p>
    </div>

    <div>
        <table border="1" cellpadding="1" cellspacing="1" class="style1" frame="box">
            <tr>
                <td>
                    <h3>Name *</h3>
                </td>
                <td>
                    <input type="text" id="txtName" />
                </td>
                <td></td>

                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>
                    <h3>Surname</h3>
                </td>
                <td>
                    <input type="text" id="txtSurname" />

                </td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td></td>

                <td>
                    <input type="button" id="btnSave" value="Save" onclick="SaveStudentToList();"></td>

                </td>
         
        <td>

            <td>&nbsp;</td>
            </tr>
            <tr>
                <td>

                    <td></td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
        </table>
    </div>

 

    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <div id="dvListView">
                <table id="tblCustomListData" border="1">
                    <thead>
                        <tr>
                            <th>Name
                            </th>
                            <th>Surname
                            </th>
                            <th>Mathematics
                            </th>
                            <th>Chemistry
                            </th>
                            <th>Physics
                            </th>
                            <th>Action
                            </th>
                         
                        </tr>
                    </thead>
                </table>

            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>



My .js code ,  added a reference in .aspx i.e. AddToList.js


$(document).ready(function () {

    ExecuteOrDelayUntilScriptLoaded("sp.js", RetrieveListItems());

});

function SaveStudentToList() {

    var ctx = new SP.ClientContext.get_current();

    var name = $("#txtName");

    var surname = $("#txtSurname");

    var lstStudent = ctx.get_web().get_lists().getByTitle('StudentList');

    var itemCreateInfo = new SP.ListItemCreationInformation(lstStudent);

    var studentItem = lstStudent.addItem(itemCreateInfo);

    studentItem.set_item('Name1', name.val());

    studentItem.set_item('Surname', surname.val());

    studentItem.update();

    ctx.load(studentItem);

    ctx.executeQueryAsync(onQuerySucceededFinal, onQueryFailed);
         
 
         
}

function onQuerySucceededFinal() {
 
    $("#txtName").text = "";
    $("#txtSurname").text = "";
 
    location.reload();
    alert("Item added successfuly");
};

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

function RetrieveListItems() {

    ctx = new SP.ClientContext.get_current();

    web = ctx.get_web();

    var list = web.get_lists().getByTitle('StudentList');

    var myquery = new SP.CamlQuery.createAllItemsQuery();

    allItems = list.getItems(myquery);

    ctx.load(allItems);

    ctx.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}


function success() {
    var Name = null;
    var Surname = null;
    var Mathematics = null;
    var Chemistry = null;
    var Physics = null;
    var txtHTML = "";
    var rowIDs = null;

    var ListEnumerator = this.allItems.getEnumerator();
    while (ListEnumerator.moveNext()) {
        var currentItem = ListEnumerator.get_current();
        Name = currentItem.get_item('Name1');
        Surname = currentItem.get_item('Surname');
        Mathematics = currentItem.get_item('Mathematics');
        Chemistry = currentItem.get_item('Chemistry');
        Physics = currentItem.get_item('Physics');
        var row = document.createElement("tr");
        var trID = 'tr' + currentItem.get_id();

        txtHTML = txtHTML + "<tr id='"+ trID +"'>";
        txtHTML = txtHTML + "<td>";
        if (Name != null) {
            txtHTML = txtHTML + "<p>" + Name + "</p>";
        }
        txtHTML = txtHTML + "</td>";

        txtHTML = txtHTML + "<td>";
        if (Surname != null) {
            txtHTML = txtHTML + "<p>" + Surname + "</p>";
        }
        txtHTML = txtHTML + "</td>";

        txtHTML = txtHTML + "<td style=' text-align:center'>";
        if (Mathematics != null && Mathematics > 0 ) {
            txtHTML = txtHTML + "<input type='text' readonly='readonly' id= math" + currentItem.get_id() + "  class='math' value='"+ Mathematics +"' style='width : 46px ; text-align:center'/>";
        }
        else
            txtHTML = txtHTML + "<input type='text' id= math" + currentItem.get_id() + "  class='math' value='0' style='width : 46px ; text-align:center'/>";
        txtHTML = txtHTML + "</td>";

        txtHTML = txtHTML + "<td style=' text-align:center'>";
        if (Chemistry != null && Chemistry > 0 ) {
            txtHTML = txtHTML + "<input type='text' readonly='readonly' id= chem" + currentItem.get_id() + "  class='chem' value='" + Chemistry + "' style='width : 46px ; text-align:center'/>";
        }
        else
            txtHTML = txtHTML + "<input type='text' id= chem" + currentItem.get_id() + " class='chem' value='0' style='width : 46px; text-align:center'/>";
        txtHTML = txtHTML + "</td>";

        txtHTML = txtHTML + "<td style=' text-align:center'>";

        if (Physics != null && Physics > 0  ) {
            txtHTML = txtHTML + "<input type='text' readonly='readonly' id= phy" + currentItem.get_id() + "  class='phy' value='" + Physics + "' style='width : 46px ; text-align:center'/>";
        }
        else
            txtHTML = txtHTML + "<input type='text'   id= phy" + currentItem.get_id() + "  class='phy' value=' 0 ' style='width : 46px; text-align:center' />";
        txtHTML = txtHTML + "</td>";

        txtHTML = txtHTML + "<td style=' text-align:center'>";
        txtHTML = txtHTML + "<input type='image' src='../images/save.gif' style='height:30px;width:30px' OnClick='updateItems(" + currentItem.get_id() + ","+ trID +");'>" + "<input type='image' src='../images/delete.gif' style='height:30px;width:30px' OnClick='removeItems(" + currentItem.get_id() + ");'>";
        txtHTML = txtHTML + "</td>";

        txtHTML = txtHTML + "</tr>";

     
     
    }
    $("#tblCustomListData").append(txtHTML);

 
}
function failed(sender, args) {
    alert("failed Message" + args.gte_message());
}

function removeItems(id) {

    var ctx = new SP.ClientContext.get_current();

    var lstStudent = ctx.get_web().get_lists().getByTitle('StudentList');

    var itemToDelete = lstStudent.getItemById(id);

    itemToDelete.deleteObject();

    ctx.executeQueryAsync(deltedItemSuccess, deletedItemFailed);

};

function deltedItemSuccess() {
    location.reload();
    alert("Item has been deleted...");
 
};

function deletedItemFailed() {

    alert("Failed to delete Item...");
};


function updateItems(id, trID) {

    var mathematics = $(document.getElementById("math" + id)).val();

    //var chemistry = document.getElementById(trID).cells[3].val();
    var chemistry = $(document.getElementById("chem" + id)).val();

    var physics = $(document.getElementById("phy" + id)).val();;

    var ctx = new SP.ClientContext.get_current();

    var lstStudent = ctx.get_web().get_lists().getByTitle('StudentList');

    var itemToUpdate = lstStudent.getItemById(id);

    itemToUpdate.set_item('Mathematics',  mathematics);

    itemToUpdate.set_item('Chemistry', chemistry);

    itemToUpdate.set_item('Physics', physics);

    itemToUpdate.update();

    ctx.executeQueryAsync(UpdateSuccess, UpdateItemFailed);

};

function UpdateSuccess() {
    location.reload();
 
    alert('Item has been updated...');
 
};

function UpdateItemFailed() {
    alert('Failed to update Item...');
}



Tuesday, 18 August 2015

App Web and Host Web

App web

The special website to which the app is deployed is called an app web.. Although the app web has its own isolated domain, it is in the same site collection as the host web.
SharePoint components are deployed to a special website with its own domain. This is called the app web.


Host Web

The Host Web is nothing but the SharePoint site where the App is actually installed.
In Short:
App Web - Site on which the App is deployed
Host Web - Site on which the App is installed

URL

HostWeb url - https://xyzonline.sharepoint.com/sites/OrgIntranet/sap



We can create our custom SharePoint artefacts like list,content types as part of our Auto Hosted or Provider hosted apps too and not only in SharePoint Hosted apps.

Your feature and list will be deployed in the AppWeb which is a subsite that gets created whenever a new app is created. So instead of checking for the list and the feature in the host web, You can see them as part of the AppWeb.

You can find the AppWeb's url from Site Settings->Site Collection Administration section->Site hierarchy, Title will be your App name.

Once you know the url, You can visit the manage features page of the App Web through "URL_of_app_web/_layouts/15/ManageFeatures.aspx". Here you can see your feature already activated if it has been properly deployed.

And to see your list visit "URL_of_app_web/lists/list_internal_name". Here you can see your list along with his items.

If I manually (i.e. SP OOTB ) created a List within site (i.e. under HostWeb - https://xyzonline.sharepoint.com/sites/OrgIntranet/sap ) and if I wanted to get this list so will go with below code

    //list created by Sharepoint OOTB - HostWeb
    var context = new SP.ClientContext(appWebUrl);
    var appCtxSite = new SP.AppContextSite(context, hostWebUrl);
    var web = appCtxSite.get_web();
    var list = web.get_lists().getByTitle("MySAPLst");
    context.load(list);

If I created a list using visual studio so the list will be reside under App Web i.e. https://xyzonline-48f6dcc328fa2.sharepoint.com/sites/OrgIntranet/sap/SharePointApp1 and if you wanted to get this list so will go with below code

//Get List created by Visual Studio - AppWeb

var context = new SP.ClientContext(appWebUrl);
var web = context.get_web();
var list = web.get_lists().getByTitle("TestList");
context.load(list);
 
   OR

//Get List created by Visual Studio
var context = new SP.ClientContext.get_current();
var web = context.get_web();
list = web.get_lists().getByTitle('TestList');
context.load(list);



Friday, 14 August 2015

CRUD operation with Sharepoint hosted app

Html code for section "PlaceHolderMain" in .aspx page

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <table>
    <tr>
        <td>
            <table>
    <tr>
        <td>Category Id</td>
        <td>
            <input type="text" id="CategoryId" class="c1"/>
        </td>
    </tr>
    <tr>
        <td>Category Name</td>
        <td>
            <input type="text" id="CategoryName" class="c1"/>
        </td>
    </tr>
    <tr>
        <td>
            <input type="button" value="New" id="btn-new" />
        </td>
        <td>
            <input type="button" value="Add" id="btn-add" />
        </td>
        <td>
            <input type="button" value="Update" id="btn-update" />
        </td>
        <td>
            <input type="button" value="Delete" id="btn-delete" />
        </td>
        <td>
            <input type="button" value="Find" id="btn-find" />
        </td>
    </tr>  
</table>
        </td>
        <td>
            <table id="tblcategories">
       
            </table>
        </td>
    </tr>
</table>
    <div id="dvMessage"></div>

   
</asp:Content>


Code in App.js


'use strict';

///The helper method to manage the Host and App Web Url
function manageQueryStringParameter(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];
        }
    }
}

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();


var hostWebUrl;
var appWebUrl;

var listItemToUpdate; // The global declaration for Update and Delete the ListItem
var listItemId; //This global list item id used for Update and delete

// 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 () {
    //getUserName();

    //SPHostUrl – the full URL of the host site
    //SPAppWebUrl – the full URL of the app web

    hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
    appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
    //debugger;
    //alert("Host Web Url " + hostWebUrl);
    //alert("App Web Url " + appWebUrl);

    listAllCategories();

    $("#btn-new").on('click', function () {
        $(".c1").val('');
    });

    $("#btn-add").on('click', function () {
        createCategory();
        listAllCategories();
    });

    $("#btn-update").on('click', function () {
        updateItem();
        listAllCategories();
    });

    $("#btn-find").on('click', function () {
        findListItem();
    });


    $("#btn-delete").on('click', function () {
        deleteListItem();
        listAllCategories();
    });
});

//My Code Here

//<------Function To Create a New Category In List ------->

function createCategory() {
    var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL
    var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);

    var web = appCtxSite.get_web(); //Get the Site

    var list = web.get_lists().getByTitle("CategoryList"); //Get the List based upon the Title
    var listCreationInformation = new SP.ListItemCreationInformation(); //Object for creating Item in the List
    var listItem = list.addItem(listCreationInformation);

    listItem.set_item("Title", $("#CategoryId").val());
    listItem.set_item("CategoryName", $("#CategoryName").val());
    listItem.update(); //Update the List Item

    ctx.load(listItem);
    //Execute the batch Asynchronously
    ctx.executeQueryAsync(
        Function.createDelegate(this, success),
        Function.createDelegate(this, fail)
       );
}
//<--------------------Ends Here-------------------------->


//<----------Function To List All Categories--------->
function listAllCategories() {

    var ctx = new SP.ClientContext(appWebUrl);
    var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);

    var web = appCtxSite.get_web(); //Get the Web

    var list = web.get_lists().getByTitle("CategoryList"); //Get the List

    var query = new SP.CamlQuery(); //The Query object. This is used to query for data in the List

    query.set_viewXml('<View><RowLimit></RowLimit>10</View>');

    var items = list.getItems(query);

    ctx.load(list); //Retrieves the properties of a client object from the server.
    ctx.load(items);

    var table = $("#tblcategories");
    var innerHtml = "<tr><td>ID</td><td>Category Id</td><td>Category Name</td></tr>";

    //Execute the Query Asynchronously
    ctx.executeQueryAsync(
        Function.createDelegate(this, function () {
            var itemInfo = '';
            var enumerator = items.getEnumerator();
            while (enumerator.moveNext()) {
                var currentListItem = enumerator.get_current();
                innerHtml += "<tr><td>"+ currentListItem.get_item('ID') +"</td><td>" + currentListItem.get_item('Title') + "</td><td>" + currentListItem.get_item('CategoryName')+"</td></tr>";
            }
            table.html(innerHtml);
        }),
        Function.createDelegate(this, fail)
        );

}
//<-----------Ends Here------------------------------>

//<------------Update List Item---------------------->
function findListItem() {

    listItemId =  prompt("Enter the Id to be Searched ");
    var ctx = new SP.ClientContext(appWebUrl);
    var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);

    var web = appCtxSite.get_web();

    var list = web.get_lists().getByTitle("CategoryList");

    ctx.load(list);

    listItemToUpdate = list.getItemById(listItemId);

    ctx.load(listItemToUpdate);

    ctx.executeQueryAsync(
        Function.createDelegate(this, function () {
            //Display the Data into the TextBoxes
            $("#CategoryId").val(listItemToUpdate.get_item('Title'));
            $("#CategoryName").val(listItemToUpdate.get_item('CategoryName'));
        }),
        Function.createDelegate(this,fail)
        );
  }
//<-----------Ends Here------------------------------>

//<-----------Function to Update List Item----------->

function updateItem() {
    var ctx = new SP.ClientContext(appWebUrl);
    var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);

    var web = appCtxSite.get_web();

    var list = web.get_lists().getByTitle("CategoryList");
    ctx.load(list);

    listItemToUpdate = list.getItemById(listItemId);

    ctx.load(listItemToUpdate);

    listItemToUpdate.set_item('CategoryName', $("#CategoryName").val());
    listItemToUpdate.update();

    ctx.executeQueryAsync(
        Function.createDelegate(this, success),
        Function.createDelegate(this,fail)
        );

}
//<-----------Ends Here------------------------------>

//<-----------Function to Update List Item----------->
function deleteListItem() {
    var ctx = new SP.ClientContext(appWebUrl);
    var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);

    var web = appCtxSite.get_web();

    var list = web.get_lists().getByTitle("CategoryList");
    ctx.load(list);

    listItemToUpdate = list.getItemById(listItemId);

    ctx.load(listItemToUpdate);

    listItemToUpdate.deleteObject();

    ctx.executeQueryAsync(
        Function.createDelegate(this, success),
        Function.createDelegate(this, fail)
        );
}
//<-----------Ends Here------------------------------>

function success() {
    $("#dvMessage").text("Operation Completed Successfully");
}

function fail() {
    $("#dvMessage").text("Operation failed  " + arguments[1].get_message());
}


//Ends Here


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

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.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());

}


Wednesday, 12 August 2015

Get list in Sharepoint Hosted App

Code in App.JS

'use strict';

///The helper method to manage the Host and App Web Url
function manageQueryStringParameter(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];
        }
    }
}


var hostWebUrl;
var appWebUrl;
var list;

// 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 () {
    hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
    appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
    getUserName();
});

// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    var context = new SP.ClientContext(appWebUrl);
    var appCtxSite = new SP.AppContextSite(context, hostWebUrl);
    var web = appCtxSite.get_web();
    list = web.get_lists().getByTitle("MySAPLst");
    context.load(list);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}


// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + list.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());
}