Create a Document Set Using CSOM

 $(document).ready(function() { 
 createDocumentSet(); 
 
 }); 
 
 
 function createDocumentSet() { 
 
 var clientContext = new SP.ClientContext.get_current(); 
 oWeb = clientContext.get_web(); 
 var oList = oWeb.get_lists().getByTitle("TestLibrary"); 
 
 clientContext.load(oList); 
 
 var LibraryFolder = oList.get_rootFolder(); 
 clientContext.load(LibraryFolder); 

 
 var documentSetContentTypeID = "0x0120D520"; 
 
 var documentSetContentType = clientContext.get_site().get_rootWeb().get_contentTypes().getById(documentSetContentTypeID); 

 clientContext.load(documentSetContentType); 
 
 clientContext.executeQueryAsync(QuerySuccess, QueryFailure); 
 } 
 
 function QuerySuccess() { 
 
 var documentSetName = "DocumentSetName"; 
 SP.DocumentSet.DocumentSet.create(clientContext, oLibraryFolder, documentSetName, documentSetContentType.get_id()); 
 clientContext.executeQueryAsync(Success, Failure); 
 } 
 
 function QueryFailure() { 
 console.log('Request failed - ' + args.get_message()); 
 } 
 
 function Success() { 
 console.log('DocumentSet Created Successfully.'); 
 } 
 
 function Failure(sender, args) { 
 console.log('Request failed - ' + args.get_message()); 
 }  

PowerShell script to move/copy files from network path to SharePoint 2013 sub folder

if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
 { Add-PSSnapin Microsoft.SharePoint.PowerShell }
 #Script settings 
 $webUrl = "http://gowtham.sharepoint.com/teams/sptest/" 
 $docLibraryName = "Shared Documents" 
 $docLibraryUrlName = "Shared Documents\testfolder" 
 # specify your subfolder url here 
 $localFolderPath = "D:\files"
 #Open web and library 
 $web = Get-SPWeb $webUrl write-host $webUrl
 $docLibrary = $web.Lists[$docLibraryName]
 write-host $docLibrary 
 $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
 write-host $files ForEach($file in $files)
 { if($file.Name.Contains(".pdf")) 
 { write-host $file 
 #Open file try 
 { 
 $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead() 
 #Add file $folder = $web.getfolder($docLibraryUrlName) 
 write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
 $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name,[System.IO.Stream]
 $fileStream, $true) 
 write-host "Success"
 #Close file stream $fileStream.Close(); 
 } 
 catch
 {
 Write "Error: $file.name: $_" >>c:\logfile.txt continue; 
 }
 }
 }
 #Dispose web $web.Dispose()
 

Removing a user/users from all SharePoint Groups in a Site Collection

Removing a user/users from all SharePoint Groups in a Site Collection will be a tedious task to manually remove the users from all the SharePoint groups.

This will remove the selected user/users from all the SharePoint groups, libraries, lists and sub sites in the Site Collection.

$LoginName = "domain\loginname"
$siteURL = "http://gowtham.sharepoint.com" #.

Clear-Host
$siteCount = 0
[system.reflection.assembly]::loadwithpartialname("Microsoft.SharePoint")
$site = new-object microsoft.sharepoint.spsite($siteURL)
$webApp = $site.webapplication
$allSites = $webApp.sites
foreach ($site in $allSites)
{

$web = $site.openweb()
$web.SiteUsers.Remove($LoginName)
$web.Dispose()
$siteCount++
}
$site.dispose()
write-host "User Deleed" $siteCount "Site Collections."

 

 

Restore Deleted Site Collections/Subsites SharePoint 2013 using PowerShell

The User has deleted a subsite/Site collection unluckily, but you can get the information navigate to Site collection recycle bin and you can find the deleted sites.
This is the code restore the deleted SharePoint sites from recycle bin using PowerShell,

  • Get-SPDeletedSite – Displays list of sites deleted.
  • Restore-SPDeletedSite – Restore a deleted site
  • Remove-SPDeletedSite – Remove the deleted site collection permanently.

Exampe:


Get-SPDeletedSite -webapplication http://gowtham.sharepoint.com
Restore-SPDeletedSite -webapplication http://gowtham.sharepoint.com
Remove-SPDeletedSite-webapplication http://gowtham.sharepoint.com
 

 

 

Create an Alert Me in SharePoint office 365

To stay updated when documents or items on your site change, you can create alerts. We usually have requirements. Where users need to be notified when a Document or a List Item is updated by someone. In SharePoint 2010, there is an option called Alert Me which is used to set the alerts. The alerts can be set at Item level or the list level.

For this option to enable Go to the library or list where you want to set the alert then set an alert for a document, select the document and click Files, then click Alert Me, and then click Set alert on this document.

Enter the details in the below section as match your requirement,

You can decide how often you want to know when specific items change. For example, if you want to know each time someone adds a new file to a library; you can create an alert for yourself or even for a co-worker.

Note: Office 365 subscriptions, alerts are enabled when your site is first created, but your site administrator can disable RSS for a site or for an entire site collection. But if you are using separate server you need to configure everything.

SharePoint on premise a server administrator has to configure outgoing e-mail in Central Administration before you can receive an alert as an e-mail message

That’s all. You have configured SharePoint Alert Me OOTB functionality successfully. 🙂

 

Gowtham Rajamanickam

Provider Hosted APP-The remote server returned an error: (401) Unauthorized

Provider Host App:

The provider Host App is hosted outside of SharePoint. The provider-hosted high trust app model is powerful tool which should be utilized when the situation either demands custom managed code or when a low-trust solution does not suffice. SharePoint Host app does not do. It has its own infrastructure and the Provider is responsible for keeping it running. They allow you to use Server Side code and uses the .NET CSOM (not the Microsoft.SharePoint.dll.

 

For more details about provider Hosted App in SharePoint follow the link,

http://www.c-sharpcorner.com/article/provider-host-app-development-in-sharepoint-2013/ 

 

 

                                 'The remote server returned an error: (401) Unauthorized'.

 

Following unexpected error is recorded in uls logs,

 

SPApplicationAuthenticationModule: Failed to authenticate request, unknown error. Exception details: System.IdentityModel.Tokens.SecurityTokenException: The issuer claim of the user identity doesn't match the nameid (name identifier) claim of the delegated identity (actor identity). It is expected that these two claims match and hence this token is rejected. at Microsoft.SharePoint.IdentityModel.SPJsonWebSecurityBaseTokenHandler.ValidateActorIsSelfIssuer(SecurityToken token, ClaimsIdentityCollection result) at Microsoft.SharePoint.IdentityModel.SPJsonWebSecurityBaseTokenHandler.ValidateToken(SecurityToken token) at Microsoft.SharePoint.IdentityModel.SPJsonWebSecurityTokenHandler.ValidateToken(SecurityToken token) at Microsoft.SharePoint.IdentityModel.SPApplicationAuthenticationModule.TryExtractAndValidateToken(HttpContext httpContext, SPIncomingTokenContext& tokenContext) at Microsoft.SharePoint.IdentityModel.SPApplicationAuthenticationModule.ConstructIClaimsPrincipalAndSetThreadIdentity(HttpApplication httpApplication, HttpContext httpContext, SPFederationAuthenticationModule fam) at Microsoft.SharePoint.IdentityModel.SPApplicationAuthenticationModule.AuthenticateRequest(Object sender, EventArgs e)

 

 

To resolve this error we need to follow the instructions carefully,

 

  • Created new self-signed certificate.

Follow this link to create a self-signed certificate.

http://sharepointexchange.com/create-a-self-signed-certificate-for-provider-host-app-in-iis-using-powershell/ 

  • Registered it with SharePoint using the following PS Commands 

Follow this link to register your Self signed certificate in SharePoint with issuer ID,

http://sharepointexchange.com/createtrustedsecuritytokenissuer-for-providerhostapp-in-sharepoint-2013-using-powershell/ 

  • Then register the App with SharePoint below location http://appdomainname/_layouts/15/appregnew.aspx 

Save the generated Appid as ClientId, AppSecret as ClientSecret and Issuer ID from 2nd step.

Then restart your devbox

  • Make sure that the SharePoint Site Collection is HTTPS Enabled.

 

  • Check IIS website permission in authentication. Windows Authentication should be enabled.

 

  • Then Application pool account should have access to the Content DB, SharePoint Sites etc.,

 

  • Set the DisableStrictNameChecking registry entry to 1

          Open REGEDIT in the SharePoint Server  then go to the below lcoation

            HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa

    • Right-click Lsa, point to New, and then click DWORD Value.

    • Type DisableLoopbackCheck, and then press ENTER.

    • Right-click DisableLoopbackCheck, and then click Modify.

    • In the Value data box, type 1, and then click OK.

 

Restart the IISAdmin service.

Try now your App in SharePoint it will work perfectly.

 

 

 

Gowtham Rajamanickam

Create a Document Set in SharePoint online (Office 365)

 

This topic explains how to enable the Document Sets feature for an office 365 SharePoint online site collection, and then how to configure the Document Set content type. Document Set is a hybrid between a folder and a list item.  It allows you group documents together as with a folder and at the same time, associate metadata to it as you would with an item.

Document Sets are a feature in SharePoint Server 2013 that enables an organization to manage a single deliverable, or work product, which can include multiple documents or files. A Document Set is a special kind of folder that combines unique Document Set attributes, the attributes and behavior of folders and documents, and provides a user interface (UI), metadata, and object model elements to help manage all aspects of the work product.

More details about this refer: https://technet.microsoft.com/en-us/library/ff603637.aspx 

Before using the Document set we need to activate the feature in site collection level,

Go to Site Settings-> select Site collection features,

Activate the Document Set feature,

Enable content Type,

Document Set is enabled for a library by enabling the Document Set content type.

Go to the library settings and select this Advance settings option to allow the content type,

Then Save this.

Add content type to this library,

Click New Document and select the content type to create a new set,

Document Set created successfully to the library.

 

 

 

 

Gowtham Rajamanickam

CreateTrustedSecurityTokenIssuer for ProviderHostAPP in Sharepoint 2013 using PowerShell


PARAM(
[Parameter(Mandatory=$true)][string]$publicCertPath,
[Parameter(Mandatory=$true)][string]$spurl,
[Parameter(Mandatory=$true)][string]$trustName,
[string]$issuerId
)

if ([string]::IsNullOrEmpty($issuerId))
{
$issuerId = [System.Guid]::NewGuid().ToString()

}
$spweb = Get-SPWeb $spurl
$realm = Get-SPAuthenticationRealm -ServiceContext $spweb.Site
$certificate = Get-PfxCertificate $publicCertPath
New-SPTrustedRootAuthority -Name $trustName -Certificate $certificate
$fullIssuerIdentifier = $issuerId + '@' + $realm
New-SPTrustedSecurityTokenIssuer -Name $issuerId -Certificate $certificate -RegisteredIssuerName $fullIssuerIdentifier –IsTrustBroker

iisreset

write-host
write-host "-------------------------------------------------------------"
write-host
write-host "Issuer ID:" $issuerId
write-host "Registered Issuer Name:" $fullIssuerIdentifier
write-host
write-host "-------------------------------------------------------------"
write-host

Gowtham Rajamanickam

Create a self-signed certificate for Provider Host App in IIS using PowerShell


$makecert = "C:\Program Files\Microsoft Office Servers\15.0\Tools\makecert.exe"
$certmgr = "C:\Program Files\Microsoft Office Servers\15.0\Tools\certmgr.exe"

# specify domain name for SSL certificate
$domain = "apps.gowtham.com"

# create output directory to create SSL certificate file
$outputDirectory = "c:\Certs\"

New-Item $outputDirectory -ItemType Directory -Force -Confirm:$false | Out-Null

# create file name for SSL certificate files

$publicCertificatePath = $outputDirectory + $domain + ".cer"
$privateCertificatePath = $outputDirectory + $domain + ".pfx"

Write-Host
Write-Host "Creating .cer certificate file..."

& $makecert -r -pe -n "CN=$domain" -b 01/01/2016 -e 01/01/2026 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 $publicCertificatePath

Write-Host
Write-Host "Registering certificate with IIS..."

& $certmgr /add $publicCertificatePath /s /r localMachine root
# get certificate to obtain thumbprint

$publicCertificate = Get-PfxCertificate -FilePath $publicCertificatePath
$publicCertificateThumbprint = $publicCertificate.Thumbprint
Get-ChildItem cert:\\localmachine\my | Where-Object {$_.Thumbprint -eq $publicCertificateThumbprint} | ForEach-Object {

Write-Host " .. exporting private key for certificate (*.PFK)" -ForegroundColor Gray

$privateCertificateByteArray = $_.Export("PFX", "Password1")

[System.IO.File]::WriteAllBytes($privateCertificatePath, $privateCertificateByteArray)

Write-Host " Certificate exported" -ForegroundColor Gray
}

Provider Host App Development in SharePoint 2013 On-Premise

In this article I would like to add step by step process to develop a provider Hosted App (PHA) in SharePoint On-premise.

This is a quick book for On Premise SharePoint 2013 environments. I decided to write this article because I knew the complexity of this PHA Configuration. Before jump in to the PHA configuration, it’s worthwhile to quickly recap what are Provider Hosted Apps.

Provider Host App:

The provider Host App is hosted outside of SharePoint. The provider-hosted high trust app model is powerful tool which should be utilized when the situation either demands custom managed code or when a low-trust solution does not suffice. SharePoint Host app does not do.

It has its own infrastructure and the Provider is responsible for keeping it running. They allow you to use Server Side code and uses the .NET CSOM (not the Microsoft.SharePoint.dll.

Picture Source: https://msdn.microsoft.com/en-us/library/office/fp179887%28v=office.15%29.aspx 

 

Why Provider Host App?

  • The Provider Host App  you can  run some server side code which is not possible with a SharePoint hosted app

  • The second is if SAML Claims authentication provider is setup with ADFS 2.0.

  • You can host a provider-hosted SharePoint Add-in on a Microsoft Azure web role instead of a web application (whether the web application is on-premises or a Azure Web Site)

 

 

Before you develop a provider Host App you may need to do some prerequisites,

  • SharePoint 2013 Server

  • Visual Studio 2012

  • IIS 

  • High Trust Certificates.

 

SharePoint you must have the following service applications provisioned and started:

  • User Profile Service Application Started

  • Subscription Service Application with proxy

  • Subscription Settings Service instance started

  • Application Management Service Application and proxy

  • App Management Service instance stared

 

High Trust Certificates:

           A high-trust Certificate is a provider-hosted SharePoint App that uses the digital certificates to establish trust between the remote web application and SharePoint.

This is the link to create a certificate in IIS.

https://msdn.microsoft.com/en-us/library/fp179901.aspx 

Here i would like to give a PowerShell code to create the self-signed certificate (.pfx file)

Note: The folder you are saved the .cer and .pfx file in SharePoint server, be sure that the App pool identity for the following IIS Apps have Read rights to the C:\Certs folder.

PowerShell Code;

Copy the below Code and save it as a Makecertificate.ps1

Then run the below cmd in PowerShell,

C:\powershells\Makecertificate.ps1-Domain apps.gowtham.com – OutputDir  C:\Certificates -$Password Password1

PowershellCode:

 

PARAM(

[Parameter(Mandatory=$true, HelpMessage="Enter the uri for the domain (e.g. www.contoso.com).")][string]$Domain,

[Parameter(Mandatory=$true, HelpMessage="Enter the full path where the certificates will be created.")][string]$OutputDir,

[Parameter(Mandatory=$true, HelpMessage="Enter the password for the certificate.")][string]$Password

)

 

if (-not $outputDir.EndsWith('\'))

{

$outputDir += "\"

}

 

$makecert = "C:\Program Files\Microsoft Office Servers\15.0\Tools\makecert.exe"

$certmgr = "C:\Program Files\Microsoft Office Servers\15.0\Tools\certmgr.exe"

 

New-Item $outputDir -ItemType Directory -Force -Confirm:$false | Out-Null

 

$pubCert = $outputDir + $domain + ".cer"

$privateCert = $outputDir + $domain + ".pfx"

 

$output = & $makecert -r -pe -n "CN=$domain" -b 01/01/2013 -e 01/01/2023 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sy 12 -sp "Microsoft RSA SChannel Cryptographic Provider" $pubCert

 

$output = & $certmgr /add $pubCert /s /r localMachine root

 

$publicCertificate = Get-PfxCertificate -FilePath $pubCert

$publicCertificateThumbprint = $publicCertificate.Thumbprint

 

Get-ChildItem cert:\\localmachine\my | Where-Object {$_.Thumbprint -eq $publicCertificateThumbprint} | ForEach-Object {

$privateCertificateByteArray = $_.Export("PFX", $password)

[System.IO.File]::WriteAllBytes($privateCert, $privateCertificateByteArray)

}

  • Domain: The url to the provider hosted web application. 

  • OutputDir: The folder where the certificates are created.

  • Password: The password for the private certificate.

Next Article, How to create IIS website and register the certificate to IIS website.

 

 

 

 

 

 

 

Gowtham Rajamanickam