Working With Azure Functions From SharePoint Components

Introduction

In this article, you will learn how to trigger Azure functions from SharePoint pages.

Azure functions are the ways to run the solutions or pieces of code over the Cloud. It helps in processing the data integrating other systems or even working with the Internet of Things.

Note. Azure functions can run only on the admin context for SharePoint. The end users from SharePoint can trigger Azure functions, using the URL but the code execution will run under the admin context.

In this sample, let us see how to trigger Azure functions, using C# from SharePoint Web parts. Consider a scenario where end users invoke the admin operations, using the Azure function. For example, creating a list on another SharePoint site.

In my previous article, you can learn about creating Azure functions for SharePoint operations, using managed CSOM.

Creating Azure Functions For SharePoint Operations Using Managed CSOM

Functions can be triggered in multiple ways. Here, we will create an HTTP trigger function. More details and pricing information about the Azure functions can be found here.

Prerequisites

  • Microsoft Azure account with Azure functions app.
  • SharePoint online portal

How it works?

Azure functions can be GET, POST, DELETE, etc. In this approach, let us look at the GET method. The trigger happens, using the function app URL.

The data to the function can be passed in two ways. One uses the query string parameter and another uses the request body (POST method).

Let us see how the data can be passed, using query string parameter and the function is executed.

From the Azure portal, create a new function app, using the HttpTrigger-CSharp component. My previous article explains in depth about creating Azure functions, using SharePoint CSOM.

To enable CORS, add the source site URL in the CORS section of Azure function app settings.

 CORS

The piece of code given below creates a SharePoint list on the Office 365 site from the Azure function and returns the success/ failure response. The site details and admin credentials are embedded within the code. The same can be retrieved from the settings (not covered in this article).

#r "Microsoft.SharePoint.Client.Runtime.dll"  
#r "Microsoft.SharePoint.Client.dll"  
using System.Net;  
using Microsoft.SharePoint.Client;  
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)  
{  
    log.Info("C# HTTP trigger function processed a request.");  
    // parse query parameter  
    string name = req.GetQueryNameValuePairs()  
        .FirstOrDefault(q => string.Compare(q.Key, "listname", true) == 0)  
        .Value;  
          
    if (name != null) 
    {  
        // Input Parameters  
        string siteUrl = ""; // specify the site URL here
        string userName = "[email protected]";  
        string password = "***";  
        System.Security.SecureString securestring = new System.Security.SecureString();  
        foreach (char ch in password)  
            securestring.AppendChar(ch);  
        SharePointOnlineCredentials creds = new SharePointOnlineCredentials(userName, securestring);  
        
        try 
        {  
            // Get and set the client context  
            // Connects to SharePoint online site using inputs provided  
            using (var clientContext = new ClientContext(siteUrl))  
            {  
                clientContext.Credentials = creds;  
                Web web = clientContext.Site.RootWeb;  
                ListCreationInformation listInfo = new ListCreationInformation();  
                listInfo.Title = name;  
                listInfo.TemplateType = 100;  
                web.Lists.Add(listInfo);  
                clientContext.Load(web);  
                clientContext.ExecuteQuery();  
                log.Info($"The list {name} is created");  
                return req.CreateResponse(HttpStatusCode.OK, "List is created");  
            }  
        }  
        catch (Exception ex) 
        {  
            log.Info($"Exception: {ex.Message}");  
            return req.CreateResponse(HttpStatusCode.BadRequest, "Error creating the list. Please reach out to admin");  
        }  
    } 
    else 
    {  
        log.Info(name);  
        return req.CreateResponse(HttpStatusCode.BadRequest, "Error creating the list. Please reach out to admin");  
    }  
}  

The piece of code given below has JavaScript triggers and the Azure function created above uses the function URL. Copy and paste the function URL from the above Azure function app (from the portal) and append listname query string.

$(document).ready(function(){  
    var listName = "DevList";  
    $.ajax({  
        url: "https://csomfunctionapp.azurewebsites.net/api/callaction?code=code&listname=" + listName,  
        type: "GET",  
        success: function (data){  
            console.log("List is created");  
        },  
        error: function (data){  
            console.log("Error Creating List");           
        }  
    });  
});

Execute AJAX call from the SharePoint page, using CEWP on the page load. The result will be displayed on the console for the code given above.

Summary

In this article, you have learned about creating a list operation on the Azure functions app and invoking the function from SharePoint site.