Showing posts with label SharePoint App. Show all posts
Showing posts with label SharePoint App. Show all posts

Sunday 20 November 2016

SharePoint 2013 Apps Environment Configuration.

Setting up a SharePoint development environment has always been challenging, and with the new Apps model in SharePoint 2013, there are even more options and requirements.


First, setup and configure DNS on a Windows server. (http://www.tomsitpro.com/articles/configure-dns-windows-server-2012,2-793.html)

The steps to configure the SharePoint 2013 apps environment.

a) Create Apps Forward Lookup Zone

SharePoint 2013 Apps have their own isolated URLs, which are separate from the URLs of the sites where the app is being deployed and where the app is being used. In order to provide isolation, apps should run in their own domain instead of in the same domain name as your farm. Using a different domain name for apps helps prevent cross-site scripting between apps and SharePoint sites.

Microsoft recommends that the new domain name should NOT be a subdomain of the domain that hosts the SharePoint sites.

1. Open DNS Manager and run it as an administrator from the Start screen.

2. In DNS Manager, right-click Forward Lookup Zones, then the New Zone context menu option.



3. Click Next on the New Zone Wizard dialogue box.

4. On the Zone Type step, select the Primary Zone and click the Next button.

5. On the Zone Name step, enter the app domain name (like spappsdeveloper.com), and click the Next button.



6. On the Dynamic Update step, select the type of dynamic updates you want to allow. Here, with the Allow both nonsecure and secure dynamic updates option selected, click the Next button.





b) Link the SharePoint App Domain to the SharePoint Server

Now DNS will forward all the requests from spappsdeveloper.com to the SharePoint server hosting the apps.

1. In DNS Manager, under Forward Lookup Zones, right-click the newly created zone or app domain (spappsdeveloper.com). Click New Alias (CNAME) from the context menu option.

2. On the New Resource Record dialogue, enter * as the Alias name.

3. For a Fully qualified domain name (FQDN) for target host box, select the Browse button.

4. On the Browse dialogue, select server > Forward Lookup Zones > SharePoint sites host domain > select the record that points to the server that hosts the SharePoint site. Ensure Hosts and Aliases (A and CNAME Records) is selected as the Record types, and click the OK button.

5. Click OK to close the dialogue box.


c) Creating the Subscription Settings and App

 Management Service Applications

1. In SharePoint Central Administration, click the Manage service applications option.

2. Click the New button, then the App Management Service menu item.

3. On the New App Management Service Application dialogue, enter “App Management Service” as the Service Application Name. Select the Use existing application pool option, and then select AppManagementService Pool from the drop-down. Ensure the Create App Management Service Application checkbox is checked. Click the OK button.

4. Or you can use the PowerShell command to create an App Management Service Application.

# get the service application pool
$serviceAppPool = Get-SPServiceApplicationPool -Identity "AppManagementService Pool"

# create app management service application and save its response in variable
$appMngmntSvc = New-SPAppManagementServiceApplication -ApplicationPool
$serviceAppPool -Name "App Management Service" -DatabaseName "App Management Service DB"

# create app management service application proxy and mapping it to service application
New-SPAppManagementServiceApplicationProxy -ServiceApplication $appMngmntSvc

5. Once returned to the list of service applications, ensure both App Management Service Applications are started.

6. Open the SharePoint 2013 Management Shell as an administrator and run.

7. Start the SPAdminV4 and SPTimerV4 service applications.

net start SPAdminV4

net start SPTimerV4

8. Set the domain used to host apps to the new zone created above. It can be set by PowerShell as "done" or via central administration. It can also be done later at the Configure App URL step (see below).

# App Domain Name.
Set-SPAppDomain "spappsdeveloper.com"


9. Start the AppManagementServiceInstance and SPSubscriptionSettingsServiceInstance service instances.

# Start the App Management & Subscription SharePoint services.
Get-SPServiceInstance | where{$_.GetType().Name -eq "AppManagementServiceInstance" -or $_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance"} | Start-SPServiceInstance


10. Ensure the AppManagementServiceInstance and SPSubscriptionSettingsServiceInstance service instances are Online.

# Check the "Online" status of the App Management & Subscription SharePoint services.
Get-SPServiceInstance | where{$_.GetType().Name -eq "AppManagementServiceInstance" -or $_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance" }


11. Create the SharePoint Subscription Service.

# get the service application pool
$account = Get-SPManagedAccount "WIN-EODPTE6TSSE\sppool"
$serviceAppPool = New-SPServiceApplicationPool -Name "SettingsServiceAppPool" -Account $account

$serviceAppPool = Get-SPServiceApplicationPool -Identity "AppManagementService Pool"

# create subscription settings service application and save its response in variable
$appSubSvc = New-SPSubscriptionSettingsServiceApplication –ApplicationPool
$appPoolSubSvc -Name "SettingsServiceApp" –DatabaseName "SPSubscriptionSettingsServiceDB"

# create subscription settings service application proxy and mapping it to service application
$proxySubSvc = New-SPSubscriptionSettingsServiceApplicationProxy –ServiceApplication $appSubSvc




d) Configure the App URL

Set the name for the site subscription.

1. Open Central Administration, click Apps, and then click Configure App URLs.

2. In the App Prefix box, type a name to use for the URL prefix for apps.

3. Or it can also be done by PowerShell.

# SharePoint App Subscription name.
Set-SPAppSiteSubscriptionName -Name "apps" -Confirm:$false



Create a new Developer Site site collection for local App deployment.
Now you're ready to deploy your SharePoint apps to your local SharePoint development environment.

I hope this will help; do write your comments and suggestions.


🚀 "Happy Coding" 🚀

Saturday 31 October 2015

Set the Master Page of the Host Web in SharePoint Hosted App 2013 using JavaScript.

SharePoint CSOM (Client Side Object Model) or apps are capable of performing almost all functions that server-side code provides. There are some limitations, but the CSOM is maturing with time.

In this article, I will tell you how to set the master page of the host web from the app web (app) using JavaScript. Host web and App web reside in different contexts at different levels of scope, so SharePoint doesn't allow app web contexts to set host web master page directly.

Steps to set the master page of the host web from App Web:
1. Create a SharePoint hosted app and add a module named "CustomMasterPage".



2. Download a copy of seattle.master from the Master Page gallery.
3. Copy and paste this file content into our modules .txt file and make custom changes to it as required (I have just changed the background colour and image for the demo).

Tip: Don't change the extension file (.txt) in the module; otherwise, it is not easy to read the file content.

4. Now create a namespace to avoid method and property conflicts.
5. Get appweb and hostweb URLs.
6. Set clientContext and hostWebContext.
7. Read the text of the above created .txt file using a jQuery ajax call.
8. Create a file (by code) in host web and set that as the master page.
9. It will be at the site and system master page level.





SharePoint Hosted App JavaScript Code

"use strict";
 
// create namespace.
window.VB = window.VB || {};
 
window.VB.HostWebApp = function () {
    var hostWebUrl,
        appWebUrl,
        context,
        hostWebContext,
        destinationServerRelativeUrl,
        masterPageFileName,
        // read the master page contents from text file.
        readFileFromAppWeb = function (appPageUrl, hostWebServerRelativeUrl, fileName) {
            destinationServerRelativeUrl = hostWebServerRelativeUrl;
            masterPageFileName = fileName;
 
            $.ajax({
                url: appPageUrl,
                type: "GET",
                async: false,
                cache: false,
                success: function (data) {
                    if (data !== null && data !== undefined && data.length > 0) {
                        uploadFileToHostWeb(destinationServerRelativeUrl, masterPageFileName, data);
                    } else {
                        alert("Failed to read file from app web.");
                    }
                },
                error: function (jqXhr, textStatus) {
                    alert("Request for page in app web failed: " + textStatus);
                }
            });
        },
        // upload file to host web.
        uploadFileToHostWeb = function (serverRelativeUrl, filename, contents) {
            var createInfo = new SP.FileCreationInformation();
            createInfo.set_content(new SP.Base64EncodedByteArray());
            var index;
            for (index = 0; i < contents.length; index = index + 1) {
                createInfo.get_content().append(contents.charCodeAt(index));
            }
            createInfo.set_overwrite(true);
            createInfo.set_url(filename);
            var files = hostWebContext.get_web().getFolderByServerRelativeUrl(serverRelativeUrl).get_files();
 
            context.load(files);
            files.add(createInfo);
            context.executeQueryAsync(setMasterPageSuccess, setMasterPageError);
        },
        setMasterPageSuccess = function () {
            $("#message").append(["<br /><div>Master Page in host web successfully: ", destinationServerRelativeUrl, "/", masterPageFileName, "</div>"].join(""));
            var masterPageUrl = ["/", hostWebUrl.split("/")[3], "/", hostWebUrl.split("/")[4], "/", destinationServerRelativeUrl, "/", masterPageFileName].join("");
            setMaster(masterPageUrl);
        },
        setMasterPageError = function (sender, args) {
            alert('Request failed,Error: ' + args.get_message() + '\n' + args.get_stackTrace());
        },
        // set master page on host web.
        setMaster = function (masterUrl) {
            var hostWeb = hostWebContext.get_web();
            hostWeb.set_masterUrl(masterUrl);
            hostWeb.update();
 
            context.load(hostWeb);
            context.executeQueryAsync(onSetMasterPageSuccess, onSetMasterPageFail);
        },
        onSetMasterPageSuccess = function () {
            $("#message").append("<br /><div>Master page updated successfully..</div>");
        },
        onSetMasterPageFail = function (sender, args) {
            alert("Failed to update master page on host web. Error:" + args.get_message());
        },
        getQueryStringParameterValue = function (paramToRetrieve) {
            var params = document.URL.split("?")[1].split("&"),
                paramsLength = params.length,
                index;
            for (index = 0; index < paramsLength; index = index + 1) {
                var singleParam = params[index].split("=");
                if (singleParam[0] == paramToRetrieve) {
                    return singleParam[1];
                }
            }
        },
        init = function () {
            appWebUrl = decodeURIComponent(getQueryStringParameterValue("SPAppWebUrl"));
            hostWebUrl = decodeURIComponent(getQueryStringParameterValue("SPHostUrl"));
 
            //load the required scripts.
            var scriptbase = hostWebUrl + "/_layouts/15/";
            $.getScript(scriptbase + "SP.Runtime.js",
            function () {
                $.getScript(scriptbase + "SP.js",
                    function () {
                        //to execute cross domain request.
                        $.getScript(scriptbase + "SP.RequestExecutor.js");
                    }
                );
            });
        };
 
    return {
        execute: function () {
            init();
 
            context = new SP.ClientContext.get_current();
            hostWebContext = new SP.AppContextSite(context, hostWebUrl);
 
            readFileFromAppWeb(appWebUrl + "/_catalogs/masterpage/CustomAppMaster.txt""_catalogs/masterpage""CustomAppMasterPage.master");
        }
    };
}();
 
(function () {
    window.VB.HostWebApp.execute();
}());

This code will work both for setting the Master Page of HostWeb and AppWeb by using appropriate context.

🚀 "Happy Coding" 🚀