1

I am developing several Azure Functions using the CSOM API for SharePoint. The main functionality is creating PDF's for various purposes and uploading these to SharePoint with CSOM.

I have followed the sample in the documentation (Using CSOM for .NET Standard instead of CSOM for .NET Framework) with some slight modifications shown below:

  [FunctionName("Function")]
    public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    ILogger log,
    ExecutionContext context)
    {

        /*******
        Code for generating new PDF
        ******/

        Uri site = new Uri("https://contoso.sharepoint.com/sites/siteA");
        string user = "[email protected]";
        SecureString password = GetSecureString($"Password for {user}");


        /*******
        Code for filepaths, filenames etc.
        ******/

        using (var authenticationManager = new AuthenticationManager())
        using (var ctx = authenticationManager.GetContext(site, user, password))
        {
            //Query for Uploading the generated PDF

            List documentLibrary = ctx.Web.Lists.GetByTitle(documentLibraryTitle);

            var fileCreationInformation = new FileCreationInformation
            {
                Content = pdf,

                Overwrite = true,

                Url = $"{_site}/{filePath}/{fileName}"
            };

            documentLibrary.RootFolder.Files.Add(fileCreationInformation);
            await ctx.ExecuteQueryAsync();
        }

        //Do stuff

        using (var authenticationManager = new AuthenticationManager())
        using (var ctx = authenticationManager.GetContext(site, user, password))
        {
            //Query for deleting old version of PDF

            file = ctx.Web.GetFileByUrl(fileUrl);
            fileStream = file.OpenBinaryStream();
            ctx.Load(file);
            await ctx.ExecuteQueryAsync();
            // delete file
            file.DeleteObject();
            await ctx.ExecuteQueryAsync();
        }
    }

Now I am wondering what the best approach is for getting the ClientContext in the functions where I make multiple calls through the ctx?

  1. Should I wrap all my calls to the SharePoint API under one using-statement and get the context once for each Azure function? Or is my current approach better where the ctx is opened and closed at each call?
  2. Does it make sense to add Dependency injection to inject the AuthenticationManager/ClientContext into my functions and register the ctx for a longer period of time as a Scoped Object for the duration of the execution?(Use dependency injection in .NET Azure Functions)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.