External Sharing of Documents with Nintex in SharePoint Online

The “Office 365 update item permissions” step available in Nintex Workflow updates item permissions. However if external users are given permissions using this step, it fails with message “failed to resolve user “. The issue with Office 365 update item permissions is that it does not allow updating permissions for external users.

With the SharePoint 2016 Remote API Sharing with external users can be achieved using method UpdateDocumentSharingInfo from class SPDocumentSharingManager which fortunately can be called using REST.

The tenant and site collection sharing property needs to be updated to either option “Allow external users who accept sharing invitations and sign in as authenticated users” or “Allow sharing with all external users, and by using anonymous links” to be able to add external users. If the first option is selected the user needs to be given access to the site.

allowsharingwithallexternalusers

The workflow will work against a list having columns Email and SharePointLink

listcolumnconfig

The first step in the workflow is to get the RequestDigest from targeted site collection. App Step to get request digest

The steps to add in the workflow are as below

  • Add “App Step” action
  • Add “Web Request” action. Fill in the following fields
    • URL: <siteURL> /_api/ContextInfo
    • Method : POST
    • Content type : text/xmlcontextinforequest
    • Body : Choose “Content” option  and enter “{}” in text field
    • UserName: Credentials who has access to targeted site
    • Password: password of above UserName
    • Store response content in : Create a variable “RequestDigest”
  • Add “Query XML” action. Fill in the following fields
    • XML source: Choose “Content” and pick variable “digest token”
    • XPath query: /d:GetContextWebInformation/d:FormDigestValuegetrequestdigest
    • Return result as :Text
    • Query result in : create a text variable strDigestInfo
  • Add “Log to History List” step. Print the strDigestInfo to make sure valid request digest are used.

Please note that workflow app permissions need to amended to give site collection full control access.

The second step is to call the UpdateDocumentSharingInfo REST API method to grant appropriate access to the external user.

appsteptoaddreadpermissiontodocument

  • Add “App Step” action
  • Add Build Dictionary step.  Rename is to “Request Headers”.
    • Add key “accept” and Value “application/json;odata=verbose”
    • Add key “content-type” and Value  “application/json;odata=verbose”
    • Add key “X-RequestDigest” and Value ‍{Variable:strDigestInfo}
    • Add Output to variable RequestHeadersPerm.

Request Headers build-request-headers

  • Add Build Dictionary step.  Rename is to “Build Metadata”.
    • Add key “type” and value “SP.Sharing.UserRoleAssignment”.
    • Output in variable MetadaPerm.

buildmetadata

  • Add Build Dictionary step.  Rename is to “Build UserRoleAssignments”.
    • Add key “__metadata” and Value of type Dictionary to variable MetadataPerm
    • Add key “Role” and value of type Integer 1. The Role property represents the level of permission you want to grant. Possible values are  1 =  View, 2 =  Edit, 3 = Owner, 0 = None.
    • Add UserId to ‍{Current Item:Email}
    • Add Output to UserRoleAssignments

build-userroleassignments

  • Add Item to Collection Step
    • Set Target collection to  collection variable RoleAssignmentCol
    • Set Index 0
    • Set Value to dictionary variable UserAssignmentts
    • Set Output to RoleAssignmentCol

roleassignmentstocollection

  • Add a Build  Dictionary step and label to “Build Parameters”
    • Add Key “userRoleAssignments” and Value of type Dictionary to variable RoleAssignmentCol
    • Add Key “resourceAddress” and Value ‍{Workflow Context:Current site URL}‍‍{Current Item:SharePointLink}
    • Add Key “validateExistingPermissions” and Value of type Boolean set to No
    • Add key “additiveMode” and Value of type Boolean set to Yes
    • Add Key “sendServerManagedNotification” and Value of type Boolean set to Yes
    • Add Key “customMessage” and Value “Document has been shared with you”
    • Add Key “includeAnonymousLinksInNotification” and Value of type Boolean set to Yes
    • Add Key “propagateAcl” and Value of type Boolean set to Yes

 

buildparameters

  • Add a Call Http Web Service step to assign permissions using SP.Sharing.DocumentSharingManager.UpdateDocumentSharingInfolistcolumnconfig
    • Set Address to ‍{Workflow Context:Current site URL}‍/_api/SP.Sharing.DocumentSharingManager.UpdateDocumentSharingInfo
    • Set Request Type to “Http Post”
    • Set Request Headers to variable RequestHeadersPerm
    • Set Request Content to variable ParametersPerm
    • Set Response Headers to variable ResponseContentPerm
    • Set Response Content to variable ResponseHeadersPerm
    • Set Response Status Code to ResponseStatusCode

 

callhttpwebservice_updatedocumentsharinginfo

You can use the Log to History List step to log the ResponseStatusCode,  ResponseContentPerm and ResponseHeadersPerm.

An email will be sent to the external user when run with a link to access the resource.

emailgeneratedwithlink

Rest Api Generate Guest Link SharePoint Online

The CreateAnonymousLink method creates an anonymous link with option either to read or edit. It is quite useful to share documents with external users.

The drawback is that anyone with the link can view/edit the document shared without sign-in.

The method “CreateAnonymousLink ” accomplishes the same as “View Link – no sign-in required” and “Edit Link -no sign-in required” from the UI.createanonymouslink

Once the link is generated, it can be sent by email to the relevant individuals.

Nintex SharePoint Online Create SharePoint Group with Contribute permissions

Nintex Workflow has actions “Web Request” and “Call HTTP Web Service” which can be used to make calls to the REST API of SharePoint Online/2013 to automate creation of SharePoint groups in a site collection.

Add the following steps to the workflow

  1. Create a Text variable GroupName and Use “Set Workflow Variable” to assign it to a value.GroupNameVariable
  2. Get request digest from targeted site collection. Please note that workflow app permissions need to amended to give site collection full control access.        App Step to get request digest
    • Add “App Step” action
    • Add “Web Request” action. Fill in the following fields
      • URL: <siteURL> /_api/ContextInfo
      • Method : POST
      • Content type : application/x-www-form-urlencoded
      • Header Name (Key) : Accept     Header value: application/json;odata=verbose

        WebRequestToGetRequestDigest

      • Body : Choose “Content” option  and enter “{}” in text field
      • UserName: Credentials who has access to targeted site
      • Password: password of above UserName
      • Store response content in : Create a variable “digest token”WebRequestToGetRequestDigest_2
    • Add “Query XML” action. Fill in the following fields
      • XML source: Choose “Content” and pick variable “digest token”
      • XPath query: /d:GetContextWebInformation/d:FormDigestValue
      • Return result as :Text
      • Query result in : create a text variable strDigestInfoQueryXMLRequestDigest
    • Add “Log to History” action. Print the strDigestInfo to make sure valid request digest are used  QueryXMLRequestDigest
  3. Create SharePoint Group using REST API ‍/_api/web/sitegroups  AppStepToCreateSpGroup
    • Add “App Step” action. Optionally add “Log to History List” action to log status of workflow.
    • Add “Build Dictionary” action to build “Request Headers”.
      •  Add the following key value pair as Text- content-type:  application/json; odata=verbose
        – X-RequestDigest : {Variable:strDigestInfo}
      • Save Output into RequestHeadersRequestHeaders
    • Add “Build Dictionary” action to build “Metadata”
      •  Add the following key/value pair- key: type    Type:Text  Value: SP.Group
        BuildMetadataForGroup
    • Add “Build Dictionary” action to build “Parameters”
      •  Add the following key/value pair- Key: __metadata   Type:Dictionary   Value: Workflow Variable GroupMetadata
        – Key: Description  Type: Text  Value: Group created automatically from Nintex workflow
        – Key: Title  Type:Text  Value:{Variable:GroupName}
      • Assign Output to a dictionary variable GroupParameters
        BuildDictionaryGroupParameters
    • Add “HTTP Web Service”action to create group
      • Fill in Address : <SiteURL>/_api/web/sitegroups
      • Set Request Type to “HTTP Post”
      • Set Request Headers to dictionary variable RequestHeaders
      • Set Request Content to dictionary variable GroupParameters
      • Set Response Headers to new dictionary variable GroupResponseHeaders
      • Set Response Content to new dictionary variable GroupResponseContent
      • Set Response Status Code to new text variable GroupResponseStatusCodeWebRequestToCreateGroup
    • Log to History list the responseLogResponseOfGroupCreated
  4. Retrieve SharePoint Group using REST API ‍ ‍/_api/web/sitegroups/getbyname AppStepToGetGroupCreated
    • Add “Add Step” action
    • Optionally add “Log History List” action to log workflow status.
    • Add a “Web Request” actionWebRequestToGetGroupCreated
      • Set URL to <SiteURL>/_api/web/sitegroups/getbyname(‘‍{Variable:GroupName}‍’)?$select=Id
      • Choose  Get for Method
      • Click Add Header
      • Set Header Key to “Accept”
      • Set Header Value to “application/json;odata=verbose”
      • Set UserName to user who has access to site collection
      • Set Password to password of specified user
      • Set Store response content in a Text variable GroupRequestIDXMLAdd
    • Add “Log History List” action to log response GroupRequestIDXMLAdd from web request. The response is in JSON format. Nintex does not have a JSON parser action to retrieve value of property. Use “Regular Expression” action as described in the next step is used to retrieve Id value
    • Add “Regular Expression” actionRegularExpressionToGetID
      • Set String to ‍{Variable:GroupRequestIDXML}
      • Set String Operation to Extract
      • Set pattern to (?<=”Id”:).*?(?=})
      • Save Output to text variable strGroupIDCol
    • Add “Get Item from Collection” action.GetGroupIDFromCollection
      • Set Target Collection to variable strGroupIDCol
      • Set Index to 0
      • Set Output to SPGroupId
    •  Add “Log History List” action to log strGroupIDCol
  5. Add Contribute Role to new Group
    • Add App Step action  AppStepToAddContributeRoleToGroup
    • Add “Call HTTP Web Service” Action WebRequestToAddContributeRole
      • Set URL to <siteURL>‍/_api/web/roleassignments/addroleassignment(principalid=‍{Variable:SPGroupId}‍,roleDefId=1073741827)
      • Set Request Type to “HTTP Post”
      • Set Request Headers to dictionary “RequestHeaders”
      • Set Response Headers to new dictionary variable RoleAssignResponseHeaders
      • Set Response Content to new dictionary variable RoleAssignmResponseContent
      • Set Response Status Code to new text variable RoleAssignmResponseStatusCode
    • Add “Log to History List” action to log response of web request

Save and Publish the workflow. If the workflow runs succesfully

WorkflowHistory

 

 

Nintex DocSign Enable Multiple Recipients

Doc Sign is a useful secure way of signing documents which is legally binding. Nintex provides the DocuSign send document action that integrates DocuSign service. A trial account for PROD can be created but the trial limit is 3 documents. For development or evaluation purposes, a free developer account can be created on DocuSign site.

Follow the instructions from The Quick Quide to Doc Sign  to configure your dev account. Part of the process is to create an integrator key which is needed to call DocuSign REST API. Also create a template which can be referred in the REST API call.

The issue with the  Nintex “DocuSign populate document” action is that it does not support multiple recipients. It tells DocuSign to send one recipient only. The workaround as suggested in the Nintex forum is to repeat the action but the document is duplicated and  tracing history is lost.

The option is to use the “Web Request” action from Nintex to send to multiple recipients.

To make a REST CALL to Doc Sign you need the following info

  1. Account ID: Can be found after you login to DocSign by clicking on the arrow down next to your picture. The number displayed after your email address is the account id to use.       DocSignAccountID
  2. Integrator Key: From the menu displayed next to your profile picture, click on “Go to Admin”> “API and Keys” under Integration section. If there is not integrator key, click on “Add Integrator key” else note down the integrator key.IntegratorKey
  3. Template ID: Click on “Templates” link and click on the i next to the template aDocSignTemplateID

In the Nintex Workflow add a “Web Request” Action

MultipleRecipientsDocSign

Set the following fields

  1. URL: https://demo.docusign.net/restapi/v2/accounts/{account id}/envelopes
  2. Method: Select POST and the following headers
    • Content Type : application/json;odata=verbose
    • X-DocuSign-Authentication : {“Username”:”{DocSign Account}”,”Password”:”{DocSign password}”,”IntegratorKey”:”{key}”}
  3. Body : Choose Content and  copy the following  JSON request{  “emailSubject”: “Please sign”,
    “emailBlurb”: “Please sign…thanks!”,
    “status”: “sent”,
    “compositeTemplates”: [
    {    “serverTemplates”: [
    {   “sequence” : 1,
    “templateId”: “{template id}”    }],
    “inlineTemplates”: [    {
    “sequence” : 2,
    “recipients”: {
    “signers” : [{
    “email”: “{test@em.com}”,
    “name”: “Test1 Test1”,
    “recipientId”: “1”,
    “roleName”: “Signer”,
    “routingOrder”: “1”
    },
    {
    “email”: “test2@yahoo.co.uk”,
    “name”: “Test2 Test 2”,
    “recipientId”: “2”,
    “roleName”: “Signer 2”,
    “routingOrder”: “2”
    }
    ]
    }
    }]
    }]  }
  4. Store response content in : Create a variable DocSignWebRequestResponse
  5. Store http status code in : Create a variable DocSignWebRequestStatusCode
  6. Store response headers in: Create a variable DocSignWebRequestHeaders
  7. Store response cookies in: Create a variable DocSignWebRequestResponseCookies

The JSON format of the response is

{
“envelopeId”: “84385783-fa5b-4b5e-8ef5-02702b505fb2”,
“uri”: “/envelopes/84385783-fa5b-4b5e-8ef5-02702b505fb2”,
“statusDateTime”: “2016-04-27T06:30:50.7530000Z”,
“status”: “sent”
}

Add “Extract Substring of String from Index with Length” action to get the envelope id from variable DocSignWebRequestResponse.

GetEnvelopeIDfromResponse

Set the following fields

  1. String: {Variable: DocSignWebRequestResponse}
  2. Index: 20
  3. Number of Characters: 36
  4. Output: Text variable EnvelopeID

You can add a “DocuSign retrieve envelope status” action specifying the envelopeID in a loop to get status of the envelope id until it is completed with a particular time interval. Fill in the following fields

  1. Authorizing user: {DocSign UserName}
  2. Envelope ID: {Variable:EnvelopeID}
  3. Status: Save into variable status
  4. Message: Save into variable message

The Status will have value “In Process” if still waiting for signatures, else the status will be completed.

DocSignRetriveEnvelopeStatus

SharePoint REST Get all items __next

When a REST query is run against a SharePoint list, not all items are returned if it contains more than 100 items. The default server paging is 100.

It is a good practice to check the __next property of the JSON results to make sure all items are returned.

Below is a code snippet running from a SharePoint hosted add-in.


var url = appUrl + "/_api/SP.AppContextSite(@target)/Web/Lists/getByTitle('Repairs')/Items?$select=Title&@target='" + hostUrl + "'";
jQuery.getScript(scriptbase + "SP.RequestExecutor.js", getRepairDetails);

function getRepairDetails() {
var executor = new SP.RequestExecutor(appUrl);
executor.executeAsync(
{
url: url,
method: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
},
success: function (data) {
var response = JSON.parse(data.body);
message.append(String.format("Retrieved {0} items", response.d.results.length));
message.append("
");

if (response.d.__next) {
url = response.d.__next;
getRepairDetails();
}
},
error: function (data, errorCode, errorMessage) {
alert(errorMessage);
}
}
);

SharePoint 2013/Online CSOM REST Web Proxy

Web Proxy

SP.WebProxy is used to make requests to external services by SharePoint.

SharePoint Add-ins must register target site as remote endpoint in app manifest.

If the URL is http://services.odata.org/v4/Northwind/Northwind.svc/Categories?$format=json, the endpoint is http://services.odata.org.

However the response size must not exceed 200 kb.

CSOM


var context = SP.ClientContext.get_current();
var request = new SP.WebRequestInfo();
request.set_url("http://services.odata.org/v4/Northwind/Northwind.svc/Categories?$format=json");
request.set_method("GET");
var response = SP.WebProxy.invoke(context,request);
context.executeQueryAsync(success, fail);

function success(){
if(response.get_statusCode() == 200 {
var data = JSON.parse(response.get_body());
} else {
var errorMessage = response.get_body();
jQuery.each(categories.d.results, function(index,value)
{
console.log(value.CategoryName);
});
}

REST

var call = jQUery.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.WebProxy.invoke",
type: "POST",
data: JSON.stringify(
{
"requestInfo": {"type":"SP.WebRequestInfo"},
"Url":"http://services.odata.org/v4/Northwind/Northwind.svc/Categories?$format=json",
"Method":"GET"
}),
headers:{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#_REQUESTDIGEST").val()
}
});