Wednesday, November 8, 2017

SharePoint Framework and Angular–Introducing SPFX with Angular


GETTING STARTED

Getting started with Angular and the SharePoint is simple. First of all, close or fork the Github project. To clone the project and install all the necessary dependencies, execute the following commands in your environment :
git clone https://github.com/mananchoksi007/SPFX-Angular.git
npm install
gulp serve
The sample that you are running is very basic. It allows to render all the items (Id and Tile) of a specified list (by its name). I works on a local Workbench using mocked data and it works on the hosted Workbench using real data.

RUNNING THE SAMPLE

Once you have a browser running the local SharePoint Workbench, please add the "BasicAngular" webpart to your authoring canvas and see the result. You will see an Angular application running and you should be able to configure it through the editor panel by changing the title of the webpart and the list name. Once the list name is configured, you should see mocked results being rendered in your interface. At this point, to prove that the we can leverage multiple Angular webparts on the same page, you can add a second webpart and change its title. Both webpart will have a different configuration and will be completely isolated.
image

WHAT'S NEXT?

Isn't it cool? I find it amazing that we can finally run real code using Angular in the SharePoint Framework and that we can leverage the great features of Angular without compromises.
This is not the end of the Angular story in the SharePoint Framework. We absolutely need the community to test, contribute and use the concepts illustrated in this sample solution. Your feedback will impact this solution as we really want to support all the nice and shiny features that Angular add to the developer tool belt.
In the next post, we will cover the general concepts used to make this solution work and how it solves the challenges of the SharePoint Framework!
Oh! And (finally), happy Angular coding on the SharePoint Framework!









Thursday, November 2, 2017

Setting up your first SharePoint On-Premises -SPFX client side web part to a SharePoint library


Setting up and Environment First

Enable auto provision for Microsoft SharePoint Foundation Subscription Settings Service

  1. $appPool = Get-SPServiceApplicationPool "ServiceApps"

$serviceApp = New-SPSubscriptionSettingsServiceApplication -ApplicationPool $appPool -name "App Management Service Application" -DatabaseName "Dev1_Subscription"

$serviceAppProxy = New-SPSubscriptionSettingsServiceApplicationProxy -ServiceApplication $serviceApp

  1. $appPool = Get-SPServiceApplicationPool "ServiceApps"

$serviceApp = New-SPSubscriptionSettingsServiceApplication -ApplicationPool $appPool -name "Subscription Settings Service Application" -DatabaseName "Dev1_Subscription"

$serviceAppProxy = New-SPSubscriptionSettingsServiceApplicationProxy -ServiceApplication $serviceApp

  1. Manage Web Applications -> Manage Features -> Activate Apps that require accessible internet facing endpoints
  2. Central Admin -> Apps -> Manage App Catalog – Set up site

image

  1. Central Admin -> Apps -> URLs (change if needed)

image

URL: https://mc-google.blogspot.com(your sharepoint on-premises server)/sites/appcatalog/_layouts/15/start.aspx

Issues:

You may be trying to access this site from a secured browser on the server. Please enable scripts and reload this page.

Resolution: Internet options -> Security -> add to trusted sites

Build your First Hello World SPFX webpart

Step 1: Create Webpart

     Setting up NPM environment for SPFX

    • npm install -g npm
    • npm install -g yo
    • npm install -g gulp
    • npm install -g @microsoft/generator-sharepoint

      After install preliminary tools you can follow the below steps. 

  • Create a new Webpart, I named here “spfx-firstwebpart”
  • md spfx-firstwebpart
  • cd spfx-firstwebpart
  • Create new Webpart yo @microsoft/sharepoint

It will create a new Webpart refer below screenshot

deploysp1deploysp2

Build the Webpart gulp serve

Step 2: Create SharePoint Library

  • Create a SharePoint Library “Myspfxwebparts” and give read permission to all users.

Step 3: Open code Visual Studio Code

  • Open the code in Visual code tool.
  • Type in cmd : code .

Step 4: Update the CDN Path

  • We need to configure the CDN path, i.e SharePoint Library what we created. https://mc-google.blogspot.com/sites/appcatalog/Myspfxwebparts
  • we have to configure our CDN path in write-manifests.json file. This file can be found in the config folder.
  • i.e

{
  “cdnBasePath”: “https://mc-google.blogspot.com/sites/appcatalog/Myspfxwebparts”
}

  • Save the file.
  • Switch to cmd prompt

Step 5: Package and Deploy the webpart

  • Generate the files to deploy in the SharePoint Library
  • gulp trust-dev-cert
  • gulp bundle –ship
  • Generated files can be found in spfx-firstwebpart\temp\deploy folder
  • upload the files in the SharePoint Library
  • Create a .spapp file for this webpart to upload in App Catalog
    • gulp package-solution –ship
    • Generated spapp file can be found in spfx-firstwebpart\sharepoint folder
    • upload the spapp file in App catalog
    • SharePoint will show you a popup and ask you to trust the client-side solution to deploy.
    • Click Deploy

Step 6: Install the App

  • Open your SharePoint Site
  • Go to “Add an App”
  • Click “From Your Organization”
  • Select and Click you app to install it.

Syep 7: Add the Webpart in your Page

  • After App installation
  • Go to your Page
  • Edit the Page
  • Click Insert tab and click Webpart
  • Select Custom folder –> you can see your webpart, refer below screenshot

image

  • Now you can add your webpart
    • Select the your webpart and Click Add
    • It will add your webpart

image


Monday, July 24, 2017

PowerShell - Add AD User/Group to Local Administrator Group


<#
.SYNOPSIS  
Script to add an AD User or group to the Local Administrator group
    
.DESCRIPTION
The script can use either a plaintext file or a computer name as input and will add the trustee (user or group) as an administrator to the computer
    
.PARAMETER InputFile
A path that contains a plaintext file with computer names
.PARAMETER Computer
This parameter can be used instead of the InputFile parameter to specify a single computer or a series of
computers using a comma-separated format
    
.PARAMETER Trustee
The SamAccount name of an AD User or AD Group that is to be added to the Local Administrators group
.NOTES  
Name: Set-ADAccountasLocalAdministrator.ps1
.EXAMPLE  
.\Set-ADAccountasLocalAdministrator.ps1.ps1 -Computer Server01 -Trustee MananChoksi
Description:
Will set the the JaapBrasser account as a Local Administrator on Server01
.EXAMPLE  
.\Set-ADAccountasLocalAdministrator.ps1.ps1 -Computer 'Server01,Server02' -Trustee Contoso\HRManagers
Description:
Will set the HRManagers group in the contoso domain as Local Administrators on Server01 and Server02
.EXAMPLE  
.\Set-ADAccountasLocalAdministrator.ps1 -InputFile C:\ListofComputers.txt -Trustee User01
Description:
Will set the User01 account as a Local Administrator on all servers and computernames listed in the ListofComputers file
#>
param(
     [Parameter(ParameterSetName='InputFile')]
     [string]
         $InputFile,
     [Parameter(ParameterSetName='Computer')]
     [string]
         $Computer,
     [string]
         $Trustee
)
<#
.SYNOPSIS
     Function that resolves SAMAccount and can exit script if resolution fails
#>
function Resolve-SamAccount {
param(
     [string]
         $SamAccount,
     [boolean]
         $Exit
)
     process {
         try
         {
             $ADResolve = ([adsisearcher]"(samaccountname=$Trustee)").findone().properties['samaccountname']
         }
         catch
         {
             $ADResolve = $null
         }
        if (!$ADResolve) {
             Write-Warning "User `'$SamAccount`' not found in AD, please input correct SAM Account"
             if ($Exit) {
                 exit
             }
         }
         $ADResolve
     }
}
if (!$Trustee) {
     $Trustee = Read-Host "Please input trustee"
}
if ($Trustee -notmatch '\\') {
     $ADResolved = (Resolve-SamAccount -SamAccount $Trustee -Exit:$true)
     $Trustee = 'WinNT://',"$env:userdomain",'/',$ADResolved -join ''
} else {
     $ADResolved = ($Trustee -split '\\')[1]
     $DomainResolved = ($Trustee -split '\\')[0]
     $Trustee = 'WinNT://',$DomainResolved,'/',$ADResolved -join ''
}
if (!$InputFile) {
     if (!$Computer) {
         $Computer = Read-Host "Please input computer name"
     }
     [string[]]$Computer = $Computer.Split(',')
     $Computer | ForEach-Object {
         $_
         Write-Host "Adding `'$ADResolved`' to Administrators group on `'$_`'"
         try {
             ([ADSI]"WinNT://$_/Administrators,group").add($Trustee)
             Write-Host -ForegroundColor Green "Successfully completed command for `'$ADResolved`' on `'$_`'"
         } catch {
             Write-Warning "$_"
         }   
     }
}
else {
     if (!(Test-Path -Path $InputFile)) {
         Write-Warning "Input file not found, please enter correct path"
         exit
     }
     Get-Content -Path $InputFile | ForEach-Object {
         Write-Host "Adding `'$ADResolved`' to Administrators group on `'$_`'"
         try {
             ([ADSI]"WinNT://$_/Administrators,group").add($Trustee)
             Write-Host -ForegroundColor Green "Successfully completed command"
         } catch {
             Write-Warning "$_"
         }       
     }
}

Comments
Save above powershell in to Set-ADAccountasLocalAdministrator.ps1
Run this powershell command with pass parameters
.\Set-ADAccountasLocalAdministrator.ps1 –Computer computerName –Trustee domaine\userID

Wednesday, July 19, 2017

PowerShell – Get the Sharepoint Manange Meta Data site colum default value and set that value in all list under that site.


Add-PSSnapin Microsoft.SharePoint.Powershell

$site  = 'Site URL’
$fieldName = 'Countries'
$web = Get-SPWeb $site
$mmsServiceName = "Managed Metadata Service"
$taxonomySite = Get-SPSite $site
$web=  $taxonomySite.OpenWeb()
$taxSession = New-Object Microsoft.SharePoint.Taxonomy.TaxonomySession($taxonomySite)
$termStore = $taxSession.TermStores[$mmsServiceName]
$field = $web.Fields.GetFieldByInternalName('Countries')
$defaultValue=$field.DefaultValue

foreach($list in $web.Lists)
     {
      if( $list.Fields.ContainsField("Countries") -eq $true)
           {                                      
               write-host $item["Title"]
               $spItem = [Microsoft.SharePoint.SPListItem]$item;
               $taxField = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$spItem.Fields["Countries"]
               $item["Countries"] = $defaultValue;
               $item.Update();
               break;
           }
     }

Thursday, July 13, 2017

Task Scheduler Error “A specified logon session does not exist”



image


Solution


I found that the above error will only occur if the following Security Policy is enabled and you select the “Run whether user is logged on or not” Security option on the General tab, when creating a new task:

SECPOL.MSC | Security Settings | Local Policies | Security Options

Network access: Do not allow storage of passwords and credentials for network authentication


8171.clip_image003_6733CA79


To resolve this issue, simply Set this policy to Disabled:

clip_image005


The new version of Task Scheduler (Windows Vista onwards) uses Windows Credential Manager to store the credentials of the account that is specified to perform a task.  If the Network access: Do not allow storage of passwords and credentials for network authentication policy is enabled and applied, Credential Manager cannot store the credentials locally, thus this error message appears.

NOTE you will not receive this error if the “Run only when user is logged on” Security option on the General tab is selected (we do not store passwords in this scenario).

Tuesday, May 16, 2017

The Latest of Microsoft Office Developer Tools: Office Add-in Commands and SharePoint 2016 – Visual Studio

 

Office’s message at Build was loud and clear: Office is an open market for developers who want to reinvent productivity, backed by a consumer base of 1.2 billion users. Qi Lu welcomed developers to the Office ecosystem in his Build keynote, and showcased new robust extensibility features that enable you to create custom experiences in Office that look and feel native. A new wave of excitement and growth is sweeping through the Office ecosystem, and there is no better time to be an Office developer. And no better tool than Visual Studio to get started!

As a Visual Studio user, you can get started right away and take advantage of all the new Office extensibility goodness inside the IDE.

We are also pleased to announce Preview 2 of Microsoft Office Developer Tools for Visual Studio 2015. Preview 2 adds the support for SharePoint 2016 solutions and add-in development in Visual Studio 2015, on top of the new features available in Update 2 of Office Developer Tools. For Visual Studio “15,” SharePoint 2016 support is available by default when you install Office Developer Tools.

Now let’s take a closer look at how the Office Developer Tools optimize getting started with add-in development.

Tuesday, May 2, 2017

Sharepoint – Powershell–Deployment script for sharepoint solutions

 

Steps)

       1) Save below scrips in to spdeploy.ps1

       2) Open Sharepoint Manangement shell and run below command.

.\ spdeploy.ps1 –solutionName solution Name-location Location to solution file

 

param(
    [Parameter(Position=0, Mandatory="True",
        HelpMessage="Need the script filename to be tested.")]
    [string]
    # The Script to test
    $solutionName,
    [Parameter(Position=1, Mandatory="True",
        HelpMessage="Need the config filename for this Farm.")]
    [string]
    # Farm Config XML File
    $location
)   

$location = $location

$solutionName = $solutionName +'.wsp'

function solutionStatus([string]$solutionName ,[string]$location)
{
    try
    {
        $s = Get-SPSolution | where-object {$_.Name -eq $solutionName}
            if ($s -ne $null)
              {
                if ($s.Deployed -eq $true -And $s.JobExists -eq $False)
                   {
                     Write-Host -NoNewline $solutionName " found - "  -ForegroundColor Yellow
                     Write-Host -ForegroundColor Green "Updating $solutionName "
                     spUpdate $solutionName $location
                     WaitForSPSolutionJobToComplete $solutionName
                   }
                   else
                   {
                   Write-Host -NoNewline  $solutionName " found - Solution status - not deployed  "  -ForegroundColor Yellow
                   spRemove $solutionName $location
                   Write-Host -ForegroundColor Green "Removing $solutionName "
                   spInstall $solutionName $location
                   WaitForSPSolutionJobToComplete $solutionName
                   }
               }
             else
               {
                 Write-Host -NoNewline $solutionName " not found - "  -ForegroundColor Yellow
                 spInstall $solutionName $location
                 WaitForSPSolutionJobToComplete $solutionName
               }
               Write-Host  $solutionName " successfully deployed"  -ForegroundColor Green
               Write-host  "--------------------------------------------" -ForegroundColor Green
               $s.DeployedServers
        
         }
         catch
         {
          Write-Host  $_.Exception.Message  -ForegroundColor Red
         }
         
}

function spInstall([string]$solutionName ,[string]$location)
{
    $solution = Add-SPSolution -LiteralPath $location'\'$solutionName
         if ($solution.ContainsWebApplicationResource)
            {
            Write-Host -ForegroundColor Green "Deploying $solutionName "
            Install-SPSolution -Identity $solutionName -AllWebApplications -GACDeployment
            }
        else
            {
               Write-Host -ForegroundColor Green "Deploying $solutionName"
               Install-SPSolution -Identity $solutionName -GACDeployment
            }
}

function spUpdate([string]$solutionName ,[string]$location)
{
    Update-SPSolution -Identity $solutionName -LiteralPath $location'\'$solutionName -GACDeployment
}

function spUnInstall([string]$solutionName ,[string]$location)
{
   
}

function spRemove([string]$solutionName ,[string]$location)
{
Remove-SPSolution -Identity $solutionName -Confirm:$false
}

function WaitForSPSolutionJobToComplete([string]$solutionName)
{
    $solution = Get-SPSolution -Identity $solutionName -ErrorAction SilentlyContinue
 
    if ($solution)
    {
        if ($solution.JobExists)
        {
            Write-Host -NoNewLine "Waiting for solution to deploy :- " -ForegroundColor Yellow
            Write-Host  $solutionName -ForegroundColor Red
 
        }
        
        # Check if there is a timer job still associated with this solution and wait until it has finished
        while ($solution.JobExists)
        {
            $jobStatus = $solution.JobStatus
            
            # If the timer job succeeded then proceed
            if ($jobStatus -eq [Microsoft.SharePoint.Administration.SPRunningJobStatus]::Succeeded)
            {
                Write-Host "Solution '$solutionName' timer job suceeded"
                return $true
            }
            
            # If the timer job failed or was aborted then fail
            if ($jobStatus -eq [Microsoft.SharePoint.Administration.SPRunningJobStatus]::Aborted -or
                $jobStatus -eq [Microsoft.SharePoint.Administration.SPRunningJobStatus]::Failed)
            {
                Write-Host "Solution '$solutionName' has timer job status '$jobStatus'."
                return $false
            }
            
            Write-Host -NoNewLine "Waiting for solution to deploy :- " -ForegroundColor Yellow
            Write-Host  $solutionName -ForegroundColor Red
            Sleep 1
        }
        
        # Write a new line to the end of the '.....'
        Write-Host
    }
   
  
}

solutionStatus $solutionName $location

Friday, April 28, 2017

Sharepoint - Microsoft.Office.Server.UserProfiles.UserProfileApplicationNotAvailableException: UserProfileApplicationNotAvailableException_Logging :: UserProfileApplicationProxy.ApplicationProperties ProfilePropertyCache does not have


Exception on UPS Service
Exception instantiating UserProfileManager, exception is Microsoft.Office.Server.UserProfiles.UserProfileApplicationNotAvailableException: UserProfileApplicationNotAvailableException_Logging :: UserProfileApplicationProxy.ApplicationProperties ProfilePropertyCache does not have afdf55d6-5c22-488d-80bb-4dd0db6c5907     at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.get_ApplicationProperties()   
at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.CheckAdministrationAccess(UserProfileApplicationAdminRights rights, Boolean requireAllRights)   
at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.CheckAdministrationAccess(UserProfileApplicationAdminRights rights)   
at Microsoft.Office.Server.UserProfiles.ProfileManagerBase.CanManagePeople(UserProfileApplicationProxy userProfileApplicationProxy)   
at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.get_IsProfileAdmin()   
at Microsoft.Office.Server.UserProfiles.ProfileManagerBase.get_IsProfileAdmin()   
at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor(SPServiceContext serviceContext, Boolean IgnoreUserPrivacy, Boolean backwardCompatible)   
at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor()   
at Microsoft.Office.Server.UserProfiles.UserProfileService.InitProfileManager()
Resolution
The error that we were seeing in ULS (UserProfileApplicationProxy.ApplicationProperties ProfilePropertyCache does not have afdf55d6-5c22-488d-80bb-4dd0db6c5907).
afdf55d6-5c22-488d-80bb-4dd0db6c5907 is one of the Machine Keys. Since the administrators did not have proper access to the keys, the error was being thrown.
 

Navigate too - C:\ProgramData\Microsoft\Crypto\RSA
· Right Click Machine Keys
- Properties > Security > Advanced > Change permissions > Adminsitrators > Edit
   - Set "Apply To" as "This folder only"
         - This Folder Only = Special Permissions
·                      Special Permissions has full control + additional permissions
-  Apply To value was set too "This folder, subfolder, and files"
                  -  Denotes Full control only
















Thursday, April 27, 2017

Powershell – StopSharePointTimerServicesInFarm –ClearTimerCache – DeleteXmlFilesFromConfigCache - StartSharePointTimerServicesInFarm

 

# Clear the SharePoint Timer Cache
#
##
# Added loading of SharePoint Snapin for Powershell. Also this script only queries
# the SharePoint servers.

# Output program information
Write-Host -foregroundcolor White ""
Write-Host -foregroundcolor White "Clear SharePoint Timer Cache"

#**************************************************************************************
# Constants
#**************************************************************************************
Set-Variable timerServiceName -option Constant -value "SPTimerV4"
Set-Variable timerServiceInstanceName -option Constant -value "Microsoft SharePoint Foundation Timer"

#**************************************************************************************
# Functions
#**************************************************************************************
#<summary>
# Loads the SharePoint Powershell Snapin.
#</summary>
Function Load-SharePoint-Powershell
{
    If ((Get-PsSnapin |?{$_.Name -eq "Microsoft.SharePoint.PowerShell"})-eq $null)
    {
            Write-Host -ForegroundColor White " - Loading SharePoint Powershell Snapin"
        Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop
    }
}

#<summary>
# Stops the SharePoint Timer Service on each server in the SharePoint Farm.
#</summary>
#<param name="$farm">The SharePoint farm object.</param>
function StopSharePointTimerServicesInFarm($farm)
{
Write-Host ""

# Iterate through each server in the farm, and each service in each server
foreach($server in $farm)
{
foreach($instance in $server.ServiceInstances)
{
# If the server has the timer service then stop the service
if($instance.TypeName -eq $timerServiceInstanceName)
{
[string]$serverName = $server.Name

Write-Host -foregroundcolor DarkGray -NoNewline "Stop '$timerServiceName' service on server: "
Write-Host -foregroundcolor Gray $serverName

$service = Get-WmiObject -ComputerName $serverName Win32_Service -Filter "Name='$timerServiceName'"
sc.exe \\$serverName stop $timerServiceName > $null

# Wait until this service has actually stopped
WaitForServiceState $serverName $timerServiceName "Stopped"

break;
}
}
}

Write-Host ""
}

#<summary>
# Waits for the service on the server to reach the required service state.
# This can be used to wait for the "SharePoint 2010 Timer" service to stop or to start
#</summary>
#<param name="$serverName">The name of the server with the service to monitor.</param>
#<param name="$serviceName">The name of the service to monitor.</param>
#<param name="$serviceState">The service state to wait for, e.g. Stopped, or Running.</param>
function WaitForServiceState([string]$serverName, [string]$serviceName, [string]$serviceState)
{
Write-Host -foregroundcolor DarkGray -NoNewLine "Waiting for service '$serviceName' to change state to $serviceState on server $serverName"

do
{
Start-Sleep 1
Write-Host -foregroundcolor DarkGray -NoNewLine "."
$service = Get-WmiObject -ComputerName $serverName Win32_Service -Filter "Name='$serviceName'"
}
while ($service.State -ne $serviceState)

Write-Host -foregroundcolor DarkGray -NoNewLine " Service is "
Write-Host -foregroundcolor Gray $serviceState
}

#<summary>
# Starts the SharePoint Timer Service on each server in the SharePoint Farm.
#</summary>
#<param name="$farm">The SharePoint farm object.</param>
function StartSharePointTimerServicesInFarm($farm)
{
Write-Host ""

# Iterate through each server in the farm, and each service in each server
foreach($server in $farm)
{
foreach($instance in $server.ServiceInstances)
{
# If the server has the timer service then start the service
if($instance.TypeName -eq $timerServiceInstanceName)
{
[string]$serverName = $server.Name

Write-Host -foregroundcolor DarkGray -NoNewline "Start '$timerServiceName' service on server: "
Write-Host -foregroundcolor Gray $serverName

$service = Get-WmiObject -ComputerName $serverName Win32_Service -Filter "Name='$timerServiceName'"
sc.exe \\$serverName start $timerServiceName > $null

WaitForServiceState $serverName $timerServiceName "Running"

break;
}
}
}

Write-Host ""
}

#<summary>
# Removes all xml files recursive on an UNC path
#</summary>
#<param name="$farm">The SharePoint farm object.</param>
function DeleteXmlFilesFromConfigCache($farm)
{
Write-Host ""
Write-Host -foregroundcolor DarkGray "Delete xml files"

[string] $path = ""

# Iterate through each server in the farm, and each service in each server
foreach($server in $farm)
{
foreach($instance in $server.ServiceInstances)
{
# If the server has the timer service delete the XML files from the config cache
if($instance.TypeName -eq $timerServiceInstanceName)
{
[string]$serverName = $server.Name

Write-Host -foregroundcolor DarkGray -NoNewline "Deleting xml files from config cache on server: "
Write-Host -foregroundcolor Gray $serverName

# Remove all xml files recursive on an UNC path
$path = "\\" + $serverName + "\c$\ProgramData\Microsoft\SharePoint\Config\*-*\*.xml"
Remove-Item -path $path -Force

break
}
}
}

Write-Host ""
}

#<summary>
# Clears the SharePoint cache on an UNC path
#</summary>
#<param name="$farm">The SharePoint farm object.</param>
function ClearTimerCache($farm)
{
Write-Host ""
Write-Host -foregroundcolor DarkGray "Clear the cache"

[string] $path = ""

# Iterate through each server in the farm, and each service in each server
foreach($server in $farm)
{
foreach($instance in $server.ServiceInstances)
{
# If the server has the timer service then force the cache settings to be refreshed
if($instance.TypeName -eq $timerServiceInstanceName)
{
[string]$serverName = $server.Name

Write-Host -foregroundcolor DarkGray -NoNewline "Clearing timer cache on server: "
Write-Host -foregroundcolor Gray $serverName

# Clear the cache on an UNC path
# 1 = refresh all cache settings
$path = "\\" + $serverName + "\c$\ProgramData\Microsoft\SharePoint\Config\*-*\cache.ini"
Set-Content -path $path -Value "1"

break
}
}
}

Write-Host ""
}

#**************************************************************************************
# Main script block
#**************************************************************************************

# Load SharePoint Powershell Snapin
Load-SharePoint-Powershell

# Get the local farm instance
$farm = Get-SPServer | where {$_.Role -match "Application"}

# Stop the SharePoint Timer Service on each server in the farm
StopSharePointTimerServicesInFarm $farm

# Delete all xml files from cache config folder on each server in the farm
DeleteXmlFilesFromConfigCache $farm

# Clear the timer cache on each server in the farm
ClearTimerCache $farm

# Start the SharePoint Timer Service on each server in the farm
StartSharePointTimerServicesInFarm $farm

Friday, April 21, 2017

SharePoint– Add/Upload MasterPage/Document in to Sharepoint Library from Powershell

 

$approveComment="Approved"
$logfile = "UploadMasterPage_$(get-date -f yyyyMMdd_hhmmss).log"
$spsite = new-object Microsoft.Sharepoint.SPSite($webAppUrl);
$web = $spsite.RootWeb;
$masterPageList = ($web).GetFolder("Master Page Gallery")
$filesfolde = Split-Path $script:MyInvocation.MyCommand.Path

$masterPageLocalDir = $filesfolde + "\Docs"
#For upload all files in document library from file system
foreach ($file in Get-ChildItem $masterPageLocalDir)
  {
    $web.AllowUnsafeUpdates=$true;
try
{
    if ([Microsoft.SharePoint.Publishing.PublishingSite]::IsPublishingSite($spsite))
    {
   
    $stream = [IO.File]::OpenRead($file.fullname)
          $destUrl = $web.Url + "/_catalogs/masterpage/" + $file.Name;
        $masterPageFile=$web.GetFile($destUrl)
    #write-host($masterPageFile)
           if($masterPageFile.CheckOutStatus -ne "None")
        {
                #$web.AllowUnsafeUpdates  = $true;
                $masterPageList.files.Add($destUrl,$stream,$true)
                $stream.close()                       
                $masterPageFile.CheckIn($checkInComment);                       
                $masterPageFile.Publish($publishComment);               
                $masterPageFile.Approve($approveComment);
                $masterPageFile.Update();        
                $web.Update();
                $web.AllowUnsafeUpdates  = $false;
                $outputText = $file.Name+ " Master Page uploaded on $web site"
                write-output $outputText
                write-output $outputText |  out-File $logfile -Append
        }
        else
        {
                  $masterPageFile.CheckOut();
                 try{
                 $masterPageList.Files.Add($destUrl,$stream,$true)
                 }
                 catch
                 {
                 write-Output $_
                 }
                 $stream.close()                             
                 $masterPageFile.CheckIn($checkInComment);                         
                 $masterPageFile.Publish($publishComment);                         
                 $masterPageFile.Approve($approveComment);
                 $masterPageFile.Update();        
                 $web.Update();
                 $web.AllowUnsafeUpdates  = $false;
                 $outputText = $file.Name +  " Master Page uploaded on $web site"
                 write-output $outputText
                 write-output $outputText |  out-File $logfile -Append
        }
    }
    else
    {
   
        $stream = [IO.File]::OpenRead($file.fullname)
        $destUrl = $web.Url + "/_catalogs/masterpage/" +$file.Name
        $masterPageFile=$web.GetFile($destUrl)
        if($masterPageFile.CheckOutStatus -ne "None")
          {
                $masterPageList.Files.Add($destUrl,$stream,$true)
                $stream.close()                       
                $masterPageFile.CheckIn($checkInComment);                       
                $masterPageFile.Publish($publishComment);               
                $masterPageFile.Approve($approveComment);
                $masterPageFile.Update();        
                $web.Update();
                $web.AllowUnsafeUpdates  = $false;
                $outputText = $file.Name +  "Master Page uploaded on $web site"
                write-output $outputText
                write-output $outputText |  out-File $logfile -Append
           }
           else
           {
                 $masterPageFile.CheckOut();
                 $masterPageList.Files.Add($destUrl,$stream,$true)
                 $stream.close()                             
                 $masterPageFile.CheckIn($checkInComment);                         
                 $masterPageFile.Publish($publishComment);                         
                 $masterPageFile.Approve($approveComment);
                 $masterPageFile.Update();        
                 $web.Update();
                 $web.AllowUnsafeUpdates  = $false;
                 $outputText = $file.Name+ "Master Page uploaded on $web site"
                 write-output $outputText
                 write-output $outputText |  out-File $logfile -Append
          }
    }      
}
catch
{
try
       {          
        $stream = [IO.File]::OpenRead($file.fullname)
        $destUrl = $web.Url + "/_catalogs/masterpage/" + $file.Name;
        $masterPageFile=$web.GetFile($destUrl)
        if($masterPageFile.CheckOutStatus -ne "None")
           {
                $masterPageList.Files.Add($destUrl,$stream,$true)
                $stream.close()                       
                $masterPageFile.CheckIn($checkInComment);
                $masterPageFile.Update();        
                $web.Update();
                $web.AllowUnsafeUpdates  = $false;
                $outputText = $file.Name+ " Master Page uploaded on $web site"
                write-output $outputText
                write-output $outputText |  out-File $logfile -Append
          }
          else
            {

               $masterPageFile.CheckOut();
               $masterPageList.Files.Add($destUrl,$stream,$true)
               $stream.close()                       
               $masterPageFile.CheckIn($checkInComment);
               $masterPageFile.Update();        
               $web.Update();
               $web.AllowUnsafeUpdates  = $false;
               $outputText = $file.Name +" Master Page uploaded on $web site"
               write-output $outputText
               write-output $outputText |  out-File $logfile -Append
           }
       }
    catch
       {
        write-Output $_ | out-File $logfile -Append
       }    
}
}
$web.dispose();
$spsite.dispose();

Tuesday, April 18, 2017

Sharepoint 2016 – Migration from Sharepoint 2015 – Upgrade Fail - Resolve Issue For–MissingWebPart , MissingAssembly , MissingSetupFile , MissingFeature

 

Add-PsSnapin Microsoft.SharePoint.PowerShell

$SqlServer = "DBServerName";
$SqlDatabase = "ContentDB";
$WebAppURL = "WebAppUrl";

Function MissingWebPart($Message)
        {
        $webparid = ((($Message -split "\[")[1]) -split "\]")[0];
        $webparid
        $testvalue = Run-SQLQuery -SqlServer $SqlServer -SqlDatabase $SqlDatabase -SqlQuery "SELECT Id, SiteId, DirName, LeafName, WebId, ListId, tp_ZoneID, tp_DisplayName from AllDocs inner join AllWebParts on AllDocs.Id = AllWebParts.tp_PageUrlID where AllWebParts.tp_WebPartTypeID = '$webparid'"
      
        Foreach($test in $testvalue )
        {
       
        if($test.SiteId)
        {
        $test
        $site = Get-SPSite -Limit all | where { $_.Id -eq  $test.SiteId }
        $web = $site | Get-SPWeb -Limit all | where { $_.Id -eq $test.WebId }
        $web.Url
        $file = $web.GetFile([Guid]$test.Id)
        $file.ServerRelativeUrl
        $file.delete()
        }
        }
        }
       
        Function MissingSetupFile($Message)
        {
        $SetupFileid = ((($Message -split "\[")[1]) -split "\]")[0];
        $SetupFileid
        $testvalue = Run-SQLQuery -SqlServer $SqlServer -SqlDatabase $SqlDatabase -SqlQuery "SELECT  Id,SiteId,DirName,LeafName,WebId,ListId from AllDocs where SetupPath = '$SetupFileid'"
        Foreach($test in $testvalue )
        {
        if($test.SiteId)
        {
        $test

        $site = Get-SPSite -Limit all | where { $_.Id -eq  $test.SiteId }
        $web = $site | Get-SPWeb -Limit all | where { $_.Id -eq $test.WebId }
        $web.Url
        $file = $web.GetFile([Guid]$test.Id)
        $file.ServerRelativeUrl
        $file.delete()
        }
        }
        }
       
        Function MissingFeature($Message)
        {
        $Featureid = ((($Message -split "\[")[2]) -split "\]")[0];
        $Featureid
        Remove-SPFeatureFromContentDB -ContentDB $SqlDatabase -FeatureId $Featureid
       
        }

        Function MissingAssembly($Message)
        {
        $Assemblyid = ((($Message -split "\[")[1]) -split "\]")[0];
        $Assemblyid
        $testvalue = Run-SQLQuery -SqlServer $SqlServer -SqlDatabase $SqlDatabase -SqlQuery "SELECT Id, Name, SiteId, WebId, HostId, HostType from EventReceivers where Assembly = '$Assemblyid'"
        #$testvalue
        Foreach($test in $testvalue )
        {
        if($test.SiteId)
        {
        $test
        $site = Get-SPSite -Limit all | where { $_.Id -eq  $test.SiteId }
        $web = $site | Get-SPWeb -Limit all | where { $_.Id -eq $test.WebId }
        $web.Url
        $list = $web.Lists | where {$_.Id -eq $test.HostId}
        $er = $list.EventReceivers | where {$_.Id -eq $test.Id}
        $er.Delete()
        #$file.delete()
        }
        }
        }

        function Remove-SPFeatureFromContentDB($ContentDb, $FeatureId, [switch]$ReportOnly)
        {
            $db = Get-SPDatabase | where { $_.Name -eq $ContentDb }
            [bool]$report = $false
            if ($ReportOnly) { $report = $true }
            $db.Sites | ForEach-Object {
                Remove-SPFeature -obj $_ -objName "site collection" -featId $FeatureId -report $report
                $_ | Get-SPWeb -Limit all | ForEach-Object {
                    Remove-SPFeature -obj $_ -objName "site" -featId $FeatureId -report $report
                }
            }
        }

        function Remove-SPFeature($obj, $objName, $featId, [bool]$report)
        {
            $feature = $obj.Features[$featId]
            if ($feature -ne $null) {
                if ($report) {
                    write-host "Feature found in" $objName ":" $obj.Url -foregroundcolor Red
                }
                else
                {
                    try {
                        $obj.Features.Remove($feature.DefinitionId, $true)
                        write-host "Feature successfully removed from" $objName ":" $obj.Url -foregroundcolor Red
                    }
                    catch {
                        write-host "There has been an error trying to remove the feature:" $_
                    }
                }
            }
            else {
                #write-host "Feature ID specified does not exist in" $objName ":" $obj.Url
            }
        }

            function Run-SQLQuery ($SqlServer, $SqlDatabase, $SqlQuery)
        {
            $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
            $SqlConnection.ConnectionString = "Server =" + $SqlServer + "; Database =" + $SqlDatabase + "; Integrated Security = True"
            $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
            $SqlCmd.CommandText = $SqlQuery
            $SqlCmd.Connection = $SqlConnection
            $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
            $SqlAdapter.SelectCommand = $SqlCmd
            $DataSet = New-Object System.Data.DataSet
            $SqlAdapter.Fill($DataSet)
            $SqlConnection.Close()
            $DataSet.Tables[0]
        }


Test-SPContentDatabase -Name $SqlDatabase -WebApplication $WebAppURL |
    ForEach-Object {
        $Category = $_.Category
        $Message = $_.Message
 
   if($Category -contains "MissingWebPart")
   {
   write-host "MissingWebPart"
   MissingWebPart $Message;
   }
   elseif ($Category -contains "MissingAssembly")
   {
    write-host "MissingAssembly"
    MissingAssembly $Message;
   }
   elseif ($Category -contains "MissingSetupFile")
   {
    write-host "MissingSetupFile"
    MissingSetupFile $Message;
   }

   elseif ($Category -contains "MissingFeature")
   {
    write-host "MissingFeature"
    MissingFeature $Message;
   }

    }

Wednesday, April 12, 2017

SharePoint 2016 - Zero-Downtime Patching - The biggest improvements

 

Disclaimer: this article only covers single aspects of the upgrade process. For a complete list of upgrade approaches including all details please check the following articles:

Patching SharePoint servers has always been a challenge. A major culprit for administrators is the fact that installing SharePoint fixes will cause downtime to the SharePoint farm. For SharePoint Server 2016 it was announced that we will have zero-downtime patching. This article intends to outline the reasons for downtimes with previous versions of SharePoint and the changes implemented in SharePoint Server 2016 to allow to perform zero-downtime patching including its constraints.

Historically this downtime can occur in two different steps:

  1. Installing the binaries
  2. Running the SharePoint configuration wizard.

Installing the binaries

While installing the actual binaries it is required to stop/restart SharePoint specific windows services and IIS websites to ensure that the updated files (e.g. dlls) are loaded.

The server specific downtime usually starts with running the hotfix executable till the hotfix installation is done.

With the huge hotfix files we are used to from SP2013 this can take several hours. Most of this time accounts for the extraction of the exe and cab file and then applying the various installer msp files which are included in the hotfix package.

Russ Maxwell has created a script which helps to significantly reduce the amount of time required to install the actual fixes but you will still experience a downtime on the specific server during the installation of the fix.

To overcome this issue we recommended to have high availability per role in your farm (at least two servers per role) to ensure that you can patch one server while the other one is online and continues to serve the requests. That means during patching you can remove one server from load balancing, patch it and add it back to load balancing. Then repeat the same steps for the other server(s).

While the patches are applied using this steps your farm will have servers with two different patch levels but that is fine as SharePoint will run in backward compatible mode if the database schema is older than the patch level of the servers in the farm.

So using redundant servers, you can achieve zero-downtime during the hotfix installation even with SharePoint 2013.

After the patch has been installed on all server you need to run the SharePoint configuration wizard.

Running the SharePoint configuration wizard

The SharePoint configuration wizard needs to be run on all machines in the farm to complete the hotfix installation.

You can use either the command line version (psconfig.exe) or the UI version (psconfigui.exe). I have discussed benefits and caveats of using the different methods in a separate article.

It is recommended to first run the configuration wizard on one of the app servers in the farm to perform the database upgrade. After this step is completed the configuration wizard can be started on all the other servers in the farm to perform the server specific upgrade operations (copy dlls, install features, apply security settings, …) on each of these servers (again you should remove the servers where psconfig is running from load balancing as services are restarted).

With SharePoint 2013 and before the database upgrade step will cause downtime on all servers in the farm as psconfig is updating databases which are used by all servers in the SharePoint farm. Depending on the specific updates applied to the database stored procedures, views, triggers and constraints could be dropped and recreated and other database content could be updated. SQL Queries issued by the SharePoint servers during this upgrade can fail if (e.g.) a stored procedure was called while the upgrade job was dropping it to replace it with an updated version or a fix contains (e.g.) two different changes to two different stored procedures where the changes depend on each other but only one stored proc was updated when the request comes in.

These limitations could also cause failed upgrades or excessive slowdowns in the upgrade process because of resource contention and locking. For these reasons accessing SharePoint content while the database is upgraded is unsupported and untested.

A partial workaround for this exists in SharePoint 2013 for updating the content database: After installing the patch and before running the SharePoint configuration wizard customers can run

Upgrade-SPContentDatabase -UseSnapshot …

Upgrade-SPContentDatabase can perform the same upgrade for a content database as the SharePoint configuration wizard. The benefit of using this Cmdlet is that you can run it in parallel in several powershell windows against different content databases. That can help to significantly reduce the database upgrade time after installing a hotfix as it allows to upgrade several content databases in parallel. The SharePoint configuration wizard would upgrade the content databases sequentially one after the other.

Another benefit is the -UseSnapshot parameter listed above.

This parameter will create a snapshot of the specified database and then perform all upgrade operations that apply to the database. Existing connections to the content database from the different SharePoint servers in the farm will be set to use the snapshot for the duration of the upgrade, and then switched back after successful completion of upgrade. Be aware that this parameter can only be used with versions of SQL Server that support creation and use of snapshots, for example, SQL Server Enterprise edition.

As all regular SharePoint operations are executed against the snapshot while the content database is upgraded the problems listed above will not occur. The caveat here is that the snapshot is read-only. That means although it prevents the above listed problems related to dropping stored procedures while they are in use they will prevent all write operations to the SQL database.

After upgrading the SharePoint content databases you still have to run the SharePoint configuration wizard to upgrade all the other SharePoint databases – and this can also cause downtime to services accessing these databases during the upgrade.

So it is not possible to achieve zero-downtime for read-write operations during the hotfix installation with SharePoint 2013.

 

Changes in SharePoint Server 2016

With SharePoint Server 2016 the amount of MSP files has been significantly reduced. This will ensure that the time to patch the servers will be much shorter. Aside of that you still have to ensure that you have more than one server per role (high availability) to guarantee zero-downtime patching as the windows services have to be restarted during patching. MinRole is not required for this! All the details on how to technically apply the patches can be found in the following Technet article:

The biggest improvements over SP2013 are on the upgrade side. Several improvements have been made to ensure that upgrading the SharePoint databases does not lead to a downtime for the end user. These changes include changes on how the changes are applied but also restricting what changes are allowed to be done in a hotfix request. E.g. all stored procedures have to be backward compatible to ensure that if one stored procedure is updated with a hotfix it can still be called from older stored procedures which are updated through a later step in the update cycle. We also update the stored procedures without dropping them to prevent outages if a stored proc is called while it is in the limbo state between drop and recreation.

These changes are long tested in SharePoint online where upgrades are performed for all SharePoint online servers every couple of weeks while the service is live without any read-only windows for customers.

These improvements apply as well to content databases and to other SharePoint databases that need to be upgraded. You can still use Upgrade-SPContentDatabase to speed up the database upgrade step but using the -SnapShot parameter will not bring a benefit when trying to minimize the downtime. It can actually be counter-productive as it leads to a read-only content database.

With the improvements implemented and using redundant servers for each role it is possible to achieve zero-downtime during the hotfix installation with SharePoint Server 2016.

Monday, April 3, 2017

Sharepoint - The feature with Id ‘GUID’ is referenced in the database ‘Content DB’ ,but is not installed on the current farm. The missing feature may cause upgrade to fail. Please install any solution which contains the feature and restart upgrade if necessary

 

Solution

The great thing about the Health Analyzer in SharePoint 2010 is that it will report on a number of potential issues with the server farm, which may cause a problem later whilst applying a cumulative update or service pack. Resolving these issues in advance will help to prevent an update failing when you run the SharePoint Configuration Wizard.

One of these problems may occur when a solution is removed from the farm before the corresponding features were deactivated from site collections and sites. The Health Analyzer will place this issue in the “Configuration” category with the title “Missing server side dependencies”.

Missing server side dependencies

The following PowerShell script will interrogate a specified content database and feature ID and do two things:

  1. Produce a report in the PowerShell console showing which sites or site collections contain the offending feature.
  2. Forcibly deactivate the feature from the applicable sites or site collections.

To use the script, run these functions in a PowerShell console with the SharePoint 2010 add-ons loaded:

function Remove-SPFeatureFromContentDB($ContentDb, $FeatureId, [switch]$ReportOnly)
{
    $db = Get-SPDatabase | where { $_.Name -eq $ContentDb }
    [bool]$report = $false
    if ($ReportOnly) { $report = $true }
    $db.Sites | ForEach-Object {
        Remove-SPFeature -obj $_ -objName "site collection" -featId $FeatureId -report $report
        $_ | Get-SPWeb -Limit all | ForEach-Object {
            Remove-SPFeature -obj $_ -objName "site" -featId $FeatureId -report $report
        }
    }
}

function Remove-SPFeature($obj, $objName, $featId, [bool]$report)
{
    $feature = $obj.Features[$featId]
    if ($feature -ne $null) {
        if ($report) {
            write-host "Feature found in" $objName ":" $obj.Url -foregroundcolor Red
        }
        else
        {
            try {
                $obj.Features.Remove($feature.DefinitionId, $true)
                write-host "Feature successfully removed from" $objName ":" $obj.Url -foregroundcolor Red
            }
            catch {
                write-host "There has been an error trying to remove the feature:" $_
            }
        }
    }
    else {
        #write-host "Feature ID specified does not exist in" $objName ":" $obj.Url
    }
}

You now have two options for using these functions. If you just want to produce a report in the console showing which sites and site collections contain the feature, type the following (note the ReportOnly switch on the end):

Remove-SPFeatureFromContentDB -ContentDB "SharePoint_Content_Portal" -FeatureId "8096285f-1463-42c7-82b7-f745e5bacf29" –ReportOnly

This command will step through all sites and site collections and display the following message whenever it finds the feature specified:

Feature found in site : http://portal/site

If you want to go ahead and remove the feature from all sites and site collections in the content database, type the same command without the ReportOnly switch on the end:

Remove-SPFeatureFromContentDB -ContentDB "SharePoint_Content_Portal" -FeatureId "8096285f-1463-42c7-82b7-f745e5bacf29"

Running this command will step through all sites and site collections, remove the feature specified, and display the following output:

Feature successfully removed from site : http://portal/site

You should now be able to reanalyse the “Missing server side dependencies” issue in the Health Analyzer to clear the problem (providing there are no other issues reported under that title, of course!).

Friday, March 31, 2017

SQL Server - SQL Server Management Studio for SQL Server 2016?

 

The option on the SQL Server 2016 Installation Center takes you to a web download. You can also download the SQL Server at Download SQL Server Management Studio (SSMS). After the download has completed you can run the installation standalone without a connection to the Internet.

Thursday, March 30, 2017

PowerShell - Enumerates through all site collections for a given web application, then enumerates through all subsites within each site collection and deactivate the given web level feature

 

Add-PsSnapin Microsoft.SharePoint.PowerShell

## SharePoint DLL

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$webApplicationURL = "webApplicationURL"

$webApp = Get-SPWebApplication $webApplicationURL

$featurefolder = "FollowingContent"

if($webApp -ne $null)

{

foreach($site in $webApp.Sites)

{

if($site -ne $null)

{

foreach($subWeb in $site.AllWebs)

{

      if($subWeb -ne $null)

      {

           Try

           {

           Disable-SPFeature -identity $featurefolder -Confirm:$false –URL  $subWeb.url -ErrorAction Stop

            Write-Output $subWeb " : Following Content Feature is Deactivated"

           }

          Catch

          {

          Write-Output $subWeb " : already Deactivated"

          }

    $subWeb.Dispose()

}

}        

$site.Dispose()

}}}

Remove-PsSnapin Microsoft.SharePoint.PowerShell

PowerShell – Download installed farm solution in SharePoint , Remove Orphaned installed Farm Feature

 

Download installed farm solution in

Add-PsSnapin Microsoft.SharePoint.PowerShell

$frm = Get-SPFarm

$file = $frm.Solutions.Item("wsp").SolutionFile

$file.SaveAs("D:\Wsps\wsp")

Remove Orphaned installed Farm Feature

In Power Shell run below command and get feature IDs

$feature = Get-SPFeature | ? { $_.Scope -eq $null }

$feature

In Command prompt run the sts command and remove that feature by its id.

cd C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\BIN

stsadm -o uninstallfeature –id <GUID> -force

Tuesday, March 28, 2017

Sharepoint - Search - Error while crawling LOB contents. ( Database Connector has throttled the response. The response from database contains more than '2000' rows. The maximum number of rows that can be read through Database Connector is '2000'. The limit can be changed via the 'Set-SPBusinessDataCatalogThrottleConfig' cmdlet. )

 

Solution

$bcs = Get-SPServiceApplicationProxy | where{$_.GetType().FullName -eq (‘Microsoft.SharePoint.BusinessData.SharedService.’ + ‘BdcServiceApplicationProxy’)}

$BCSThrottle = Get-SPBusinessDataCatalogThrottleConfig -Scope database -ThrottleType items -ServiceApplicationProxy $bcs

$BCSThrottle

Set-SPBusinessDataCatalogThrottleConfig -Identity $BCSThrottle -Maximum 1000000 -Default 400000

$BCSThrottle = Get-SPBusinessDataCatalogThrottleConfig -Scope database -ThrottleType items -ServiceApplicationProxy $bcs

$BCSThrottle

Friday, March 24, 2017

Windows Server - UAC Folder problem - "Access is Denied" as Windows Administrator - Domain Administrators permissions

 

Solution -

regedit - HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUE=0 worked for me to resolve this.

Friday, March 17, 2017

SharePoint 2016 - New-SPConfigurationDatabase Server role parameter is required when creating or joining a farm

 

While installing SharePoint 2016, I got the below error which says New-SPConfigurationDatabase Server role parameter is required when creating or joining a farm. The error comes when I run New-SPConfigurationDatabase through SharePoint 2016 Management Shell

While installing SharePoint 2016, I got the below error which says New-SPConfigurationDatabase Server role parameter is required when creating or joining a farm. The error comes when I run New-SPConfigurationDatabase through SharePoint 2016 Management Shell

Solution:

In SharePoint Server 2016 MinRole you need to give while installing, this can be used to specify the role that should be assigned to a specific server when configuring SharePoint Products and Technologies. The MinRole can be like below:

New-SPConfigurationDatabase –DatabaseName SharePoint_Config –DatabaseServer WIN-JC2B1V15KM5 –AdministrationContentDatabaseName SharePoint_Content –Passphrase (ConvertTo-SecureString ‘Passphrase’ –AsPlaintext –Force) –FarmCredentials (Get-Credential) -localserverrole SingleServerFar

Here -localserverrole SingleServerFarm is the main parameter. 

Hope this will be helpful.

Monday, March 13, 2017

C# - Client Object model to Delete the file, upload file , Check in and Publish it in to sharepoint Document library

 

 

    string FileName = Path.GetFileName(“FileLocation”");
    string docLibName = "Site Collection Documents";
    string spPath = siteUrl + "/SiteCollectionDocuments/SaleRanking.xlsx";

    // get the server relative URL
    Uri filename = new Uri(@spPath);
    string server = filename.AbsoluteUri.Replace(filename.AbsolutePath, "");
    string serverrelative = filename.AbsolutePath;

    try
    {      
            Microsoft.SharePoint.Client.File f = null;
            SP.ClientContext ctx = new SP.ClientContext(siteUrl);
            Web web = ctx.Web;
            List docs = web.Lists.GetByTitle(docLibName);
            f = web.GetFileByServerRelativeUrl(serverrelative);
            ctx.Load(f);
            f.DeleteObject();ctx.ExecuteQuery(); // Delete file here but throw Exception       
            ctx.ExecuteQuery(); // Delete file here but throw Exception
           
            FileCreationInformation newFile = new FileCreationInformation();
            newFile.Content = System.IO.File.ReadAllBytes(@FileLocation);
            newFile.Url = spPath;
            Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
            ctx.Load(uploadFile);
            ctx.ExecuteQuery(); // Add new file here    

            f.CheckIn(string.Empty, CheckinType.MajorCheckIn);  // Check in File
            ctx.ExecuteQuery(); // Check in File             

             f.Publish("file published");
             ctx.ExecuteQuery(); // Publish File 

      }catch (Exception ex)   {
      }

Wednesday, March 8, 2017

Powershell - Update web config file from all servers under farm

 

- Take back up of Existing Web Config

- Check if appSettings node is there then throw exception

- If property node is then delete it and recreate with new node.

 

Add-PSSnapin Microsoft.SharePoint.PowerShell
$serverInfo = get-spserver | ? { $_.Role -eq "Application" }
$serverInfo.Name
#$Folderpath = '\C$\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\WebServices\SecurityToken';
$Folderpath ='\C$\inetpub\wwwroot\wss\VirtualDirectories\'

$webappName = @("abc443\")
$PropertyName = @("HostName","PortNumber)
$PropertyValue = @("abc","636)

for($j=0 ; $j -lt $serverInfo.count ; $j++)
{
        write-host*****************************"  -foreground Green
        write-host " Server :  " + $serverInfo[$j].Name -foreground Green
        write-host "*************************************************" -foreground Green
  
    for($i=0 ; $i -lt $webappName.count ; $i++)
        { 
        $path = '\\'+$serverInfo[$j].Name + $Folderpath
        write-host $path
        $webConfig = $path+$webappName[$i]+'Web.config'
        write-host "Updatng Web Config for " + $webConfig
        if(Test-Path $webConfig -PathType Any)
        {
            $backup = $path+$webappName[$i]+ 'web_'+ (get-date).tostring("yyyy_MM_dd_hh_mm_ss")+'.bak';
            write-host "Taking Back up for Web Config "   +  $backup -foreground Green
            copy-item $webConfig -destination $backup

            for($k=0 ; $k -lt $PropertyName.count ; $k++)
                {
                Set-ApplicationSettingConfigProperty $webConfig $PropertyName[$k] $PropertyValue[$k] ;
                Function Set-ApplicationSettingConfigProperty
                {
                    param (
                        [parameter(Mandatory = $true)][ValidateScript ({Test-Path $_})][string] $PathToConfigFile,
                        [parameter(Mandatory = $true)][string] $PropertyName,
                        [parameter(Mandatory = $true)][string] $PropertyValue,
                        [Parameter(Mandatory = $false)][Validatescript ({(Get-Service $_) -ne $null})][string] $NameOfServiceToRestart = $null)
   

                    $configurationAppSettingXmlPath = "//configuration/appSettings"

                    [xml] $configurationDocument = Get-Content $PathToConfigFile
                    $appSettingsNode = $configurationDocument.SelectSingleNode($configurationAppSettingXmlPath)
   
                    if($appSettingsNode -eq $null)
                    {
                       # $(throw "App Settings Does not Exists! Invalid Configuration File.")
                       write-host "App Settings Does not Exists! Invalid Configuration File." -foreground red
                    }

                    $nodeToUpdate = $configurationDocument.SelectSingleNode($configurationAppSettingXmlPath+"/add[@key='$PropertyName']")
                    if($nodeToUpdate -ne $null)
                    {
                        Write-Host "[$PropertyName] Already exists, Removing it to re-set its value." -foreground red
                        $removedElement = $appSettingsNode.RemoveChild($nodeToUpdate)
                    }

                    Write-Host "Creating new Configuration Node." -foreground Green
                    $newPropertyNode = $configurationDocument.CreateNode("element", "add","")
                    $newPropertyNode.SetAttribute("key", $PropertyName)
                    $newPropertyNode.SetAttribute("value", $PropertyValue)
                    $appSettingsNode = $configurationDocument.SelectSingleNode($configurationAppSettingXmlPath).AppendChild($newPropertyNode)
                    Write-Host "Adding new property into the configuration file."  -foreground Green
                    $configurationDocument.Save($PathToConfigFile)
                    Write-Host "Property was Successfully Updated." -foreground Yellow
                    Write-Host "---------------------------------------------------------------------------" -foreground Yellow
                    Write-Host "---------------------------------------------------------------------------" -foreground Yellow

                    if([string]::IsNullOrWhiteSpace($NameOfServiceToRestart) -eq $false)
                    {
                        Write-Host "Service [$NameOfServiceToRestart] was defined.., Restarting it"
                        Restart-Service -Name $NameOfServiceToRestart
                        Write-Host "Service was Restarted..."
                    }
                }
            }
        }
    }
}