Read SharePoint online data from c# console Application using App Id/Password

Step 1: Register an App in SharePoint online

Go to the SharePoint online url : https://<sitename&gt;

Register an App


Provide the information and click on the create button


Now go to the https://<sitename&gt; and provide the permission

Enter the client ID (from the previous screen) click on the lookup button


Enter the below xml in the permission Request XML Text box

Format :

<AppPermissionRequests AllowAppOnlyPolicy=”true”>

<AppPermissionRequest Scope=”http://sharepoint/content/sitecollection/web&#8221; Right=”Read” />


Click on the Create button and trust the app



Step 2: Write a console Application using to get the access token and call REST API



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace SPTokenService
public class RequestState
// This class stores the request state of the request.
public WebRequest request;
public RequestState()
request = null;
public class ResponseState
// This class stores the response state of the request.
public WebResponse response;
public ResponseState()
response = null;
class RetrieveSPListData
static void Main(string[] args)
Console.WriteLine(” ################################### “);
Console.WriteLine(” Read SP online Data “);
Console.WriteLine(” ################################### “);
// To create a new app go to url : https://<sitename&gt;
// To set the permission https://<sitename&gt;
// To list : http://<SharePointWebsite&gt; /_layouts/15/AppPrincipals.aspx
// XML : <AppPermissionRequests AllowAppOnlyPolicy=”true”>
// <AppPermissionRequest Scope=”http://sharepoint/content/sitecollection/web&#8221; Right=”Read” />
// </AppPermissionRequests>
#region URL
WebRequest myWebRequest;
string stGetTenantDetailsUrl = “;;
string stGetAccessTokenUrl = “{0}/tokens/OAuth/2 “;

string tenantID = string.Empty;
string resourceID = string.Empty;
string accessToken = string.Empty;
string stClientID = “Client_ID”; // pass the client id which is created in Step 1, https://<sitename&gt;
string stClientSecret = “Client_SecretCode”; // pass the client secret code which is created in step 1
string stSiteDomain = “”;
string stSiteDetailsUrl = “$select=Title&#8221;;

#region Get Tenant ID by HttpRequest

//read the url https://<sitename>/
// get the http header of WWW-Authenticate
// and get the Realm value
// and the resource value (which will come in Client id attribute

myWebRequest = WebRequest.Create(stGetTenantDetailsUrl);
myWebRequest.Method = “GET”;
myWebRequest.Headers.Add(“Authorization”, “Bearer”);

WebResponse myWebResponse = null; ;

myWebResponse = myWebRequest.GetResponse();

catch (System.Net.WebException ex)
//get the Web exception and read the headers
#region Parse the WebException and read the WWW-Authenticate

string[] headerAuthenticateValue = ex.Response.Headers.GetValues(“WWW-Authenticate”);
if (headerAuthenticateValue != null)
//get the array separated by comma
//Console.WriteLine(” Value => ” + headerAuthenticateValue.Length);

foreach (string stHeader in headerAuthenticateValue)
string[] stArrHeaders = stHeader.Split(‘,’);
//loop all the key value pair of WWW-Authenticate

foreach (string stValues in stArrHeaders)
// Console.WriteLine(” Value =>” + stValues);
if (stValues.StartsWith(“Bearer realm=”))
tenantID = stValues.Substring(14);
tenantID = tenantID.Substring(0, tenantID.Length – 1);
if (stValues.StartsWith(“client_id=”))
//this value is consider as resourceid which is required for getting the access token
resourceID = stValues.Substring(11);
resourceID = resourceID.Substring(0, resourceID.Length – 1);




Console.WriteLine(” Tenant ID ” + tenantID);
Console.WriteLine(” Resource ID ” + resourceID);

#region Get Access Token using TenantID and App secret ID & Password
// URL Format

stGetAccessTokenUrl = string.Format(stGetAccessTokenUrl, tenantID);
myWebRequest = WebRequest.Create(stGetAccessTokenUrl);
myWebRequest.ContentType = “application/x-www-form-urlencoded”;
myWebRequest.Method = “POST”;

// Add the below body attributes to the request
* grant_type client_credentials client_credentials
client_id ClientID@TenantID
client_secret ClientSecret
resource resource/SiteDomain@TenantID resourceid/

var postData = “grant_type=client_credentials”;
postData += “&client_id=” + stClientID +”@” +tenantID;
postData += “&client_secret=” + stClientSecret;
postData += “&resource=” + resourceID + “/” + stSiteDomain + “@” + tenantID;
var data = Encoding.ASCII.GetBytes(postData);

using (var stream = myWebRequest.GetRequestStream())
stream.Write(data, 0, data.Length);
var response = (HttpWebResponse)myWebRequest.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

string[] stArrResponse = responseString.Split(‘,’);

//get the access token and expiry time ,etc

foreach(var stValues in stArrResponse)

//Console.WriteLine(” Result => ” + stValues);
accessToken = stValues.Substring(16);
//Console.WriteLine(” Result => ” + accessToken);
accessToken = accessToken.Substring(0,accessToken.Length-2);
// Console.WriteLine(” Result => ” + accessToken);

#region Call REST Service

myWebRequest = null;
myWebRequest = WebRequest.Create(stSiteDetailsUrl);

// Add the below headers attributes to the request
* Accept application/json;odata=verbose application/json;odata=verbose
Authorization <token_type> <access_token> Bearer eyJ0eX….JQWQ

// myWebRequest.Headers.Add(“Accept”, “application/json;odata=verbose”);
myWebRequest.ContentType = “application/json;odata=verbose”;
myWebRequest.Headers.Add(“Authorization”, “Bearer ” + accessToken);
myWebRequest.ContentLength = 0;
myWebRequest.Method = “POST”;

//call Asyncronously
//RequestState objRequestState = new RequestState();
//objRequestState.request = myWebRequest;
// myWebRequest.BeginGetResponse(GetResponseCallBack, objRequestState);

var responseREST = (HttpWebResponse)myWebRequest.GetResponse();
ResponseState objResponseState = new ResponseState();
objResponseState.response = responseREST;
myWebRequest.BeginGetResponse(GetResponseCallBack, objResponseState);

//var responseRestString = new StreamReader(response.GetResponseStream()).ReadToEnd();
// Console.WriteLine(” Site Details ” + responseRestString);


catch (Exception ex)
Console.WriteLine(” Error occured ” + ex.Message);
static void GetResponseCallBack(IAsyncResult asynchronousResult)
//RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
//WebRequest myWebRequest = myRequestState.request;
ResponseState myResponseState =(ResponseState) asynchronousResult.AsyncState;
Console.WriteLine(” Site Info ” + new StreamReader(myResponseState.response.GetResponseStream()).ReadToEnd());

catch(Exception ex)




SP 2013 installation error due to .net Framework 4.5 required in Windows 2012 R2

Uninstall KB Article 3151864 (for .net framework 4.6.2 if its installed) or KB 3102467 (for .net framework 4.6.1) to proceed further  in Windows Server 2012

This will resolve the issue ” This Product requires .net framework 4.5 ”


SP 2013 Publish Master page gallery using Powershell script

The below script will be useful for approving the master page gallery files using Powershell script

Add-PsSnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue
$strStatusApproved= [Microsoft.SharePoint.SPModerationStatusType]::Approved;
$strStatusRejected= [Microsoft.SharePoint.SPModerationStatusType]::Rejected;
$strStatusPending= [Microsoft.SharePoint.SPModerationStatusType]::Pending;
$webAppUrl = "http://SPSiteURL"
function fnCheckInFolder($folder)
if($folder-ne $null -and $folder.item -ne $null -and $folder.item.ModerationInformation -ne $strStatusApproved -and $folder.item.ModerationInformation -ne $strStatusRejected )
write-host (" Approving the folder {0} " -f $folder.item.Url)
$comment = $folder.item.ModerationInformation
$comment.Status = $strStatusApproved
if($folder-ne $null -and $folder.Url.Contains("/img") -eq $true)

$folder.Files |?{ $_.Item -ne $null -and $_.Item.File.CheckOutType -ne “None”} | % {

$folder.Files | ?{ $_.Item -ne $null -and $_.Item.Properties[“HtmlDesignLockedFile”] -eq $null -and $_.MinorVersion -ne 0 } | %{
if($_.Url.Contains(“.html”) ){
# design file .html master page checkin
Write-Host (” Master page {0} status ” -f $_.Url,$_.item.File.CheckOutStatus);


if($_.Url.Contains(“.css”) -or $_.Url.Contains(“.js”)) {

$i =0
if ($_.Item.File.CheckOutType -ne “None”)
# design files css/js checkin
Write-Host (” Items Publishing {0} ” -f $_.Url,$_.Item.ContentType.Name );



$folder.SubFolders | %{ fnCheckInFolder $_;}

$rootWeb = Get-SPWeb $webAppUrl
$masterPageFolder= $rootWeb.GetFolder(“_catalogs/masterpage”)


SSRS 2012 installation failed in SharePoint 2013 integrated mode

SSRS 2012 installation in SharePoint 2013 integration mode , sometimes failed. It may be the due to the SharePoint web applications web.config file may contains < ! - - comments - - > lines (this is one of the reason for the failure)

Try to remove the comments < ! - - comments - - > lines lines  and try to install.

It’s better to install SSRS in SharePoint 2013 server at initial stage so that before customizing the web.config (with comments lines) to avoid this problem.

Hope this may helpful for someone.

SharePoint Central Administration Application Pool is stopping automatically

In SharePoint 2013/2010 sometimes CA application pool may be stopped automatically, even after giving correct service account password.

This may be related to huge log files added into the 15\Logs folder, clear some of the old logs will help to resolve the issue. Alternatively always set the log folder size (in GB) in CA -> Monitoring -> diagnostics logging section. This will avoid the issues.

Warm-up Script for Web Front End Servers (WFE) in Load Balanced SharePoint Farms

There is a great article on warming up all WFE servers using Powershell scripts


Thanks to Scott for creating the PowerShell script.

Vs 2013 SharePoint visual webpart .ascx.g.cs file missing

During SharePoint 2013 visual webpart development, some time VS 2013 will miss or delete the .g.cs and during compilation, we may get the errors like “InitializeControl does not exist in current context” .

To generate a new webpartusercontrol.ascx.g.cs file we need to follow the below steps

1. Unload the SharePoint Project

2. Right click the project and Unload the project(Edit the .csproj file)

3. Find the webpart where the .g.cs file is missing

4. Check the below XML Tag in that place, if its missing or “LastGenOutput” is missing then add accordingly

<Content Include=”Webparts\WP_TestWebpart\WP_TestWebpart.ascx”>

5. Save the .csproj file and load the project

6. Now Right click on the .ascx file and Run the Custom Toll. (Make sure in the properties of ascx , customTool is SharePointWebPartCodeGenerator)

7. Now the webpart .g.cs file will be generated and we can compile without any errors

I hope this may help someone who struggle or delete the webpart again , to generate the .g.cs file 🙂

Update Panel with Required Field Validator Not Working

Recently i faced some strange problem with required field validator, inside a update panel its not working, since some controls are dynamically loaded with required field validattion.

But its not working properly (few buttons which has causes validation set to false also not triggering properly), then i found a solution that for any required field validation (or any validation controls), it has to load during the page load itself , so i have created a dummy text box and dummy required field validator to make sure that the validation controls emits the javascripts properly to browser.

<div style=”display:none”>

<asp:TextBox id=”txtDummy” runat=”server” Visible=”false”/>

<asp:RequiredFieldValidator ID=”reqDummy1″ runat=”server” ControlToValidate=”txtDummy” Text=”*” ValidationGroup=”DummyValgroup” ErrorMessage=”Please provide text”></asp:RequiredFieldValidator>


This helps to do the validation for dynamically created controls with validation.

 I hope this may helpful for