Manage User Custom Actions in Office 365

Overview

Custom Actions offer a flexible way to extend capabilities of the SharePoint. The possibilities span the range of including custom JavaScript on every page to extending the Ribbon. In SharePoint 2013/SharePoint Online you can leverage the CSOM/REST  to manage custom actions. Below are demonstrated two simple examples of using custom actions in real world scenarios and I hope you you’ll find them useful.

Example 1. Enable jQuery

Let’s get started with an example that demonstrate how to add jQuery library to Office 365/SharePoint Online site. Unfortunately  it is not supported to reference external resources, for example from Microsoft Ajax Content Delivery Network (CDN) that hosts popular third party JavaScript libraries including jQuery. The prerequisite for referencing JavaScript files is that they could only be accesible when located within the site collection. So, the first step would be to save a jQuery library into Style Library: /Style Library/Scripts/jQuery/jquery-2.1.1.js.

The following Activate-JQuery.ps1 script  demonstrates how to enable jQuery library  in Office 365/SharePoint Online site

Dependencies: UserCustomActions.ps1

Example 2. Enable Google Analytics

The following Activate-GoogleAnalytics.ps1 script demonstrates how to activate tracking code in Office 365/SharePoint Online site

Dependencies: UserCustomActions.ps1

Follow these instructions to use Google Analytics to collect data from Office 365/SharePoint Online sites.

To set up the web tracking code:

  1. Find the tracking code snippet for your property.
    Sign in to your Google Analytics account, and click Admin in the top menu bar. From the Account and Propertycolumns, select the property you’re working with. Click Tracking Info / Tracking Code.
    SNP_8C6378625835DB93E9293E76F24E9AC45177_3517951_en_v4
  2. Find your tracking code snippet. It’s in a box with several lines of JavaScript in it. Everything in this box is your tracking code snippet. It starts with <script> and ends with </script>.
    The tracking code contains a unique ID that corresponds to each Google Analytics property. Don’t mix up tracking code snippets from different properties, and don’t reuse the same tracking code snippet on multiple domains. Click to expand this image and see where the tracking code snippet is in the interface.
  3. Open , paste the tracking code into $TrackingCode variable and run the script to register tracking code in Office 365/SharePoint Online site
  4. Check your set up.
    Make sure that the tracking snippet installed on your website matches the code shown in the view, and see more ways you can verify your set up.

Working with folders and files via SharePoint 2013 REST in PowerShell

Overview

In the previous post we’ve already discussed how to perform CRUD operations by sending HTTPS requests to SharePoint RESTful web services in PoweShell. The Invoke-RestSPO function was introduced for that purpose since  Invoke-RestMethod cmdlet does not support claims based authentication and it makes this cmdlet impossible to use in O365 and SharePoint Online scenarios.

This time I am going to demonstrate how  to perform basic create, read, update, and delete (CRUD) operations on folders and files with the SharePoint 2013 REST interface using Invoke-RestSPO function.

Explore the REST service files and folder syntax

SharePoint 20123 Files and Folders REST syntax

 

Working with folders

Folder resource: represents a folder on a SharePoint Web site

Endpoint URI: http://<site url>/_api/web/getfolderbyserverrelativeurl(‘/<folder name>‘)

Supported HTTP methods:  GET  |  POST  |  DELETE  |  MERGE  |  PUT

The following examples demonstrates how to perform basic CRUD operations with Folder resource.

 

 

Working with files

Folder resource: represents a file in a SharePoint Web site that can be a Web Part Page, an item in a document library, or a file in a folder.

Endpoint URI: http://<site url>/_api/web/getfilebyserverrelativeurl(‘/<folder name>/<file name>‘)

Supported HTTP methods:  GET  |  DELETE  |  POST  (File resource)

The following examples demonstrates how to perform basic operations with File resource including:

  • upload file into SharePoint
  • download  file from a SharePoint

 

Summary

To summarize, it was demonstrates how to perform basic operations with files and folders, in particular how to  download and upload files via REST. For that purpose we  utilized Invoke-RestSPO function  that is intended for sending HTTPS requests to O365/SharePoint Online REST service.

References

How to: Upload files into Office 365 via PowerShell

Overview

Being one of the most common questions “How to upload files to SharePoint Library?”, i noticed that usually folder structure is not taken into account in the provided solutions.
So i decided to fill the gap and implement another version that allows to preserve folder structure while uploading files.

Prerequisites

PowerShell script

PowerShell script demonstrates how to upload  files within a specified local directory to a Document Library within a Site in an O365 tenant.

 

SharePoint Online client for PHP

In this post I would like to introduce you to a SharePoint client for PHP available on GitHub. The library provides a SharePoint Online (SPO) client for PHP applications. It allows you to performs CRUD operations on SharePoint data using an SharePoint 2013 REST/OData based API.

 API

PHP:cURL library is used to make HTTP requests to performs CRUD operations on SharePoint data using SharePoint 2013 REST API.

Getting started

A first example

Key points:

  • SPOClient class represents a REST Service client for the specified SharePoint Online (SPO) site
  • The signIn method performs a claims-based authentication. You can find more details about remote authentication in Remote authentication in SharePoint Online post.

The following examples demonstrates how to perform the remaining CRUD operations on SharePoint list data.

 List data generator

And finally one more example that demonstrates how to populate Contacts list in SharePoint. For generating fake data we will utilize Faker PHP library, below is provided the complete example:

Summary

The library currently supports CRUD operations against SharePoint list data. But since SharePoint 2013 REST covers a much broader set of API, the library could be extended.

Hopefully this helps you get started how you can interact with a SharePoint Online site from a remote Web application written in PHP!

Consuming the SharePoint 2013 REST Service from SharePoint Designer

In SharePoint 2013 workflows  was introduced  a new action named Call HTTP Web Service. This action is flexible enough  to make requests to a variety web services including SharePoint REST service.

Figure 1 shows you the Call HTTP Web Service action on the SharePoint Designer 2013 surface.

Call HTTP Web Service Get Operation

 

Figure 1. SPD Workflow that demonstrates how to leverage Call HTTP Web Service action for Read operation

The specified example demonstrates how to perform Read operation for retrieving webs information:

  1. Create a workflow variable named Url and set it’s value to [%Workflow Context:Current Site URL%]_api/web/webinfos
  2. Insert Build Dictionary action to construct request headers. Add key value pairs  from table 1. Save results into a variable of type Dictionary and named  RequestHeaders
  3. Insert Call HTTP Web Service action. Open Properties window and specify it’s properties as shown in table 2.

 

Table 1. Request Headers for a RequestHeaders dictionary variable

Name Type Value
 Accept String  application/json;odata=verbose
 Content-Type String  application/json;odata=verbose

 

Table 2. Call HTTP Web Service action properties for Read operation

Property Name Value
 Address Set value to variable Url that was created in step 1
 RequestType Set value to HTTP GET
 RequestHeaders Set value to dictionary variable RequestHeaders that we’ve constructed to store request header properties in step 2 
 ResponseContent Create a new dictionary variable named Result for storing the response returned by the REST service and set value to variable Result

Scenario: Create Site Workflow

The below example demonstrates how to  perform Create operation using Call HTTP Web Service action, in particular how to create web site from a workflow. 

Note: In order to perform Create/Update/Delete operations using  Call HTTP Web Service action, App permissions for workflow have to be configured.  Please follow the steps in article Create a workflow with elevated permissions by using the SharePoint 2013 Workflow platform to configure App permissions for workflow.

   

Figure 2 shows you the configured Call HTTP Web Service action for creating web site

Call HTTP Web Service Create Operation

SPD Workflow

Figure 2. SharePoint Designer workflow for creating web site

Steps:

1.   Create a workflow variable named Url and set it’s value to [%Workflow Context:Current Site URL%]_api/web/webinfos/add

2,3 and 5.   Those steps serve for building payload to submit to the service.  RequestContent parameter of  Call HTTP Web Service action is used for setting payloads to submit to the service.  See tables 4,5 and 6 for a details.

4.   Insert Build Dictionary action to construct request headers. Add key value pairs  from table 1. Save results into a variable of type Dictionary and named  RequestHeaders

6.   Insert Call HTTP Web Service action. Open Properties window and specify it’s properties as shown in table 3.

Table 3. Call HTTP Web Service action properties for Create operation

Property Name Value
 Address Set value to variable Url that was created in step 1
 RequestType Set value to HTTP POST
 RequestHeaders Set value to dictionary variable RequestHeaders that we’ve constructed to store request header properties in step 4 
 RequestContent Set value to dictionary variable RequestContent that was created for storing payload in step 5
 ResponseContent Create a new dictionary variable named Result for storing the response returned by the REST service and set value to variable Result

 Specifying  web site  creation information

For building payload to be submitted to the service the following dictionary variables are initialized in the workflow

Table 4. Metadata dictionary variable

Name Type Value
 type String  SP.WebInfoCreationInformation
 

 

Table 5. WebParameters dictionary variable

Name Type Value
 __metadata Dictionary  Variable:Metadata
 Url  String  Parameter:WebTitle
 Title  String  Parameter:WebTitle
 Description  String  Parameter:WebDesc
 Language  Integer  Parameter:Language
 WebTemplate  String  sts
 UseIniquePermissions  Boolean  false

 

Table 6. RequestContent dictionary variable

Name Type Value
 parameters Dictionary  Variable:WebParameters

For passing information about web site, an Initiation form is used as shown on figure 3

CreateSiteInitForm

Figure 3. Initiation Form

 

 

References

 

Consuming the SharePoint 2013 REST API from PowerShell

Introduction

SharePoint 2013 introduces a Representational State Transfer (REST) service that is comparable to the  SharePoint CSOM and in addition to CSOM, REST API opens up a huge capabilities, in particular for administering and automating SharePoint Online when used with PowerShell.

Sending  REST requests to a SharePoint Online 

In the previous post we’ve already covered how to perform read operations by sending HTTPS requests to SharePoint RESTful web services. This time we are going to extend PowerShell script  in order to support all the CRUD operations.

The Invoke-RestSPO function sends  HTTPS requests to SharePoint REST web services that returns richly structured data (JSON)

Request Digests

Since SharePoint requires the user to include a request digest value with each create, update and delete operation, an additional request is invoked using Get-SPOContextInfo function to request Context Info entity that contains request digest value.

 ETag

In order to avoid an additional request, “*” eTag value is used to match any eTag value resulting in the operation being performed regardless of the actual value.

Lists manipulation using REST API in PowerShell

This section contains sample code for all of the CRUD operations.

References

 

List Items manipulation via REST API in SharePoint 2010

Introduction

Apart from CSOM API,  REST API introduces another approach to access SharePoint list data from platforms on which the CSOM may be unavailable. The SharePoint REST interface is based on the REST-based Open Data protocol (OData) which  is a platform-independent open standard.

Examples

This section contains sample code for all of the CRUD operations.

Create

In order to  perform a Create operation via REST, you must perform the following actions:

  • Create an HTTP request using the POST verb.
  • Use the service URL of the list to which you want to add an entity as the target for the POST.
  • Set the content type to application/json.
  • Serialize the JSON objects that represent your new list items as a string, and add this value to the request body.

The following code snippet demonstrates how to perform a Create operation against a SharePoint list.

Read

In order to  perform a Read operation via REST, you must perform the following actions:

  • Create an HTTP request using the GET verb.
  • Use the service URL of the list item to which you want to add an entity as the target for the GET.
  • Set the content type to application/json.

The code sample demonstrates of how to retrieve an item based on its ID:

Update

To  update an existing entity, you must perform the following actions:

  • Create an HTTP request using the POST verb.
  • Add an X-HTTP-Method header with a value of MERGE.
  • Use the service URL of the list item you want to update as the target for the POST
  • Add an If-Match header with a value of the entity’s original ETag.

In contrast to reading list item  to update an item you will need to pass the eTag value, which could be obtained during item read.

About eTags

When updating or deleting items within SharePoint lists via REST you must specify the Entity Tag (eTag) value that was returned with the item during the initial query. This enables SharePoint to determine if the item has changed since it was requested. Alternatively you can tell SharePoint to perform the operation regardless by specifying * as the eTag value. For example:

  1. “If-Match”: item.__metadata.etag can be used to specify the actual eTag value (‘item’ is the object returned from SharePoint containing the list item in JSON format).
  2. “If-Match”: “*” can be used to match any eTag value resulting in the operation being performed regardless of the actual value.

They form part of the Ajax call for updating an item. eTags are part of the HTTP Protocol V1.1, more information on the topic can be found here.

Delete

To  delete an  entity, you must perform the following actions:

  • Create an HTTP request using the POST verb.
  • Add an X-HTTP-Method header with a value of DELETE.
  • Use the service URL of the list item you want to update as the target for the POST
  • Add an If-Match header with a value of the entity’s original ETag.

The Delete operation is similar to Update operation,  the code below demonstrates how to perform a Delete operation:

References

Introduction to Client Forms Validation in SharePoint 2013

Client side event handlers in SharePoint

In addition to server side Event Model,  SharePoint also provides client side  event handling capabilities when working with List Forms.

Let’s see briefly how it works. In List Forms pages Save button click handler triggers PreSaveItem function , PreSaveItem function is declared in forms.js:

PreSaveAction function from another hand, is a user defined function that allows to override standard behavior for a Save button handler, so in terms of server side event model it is a binding mechanism.

I find this mechanism  pretty convenient for implementing custom client side validation in List Forms,  the following example demonstrates how to implement client side validation for Email field in Contacts list:

EmailValidate

Client forms validation in SharePoint 2013

In SharePoint 2013 as part of  Client-Side Rendering (CSR), there is SPClientForms.ClientValidation  namespace (clientforms.js) that contains  types and objects for performing  client side validation in List Forms. For example,

SPClientForms.ClientValidation.RequiredValidator object is intended for evaluating the value of an field control to ensure that the user enters a value (it  is invoked for a fields when SPField.Required property is set to True):

Below is provided a complete example that demonstrates how to implement  client-side validation for Email field in Contacts list:

Key points:

  • CustomClientValidation.EmailValidator object implements a custom validation  for Email field
  • since Email field is a standard Text Field,  the rendering of field control is reused, only custom validator is registered for a field (see function EmailField_Edit for a details)

Working with the SharePoint Online REST service via PowerShell

Since SharePoint 2013 introduces a Representational State Transfer (REST) service that is comparable to the existing SharePoint client object models, it opens up a huge capabilities, in particular for administering and automating SharePoint Online when used with PowerShell.

My first idea was to utilize  Invoke-RestMethod cmdlet, which was introduced in Windows PowerShell 3.0.  Invoke-RestMethod cmdlet contains Credential parameter which could  accept basic, digest, NTLM, and Kerberos authentication.

SharePoint Client Component SDK comes with  a SharePointOnlineCredentials class  which represents an object that provides credentials to access SharePoint Online resources. But unfortunately SharePoint Online credentials could not be passed in Invoke-RestMethod cmdlet, since claims based authentication is not supported by this cmdlet.

Below is demonstrated a simplified PowerShell script  that to some extent mimics Invoke-RestMethod cmdlet. This script is intended for sending HTTPS request to a SharePoint Online REST service:

Examples

References

Working with Discussions List via SharePoint Client Object Model

Overview

In this post  will be demonstrated how to perform a common CRUD operations when working with Discussions List via  Client Object Model (JavaScript CSOM) in SharePoint 2010/2013.

Create a Discussion

So, let’s get started with creating a Discussion item. SP.Utilities.Utility.createNewDiscussion method is used for creating a discussion item:

Load all Discussions

Since Discussion Content Type derives from Folder Content Type  we could utilize SP.CamlQuery.createAllFoldersQuery method to construct a query to retrieve all the discussions:

Create a Message

The SP.Utilities.Utility.createNewDiscussionReply method is used to create a Message item (add reply to a discussion item):

Load all Messages

Since message items  are contained within discussion container (Folder) , to identify messages by discussion we will use SPBuiltInFieldId.ParentFolderId field in CAML query:

Import Discussion List

And finally in order to see how to work with Discussions List in action,  let’s discuss one more example.  Suppose we need to import Discussions List content from an external source, let’s say from Stack Exchange. To access Stack Exchange content (Questions and Answers in our case) we will utilize Stack Exchange API: