Exporting workflows

You can use the Nintex Workflow for Office 365 REST API to export a site workflow or list workflow from a SharePoint site to a Nintex Workflow for Office 365 export (.nwp) file. The export file can then be used for a variety of other operations in the REST API, such as migrating an exported list workflow to a different list on a different SharePoint site, or you can import the export file right into the Workflow designer in Nintex Workflow for Office 365.

For more information about the REST resource used to export workflows, see Export a workflow.

Considerations

To avoid surprises while trying to export a workflow, take the following points into consideration:

Prerequisites

To use the example, ensure that you have the following prerequisites:

Code

You can download the code used in this example from the following location:

O365_RESTAPI_Export.zip

Note: You need to configure the code for the example before you can build and run it. See step 4 in the following example for instructions about how to configure the code for the example.

Example

The following example describes how to create a Visual Studio 2013 project to export a workflow from your SharePoint Online site, by using the REST API to get the workflow definition from the site and then saving it to an export (.nwp) file.

  1. Create a new Visual Studio 2013 project, using the Console Application template for Visual C#.

  2. Add the following references to your new Visual Studio project.

  3. In your new Visual Studio project, paste the following code into the file named Program.cs, overwriting the existing using statements at the beginning of the file:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.SharePoint.Client;
    using System.Security;
    using System.Net.Http.Headers;
    using System.Net.Http;
    using System.Net;
    using System.IO;
  4. Paste the following code into Program.cs, overwriting the Main() static method already included in the Program static class, and then configure the code as described in the comments:

    // The API key and base URL for the REST API.
    // TODO: Replace with your API key and root URL.
    static private string apiKey = "";
    static private string apiRootUrl = "";
    
    // The SharePoint site and credentials to use with the REST API.
    // TODO: Replace with your site URL, user name, and password.
    static private string spSiteUrl = "";
    static private string spUsername = "";
    static private string spPassword = "";
    
    // The workflow to export, and the file path in which to create
    // the export file.
    // TODO: Replace with your workflow identifier and the file path
    // in which to create your export file.
    static private string workflowId = "";
    static private string exportPath = "";
    
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        // Export the workflow to an export file.
        ExportWorkflowToFile();
    }

    All the configuration you need to do for this example happens here, and the code provided in subsequent steps uses these variables to get an authentication cookie from SharePoint and then export your workflow from your SharePoint site.

  5. Paste the following code into Program.cs, immediately after the Main static method in the Program static class:

    static private string GetSPOCookie()
    {
        // If successful, this variable contains an authentication cookie; 
        // otherwise, an empty string.
        string result = String.Empty;
        try
        {
            // Construct a secure string from the provided password.
            // NOTE: For sample purposes only.
            var securePassword = new SecureString();
            foreach (char c in spPassword) { securePassword.AppendChar(c); }
    
            // Instantiate a new SharePointOnlineCredentials object, using the 
            // specified username and password.
            var spoCredential = new SharePointOnlineCredentials(spUsername, securePassword);
            // If successful, try to authenticate the credentials for the
            // specified site.
            if (spoCredential == null)
            {
                // Credentials could not be created.
                result = String.Empty;
            }
            else
            {
                // Credentials exist, so attempt to get the authentication cookie
                // from the specified site.
                result = spoCredential.GetAuthenticationCookie(new Uri(spSiteUrl));
            }
        }
        catch (Exception ex)
        {
            // An exception occurred while either creating the credentials or
            // getting an authentication cookie from the specified site.
            Console.WriteLine(ex.ToString());
            result = String.Empty;
        }
    
        // Return the result.
        return result;
    }
    

    The GetSPOCookie static method uses the SharePoint site and credentials that you configured in step 4 to get an authentication cookie from SharePoint.

  6. Paste the following code into Program.cs, immediately after the code you pasted in the previous step:

    static async private void ExportWorkflowToFile()
    {
        // Create a new HTTP client and configure its base address.
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(spSiteUrl);
    
        // Add common request headers for the REST API to the HTTP client.
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("Api-Key", apiKey);
    
        // Get the SharePoint authorization cookie to be used by the HTTP client
        // for the request, and use it for the Authorization request header.
        string spoCookie = GetSPOCookie();
        if (spoCookie != String.Empty)
        {
            var authHeader = new AuthenticationHeaderValue(
                "cookie",
                String.Format("{0} {1}", spSiteUrl, spoCookie)
            );
            // Add the defined authentication header to the HTTP client's
            // default request headers.
            client.DefaultRequestHeaders.Authorization = authHeader;
        }
        else
        {
            throw new InvalidOperationException("Cannot define Authentication header for request.");
        }
    
        // If we're at this point, we're ready to make our request.
        // Note that we're making this call synchronously - you can call the REST API
        // asynchronously, as needed.
        var exportWorkflowUri = String.Format("{0}/api/v1/workflows/packages/{1}",
            apiRootUrl.TrimEnd('/'),
            Uri.EscapeUriString(workflowId));
        HttpResponseMessage response = client.GetAsync(exportWorkflowUri).Result;
    
        // If we're successful, write an export file from the body of the response.
        if (response.IsSuccessStatusCode)
        {
            // Concatenate the export file name from the response headers.
            string exportFilePath = String.Empty;
            if (response.Content.Headers.ContentDisposition.FileName != null)
            {
                // Get the suggested file name from the Content-Disposition header.
                exportFilePath = Path.Combine(exportPath, 
                    response.Content.Headers.ContentDisposition.FileName.Trim('"'));
            }
            else
            {
                // Use a default file name if the suggested file name couldn't be retrieved.
                exportFilePath = Path.Combine(exportPath, "DefaultWorkflow.nwp");
            }
    
            // The response body contains a Base64-encoded binary string, which we'll
            // asynchronously retrieve and then write to a new export file.
            byte[] exportFileContent = await response.Content.ReadAsByteArrayAsync();
            System.IO.File.WriteAllBytes(exportFilePath, exportFileContent);
        }
    }
    

    The ExportWorkflowToFile static method uses an HTTP client to invoke the REST resource provided by the REST API to export your workflow from your SharePoint site. The client's default request headers are configured, the GetAsync method is used to invoke the REST resource, and, if successful, the response is written to an export file.

  7. Build and run the Visual Studio project.

    If you've configured the variables provided in step 4 appropriately, running the project produces an export file in the specified file path for the workflow you specified from your SharePoint site. The export file's name is typically determined by the Content-Disposition content header included in the response.

Related Information

Export a workflow

Guide