In the earlier article, we saw how to get the PNP Core Context through interactive login, similarly in this article, let us see to get the context by Providing the Username and Password. Usually this could be the Service Account credentials.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PnP.Core.Auth;
using PnP.Core.Services;
using System.Linq;
using System.Threading.Tasks;
namespace AZ.Help.Core
{
class Program
{
public static async Task Main(string[] args)
{
var host = Host.CreateDefaultBuilder()
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConsole();
})
.ConfigureServices((hostingContext, services) =>
{
var customSettings = new CustomSettings();
hostingContext.Configuration.Bind("CustomSettings", customSettings);
//Create an instance of the Authentication Provider that uses Credential Manager
var authenticationProvider = new UsernamePasswordAuthenticationProvider(
customSettings.ClientId,
customSettings.TenantId,
customSettings.UserPrincipalName,
customSettings.Password.ToSecureString());
services.AddPnPCore(options =>
{
options.DefaultAuthenticationProvider = authenticationProvider;
options.Sites.Add("DemoSite",
new PnP.Core.Services.Builder.Configuration.PnPCoreSiteOptions
{
SiteUrl = customSettings.DemoSiteUrl,
AuthenticationProvider = authenticationProvider
});
});
})
// 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<IPnPContextFactory>();
using (var context = await pnpContextFactory.CreateAsync("DemoSite"))
{
var page = (await context.Web.GetPagesAsync("DemoPage")).FirstOrDefault();
await page.TranslatePagesAsync();
}
}
host.Dispose();
}
}
}
Happy Coding
Sathish Nadarajan
Leave a comment