Monday, December 26, 2016

Upload and Publish MasterPage to SharePoint Online by using PowerShell/CSOM


cls
#Specify tenant admin and site URL
$User = "Naga@contoso.com"
$SiteURL = "https://*****.sharepoint.com/Subsite"
$MasterPageDeploymentFolder = $("C:\MasterPage")
#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
if (!$Context.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint Online site: '$SiteURL'" -ForegroundColor Green
}
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

function Upload-Files()
{
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds
# Get the SharePoint web
    $web = $Context.Web;
    $usrRDBC = $null
#Upload page layouts file
Foreach ($MSFile in (dir $MasterPageDeploymentFolder -File))
{
Write-Host $MSFile.FullName
Deploy-MasterPage -Web $Context.Web -FilePath $MSFile.FullName
}
}
Function Deploy-MasterPage([Microsoft.SharePoint.Client.Web]$Web,[string]$FilePath)
{
     $htmlMasterPageContentTypeId = "0x0101000F1C8B9E0EB4BE489F09807B2C53288F0054AD6EF48B9F7B45A142F8173F171BD10003D357F861E29844953D5CAA1D4D8A3A00F416DBD8A79A6643A8465E6D4B8B558A"
     $fileName = [System.IO.Path]::GetFileName($FilePath)
     $fileContent = [System.IO.File]::ReadAllBytes($FilePath)
     $fileInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
     $fileInfo.Content = $fileContent
     $fileInfo.Url = $catalogList.RootFolder.ServerRelativeUrl + "/" + $fileName
     $fileInfo.Overwrite = $true
     $file = $catalogList.RootFolder.Files.Add($fileInfo)
     $Web.Context.Load($file)
     $Web.Context.ExecuteQuery()

     $listItem = $file.ListItemAllFields
     $listItem["Title"] = $file.Name;
     #listItem["MasterPageDescription"] = description;
     $listItem["ContentTypeId"] = $htmlMasterPageContentTypeId
     $listItem["UIVersion"] = [Convert]::ToString(15)
     $listItem["PublishingHidden"] = $false
     $listItem["HtmlDesignAssociated"] = $true
     $listItem.Update()
$listItem.File.Publish("")
     $Web.Context.ExecuteQuery()
}
#Execute the function
Upload-Files

Upload and Publish page layouts to SharePoint Online by using PowerShell/CSOM

cls
#Specify tenant admin and site URL
$User = "Naga@contoso.com"
$SiteURL = "https://*****.sharepoint.com/Subsite"
$PageLayoutDeploymentFolder = $("C:\PageLayouts")

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"

$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
if (!$Context.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint Online site: '$SiteURL'" -ForegroundColor Green
}
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds


function Upload-Files()
{
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

# Get the SharePoint web
    $web = $Context.Web;
    $usrRDBC = $null

$ArticlePageContentTypeId = "0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D"
#Upload page layouts file
Foreach ($PLFile in (dir $PageLayoutDeploymentFolder -File))
{
Write-Host $PLFile.FullName
Deploy-PageLayout -Web $Context.Web -FilePath $PLFile.FullName -AssociatedContentTypeId $ArticlePageContentTypeId
}
}

Function Deploy-PageLayout([Microsoft.SharePoint.Client.Web]$Web,[string]$FilePath,[string]$AssociatedContentTypeId)
{
     $pageLayoutContentTypeId = "0x01010007FF3E057FA8AB4AA42FCB67B453FFC100E214EEE741181F4E9F7ACC43278EE811002985A1BA00CCBC45B088E4150D7BC86C"
     $fileName = [System.IO.Path]::GetFileName($FilePath)
     $associatedContentType = $Web.AvailableContentTypes.GetById($AssociatedContentTypeId)
     $catalogList = $Web.GetCatalog([Microsoft.SharePoint.Client.ListTemplateType]::MasterPageCatalog)  
     $Web.Context.Load($catalogList.RootFolder)
     $Web.Context.Load($associatedContentType)
     $Web.Context.ExecuteQuery()
     $fileContent = [System.IO.File]::ReadAllBytes($FilePath)
     $fileInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
     $fileInfo.Content = $fileContent
     $fileInfo.Url = $catalogList.RootFolder.ServerRelativeUrl + "/" + $fileName
     $fileInfo.Overwrite = $true
     $file = $catalogList.RootFolder.Files.Add($fileInfo)
     $Web.Context.Load($file)
     $Web.Context.ExecuteQuery()

     $listItem = $file.ListItemAllFields
     $listItem["Title"] = $file.Name;
     #listItem["MasterPageDescription"] = description;
     $listItem["ContentTypeId"] = $pageLayoutContentTypeId
     $listItem["PublishingAssociatedContentType"] = [string]::Format(";#{0};#{1};#", $associatedContentType.Name, $associatedContentType.Id.StringValue)
     $listItem["UIVersion"] = [Convert]::ToString(15)
$listItem["PublishingHidden"] = $false
     $listItem.Update()
$listItem.File.Publish("")
     $Web.Context.ExecuteQuery()
}

#Execute the function
Upload-Files

Happy coding.. :)

Activate SharePoint Online features by using PowerShell/CSOM

Using below script we can activate the feature in sharepoint online site

############################################################################################################################################
# Required Parameters:
#  -> $UserName: User Name to connect to the SharePoint Online Site
#  -> $sPass: Password for the user.
#  -> $SiteUrl: SharePoint Online Site Collection
#  -> $FeatureGuid: GUID of the feature to be enabled
############################################################################################################################################

#Definition of the function that allows to enable a SPO Feature
function Activate-SPOFeature
{
    param ($SiteUrl,$UserName,$sPass,$FeatureGuid)
    try
    {    
        #Adding the Client OM Assemblies        
        Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"

  $context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,$sPass)
if (!$context.ServerObjectIsNull.Value)
{
   #Write-Host "Connected to SharePoint Online site: '$SubSiteURL'" -ForegroundColor green
#Add-Content -Path $LogFileName -Value([string]::Concat("Connected to SharePoint Online site:",$url))
}
$context.Credentials = $Creds
$checkAlertEmailFeature = $context.Web.Features.GetById($FeatureGuid)
   $checkAlertEmailFeature.Retrieve("DisplayName")
   $context.Load($checkAlertEmailFeature)
   $context.ExecuteQuery()
   
   if($checkAlertEmailFeature.DefinitionId -eq $null){
       Write-Host "Alert Notification  Feature need to active"  -ForegroundColor Green
$newSiteFeature = $context.Web.Features.Add($FeatureGuid, $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::Site)
$context.Load($newSiteFeature)
$context.ExecuteQuery()
if($newSiteFeature.DefinitionId -ne $null)
{
          Add-Content -Path $LogFileName -Value([string]::Concat("Alert Notification feature activated"))
Write-Host "Alert Notification feature activated"  -ForegroundColor Green
      }
else
{
Write-Host "Alert Notification feature not yet activated"  -ForegroundColor Green
Add-Content -Path $LogFileName -Value([string]::Concat("Alert Notification feature not yet activated"))
}
   }
   else
{
       Add-Content -Path $LogFileName -Value([string]::Concat("Alert Notification feature activated"))
   }
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()  
    }    
}

#Required Parameters
$SiteUrl = "https://*****.sharepoint.com/Subsite"
$UserName = "Naga@contoso.com"
$FeatureGuid= "ab2e9a62-d1b3-4f47-9678-7e7a72e1c645"
#$sPass = Read-Host -Prompt "Enter your password: " -AsSecureString  
$sPass=convertto-securestring "******" -asplaintext -force

Activate-SPOFeature -sSiteColUrl $SiteUrl -sUserName $UserName -sPassword $sPass -sFeatureGuid $FeatureGuid

Happy code.. :)

Steps to update SharePoint Top Navigation in Mobile view

when we access Top Navigation in desktop view mouse hover functionality will work to see all child menus but it wouldn't work on mobile view.
In mobile view we have to inject custom click functionality on parent menu by help of jquery.


Add below meta tags in master page html file

<meta http-equiv="Expires" content="0" />
 <meta name="viewport" content="width=device-width, initial-scale=1" />

Find and replace Top Navigation id using below script line

$("ul[id*='RootAspMenu']").attr( "id", "myTopNav" );



And have below function on Master Page body

$(function() {
if ($.browser.msie && $.browser.version.substr(0,1)<7)
{
$('li').has('ul').mouseover(function(){
$(this).children('ul').css('visibility','visible');}).mouseout(function(){
$(this).children('ul').css('visibility','hidden');})
}

// Mobile
$('#menu-wrap').prepend('<div id="menu-trigger">Menu</div>');
$("#menu-trigger").on("click", function(){$("#myTopNav").slideToggle();});

// iPad
var isiPad = navigator.userAgent.match(/iPad/i) != null;
if (isiPad) $('#myTopNav ul').addClass('no-transition');    
    });  


Add below code into JS file and gave this reference into master page

$(function () {
    var pull = $('#pull');
    menu = $('div#DeltaTopNavigation ul#myTopNav');
    menu.find("ul").slideToggle();
    menu.find("li").on('click', function (e) {
        e.stopImmediatePropagation();
        $($(this).find('ul')[0]).slideToggle();
    });

    $(pull).on('click', function (e) {
        e.stopImmediatePropagation();
        menu.slideToggle();

    });

    $(window).resize(function () {
        var w = $(window).width();
        if (w > 320 && menu.is(':hidden')) {
            menu.removeAttr('style');
        }
    });

});

Save and upload masterpage to respective library.

Please reach me if you are not clear at any point of implementation.