.Net Core Console Application for SharePoint Online using PNPCore library Interactive Login

Sathish Nadarajan
 
Solution Architect
October 16, 2021
 
Rate this article
 
Views
11658

In Many cases, we may need a Console application to do some sort of maintenance or any patch work to be done on the SharePoint Environment.

To connect with the SharePoint, we usually use the SharePointPNPCoreOnline Nuget package. But now, it is deprecated. Instead, we can use either PNP.Framework or PNP.Core.

PNP.Framework can be used from a .Net Framework application.

PNP.Core can be used from a .Net Core application.

In this application, let us see the steps to create the application step by step.

1. Open VS 2019 and create a new project.

 

2. Select the Framework as .Net 5.0

 

3. Open the NuGet Manager.

 

4. The below one is deprecated.

 

5. Install the PnP.Core

 

 

 

6. Install PnP.Core.Auth

 

 

7. After installing, the Program.cs will looks as below.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PnP.Core.Services;

using System;
using System.Linq;
using System.Threading.Tasks;

namespace DotNet.Core.Console
{
class Program
{
public static async Task Main(string[] args)
{
var host = Host.CreateDefaultBuilder()

.ConfigureLogging((hostingContext, logging) =>
{
logging.AddEventSourceLogger();
logging.AddConsole();
})
.ConfigureServices((hostingContext, services) =>
{
// Read the custom configuration from the appsettings..json file
var customSettings = new CustomSettings();
hostingContext.Configuration.Bind("CustomSettings", customSettings);

// Add the PnP Core SDK services
services.AddPnPCore(options => {

options.PnPContext.GraphFirst = true;

options.Sites.Add("DemoSite",
new PnP.Core.Services.Builder.Configuration.PnPCoreSiteOptions
{
SiteUrl = customSettings.DemoSiteUrl

});
});

services.AddPnPCoreAuthentication(
options =>
{
options.Credentials.Configurations.Add("interactive",
new PnP.Core.Auth.Services.Builder.Configuration.PnPCoreAuthenticationCredentialConfigurationOptions
{
ClientId = customSettings.ClientId,
TenantId = customSettings.TenantId,
Interactive = new PnP.Core.Auth.Services.Builder.Configuration.PnPCoreAuthenticationInteractiveOptions
{
RedirectUri = customSettings.RedirectUri
}
});

options.Credentials.Configurations.Add("credentials",
new PnP.Core.Auth.Services.Builder.Configuration.PnPCoreAuthenticationCredentialConfigurationOptions
{
ClientId = customSettings.ClientId,
TenantId = customSettings.TenantId,
Interactive = new PnP.Core.Auth.Services.Builder.Configuration.PnPCoreAuthenticationInteractiveOptions
{
RedirectUri = customSettings.RedirectUri
},
//},
//CredentialManager = new PnP.Core.Auth.Services.Builder.Configuration.PnPCoreAuthenticationCredentialManagerOptions
//{
// CredentialManagerName = customSettings.CredentialManager
//}

});

// Configure the default authentication provider
options.Credentials.DefaultConfiguration = "interactive";

// Map the site defined in AddPnPCore with the
// Authentication Provider configured in this action
options.Sites.Add("DemoSite",
new PnP.Core.Auth.Services.Builder.Configuration.PnPCoreAuthenticationSiteOptions
{
AuthenticationProviderName = "interactive"
});
});
})
// Let the builder know we're running in a console
.UseConsoleLifetime()
// Add services to the container
.Build();

await host.StartAsync();

using (var scope = host.Services.CreateScope())
{
var pnpContextFactory = scope.ServiceProvider.GetRequiredService();

using (var context = await pnpContextFactory.CreateAsync("DemoSite"))
{
//Use the context to do the operations.

}
}

host.Dispose();
}
}
}

8. Appsettings.json will be as below.

{
"key": "generic",
"CustomSettings": {
"ClientId": "2ab1db09-3a59-48bc-*******-******",
"TenantId": "61943e96-b3a9-49dd-*****-*****",
"DemoSiteUrl": "https://sppalsmvp.sharepoint.com/sites/MySiteCollection/",
"DemoSubSiteUrl": "https://sppalsmvp.sharepoint.com/sites/MySiteCollection/",
"CredentialManager": "sppalsmvp",
"RedirectUri": "http://localhost",
"UserPrincipalName": "sathish@sppals.com",
"Password": "*****"
},
"Logging": {
"LogLevel": {
"Default": "Information"
}
}
}

9. Csproj as below

<Project Sdk="Microsoft.NET.Sdk">

 

<PropertyGroup>

<OutputType>Exe</OutputType>

<TargetFramework>net5.0</TargetFramework>

 

</PropertyGroup>

 

<ItemGroup>

<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />

<PackageReference Include="PnP.Core" Version="1.4.0" />

<PackageReference Include="PnP.Core.Auth" Version="1.4.0" />

</ItemGroup>

 

<ItemGroup>

<None Update="appsettings.json">

<CopyToOutputDirectory>Always</CopyToOutputDirectory>

</None>

</ItemGroup>

 

</Project>

 

10. When we execute this, the interactive login will be popped up.

 

With this, the .Net Core Console application is ready to work with SharePoint tenant.  We can do our activities with this PNPCoreContext object.

 

There are many other ways of authentication and getting the client context.  In this article, I have demonstrated the Interactive Login and the Client Credentials method.  In the upcoming articles, let us see how to get the context using user name and password, Azure Certificates etc.,

 

Happy Coding
Sathish Nadarajan

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

NodeJS – Get SharePoint PnP-Core Client Context using UserName and Password and access SharePoint Objects from Node Application

Sathish Nadarajan
 
Solution Architect
October 11, 2021
 
Rate this article
 
Views
1000

In the earlier article, we saw how to setup a NodeJS application and start the development. As a continuation, let us see, how to create the SharePoint Context and access the SharePoint Sites.

The intention is to access the SharePoint objects and do some functionality from a Node JS application. i.e., a Separate standalone application which will do some action on our SharePoint Tenant.

To get the SharePoint Client Context, install the node-pnp-js and sp-pnp-js.

Let us take the earlier application itself for this continuation.

Install the following node modules.

npm install node-pnp-js –save
npm install sp-pnp-js –save
npm install pnp-auth –save
npm install @pnp/logging @pnp/common @pnp/odata @pnp/sp –save

Update the Index.ts file as below.

import express, { Application, ErrorRequestHandler, Request, response, Response } from 'express';
import NodeFetchClient from 'node-pnp-js';
import * as pnp from 'sp-pnp-js';


const app: Application = express();
const PORT = process.env.PORT || 2000;

let url = "https://sppalsmvp.sharepoint.com/sites/MySiteCollection/";
let credentialOptions = {
    username: 'sathish@sppals.com',
    password: '*******'
};

app.get("/", async (req: Request, res: Response): Promise<void> => {


    pnp.setup({
        sp: {
            fetchClientFactory: () => {
                return new NodeFetchClient(credentialOptions, url);
            }
        }
    });

    try {
        let list = await pnp.sp.web.lists.getByTitle('TempList').get();
        console.log(list);
        res.send(list);
    }
    catch (error) {
        res.send(error);
    }

});

app.use(function (err: any, req: Request, res: Response, next: ErrorCallback) {
    res.status(err.status || 500);
    res.send(err);
});

app.listen(PORT, (): void => {
    console.log(`Server Running here https://localhost:${PORT}`);
});

Then on the command prompt, execute npm run dev to run the server.

If we browse, then the output will be as below.

Download the Source HERE

Happy Coding
Sathish Nadarajan

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

The Context has expired and can no longer be used. (Exception from HRESULT: 0x80090317) in SharePoint 2013

Sathish Nadarajan
 
Solution Architect
March 10, 2014
 
Rate this article
 
Views
21452

In one of the SiteCollection, I have some content pages. I was able to edit the pages without any problem till now. All of a sudden, (Probably after the day light saving starts), when I tried to edit the page, I was getting the above mentioned exception.

image

 

After some analysis, found the root cause as the Time zone as suspected. 

 

The fix for this would be,

1. Go to Central Administration.

2. Manage Web Application.

3. Select the Web application.

4. Go the General Settings.

image

 

image

See, the Time Zone is missing.

 

Go and check the server’s time zone and select the Default Time Zone appropriately.

 

image

Come back to the site and edit the page. Oops, the edit screen appears without any problem.

 

Happy Coding.

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment