SharePoint Hosted App Data Manipulation With Office 365 Using Custom JavaScript Library - Part 1

Here are the steps, 
 
Step 1: Create SharePoint Hosted App with Office 365 account credentials. Open Visual Studio and select New Project as in the following,
 

 Step 2
: Specify Site URL & app type to proceed next.



Step 3: Provide Office365 credentials to continue further.


Step 4
: Project structure is as in the following,



Step 5: We first need to set permission for App, so that we can communicate with site properly.


Step 6
: Deploy the app into Office 365 environment.

Step 7: User Interface creation code

In this part, we are going to perform simple operation so UI is also very simple as in the following example,

Source Code
  1. <%@ Page Language="C#" MasterPageFile="~masterurl/default.master" Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>  
  2. <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>  
  3. <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>  
  4. <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>  
  5. <asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">  
  6.                 <SharePoint:ScriptLink Name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />  
  7.                 <script src="../Scripts/jquery-1.8.2.js" type="text/javascript"></script>  
  8.                 <script src="../Scripts/JSLibrary.js" type="text/javascript"></script>  
  9.             </asp:Content>  
  10.             <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">  
  11.                 <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="full" Title="loc:full" />  
  12.                 <hr />  
  13.                 <div>  
  14.                     <h2><b>Office 365 Host Web Details</b></h2>  
  15.                     <br />  
  16.                     <div id="HostwebDetails"></div>  
  17.                 </div>  
  18.                 <hr />  
  19.                 <div>  
  20.                     <h3><b>Folder Creation</b></h3>  
  21.                     <input type="text" id="txtFolderName" /> <a href="#" onclick="Wingtip.JSOMHostWebCollections.HWCreateFolder()">Create Folder</a> </div>  
  22.                 <hr />  
  23.                 <div>  
  24.                     <h3><b>List Creation</b></h3>  
  25.                     <input type="text" id="txtListName" /> <a href="#" onclick="Wingtip.JSOMHostWebCollections.HWCreateList()">Create List</a> </div>  
  26.                 <hr />  
  27.                 <div>  
  28.                     <h3><b>List Deletion</b></h3>  
  29.                     <input type="text" id="txtDeletionListName" /> <a href="#" onclick="Wingtip.JSOMHostWebCollections.HWDeleteList()">Delete List</a> </div>  
  30.                 <hr/> </asp:Content>  
Step 8: Fetch current Web Site details on page load. The following code is used to perform this operation.
  1. var clientContext;  
  2. var factory;  
  3. var appContextSite;  
  4. var web;  
  5. var collList;  
  6. var itemCreateInfo;  
  7. var param1, param2, param3;  
  8. var oList, targetList, listFields, oListItem, oField, itemId;  
  9. var ExsitingListNameVal;  
  10. window.Wingtip = window.Wingtip ||  
  11. {}  
  12. Wingtip.JSOMHostWebCollections = function()  
  13. {  
  14.     LoadlayoutsJS = function()  
  15.     {  
  16.         //debugger    
  17.         hostweburl = decodeURIComponent(Wingtip.JSOMHostWebCollections.QSParameter("SPHostUrl"));  
  18.         appweburl = decodeURIComponent(Wingtip.JSOMHostWebCollections.QSParameter("SPAppWebUrl"));  
  19.         var Sessionhostweburl = sessionStorage.getItem("hostweburl");  
  20.         var Sessionappweburl = sessionStorage.getItem("appweburl");  
  21.         if (Sessionhostweburl == null || Sessionappweburl == null)  
  22.         {  
  23.             sessionStorage.setItem("hostweburl", hostweburl);  
  24.             sessionStorage.setItem("appweburl", appweburl);  
  25.         }  
  26.         if (hostweburl == null || appweburl == null || hostweburl == 'undefined' || appweburl == 'undefined')  
  27.         {  
  28.             hostweburl = sessionStorage.getItem("hostweburl");  
  29.             appweburl = sessionStorage.getItem("appweburl");  
  30.         }  
  31.         var scriptbase = hostweburl + "/_layouts/15/";  
  32.         $.getScript(scriptbase + "SP.Runtime.js", function()  
  33.         {  
  34.             $.getScript(scriptbase + "SP.js", function()  
  35.             {  
  36.                 $.getScript(scriptbase + "SP.RequestExecutor.js", Wingtip.JSOMHostWebCollections.HWLoadClientContext);  
  37.             });  
  38.         });  
  39.     }  
  40.     getQueryStringParameter = function(paramToRetrieve)  
  41.     {  
  42.         //debugger    
  43.         try  
  44.         {  
  45.             var params = document.URL.split("?")[1].split("&");  
  46.             var strParams = "";  
  47.             for (var i = 0; i < params.length; i = i + 1)  
  48.             {  
  49.                 var singleParam = params[i].split("=");  
  50.                 if (singleParam[0] == paramToRetrieve) return singleParam[1];  
  51.             }  
  52.         }  
  53.         catch (ex)  
  54.         {}  
  55.     }  
  56.     LoadClientContext = function()  
  57.     {  
  58.         //debugger    
  59.         clientContext = new SP.ClientContext(appweburl);  
  60.         factory = new SP.ProxyWebRequestExecutorFactory(appweburl);  
  61.         clientContext.set_webRequestExecutorFactory(factory);  
  62.         appContextSite = new SP.AppContextSite(clientContext, hostweburl);  
  63.         web = appContextSite.get_web();  
  64.         clientContext.load(web);  
  65.         Wingtip.JSOMHostWebCollections.HWGetTitle();  
  66.         //Wingtip.JSOMHostWebCollections.HWCreateFolder("Rupali");    
  67.         //Wingtip.JSOMHostWebCollections.HWCreateList("Book");          
  68.         //Wingtip.JSOMHostWebCollections.HWDeleteList("Book");    
  69.     }  
  70.     GetTitle = function()  
  71.         {  
  72.             //debugger    
  73.             web.set_title('Office365 Host Web');  
  74.             web.update();  
  75.             clientContext.load(web);  
  76.             clientContext.executeQueryAsync(Function.createDelegate(this, SPHostWebDetailsSuccessHandler), Function.createDelegate(this, SPHostWebDetailsErrorHandler));  
  77.   
  78.             function SPHostWebDetailsSuccessHandler()  
  79.             {  
  80.                 var Result = "";  
  81.                 Result = Result + "<b>Title :</b> " + web.get_title() + "<br/>";  
  82.                 Result = Result + "<b> ID :</b> " + web.get_id() + "</br>";  
  83.                 Result = Result + "<b> Created :</b> " + web.get_created() + "</br>";  
  84.                 document.getElementById("HostwebDetails").innerHTML = Result;  
  85.             }  
  86.   
  87.             function SPHostWebDetailsErrorHandler(data, errorCode, errorMessage)  
  88.             {  
  89.                 alert("fail" + errorMessage);  
  90.                 document.getElementById("HostwebTitle").innerText = "Could not complete cross-domain call: " + errorMessage;  
  91.             }  
  92.         }  
  93.         //public interface    
  94.     return {  
  95.         HWLoadlayoutsJS: LoadlayoutsJS,  
  96.         QSParameter: getQueryStringParameter,  
  97.         HWLoadClientContext: LoadClientContext,  
  98.         HWGetTitle: GetTitle,  
  99.         HWCreateFolder: CreateFolder,  
  100.         HWCreateList: CreateList,  
  101.         HWDeleteList: DeleteList,  
  102.         HWEmpty: Empty  
  103.     }  
  104. }();  
  105. $(document).ready(function()  
  106. {  
  107.     //Load Out Of Box JS file for List Operation    
  108.     Wingtip.JSOMHostWebCollections.HWLoadlayoutsJS();  
  109. });  
Output


Step 9:
Create folder at site, we can use the following code,
  1. CreateFolder = function()  
  2. {  
  3.     //debugger        
  4.     oList = web.get_lists().getByTitle("Documents");  
  5.     itemCreateInfo = new SP.ListItemCreationInformation();  
  6.     itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);  
  7.     var FolderNameVal = $(txtFolderName).val();  
  8.     console.log(FolderNameVal);  
  9.     itemCreateInfo.set_leafName(FolderNameVal);  
  10.     //itemCreateInfo.set_leafName("My new folder!!!");    
  11.     oListItem = oList.addItem(itemCreateInfo);  
  12.     oListItem.update();  
  13.     clientContext.load(oListItem);  
  14.     clientContext.executeQueryAsync(Function.createDelegate(this, CreateFolderSuccessHandler), Function.createDelegate(this, CreateFolderErrorHandler));  
  15.   
  16.     function CreateFolderSuccessHandler()  
  17.     {  
  18.         alert("Go to Site Content ->Documents to see your new folder.");  
  19.     }  
  20.   
  21.     function CreateFolderErrorHandler()  
  22.     {  
  23.         alert("Request failed: " + arguments[1].get_message());  
  24.     }  
  25. }  
Output


New folder is getting created inside Document folder at root level.


Step 10:
Create List at host web using the following code,
  1. CreateList = function()  
  2. {  
  3.     //debugger    
  4.     var listCreationInfo = new SP.ListCreationInformation();  
  5.     var ListNameVal = $(txtListName).val();  
  6.     //var ListNameVal = ListName;    
  7.     listCreationInfo.set_title(ListNameVal);  
  8.     listCreationInfo.set_templateType(SP.ListTemplateType.announcements);  
  9.     oList = web.get_lists().add(listCreationInfo);  
  10.     clientContext.load(oList);  
  11.     oList.set_description(ListNameVal + 'created via JSOM Model ...');  
  12.     oList.update();  
  13.     clientContext.executeQueryAsync(Function.createDelegate(this, SPHostWebCreateListSuccessHandler), Function.createDelegate(this, SPHostWebCreateListErrorHandler));  
  14.   
  15.     function SPHostWebCreateListSuccessHandler()  
  16.     {  
  17.         var result = oList.get_title() + ' List created successfully.';  
  18.         alert(result);  
  19.     }  
  20.   
  21.     function SPHostWebCreateListErrorHandler(sender, args)  
  22.     {  
  23.         alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
  24.     }  
  25. }  
Output


Finally list is created at host web.


Step 11:
Delete list at host web using the following code,
  1. DeleteList = function()  
  2. {  
  3.     // debugger    
  4.     var DeleteListNameVal = $(txtDeletionListName).val();  
  5.     oList = web.get_lists().getByTitle(DeleteListNameVal);  
  6.     oList.deleteObject();  
  7.     clientContext.executeQueryAsync(Function.createDelegate(this, DeleteListHostWebSucceeded), Function.createDelegate(this, DeleteListHostWebFailed));  
  8.   
  9.     function DeleteListHostWebSucceeded()  
  10.     {  
  11.         alert("Delete List done Successfully ...");  
  12.     }  
  13.   
  14.     function DeleteListHostWebFailed(sender, args)  
  15.     {  
  16.         alert('Request failed. ' + args.get_message() + '\n StackTrace : ' + args.get_stackTrace());  
  17.     }  
  18. }  
Output


Full Source Code
  1. var clientContext;  
  2. var factory;  
  3. var appContextSite;  
  4. var web;  
  5. var collList;  
  6. var itemCreateInfo;  
  7. var param1, param2, param3;  
  8. var oList, targetList, listFields, oListItem, oField, itemId;  
  9. var ExsitingListNameVal;  
  10. window.Wingtip = window.Wingtip ||  
  11. {}  
  12. Wingtip.JSOMHostWebCollections = function()  
  13. {  
  14.     LoadlayoutsJS = function()  
  15.     {  
  16.         //debugger    
  17.         hostweburl = decodeURIComponent(Wingtip.JSOMHostWebCollections.QSParameter("SPHostUrl"));  
  18.         appweburl = decodeURIComponent(Wingtip.JSOMHostWebCollections.QSParameter("SPAppWebUrl"));  
  19.         var Sessionhostweburl = sessionStorage.getItem("hostweburl");  
  20.         var Sessionappweburl = sessionStorage.getItem("appweburl");  
  21.         if (Sessionhostweburl == null || Sessionappweburl == null)  
  22.         {  
  23.             sessionStorage.setItem("hostweburl", hostweburl);  
  24.             sessionStorage.setItem("appweburl", appweburl);  
  25.         }  
  26.         if (hostweburl == null || appweburl == null || hostweburl == 'undefined' || appweburl == 'undefined')  
  27.         {  
  28.             hostweburl = sessionStorage.getItem("hostweburl");  
  29.             appweburl = sessionStorage.getItem("appweburl");  
  30.         }  
  31.         var scriptbase = hostweburl + "/_layouts/15/";  
  32.         $.getScript(scriptbase + "SP.Runtime.js", function()  
  33.         {  
  34.             $.getScript(scriptbase + "SP.js", function()  
  35.             {  
  36.                 $.getScript(scriptbase + "SP.RequestExecutor.js", Wingtip.JSOMHostWebCollections.HWLoadClientContext);  
  37.             });  
  38.         });  
  39.     }  
  40.     getQueryStringParameter = function(paramToRetrieve)  
  41.     {  
  42.         //debugger    
  43.         try  
  44.         {  
  45.             var params = document.URL.split("?")[1].split("&");  
  46.             var strParams = "";  
  47.             for (var i = 0; i < params.length; i = i + 1)  
  48.             {  
  49.                 var singleParam = params[i].split("=");  
  50.                 if (singleParam[0] == paramToRetrieve) return singleParam[1];  
  51.             }  
  52.         }  
  53.         catch (ex)  
  54.         {}  
  55.     }  
  56.     LoadClientContext = function()  
  57.     {  
  58.         //debugger    
  59.         clientContext = new SP.ClientContext(appweburl);  
  60.         factory = new SP.ProxyWebRequestExecutorFactory(appweburl);  
  61.         clientContext.set_webRequestExecutorFactory(factory);  
  62.         appContextSite = new SP.AppContextSite(clientContext, hostweburl);  
  63.         web = appContextSite.get_web();  
  64.         clientContext.load(web);  
  65.         Wingtip.JSOMHostWebCollections.HWGetTitle();  
  66.         //Wingtip.JSOMHostWebCollections.HWCreateFolder("Rupali");    
  67.         //Wingtip.JSOMHostWebCollections.HWCreateList("Book");          
  68.         //Wingtip.JSOMHostWebCollections.HWDeleteList("Book");    
  69.     }  
  70.     GetTitle = function()  
  71.     {  
  72.         //debugger    
  73.         web.set_title('Office365 Host Web');  
  74.         web.update();  
  75.         clientContext.load(web);  
  76.         clientContext.executeQueryAsync(Function.createDelegate(this, SPHostWebDetailsSuccessHandler), Function.createDelegate(this, SPHostWebDetailsErrorHandler));  
  77.   
  78.         function SPHostWebDetailsSuccessHandler()  
  79.         {  
  80.             var Result = "";  
  81.             Result = Result + "<b>Title :</b> " + web.get_title() + "<br/>";  
  82.             Result = Result + "<b> ID :</b> " + web.get_id() + "</br>";  
  83.             Result = Result + "<b> Created :</b> " + web.get_created() + "</br>";  
  84.             document.getElementById("HostwebDetails").innerHTML = Result;  
  85.         }  
  86.   
  87.         function SPHostWebDetailsErrorHandler(data, errorCode, errorMessage)  
  88.         {  
  89.             alert("fail" + errorMessage);  
  90.             document.getElementById("HostwebTitle").innerText = "Could not complete cross-domain call: " + errorMessage;  
  91.         }  
  92.     }  
  93.     CreateFolder = function()  
  94.     {  
  95.         //debugger        
  96.         oList = web.get_lists().getByTitle("Documents");  
  97.         itemCreateInfo = new SP.ListItemCreationInformation();  
  98.         itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);  
  99.         var FolderNameVal = $(txtFolderName).val();  
  100.         console.log(FolderNameVal);  
  101.         itemCreateInfo.set_leafName(FolderNameVal);  
  102.         //itemCreateInfo.set_leafName("My new folder!!!");    
  103.         oListItem = oList.addItem(itemCreateInfo);  
  104.         oListItem.update();  
  105.         clientContext.load(oListItem);  
  106.         clientContext.executeQueryAsync(Function.createDelegate(this, CreateFolderSuccessHandler), Function.createDelegate(this, CreateFolderErrorHandler));  
  107.   
  108.         function CreateFolderSuccessHandler()  
  109.         {  
  110.             alert("Go to Site Content ->Documents to see your new folder.");  
  111.         }  
  112.   
  113.         function CreateFolderErrorHandler()  
  114.         {  
  115.             alert("Request failed: " + arguments[1].get_message());  
  116.         }  
  117.     }  
  118.     CreateList = function()  
  119.     {  
  120.         //debugger    
  121.         var listCreationInfo = new SP.ListCreationInformation();  
  122.         var ListNameVal = $(txtListName).val();  
  123.         //var ListNameVal = ListName;    
  124.         listCreationInfo.set_title(ListNameVal);  
  125.         listCreationInfo.set_templateType(SP.ListTemplateType.announcements);  
  126.         oList = web.get_lists().add(listCreationInfo);  
  127.         clientContext.load(oList);  
  128.         oList.set_description(ListNameVal + 'created via JSOM Model ...');  
  129.         oList.update();  
  130.         clientContext.executeQueryAsync(Function.createDelegate(this, SPHostWebCreateListSuccessHandler), Function.createDelegate(this, SPHostWebCreateListErrorHandler));  
  131.   
  132.         function SPHostWebCreateListSuccessHandler()  
  133.         {  
  134.             var result = oList.get_title() + ' List created successfully.';  
  135.             alert(result);  
  136.         }  
  137.   
  138.         function SPHostWebCreateListErrorHandler(sender, args)  
  139.         {  
  140.             alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
  141.         }  
  142.     }  
  143.     DeleteList = function()  
  144.     {  
  145.         // debugger    
  146.         var DeleteListNameVal = $(txtDeletionListName).val();  
  147.         oList = web.get_lists().getByTitle(DeleteListNameVal);  
  148.         oList.deleteObject();  
  149.         clientContext.executeQueryAsync(Function.createDelegate(this, DeleteListHostWebSucceeded), Function.createDelegate(this, DeleteListHostWebFailed));  
  150.   
  151.         function DeleteListHostWebSucceeded()  
  152.         {  
  153.             alert("Delete List done Successfully ...");  
  154.         }  
  155.   
  156.         function DeleteListHostWebFailed(sender, args)  
  157.         {  
  158.             alert('Request failed. ' + args.get_message() + '\n StackTrace : ' + args.get_stackTrace());  
  159.         }  
  160.     }  
  161.   
  162.     function Empty()  
  163.     {  
  164.         console('Hello');  
  165.     }  
  166.     //public interface    
  167.     return {  
  168.         HWLoadlayoutsJS: LoadlayoutsJS,  
  169.         QSParameter: getQueryStringParameter,  
  170.         HWLoadClientContext: LoadClientContext,  
  171.         HWGetTitle: GetTitle,  
  172.         HWCreateFolder: CreateFolder,  
  173.         HWCreateList: CreateList,  
  174.         HWDeleteList: DeleteList,  
  175.         HWEmpty: Empty  
  176.     }  
  177. }();  
  178. $(document).ready(function()  
  179. {  
  180.     //Load Out Of Box JS file for List Operation    
  181.     Wingtip.JSOMHostWebCollections.HWLoadlayoutsJS();  
  182. });  

Up Next
    Ebook Download
    View all
    Learn
    View all