February 14, 2013

Link Custom Fields and Content Types Back to Custom List Definition in SharePoint 2010

If you are interested in how to link your custom fields and content types that are generated through a custom list definition (schema.xml), please contact me and I will send you the program, I will update this post with the actual details as soon as I fully test my little tool.

image

August 16, 2012

PowerShell: Rename a SharePoint 2010 Content Database

This script will Dismount –> Rename the SQL Database –> Mount again, all in one step while preserving the following information:

  • Web Application
  • Database Server alias being used (if any different)
  • Max sites count
  • Warning sites count
# Created by Dennis Alzoubi    
# Version 1.6
# Last Updated 8/16/2012 11:35 am
# Purpose: Rename a SharePoint content database
param([Parameter(Position=0, Mandatory=$true, HelpMessage="Name of the content database to rename")][string]$databaseName,
      [Parameter(Position=1, Mandatory=$true, HelpMessage="New name for the content database")][string]$newDatabaseName)
      
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
    Write-Host 'Reading in SharePoint SnapIn'
    Add-PsSnapin Microsoft.SharePoint.PowerShell;
}
 
#Load the assemblies required for the SQL database rename.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") 
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended")
 
#Method that renames the Database in SQL
function RenameDatabase($dbServerName, $oldDatabaseName, $newDatabaseName)
{
    try
    {
        Write-Host "Getting SQL server information" -foregroundcolor "Yellow"
        $srv = new-Object Microsoft.SqlServer.Management.Smo.Server($dbServerName)
        Write-Host "Getting database information" -foregroundcolor "Yellow"
        $db = $srv.Databases.Item($oldDatabaseName)
        Write-Host "Killing all active connections to the SQL database" -foregroundcolor "Yellow"
        $srv.KillAllprocesses($oldDatabaseName)
        Write-Host "Renaming the database" -foregroundcolor "Yellow"
        $db.Rename($newDatabaseName)
    }
    catch
    {
        Write-Error "Error in 'RenameDatabase'"
        Write-Error $_.Exception.Message
    }
}
 
Write-Host "Getting the content database to Rename" -foregroundcolor "Yellow"
$contentDB = Get-SPContentDatabase | Where-object {$_.Name -eq $databaseName}
 
Write-Host "Getting the content database settings to preserve" -foregroundcolor "Yellow"
$webApp = $contentDB.WebApplication.Url
$dbServer = $contentDB.Server
$maxSites = $contentDB.MaximumSiteCount
$warningSites = $contentDB.WarningSiteCount
 
try
{
    Write-Host Dismounting $databaseName -foregroundcolor "Yellow"
    Dismount-SPContentDatabase $databaseName -Confirm:$False
 
    Write-host Renaming Database: $databaseName to $newDatabaseName -foregroundcolor "Yellow"
    RenameDatabase $dbServer $databaseName $newDatabaseName
 
    Write-host Mounting Database: $newDatabaseName -foregroundcolor "Yellow"
    Mount-SPContentDatabase -Name $newDatabaseName -WebApplication $webApp -DatabaseServer $dbServer -MaxSiteCount $maxSites -WarningSiteCount $warningSites | out-null
}
catch
{
    Write-Error "Error in 'Process'"
    Write-Error $_.Exception.Message
}
finally
{
    Write-Host "Press any key to continue ..."
    $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}

Let me know if you have any comments or like it to preserve any other information, I can always tweak it Smile

August 6, 2012

SharePoint 2010: Set Default Ribbon Tab on Page Load

Say you need to set the default Ribbon tab when page is loaded, and you want to do it in code-behind, this is how it is accomplished, in your Page_Load method for SharePoint page being rendered:

if (Request.QueryString["InitialTabId"] == null)
{
    var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
    nameValues.Set("InitialTabId", SPRibbon.ReadTabId);
    Response.Redirect(string.Format("{0}?{1}", Request.Url.AbsolutePath, nameValues));
}

This will make sure the browse tab is selected by default on page load. Nice and quick! If you know of a better way to do it from code, please let me know, as I have tried the InitialTabId stuff from MSDN and it didn’t work for me.

July 17, 2012

SharePoint 2010 Custom List: Duplicate Columns with Same ID!

Background

I have a SharePoint 2010 site with a custom list (build in Visual Studio with a custom content type). This site has been migrated from SharePoint 2007.

Issue

After the migration, I noticed that the list has duplicate fields:

image

Looking at the content type, I can see that there are duplicate fields in there:
782fda9b-db6f-4f19-9e4a-2eefe8bd49e0    ParentFolder
7fb88270-d7cb-45b0-9fd1-5118b6441587  FolderPath
7fb88270-d7cb-45b0-9fd1-5118b6441587  FolderPath
d5a17075-45bf-4ef5-83dd-057d771755cb  SortOrder
d5a17075-45bf-4ef5-83dd-057d771755cb  SortOrder

The weird thing is that the content type has Field links with the same ID and internal name, how is that even possible?!!

Trying to hide one of the fields hides both, what the heck!

Solution

After a few failed tries, I decided to delete the FieldLink in the content type and readding them, so I used PowerShell:

$web = Get-SPWeb http://gtnahoui948/fg/cmg
$list = $web.Lists["Contract Structure"]
$cType = $list.ContentTypes["Folder Structure Item"]
$cType.FieldLinks.Delete("FolderPath")
$cType.Update()
$cType.FieldLinks.Delete("SortOrder")
$cType.Update()


After running the above code in PowerShell, I checked the FieldLinks and found out it only deleted the duplicates and kept one instance in the FieldLinks, Awesome!


782fda9b-db6f-4f19-9e4a-2eefe8bd49e0    ParentFolder
7fb88270-d7cb-45b0-9fd1-5118b6441587  FolderPath
d5a17075-45bf-4ef5-83dd-057d771755cb  SortOrder


That being said; no need to add the links again Smile

July 12, 2012

SharePoint PowerShell Script: Deploy WSP Solution

# Created by Dennis Alzoubi    
# Version 1.1
# Last Updated 6/18/2012 8:34 am
# Purpose: Deploys a new solution to the specified web application. If solution already exists, it updates it.
param([Parameter(Position=0, Mandatory=$true, HelpMessage="Url of Web Application. 'All' for All Web Applications)")][string]$WebAppUrl, 
      [Parameter(Position=1, Mandatory=$true, HelpMessage="Name of Solution")][string]$WspName)
 
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
    Write-Host 'Reading in SharePoint SnapIn'
    Add-PsSnapin Microsoft.SharePoint.PowerShell;
}
 
function WaitForSPSolutionJobToComplete([string]$solutionName)
{
    $solution = Get-SPSolution -Identity $solutionName -ErrorAction SilentlyContinue
    if ($solution)
    {
        if ($solution.JobExists)
        {
            Write-Host -NoNewLine "Waiting for timer job to complete for solution '$solutionName'."
        }
        # 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
            }    
            # Otherwise wait for the timer job to finish
            Write-Host -NoNewLine "."
            Sleep 1
        }    
        # Write a new line to the end of the '.....'
        Write-Host
    }    
    return $true
}
 
Write-Host 'Checking to see if solution is already deployed'
$farm = Get-SPFarm
$solutions = $farm.Solutions
$exists = $false
 
foreach ($solution in $solutions)
{
    if ($solution.Name -eq $WspName)
    {
        $exists = $true
        break
    }
}
 
if ($exists)
{
    $location = Get-Location
    Write-Host Updating $WspName
    Update-SPSolution -Identity $WspName -LiteralPath "$location\$WspName" -GACDeploym
}
else
{    
    Write-Host Adding $WspName
    Add-SPSolution -LiteralPath $WspName
    
    Write-Host Installing $WspName
    if ($WebAppUrl -eq 'All')
    {
        Install-SPSolution -Identity $WspName –GACDeployment -AllWebApplications
    }
    else
    {
        Install-SPSolution -Identity $wspName –GACDeployment -WebApplication $WebAppUrl
    }
}
WaitForSPSolutionJobToComplete $wspName
 
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")