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;.sharepoint.com/_layouts/15/appregnew.aspx

Register an App

1

Provide the information and click on the create button

2

Now go to the https://<sitename&gt;.sharepoint.com/_layouts/15/appinv.aspx and provide the permission

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

3

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” />

</AppPermissionRequests>

Click on the Create button and trust the app

4

5

Step 2: Write a console Application using c#.net 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)
{
try
{
Console.WriteLine(” ################################### “);
Console.WriteLine(” Read SP online Data “);
Console.WriteLine(” ################################### “);
// To create a new app go to url : https://<sitename&gt;.sharepoint.com/_layouts/15/appregnew.aspx
// To set the permission https://<sitename&gt;.sharepoint.com/_layouts/15/appinv.aspx
// 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 = “https://gandxb1.sharepoint.com/_vti_bin/client.svc/&#8221;;
string stGetAccessTokenUrl = “https://accounts.accesscontrol.windows.net/{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;.sharepoint.com/_layouts/15/appregnew.aspx
string stClientSecret = “Client_SecretCode”; // pass the client secret code which is created in step 1
string stSiteDomain = “gandxb1.sharepoint.com”;
string stSiteDetailsUrl = “https://gandxb1.sharepoint.com/_api/web?$select=Title&#8221;;

#endregion
#region Get Tenant ID by HttpRequest

//read the url https://<sitename>/sharepoint.com/_vti_bin/client.svc
// 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; ;
try
{

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);
}
}

}

}

#endregion

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

#region Get Access Token using TenantID and App secret ID & Password
// URL Format
//https://accounts.accesscontrol.windows.net/tenant_ID/tokens/OAuth/2

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/abc.sharepoint.com@tenantID
*/

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)
{

if(stValues.StartsWith(“\”access_token\”:”))
{
//Console.WriteLine(” Result => ” + stValues);
accessToken = stValues.Substring(16);
//Console.WriteLine(” Result => ” + accessToken);
accessToken = accessToken.Substring(0,accessToken.Length-2);
// Console.WriteLine(” Result => ” + accessToken);
}
}
#endregion

#region Call REST Service

//https://<sitename>.sharepoint.com/_api/web?$select=Title
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);

#endregion

Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(” Error occured ” + ex.Message);
Console.ReadLine();
}
}
static void GetResponseCallBack(IAsyncResult asynchronousResult)
{
try
{
//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
$folder.Item.Update()
$folder.update()
}
$j=0
if($folder-ne $null -and $folder.Url.Contains("/img") -eq $true)
{

$folder.Files |?{ $_.Item -ne $null -and $_.Item.File.CheckOutType -ne “None”} | % {
$_.Item[“ContentTypeId”]=”0x010100C5033D6CFB8447359FB795C8A73A2B19″
$_.Item.Update()
$_.Item.File.CheckIn(“”)
$_.Item.file.Publish(“”)
$_.Item.file.Approve(“”)

}
}
$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
$_.Item[“ContentTypeId”]=”0x0101000F1C8B9E0EB4BE489F09807B2C53288F0054AD6EF48B9F7B45A142F8173F171BD10003D357F861E29844953D5CAA1D4D8A3A”
$_.Item.Update()
$_.Item.File.CheckIn(“”)
$_.Item.file.Publish(“”)
$_.Item.file.Approve(“”)
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 );
$_.Item[“ContentTypeId”]=”0x010100C5033D6CFB8447359FB795C8A73A2B19″
$_.Item.Update()
$_.Item.File.CheckIn(“”)
$_.Item.file.Publish(“”)
$_.Item.file.Approve(“”)
}

}

}

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

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

 

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

https://blogs.technet.microsoft.com/scottstewart/2014/09/29/warm-up-script-for-web-front-end-servers-wfe-in-load-balanced-sharepoint-farms/

 

Thanks to Scott for creating the PowerShell script.