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 piece of code over Cloud. It helps in processing the data or 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 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 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.
Functions can be triggered in multiple ways. Here, we will create 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 using the query string parameter and another using the request body (POST method).
Let us see how the data can be passed, using query string parameter and the function is executed.
From Azure portal, create new function app, using 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.
The piece of code given below creates a SharePoint list on Office 365 site from 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 = "https://nakkeerann.sharepoint.com/"; Â
string userName = "abc@nakkeerann.onmicrosoft.com"; Â
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 Azure function created above use the function URL. Copy and paste the function URL from the above Azure function app (from 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 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.
Comments