Monthly Archives: May 2015

SharePoint 2013 Hosted App (Part 3) – Access list from SharePoint Hosted App

SharePoint Hosted App series:

Following from my SharePoint Hosted App series, In this post I would like to show you how you could access a list from your SharePoint Hosted App.

Without further ado, please find below the list of steps to add SharePoint Hosted App Part:

1. Continue from previous solution in Part 2, we need to provision the list. To do that, I created new site column

myfirstapp18.2

2. Create new content type

myfirstapp18.3

myfirstapp18.4

3. Create new list and assign the content type

myfirstapp18.6

myfirstapp18.7

myfirstapp18.8

4. Update Default.aspx to add drop down control to show all list items

<%-- 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="VB" %>
<%@ 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" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
    <meta name="WebPartPageExpansion" content="full" />

    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
    <!-- Add your JavaScript to the following file -->
    <script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Page Title
</asp:Content>

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

    <div>
        <input id="clickMe" type="button" value="I can guess your name" />
    </div>

    <div id="myHomeTown">
    </div>
</asp:Content>

5. Update App.js to include all methods required

// 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 () {
    MyFirstApp = {
        element: '',
        loadUrl: '',
        createUrl: '',
        user: '',
        init: function (element) {
            var context = SP.ClientContext.get_current();
            var user = context.get_web().get_currentUser();
            context.load(user);

            MyFirstApp.element = element;
            MyFirstApp.loadUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Cities')/items?$select=Title,Country";
            MyFirstApp.createUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Cities')/items";
            MyFirstApp.user = user;
        },
        load: function () {
            $.ajax({
                url: MyFirstApp.loadUrl,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: MyFirstApp.onLoadSuccess,
                error: MyFirstApp.onLoadError
            });
        },
        onLoadSuccess: function (data) {
            var results = data.d.results;
            var html = "My sweet home town: <select>";
            for (var i = 0; i < results.length ; i++) {
                html += "<option value='" + results[i].Title + "'>" + results[i].Title + ", " + results[i].Country + "</option>";
            }
            html += "</select>";
            MyFirstApp.element.html(html);
        },
        onLoadError: function (errMsg) {
            MyFirstApp.element.html(JSON.stringify(errMsg));
        },
        add: function (city, country) {
            var itemType = "SP.Data.CitiesListItem";
            var item = {
                "__metadata": { "type": itemType },
                "Title": city,
                "Country": country,
            };

            $.ajax({
                url: MyFirstApp.createUrl,
                type: "POST",
                contentType: "application/json;odata=verbose",
                data: JSON.stringify(item),
                headers: {
                    "Accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                },
                success: MyFirstApp.onAddSuccess,
                error: MyFirstApp.onAddError
            });
        },
        onAddSuccess: function () {

        },
        onAddError: function (errMsg) {
            MyFirstApp.element.html(JSON.stringify(errMsg));
        },
        getUserName: function () {
            var context = SP.ClientContext.get_current();
            var user = context.get_web().get_currentUser();
            context.load(user);
            context.executeQueryAsync(MyFirstApp.onGetUserNameSuccess, MyFirstApp.onGetUserNameError);
        },
        onGetUserNameSuccess: function () {
            $('#message').text('Hello ' + MyFirstApp.user.get_title());
        },
        onGetUserNameError: function (sender, args) {
            $('#message').text('Failed to get user name. Error:' + args.get_message());
        }
    }

    // initialization
    MyFirstApp.init($('#myHomeTown'));

    // attach clickMe onclick event
    $('#clickMe').onclick = MyFirstApp.getUserName();

    // add items into Cities list 
    MyFirstApp.add("Jakarta", "Indonesia");
    MyFirstApp.add("Melbourne", "Australia");
    MyFirstApp.add("Cleveland", "USA");
    MyFirstApp.add("Boston", "USA");

    // populate dropdown from Cities list
    MyFirstApp.load();
});

6. Update App.manifest to provide app Read permission to access the list

myfirstapp19.2

7. Rebuild the solution and Package the app

myfirstapp6

myfirstapp8

8. Remove existing MyFirstApp from your Site Collection > Site Actions > Site Contents

myfirstapp17

9. Update MyFirstApp.app from App Catalog site

myfirstapp9

10. Browse to your Site Collection > Site Actions > Site Contents > Add an App > From your Organization > click MyFirstApp to add the custom app to your SharePoint site

myfirstapp1011. Result

myfirstapp20

Advertisements

SharePoint 2013 Hosted App (Part 4) – Create App Part

Following from my previous post for SharePoint 2013 Hosted App (Part 2), In this post I would like to show you another entrance to your SharePoint App. SharePoint App can be added like a web part as well into web part zone.

SharePoint Hosted App series:

Without further ado, please find below the list of steps to add SharePoint Hosted App Part:

1. Continue from previous solution in Part 2, right click on the MyFirstApp project > Add > New Item … 

myfirstapp12

2. In New Item page, select Client Web Part (Host Web) and click Add

myfirstapp13

3. In Specify the client web part page window, select Create a new web page for the client web part content, enter Page Name and click Finish

myfirstapp13.2

4. Now the project should have additional MyFirstAppPart module with Elements.xml and MyFirstAppPart.aspx page. Update MyFirstAppPart.aspx page to have:

  • same body content as Default.aspx
  • App.js and App.css linked
<%@ Page language="C#" Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, 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" %>
<%@ 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" %>

<WebPartPages:AllowFraming ID="AllowFraming" runat="server" />

<html>
<head>
    <title></title>

    <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>

    <script type="text/javascript">
        // Set the style of the client web part page to be consistent with the host web.
        (function () {
            'use strict';

            var hostUrl = '';
            if (document.URL.indexOf('?') != -1) {
                var params = document.URL.split('?')[1].split('&');
                for (var i = 0; i < params.length; i++) {
                    var p = decodeURIComponent(params[i]);
                    if (/^SPHostUrl=/i.test(p)) {
                        hostUrl = p.split('=')[1];
                        document.write('<link rel="stylesheet" href="' + hostUrl + '/_layouts/15/defaultcss.ashx" />');
                        break;
                    }
                }
            }
            if (hostUrl == '') {
                document.write('<link rel="stylesheet" href="/_layouts/15/1033/styles/themable/corev15.css" />');
            }
        })();
    </script>
    <!-- Add your JavaScript to the following file -->
    <script type="text/javascript" src="../Scripts/App.js"></script>
    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
</head>
<body>
    <div id="message">
        Hello ...
    </div>

    <div>
        <input id="clickMe" type="button" value="I can guess your name" />
    </div>
</body>
</html>

5. Rebuild the solution

myfirstapp6

6. Publish the solution, then click Package the app

myfirstapp7

myfirstapp8

7. Browse to your App Catalog Site. Click new app to add new custom app, then enter the Name,Short Description, Long Description, checked Enabled and click Save

myfirstapp9

myfirstapp9.2

8. Remove existing MyFirstApp from your Site Collection > Site Actions > Site Contents

myfirstapp17

9. Browse to your Site Collection > Site Actions > Site Contents > Add an App > From your Organization > click MyFirstApp to add the custom app to your SharePoint site

myfirstapp10

10. Edit Home.aspx page to add Part and Save back the page

myfirstapp15

myfirstapp16

SharePoint 2013 Hosted App (Part 2) – Create simple SharePoint Hosted App

Its been a while since the last time I’ve created my post for SharePoint 2013 Hosted App (Part 1) and now I would like to continue the series.

SharePoint Hosted App series:

Without further ado, please find below the list of steps to create SharePoint Hosted App:

1. Create new Project using App for SharePoint template in Microsoft Visual Studio 2013, enter the Name and Location, then click Ok

myfirstapp1

2. In Specifying the app for SharePoint settings window, enter the Site Collection URL and select SharePoint-hosted, then click Finish

myfirstapp2

3. By default, the SharePoint App Project already has Default.aspx with App.js and App.css linked. I’ve updated the Default.aspx to have message div and a button

<%-- 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="VB" %>
<%@ 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" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
    <meta name="WebPartPageExpansion" content="full" />

    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
    <!-- Add your JavaScript to the following file -->
    <script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Page Title
</asp:Content>

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

    <div>
        <input id="clickMe" type="button" value="I can guess your name" />
    </div>
</asp:Content>

4. In App.js file, I’ve implemented clickMe_Click function

// 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 () {
    MyFirstApp = {
        user: '',
        init: function (element) {
            var context = SP.ClientContext.get_current();
            var user = context.get_web().get_currentUser();
            context.load(user);
            MyFirstApp.user = user;
        },
        getUserName: function () {
            var context = SP.ClientContext.get_current();
            var user = context.get_web().get_currentUser();
            context.load(user);
            context.executeQueryAsync(MyFirstApp.onGetUserNameSuccess, MyFirstApp.onGetUserNameError);
        },
        onGetUserNameSuccess: function () {
            $('#message').text('Hello ' + MyFirstApp.user.get_title());
        },
        onGetUserNameError: function (sender, args) {
            $('#message').text('Failed to get user name. Error:' + args.get_message());
        }
    }

    // initialization
    MyFirstApp.init($('#myHomeTown'));

    // attach clickMe onclick event
    $('#clickMe').onclick = MyFirstApp.getUserName();
});

5. In App.cs file, I’ve added bit of styling to message div

#message {
    font-family: Arial;
    font-size: 18px;
    font-weight: bold;
}

6. Rebuild the solution

myfirstapp6

7. Publish the solution, then click Package the app

myfirstapp7

myfirstapp8

8. Browse to your App Catalog Site. Click new app to add new custom app, then enter the Name, Short Description, Long Description, checked Enabled and click Save

myfirstapp9

myfirstapp9.2

9. Browse to your Site Collection > Site Actions > Site Contents > Add an App > From your Organization > click MyFirstApp > Add it to add the custom app to your SharePoint site

myfirstapp10

10. Click MyFirstApp from your Site Collection > Site Actions > Site Contents, it will launch your new custom app

myfirstapp11

myfirstapp11.2

%d bloggers like this: