Wednesday, May 3, 2017

SharePoint Hosted App that Does CRUD-Q with REST, JavaScript, KnockoutJS, Q

SharePoint Hosted App that Does CRUD-Q with REST, JavaScript, KnockoutJS, Q.
1. Microsoft visual studio 2013 -> file -> project -> “RestClientSide”.
2. “RestClientSide” -> right click -> add -> new item -> select ‘List’ -> 
3. Open “CeoLsit” -> add below columns.
4. Go to “CeoList” -> “CeoListInstance” -> “Elements.xml” -> add below code.
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ListInstance Title="CeoList" OnQuickLaunch="TRUE" TemplateType="10000" Url="Lists/CeoList" Description="My List Instance">
    <Data>
      <Rows>
        <Row>
          <Field Name="Title">John Doe</Field>
          <Field Name="TenureStartYear">1971</Field>
          <Field Name="TenureEndYear">1972</Field>
        </Row>
        <Row>
          <Field Name="Title">Bill Gates</Field>
          <Field Name="TenureStartYear">1975</Field>
          <Field Name="TenureEndYear">2000</Field>
        </Row>
        <Row>
          <Field Name="Title">Steve Ballmer</Field>
          <Field Name="TenureStartYear">2000</Field>
          <Field Name="TenureEndYear">Present</Field>
        </Row>
      </Rows>
    </Data>
  </ListInstance>
</Elements>
5. Install-Package KnockoutJS
6. Install-Package Q
7. Go to “Pages” -> open “Default.aspx” page and add below code.
<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>
<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/knockout-3.4.2.js"></script>
    <script type="text/javascript" src="../Scripts/q.min.js"></script>
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <SharePoint:ScriptLink Name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
    <meta name="WebPartPageExpansion" content="full" />
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
    <script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Page Title
</asp:Content>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <input type="button" disabled="disabled" value="refresh list" data-bind="click: getAllChiefExecutives" />&nbsp;
    <input type="button" disabled="disabled" value="appoint 3rd ceo" data-bind="click: addThirdCeo" />&nbsp;
    <input type="button" disabled="disabled" value="delete first person" data-bind="click: deleteFirstCeo" />
    <h1>Microsoft CEO's</h1>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Tenure</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: chiefExecutives">
            <tr>
                <td data-bind="text: Title"></td>
                <td><span data-bind="text: TenureStartYear"></span>- <span data-bind="    text: TenureEndYear"></span></td>
            </tr>
        </tbody>
    </table>
</asp:Content>
8. Go to “Scripts” -> open “App.js” page and add below code.
(function () {
    'use strict';
    var viewModel = function () {
        var self = this;
        self.chiefExecutives = ko.observableArray([]);
        self.getAllChiefExecutives = getAllChiefExecutives;
        self.addThirdCeo = addThirdCeo;
        self.deleteFirstCeo = deleteFirstCeo;
        function getAllChiefExecutives() {
            var endpoint = _spPageContextInfo.webAbsoluteUrl +
                '/_api/web/lists/getbytitle(\'CeoList\')/items?$select=Title,TenureStartYear,TenureEndYear&$orderby=TenureStartYear';
            var requestHeaders = {
                'Accept': 'application/json;odata=verbose'
            };
            return jQuery.ajax({
                url: endpoint,
                type: 'GET',
                headers: requestHeaders
            }).done(function (response) {
                self.chiefExecutives([]);
                self.chiefExecutives(response.d.results);
            });
        };
        function addThirdCeo() {
            var jobs = [];
            var totalCeos = self.chiefExecutives().length;
            var endpoint = self.chiefExecutives()[totalCeos - 1].__metadata.uri;
            var requestHeaders = {
                'Accept': 'application/json;odata=verbose',
                'Content-Type': 'application/json;odata=verbose',
                'X-RequestDigest': jQuery("#__REQUESTDIGEST").val(),
                'X-Http-Method': 'MERGE',
                'If-Match': self.chiefExecutives()[totalCeos - 1].__metadata.etag
            };
            var firstCeoUpdateData = {
                __metadata: { type: 'SP.Data.CeoListListItem' },
                TenureEndYear: '2014'
            };
            jobs.push(jQuery.ajax({
                url: endpoint,
                type: 'POST',
                headers: requestHeaders,
                data: JSON.stringify(firstCeoUpdateData),
                success: function (resonse) {
                    alert('second ceo updated');
                },
                fail: function (error) {
                    alert('error occurred updating second ceo: ' + error.message);
                }
            }));
            var endpoint = _spPageContextInfo.webAbsoluteUrl + '/_api/web/lists/getbytitle(\'CeoList\')/items';
            var requestHeaders = {
                'Accept': 'application/json;odata=verbose',
                'Content-Type': 'application/json;odata=verbose',
                'X-RequestDigest': jQuery("#__REQUESTDIGEST").val()
            };
            var thirdCeoUpdateData = {
                __metadata: { type: 'SP.Data.CeoListListItem' },
                Title: 'Satya Nadella',
                TenureStartYear: '2014',
                TenureEndYear: 'present'
            };
            jobs.push(jQuery.ajax({
                url: endpoint,
                type: 'POST',
                headers: requestHeaders,
                data: JSON.stringify(thirdCeoUpdateData),
                success: function (resonse) {
                    alert('third ceo created');
                },
                fail: function (error) {
                    alert('error occurred creating third ceo: ' + error.message);
                }
            }));
            Q.all(jobs)
                .then(function () {
                    self.getAllChiefExecutives();
                });
        }
        function deleteFirstCeo() {
            var jobs = [];
            var endpoint = self.chiefExecutives()[0].__metadata.uri;
            var requestHeaders = {
                'Accept': 'application/json;odata=verbose',
                'X-RequestDigest': jQuery("#__REQUESTDIGEST").val(),
                'If-Match': '*'
            };
            jobs.push(jQuery.ajax({
                url: endpoint,
                type: 'DELETE',
                headers: requestHeaders,
                success: function (resonse) {
                    alert('first person deleted');
                },
                fail: function (error) {
                    alert('error occurred deleting first person: ' + error.message);
                }
            }));
            Q.all(jobs)
                .then(function () {
                    self.getAllChiefExecutives();
                });
        }
    }
    jQuery(document).ready(function () {
        ko.applyBindings(new viewModel());
        jQuery('input[type="button"]').removeAttr('disabled');
    });
})();
9. Press “F5” to deploy and test.

No comments:

Post a Comment

Featured Post

Mention a Channel or Team – Power Automate

Mention a Channel or Team – Power Automate graph.microsoft.com/v1.0/teams/{teamId}/channels/{channelId}/messages Channel: ---------- {   &qu...

Popular posts