Tuesday, October 13, 2015

Create a Menu Item Custom Action using SharePoint Hosted App

Create a Menu Item Custom Action using SharePoint Hosted App.
Create a new SharePoint Hosted App as follows in Visual Studio. 
Go to "Pages" -> Open "Default.aspx" page. update the page as shown below.
 ---------------------------------------------------------------------
<%-- 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" %>
<%-- 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>
    <script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.requestexecutor.js"></script>
    <script type="text/javascript" src="../Scripts/MenuItemCustomActionJS.js"></script>
    <meta name="WebPartPageExpansion" content="full" />
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
    <script type="text/javascript" src="../Scripts/App.js"></script>
    <script type="text/javascript">
        (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>
</asp:Content>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Page Title
</asp:Content>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <div>
        <p id="message">
            initializing...
        </p>
    </div>
     <div>       
        <ul id="songList"></ul>
    </div>
</asp:Content>
 ---------------------------------------------------------------------
Go To "Script" Folder and add new "MenuItemCustomActionJS.js" JavaScript file as follows.
Add below code to "MenuItemCustomActionJS.js"
 ---------------------------------------------------------------------
(function () {
    "use strict";
    $(function () {
        setTimeout(function () {
            var artist;
            var responseDocument = "";
            var appWebUrl = getQueryStringParameter("SPAppWebUrl");
            var hostWebUrl = getQueryStringParameter("SPHostUrl");
            var listId = getQueryStringParameter("SPListId");
            var listItemId = getQueryStringParameter("SPListItemId");
            var ctx = SP.ClientContext.get_current();
            var request = new SP.WebRequestInfo();
            if (typeof (artist) == "undefined") {
                if (typeof (listId) != "undefined" && typeof (listItemId) != "undefined") {
                    listId = listId.substring(1, listId.length - 1);
                    var executor = new SP.RequestExecutor(appWebUrl);
                    executor.executeAsync({
                        url: "../_api/SP.AppContextSite(@target)/web/lists(guid'" + listId + "')/getItemByStringId('" + listItemId + "')?@target='" + hostWebUrl + "'",
                        method: "GET",
                        headers: { "accept": "application/json;odata=verbose", },
                        success: function (data) {
                            artist = JSON.parse(data.body).d.Title;
                        },
                        error: function (data) {
                            artist = "artist";
                        }
                    });
                }
                setTimeout(function () {
                    request.set_url("http://www.musicbrainz.org/ws/2/release-group?query=artist:" + artist);
                    request.set_method("GET");
                    responseDocument = SP.WebProxy.invoke(ctx, request);
                    ctx.executeQueryAsync(onSuccess, onError);
                }, 2000)
            }
            var onSuccess = function () {
                var xmlDoc = $.parseXML(responseDocument.get_body());
                $(xmlDoc).find("release-group").each(function (i) {
                    var title = $(this).children("title").first().text();
                    $("#songList").append("<li>" + title + "</li>")
                });
            }
            var onError = function () {
                alert("failed!");
            }
        }, 3000)
    });
}());
var getQueryStringParameter = function (p) {
    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] == p)
            return decodeURIComponent(singleParam[1]);
    }
}
 ---------------------------------------------------------------------
Add new Menu Item Custom Action "MenuItemCustomAction1" to solution as follows.
Open "MenuItemCustomAction1" -> "Elements.xml" 
 ---------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="cd833011-377a-4851-a831-075e620a0e3f.MenuItemCustomAction1"
                RegistrationType="List"
                RegistrationId="100"
                Location="EditControlBlock"
                Sequence="10001"
                Title="APP Search">
    <UrlAction Url="~appWebUrl/Pages/Default.aspx?{StandardTokens}&amp;SPListItemId={ItemId}&amp;SPListId={ListId}" />
  </CustomAction>
</Elements>
 ---------------------------------------------------------------------
Now go to "AppManifest.xml" double click on it.
Go to Permission Tab and give "Read" permission to "Web" Scope.
Now go to "Remote Endpoints" tab and add "http://www.musicbrainz.org" url as "EndPoints".
Press "F5" to deploy. after deploy click on "Trust It" to trust this app.
Navigate away from the app home page to the home page of the "Host Web". Now we have to add one custom list in host web. 
Create a custom list as shown below.
 Add new item as "Lore Unfolds" to test "Menu Item Custom Action".
 
Once click on "APP Search" it will navigate to App Home Page and will display Search result from http://www.musicbrainz.org url as shown below.
Thank You.

1 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: ---------- {   ...

Popular posts