Search This Blog

Tuesday, September 24, 2019

Custom Master - SharePoint Online site provisioning solutions App

DowloadCode

Steps to set master page of host web from app web
1. Create a SharePoint hosted app and add a module named as "CustomMasterPage".
2. Download a copy of seattle.master from Master Page gallery.
3. Copy paste this file content into our modules .txt file and do custom changes on it as required (i have just changed the background color and image for demo).
 Tip: Don't change the extension file (.txt) in module otherwise it is not easy to read file content.
4. Refere sp.JS and sp.runtime.JS on default aspx page
5. below code copy paste on App.js
6. Deploy app
-------------------------------------------
MasterPageModule/Elements

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="MasterPageModule">
    <File Path="MasterPageModule\CustomAppMaster.txt" Url="MasterPageModule/CustomAppMaster.txt" Level="Published" ReplaceContent="TRUE" />
  </Module>

</Elements>

App.JS
-----------------------------------------
'use strict';
window.COB = window.COB || {};

window.COB.HostWebApp = function () {
    var hostWebUrl,
        appWebUrl,
        hostWebContext,
        destinationServerRelativeUrl,
        destinationFileName,

    // locate a file in the app web and retrieve the contents. If successful, provision to host web..
    readFromAppWebAndProvisionToHost = function (appPageUrl, hostWebServerRelativeUrl, hostWebFileName) {
        destinationServerRelativeUrl = hostWebServerRelativeUrl;
        destinationFileName = hostWebFileName;

        var req = $.ajax({
            url: appPageUrl,
            type: "GET",
            cache: false
        }).done(function (fileContents) {
            if (fileContents !== undefined && fileContents.length > 0) {
                uploadFileToHostWebViaCSOM(destinationServerRelativeUrl, destinationFileName, fileContents);
            }
            else {
                alert('Failed to read file from app web, so not uploading to host web..');
            }
        }).fail(function (jqXHR, textStatus) {
            alert("Request for page in app web failed: " + textStatus);
        });
    },

    // utility method for uploading files to host web..
    uploadFileToHostWebViaCSOM = function (serverRelativeUrl, filename, contents) {
        var createInfo = new SP.FileCreationInformation();
        createInfo.set_content(new SP.Base64EncodedByteArray());
        for (var i = 0; i < contents.length; i++) {

            createInfo.get_content().append(contents.charCodeAt(i));
        }
        createInfo.set_overwrite(true);
        createInfo.set_url(filename);
        var files = hostWebContext.get_web().getFolderByServerRelativeUrl(serverRelativeUrl).get_files();
        hostWebContext.load(files);
        files.add(createInfo);

        hostWebContext.executeQueryAsync(onProvisionFileSuccess, onProvisionFileFail);
    },
    onProvisionFileSuccess = function () {
        $('#message').append('<br /><div>File provisioned in host web successfully: ' + destinationServerRelativeUrl + '/' + destinationFileName + '</div>');
        var masterPageUrl = ["/", hostWebUrl.split("/")[3], "/", hostWebUrl.split("/")[4], "/", destinationServerRelativeUrl, "/", destinationFileName].join("");
        setMaster(masterPageUrl);
        //setMaster('/' + destinationServerRelativeUrl + '/' + destinationFileName);
    },
    onProvisionFileFail = function (sender, args) {
        alert('Failed to provision file into host web. Error:' + sender.statusCode);
    },

    // set master page on host web..
    setMaster = function (masterUrl) {
        var hostWeb = hostWebContext.get_web();
       // hostWeb.set_masterUrl(masterUrl);      
        hostWeb.set_customMasterUrl(masterUrl);
        hostWeb.set_masterUrl(masterUrl);
        hostWeb.update();      
        hostWebContext.load(hostWeb);
        hostWebContext.executeQueryAsync(onSetMasterSuccess, onSetMasterFail);
    },
    onSetMasterSuccess = function () {
        $('#message').append('<br /><div>Master page updated successfully..</div>');
    },
    onSetMasterFail = function (sender, args) {
        alert('Failed to update master page on host web. Error:' + args.get_message());
    },

    init = function () {
        var hostWebUrlFromQS = $.getUrlVar("SPHostUrl");
        hostWebUrl = (hostWebUrlFromQS !== undefined) ? decodeURIComponent(hostWebUrlFromQS) : undefined;

        var appWebUrlFromQS = $.getUrlVar("SPAppWebUrl");
        appWebUrl = (appWebUrlFromQS !== undefined) ? decodeURIComponent(appWebUrlFromQS) : undefined;
    }

    return {
        execute: function () {
            init();

            hostWebContext = new SP.ClientContext(window.COB.AppHelper.getRelativeUrlFromAbsolute(hostWebUrl));
            readFromAppWebAndProvisionToHost(appWebUrl + '/MasterPageModule/CustomAppMaster.txt', '_catalogs/masterpage', 'CustomAppMaster.master');
        }
    }
}();
jQuery.extend({ 
    getUrlVars: function () { 
        var vars = [], hash; 
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); 
        for (var i = 0; i < hashes.length; i++) { 
            hash = hashes[i].split('='); 
            vars.push(hash[0]); 
            vars[hash[0]] = hash[1]; 
        } 
        return vars; 
    }, 
    getUrlVar: function (name) { 
        return jQuery.getUrlVars()[name]; 
    } 
});
window.COB.AppHelper = {
    getRelativeUrlFromAbsolute: function (absoluteUrl) {
        absoluteUrl = absoluteUrl.replace('https://', '');
        var parts = absoluteUrl.split('/');
        var relativeUrl = '/';
        for (var i = 1; i < parts.length; i++) {
            relativeUrl += parts[i] + '/';
        }
        return relativeUrl;
    },
};
$(document).ready(function () {  
    window.COB.HostWebApp.execute();
});




default.aspx


<%-- 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>
    <SharePoint:ScriptLink name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
    <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 src="/_layouts/15/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="/_layouts/15/sp.core.js" type="text/javascript"></script>
    <script src="/_layouts/15/sp.runtime.js" type="text/javascript"></script>
    <script src="/_layouts/15/sp.js" type="text/javascript"></script>
    <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 >
        <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        </p>
    </div>

</asp:Content>

No comments:

Post a Comment