Hello,
This is continuation article; in part 1 we have seen how to create App Id in SharePoint. In part 2 we will see how to access SharePoint Online site from Console Application using App Id and Secret key.
Creating new Console Application,
I need to add SharePointPnPCore2013 package from nuget package manager
And add the AppForSharePointOnlineWebToolkit package to have TokenHelper.cs file which have necessary function for authentication.
I have my site name, App Id and Secret key in App.config file so that it’s easy to access and update.
In Program.cs we requesting user to choose the environment based on the value we are taking URL from app.config file
using System;
using System.Configuration;
using Microsoft.SharePoint.Client;
namespace TestSP_access
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("nSelect The Environment to Provision- ");
Console.WriteLine("nnote* - The Site URL and other properties will be taken from App.config file- n");
Console.WriteLine("n'dev' or 'test' or 'qa' or 'prod'");
Console.WriteLine("nEnter Your Choice : ");
var envValue = Console.ReadLine();
if (envValue != "dev" && envValue != "test" && envValue != "qa" && envValue != "prod")
{
Console.WriteLine("nInvalid Environment value. Please select'dev' or 'test' or 'qa' or 'prod'");
}
else
{
try
{
var siteUri = new Uri(ConfigurationManager.AppSettings["SiteUrl-" + envValue]);
var realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
var accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal,
siteUri.Authority, realm).AccessToken;
using (var ctx = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), accessToken))
{
Console.WriteLine("nAccessing SP...");
ctx.Load(ctx.Web);
ctx.ExecuteQueryRetry();
Console.WriteLine("The site name is " + ctx.Web.Title);
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong. " + ex.Message);
Console.ReadLine();
}
}
}
}
}
This is my test SharePoint site
Now I can access SP online site from my console application using App Id Access Token
Happy Coding
Ahamed
Leave a comment