SharePoint Online: Team site is not responsive

Scenario: My team site is not responsive on mobile devices

  • If you have an existing custom master page, by using Custom Master Page and provision script to apply it
    PnP Example:

    #enable publishing feature on all sites
    
    $subWebs = Get-SPOSubWebs
    foreach ($web in $subWebs) {
    	Enable-SPOFeature -Identity "94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb" `
                              -Force -Web $web.ServerRelativeUrl
    }
    #Add/update the master page
    Add-SPOMasterPage -SourceFilePath "C:/temp" -Title "master.aspx" `
                      -Description "customer master page" `
                      -DestinationFolderHierarchy "test" -UiVersion 15
    
    #Apply it on the root site
    Set-SPOMasterPage -MasterPageServerRelativeUrl $MasterPageServerRelativeUrl `
    		  -CustomMasterPageServerRelativeUrl $MasterPageServerRelativeUrl
    
    #Apply it to all subsites
    $MasterPageServerRelativeUrl = "/_catalogs/masterpage/test/master.aspx"
    $subWebs = Get-SPOSubWebs
    foreach ($web in $subWebs) {
    Set-SPOMasterPage -MasterPageServerRelativeUrl $MasterPageServerRelativeUrl `
                -CustomMasterPageServerRelativeUrl $MasterPageServerRelativeUrl `
      	    -Web $web.ServerRelativeUrl
    }
    
    
  • Register Site Action and use jQuery to apply responsive elements: e.g: https://github.com/SharePoint/PnP-Tools/tree/master/Solutions/SharePoint.UI.Responsive, but if you already have customized publishing site, you might have to modify the scripts to apply these responsive actions only to certain site templates.
  •     .\Enable-SPResponsiveUI.ps1 -TargetSiteurl "https://intranet.mydomain.com/sites/targetSite"
    
  • Using SPMeta2, example code snippet
    
     public ModelNode GetModel()
     {            
           var model = SPMeta2Model.NewWebModel(rootWeb =>
           {
               rootWeb.AddWeb(intranetWebs.TeamSites, web =>
               {
                    web.AddMasterPageSettings(intranetMasterPages.masterPageSettings);
                      
               });
           });
           return model;
    }
    
    public static class intranetMasterPages
    {
        public static MasterPageSettingsDefinition masterPageSettings = new MasterPageSettingsDefinition
        {
            // both should be site relative URLs
            SiteMasterPageUrl = "/_catalogs/masterpage/Intranet.master",
            SystemMasterPageUrl = "/_catalogs/masterpage/Intranet.master"
            //"/_catalogs/masterpage/seattle.master"
        };
    }
    
  • More(TBA)…

SharePoint Online: List and List Items operation with PnP PowerShell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

Retrieving List


#Get all lists
$lists = Get-SPOList  
foreach($list in $lists){              
       #Properties
       $list.Title  
       $list.Description  
       $list.ItemCount  
       #etc...
}  

#Get Single list
Get-SPOList "Test"

Create List
This will create the list if the list does not exist

Function CreateList {
	Param (
		[Parameter(Mandatory=$True)]
		[string]$title,
		[Parameter(Mandatory=$True)]
		[string]$removeContentType,
		[Parameter(Mandatory=$True)]
		[string]$contentType,
		[Parameter(Mandatory=$True)]
		[string]$template,
		[Parameter(Mandatory=$False)]
		[string]$url
	)

	$list = Get-SPOList $title -ErrorAction SilentlyContinue
	if($list -eq $null) {
		Write-Host "Creating List title:" $title "template:" $template "url:" $url -ForegroundColor Yellow
		if($url -eq $null) {
			New-SPOList -Title $title -Template $template -Url $title
		}
		else {
			New-SPOList -Title $title -Template $template -Url $url
		}

		if($removeContentType -ne $null){
			Remove-SPOContentTypeFromList -List $title -ContentType $removeContentType
		}
		
		if($contentType -ne $null) {
			Add-SPOContentTypeToList -List $title -ContentType $contentType -DefaultContentType
		}
				
		Write-Host "Created List" $title -ForegroundColor Green
	}
	else {
		Write-Host "List" $title "already exist" -ForegroundColor Yellow
	}
}

Execute the function
CreateList -title "Custom Link List" `
           -removeContentType Link `
           -contentType "SpecialLink" `
           -template Links

Update List

#Update List
Set-SPOList -Identity "Test" -Title "Test List 2" 

#Unique Permission
Set-SPOList -Identity "Test" -BreakRoleInheritance

Delete List

Remove-SPOList -Identity "Test" -Force

How to add an item

#Add an empty item
Add-SPOListItem -List "Test"

#Add an item with value(s)
Add-SPOListItem -List "PnPList" -Values @{"Title"="1";"TestColumn"="1"}

Example: Retrieving view

Get-SPOView -List "Test"

Example: Add view to list

Add-SPOView -List "Target List" -SetAsDefault `
	-Title "View Title" `
	-ViewType None `
	-Fields @("Field you wanted to display: e.g: ID", "URLwMenu", "etc..") `
	-Query "CAML Query: <Where>...</Where>"

Example: Remove view from list

Remove-SPOView -List "Target List" -Identity "View Title" -Force

SharePoint Online: Content Type and Site Column operation with PnP PowerShell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

========== Site Columns ==========

Example: Adding a site column

#Adding Text Column
Add-SPOField -DisplayName "Text Column" -InternalName "TextColumn" -Group "Test" -Type Text -Required
#Adding Note Column
Add-SPOField -DisplayName "Note Column" -InternalName "NoteColumn" -Group "Test" -Type Note -Required
#Adding Choice Column
Add-SPOField -DisplayName "Choice Column" -InternalName "ChoiceColumn" -Group "Test" -Type Choice -Choices @("Test Value 1","Test Value 2","etc..")
#Other field types such as: Boolean, Integer, DateTime, Lookup, Number, etc...

Example: Retrieving site column(s)

#Get all site column
Get-SPOField

#Get single site column
Get-SPOField -identity "TextColumn"

Example: Retrieving site column properties

#Get all site column
$fields = Get-SPOField
foreach(var $field in $fields) {
    #Properties
    $field.Title
    $field.InternalName
    $field.DefaultValue
    #etc...
}

#Get single site column
$field = Get-SPOField -identity "TextColumn"
#Properties
$field.Title
$field.InternalName
$field.DefaultValue
#etc...

========== Content Type ==========

Example: Create Content Type

$parentCT = Get-SPOContentType -Identity Link
Add-SPOContentType -Name "SpecialLink" -Group "Custom" -ParentContentType $parentCT

Example: Associate site column with content type

#By Name
Add-SPOFieldToContentType -Field "TextColumn" -ContentType "SpecialLink"

#By Reference
$field = Get-SPOField -identity "TextColumn"
$parentCT = Get-SPOContentType -Identity "SpecialLink"
Add-SPOFieldToContentType -Field $field -ContentType $parentCT

Example: Deleting Site Column

Remove-SPOField -Identity "TextColumn" -Force

SharePoint Online: [Rest API & SharePoint App] How to access other web context

Required App permission to be setup in order to access the web, under AppManifest.xml

Example code snippet:

SP.AppContextSite is the core part to call from App to SharePoint


var hostweburl =
        decodeURIComponent(getQueryStringParameter("SPHostUrl"));

var appweburl =
        decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

//Example: Get List Item
function getItems (listName, queryText, rowLimit) {
     var d = $.Deferred();
     var viewXml = '<View><Query>' + queryText + '</Query></View>';
     var query = {
         'query': {
            '__metadata': { 'type': 'SP.CamlQuery' },
            'ViewXml': viewXml
         }
     };
     //default limit
     var limit = 10;
     if (rowLimit)
        limit = rowLimit;
                
     var settings = {
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/GetByTitle('" + listName + "')/items?@target='" + hostweburl + "'&$top=" + limit,
        contentType: "application/json;odata=verbose",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {                                                
           d.resolve(data.d.results);
        },
        error: function (data) {
            d.reject(data);
        }
      };

      if (queryText) {
        settings["data"] = JSON.stringify(query);
      }

      $.ajax(settings);

      return d.promise();
}

SharePoint Online: Page layouts operation with PnP PowerShell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

Example: Adding Page Layout (e.g: Inherit from Article Page)

$ct = Get-SPOContentType -Identity "Article Page"
Add-SPOPublishingPageLayout -SourceFilePath "Path to your page layout aspx" `
                            -Title "Test layout" -Description "Test Page Layout" `
                            -AssociatedContentTypeID $ct.Id

Example: Retrieving Page Layout

Get-SPOListItem -List "Master Page Gallery" `
                -Query "<View><Query><Where><Contains><FieldRef Name='Title'/><Value Type='Text'>Test Layout</Value></Contains></Where></Query></View>"

Example: Deleting Page Layout

Will not be able to be deleted if any pages is using the page layout)

$layout = Get-SPOListItem -List "Master Page Gallery" `
                          -Query "<View><Query><Where><Contains><FieldRef Name='Title'/><Value Type='Text'>Test Layout</Value></Contains></Where></Query></View>"

Remove-SPOListItem -List "Master Page Gallery" -Identity $layout

SharePoint Online: Files operation with PnP Powershell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

Example: How to retrieve/find files
*Site wide, not recommended

Find-SPOFile -Match *

From a list

Find-SPOFile -Match * -List "Documents"

From a site

$web = Get-SPOWeb -Identity "Subsite"
Find-SPOFile -Match * -Web $web

From a list in a site

$web = Get-SPOWeb -Identity "Subsite"
Find-SPOFile -Match * -Web $web -List "Pages"

Access file properties

$web = Get-SPOWeb -Identity "Subsite"
$files = Find-SPOFile -Match * -Web $web -List "Pages"
foreach($file in $files) {
     #get file properties
     $file.Title
     $file.Name
     $file.ServerRelativeUrl
     #etc...
}

Example: How to download file

Get-SPOFile -ServerRelativeUrl "Relative path to your file, e.g: /documents/testing.docx" `
            -Path "Local folder path, e.g: C:\temp" `
            -FileName "Download file name, e.g: test.docx"

Example: To check out the file

Set-SPOFileCheckedOut -Url "Relative path to your file, e.g: /documents/testing.docx"  

Example: To check-in the file

Set-SPOFileCheckedIn -Url "Relative path to your file, e.g: /documents/testing.docx" `
                     -CheckinType MajorCheckIn -Comment "Check"

Example: To add a single file

Add-SPOFile -Path "Path to source file" `
            -Folder "Path to destination folder" -Checkout

You can publish the file by adding -Publish, and publishing comments by adding -PublishingComment

Add-SPOFile -Path "Path to source file" `
            -Folder "Path to destination folder" `
            -Publish -PublishComment "Published by PnP script"

Example: To add a folder

Upload folder function

Function UploadFolder {
	Param(
	  [Parameter(Mandatory=$True)]
	  [String]$targetWeb,

	  [Parameter(Mandatory=$True)]
	  [String]$targetDir,

	  [Parameter(Mandatory=$True)]
	  [String]$path 

	)
	## get the full path to the source folder
	$fullPath = (Get-Item $path).FullName
	## recursively get all files in the directory
	$files = Get-ChildItem -Path $path -Recurse -File
	## upload each file to the directory specified before
	foreach($currentFile in $files)
	{
		## get relative path of documents
		$relativeDirectory = $currentFile.DirectoryName.Replace($fullPath, "").Replace("\","/")
		$uploadDirectory = $targetDir + $relativeDirectory
		Write-Host "Uploading" $currentFile.Name "to" $uploadDirectory "..." -ForegroundColor Yellow
		## Upload the document
		Add-SPOFile -Path $currentFile.FullName -Folder $uploadDirectory -Checkout
		Write-Host "Uploaded" $currentFile.Name "to" $uploadDirectory -ForegroundColor Green
	}
}

Example: How to use the function

UploadFolder -targetWeb "https://yourspsite.sharepoint.com/sites/test/" -targetDir "Style Library/folder" `
	     -path ("path to source folder in local drive")

 

SharePoint Online: Site Operation with PnP Powershell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

Example: How to retrieve top level subsites

Get-SPOWeb -Identity "Subsite"

Example: Create a new subsite

$subsite = Get-SPOWeb -Identity "Subsite" -ErrorAction SilentlyContinue
if($subsite -eq $null) {
	Write-Host "Site does not exist, create..." -ForegroundColor Yellow
	#Create a Team Site STS#0
	#Create a Project Site PROJECTSITE#0
	#Create a Publishing Site CMSPUBLISHING#0
	#etc...
	New-SPOWeb -Title "Subsite" -Url "Subsite" -Template "STS#0" 
	Write-Host "Created site Subsite" -ForegroundColor Yellow		
}
else {
	Write-Host "Subsite already exist" -ForegroundColor Green
}

Getting subsites under the top level subsites

#assuming subsite exists
$subsite = Get-SPOWeb -Identity "Subsite"
$subsubsite =  Get-SPOSubWebs -Web $subsite | Where-Object -property Title -EQ -Value "subsubsite"