HowTo: Copy discussions to a new discussion board

Scenario:
You want to copy all discussions from a discussion board to another

PowerShell script:

#Copy discussions to a new discussion board

$web = Get-SPWeb "http://sharepoint.com"
$sourceList = $web.GetList("http://sharepoint.com/Lists/OldDiscussions/AllItems.aspx")
$destinationList = $web.GetList("http://sharepoint.com/Lists/NewDiscussions/AllItems.aspx")

$sourceListItems = $sourceList.Folders

foreach($item in $sourceListItems)
{
 $title = $item['Title']
 write-host "Copying $title"
 #Get desired discussion by ID
 $sourceDiscussion = $sourceList.Folders | Where-Object {$_.ID -eq $item['ID']}

 #Add new discussion to destination list
 $destinationDiscussion = [Microsoft.SharePoint.Utilities.SPUtility]::CreateNewDiscussion($destinationList.Items, $sourceDiscussion.Title)

 #Copy field values
 $destinationDiscussion["Body"] = $sourceDiscussion["Body"]
 $destinationDiscussion["Author"] = $sourceDiscussion["Author"]
 $destinationDiscussion["Editor"] = $sourceDiscussion["Editor"]
 $destinationDiscussion["Modified"] = $sourceDiscussion["Modified"]
 $destinationDiscussion["Created"] = $sourceDiscussion["Created"]
 
 #Copy attachments
 $attachmentCollection = $sourceDiscussion.Attachments
 $folder = $web.GetFolder($attachmentCollection.UrlPrefix);
 foreach ($file in $folder.Files) {
  $fileName = $file.Name
  $bytes = $file.OpenBinary() 
  $filePath = "$webURL/$folder/$fileName"
  $destinationDiscussion.Attachments.Add([System.IO.Path]::GetFileName($filePath), $bytes);
 }  
 
 #Add discussion
 $destinationDiscussion.SystemUpdate($false)

 #Get all discussion messages
 $caml='<Where><Eq><FieldRef Name="ParentFolderId" /><Value Type="Integer">{0}</Value></Eq></Where>' -f $sourceDiscussion.ID
 $query = new-object Microsoft.SharePoint.SPQuery
 $query.Query = $caml
 $query.ViewAttributes = "Scope='Recursive'";
 $sourceMessages = $sourceList.GetItems($query)

 foreach ($sourceMessage in $sourceMessages) {
  #Add new message to discussion
  $destinationMessage = [Microsoft.SharePoint.Utilities.SPUtility]::CreateNewDiscussionReply($destinationDiscussion)
  
  #Copy field values
  $destinationMessage["Body"] = $sourceMessage["Body"]
  $destinationMessage["TrimmedBody"] = $sourceMessage["TrimmedBody"]
  $destinationMessage["Author"] = $sourceMessage["Author"]
  $destinationMessage["Editor"] = $sourceMessage["Editor"]
  $destinationMessage["Modified"] = $sourceMessage["Modified"]
  $destinationMessage["Created"] = $sourceMessage["Created"]

  #Copy attachments
  $attachmentCollection = $sourceMessage.Attachments
  $folder = $web.GetFolder($attachmentCollection.UrlPrefix);
  foreach ($file in $folder.Files) {
   $fileName = $file.Name
   $bytes = $file.OpenBinary() 
   $filePath = "$webURL/$folder/$fileName"
   $destinationMessage.Attachments.Add([System.IO.Path]::GetFileName($filePath), $bytes);
  }
  
  #Add message
  $destinationMessage.SystemUpdate($false)

 }

}
write-host 'Done'

Note:
If you have created additional column you will have to add them to the script. Also make sure the columns in the script are present in both discussion boards.

Fix: The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered.

Scenario:
Trying to run a PowerShell script you get the following error:
The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered.

Fix:
Run this PowerShell script:

Add-SPShellAdmin -username domain\user

Note:
Sometimes the fix is required although the Get-SPShellAdmin command returns the user as having shell admin privileges. It could be the case that not all the farm servers are in sync.

Fix: workflow does not start triggered by incoming email

Scenario:
Your SharePoint designer workflow is triggered by the creation of a new item through UI but not by the receiving of an email (which also creates a new item).

Script / Fix:

stsadm -o setproperty -pn declarativeworkflowautostartonemailenabled -pv true
Note:
You can also check the state of the declarativeworkflowautostartonemailenabled flag by running this command:
stsadm -o getproperty -pn declarativeworkflowautostartonemailenabled

Fix: cannot login to host-named site collection

Scenario:
You cannot login into a host-named site collection (SharePoint will prompt you for login over and over) while you can login to a non-host-names site collection on the same server.

Fix:

Update the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0\BackConnectionHostNames registry entry:
  1. Click Start, click Run, type regedit, and then click OK.
  2. In Registry Editor, locate and then click the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
  3. Right-click MSV1_0, point to New, and then click Multi-String Value. Type BackConnectionHostNames, and then press ENTER.
  4. Right-click BackConnectionHostNames, and then click Modify.
  5. In the Value data box, type the host name or the host names for the sites that are on the local computer, and then click OK.
You may need to restart IIS.

Fix: The password supplied with the username ... was not correct. Verify that it was entered correctly and try again.

Scenario:
Trying to create a new web application fails with this message:
The password supplied with the username ... was not correct. Verify that it was entered correctly and try again.


Fix:
run this script:
stsadm -o updatefarmcredentials -userlogin <domain\username> -password <newpassword>

Note:
I just changed my windows account password and that may have triggered the issue.

Fix: No document templates uploaded for list "$Resources:core,MasterPageGallery;" -- none found for list template "100".

Scenario:
In SharePoint 2010, trying to create a Publishing Site with Workflow fails with this message:




The error logged is a bit more descriptive but not really helping:
No document templates uploaded for list "$Resources:core,MasterPageGallery;" -- none found for list template "100".

Fix:
Activate the "SharePoint Server Publishing Infrastructure" feature at the site collection level.
If the feature is active, deactivate it and then activate it again.


FIX: Coercion Failed: Unable to transform the input lookup data into the requested type.

Scenario:
When trying to set a lookup field value in a sharepoint designer workflow you get this error:
Coercion Failed: Unable to transform the input lookup data into the requested type.

Background:
In a sharepoint blog site I wanted to add the post category field to the comments list in a column called PostCategory (lookup on categories). I chose to use a workflow for this task. The workflow is triggered on item creation and update.

Here is the simple worklfow I have created:




The key is the "Return field as" field in the last dialogue box. I was getting the Coercion Failed error when setting the field type as integer. Setting it to lookup id (as integer) solved the problem.

How to: Open SharePoint page in edit mode

Scenario:
Open the page in edit mode by adding some query string parameters to the url

Simply append the following to the URL:

?ToolPaneView=2&pagemode=edit

Your url:
http://site:port/web/page.aspx

... will become:
http://site:port/web/page.aspx?ToolPaneView=2&pagemode=edit

The page will open in edit mode with the "Add Web Parts" web part visible.

FIX: Deployment was not performed for this project because it is a dependent project

Scenario:
Trying to deploy multiple SharePoint solutions from Visual Studio you are getting the following error:
Deployment was not performed for this project because it is a dependent project

You probably have a helper/utility project defined SharePoint project but with an empty package:




Fix:
Open the Configuration Manager (right click on the solution file in Solution Explorer and select Configuration Manager ...)
Clear the Deploy checkbox for your project.

FIX: Error MSB4018: The "ValidatePackage" task failed unexpectedly. The project service does not contain the specified project.

Scenario:
Your SharePoint solution build fails with this error:
The "ValidatePackage" task failed unexpectedly.
The project service does not contain the specified project.
and the GUID provided is the ID of the project you are trying to build

Build log:

...

  CopyFilesToOutputDirectory:
  Copying file from "obj\Debug\Helpers.dll" to "D:\Builds\Binaries\Helpers.dll".
  Helpers -> D:\Builds\Binaries\Helpers.dll
  Copying file from "obj\Debug\Helpers.pdb" to "D:\Builds\Binaries\Helpers.pdb".
(...): error MSB4018: The "ValidatePackage" task failed unexpectedly. [D:\Builds\SPTest\Helpers\Helpers.csproj]
(...): error MSB4018: System.InvalidOperationException: The project service does not contain the specified project: 618318f6-eff6-4fa9-9b39-3a9a6febb01b. [D:\Builds\SPTest\Helpers\Helpers.csproj]
(...): error MSB4018:    at Microsoft.VisualStudio.SharePoint.Tasks.ValidatePackage.OnCheckParameters() [D:\Builds\SPTest\Helpers\Helpers.csproj]
(...): error MSB4018:    at Microsoft.VisualStudio.SharePoint.Tasks.BuildTask.Execute() [D:\Builds\SPTest\Helpers\Helpers.csproj]
(...): error MSB4018:    at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute() [D:\Builds\SPTest\Helpers\Helpers.csproj]
(...): error MSB4018:    at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__20.MoveNext() [D:\Builds\SPTest\Helpers\Helpers.csproj]
Done Building Project "D:\Builds\SPTest\Helpers\Helpers.csproj" (default targets) -- FAILED.

...

Fix C#:
Open the *.csproj in a text editor.
look for the <ProjectTypeGuids> entry and make sure the following guids are listed there:
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    ...
    <ProjectTypeGuids>{BB1F664B-9266-4fd6-B973-E1E44974B511};{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    ...
  </PropertyGroup>
  ...
</Project>

Fix VB.NET:
Open the *.vbproj in a text editor.
look for the <ProjectTypeGuids> entry and make sure the following guids are listed there:
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    ...
    <ProjectTypeGuids>{BB1F664B-9266-4fd6-B973-E1E44974B511};{D59BE175-2ED0-4C54-BE3D-CDAA9F3214C8};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>
    ...
  </PropertyGroup>
  ...
</Project>
Note:
The above guids identify these project types:

{BB1F664B-9266-4fd6-B973-E1E44974B511} – SharePoint 2011 project
{C1CDDADD-2546-481F-9697-4EA41081F2FC} – SharePoint 2013 project
{14822709-B5A1-4724-98CA-57A101D1B079} – Workflow C# project
{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} – C# project
{D59BE175-2ED0-4C54-BE3D-CDAA9F3214C8} - Workflow VB.NET project
{F184B08F-C81C-45F6-A57F-5ABD9991F28F} - VB.NET project

FIX: Error occurred in deployment step 'Recycle IIS Application Pool': Exception has been thrown by the target of an invocation.

Scenario:
Trying to deploy a SharePoint 2010 solution from Visual Studio 2012 you get this error:
Error occurred in deployment step 'Recycle IIS Application Pool': Exception has been thrown by the target of an invocation.

Output:

------ Deploy started: Project: Helpers, Configuration: Debug Any CPU ------
Deployment was not performed for this project because it is a dependent project.
------ Deploy started: Project: SiteColumns, Configuration: Debug Any CPU ------
Active Deployment Configuration: No Activation
Run Pre-Deployment Command:
  Skipping deployment step because a pre-deployment command is not specified.
Recycle IIS Application Pool:
Error occurred in deployment step 'Recycle IIS Application Pool': Exception has been thrown by the target of an invocation.
========== Build: 1 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
========== Deploy: 1 succeeded, 1 failed, 0 skipped ==========

Background:
I am referencing some DLL files located in the "..\..\Binaries\Sharepoint" custom folder (this section in the *.csproj was generated by Visual Studio when I added references through the UI):
  <ItemGroup>
    <Reference Include="Microsoft.SharePoint.Linq, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
      <HintPath>..\..\Binaries\SharePoint\Microsoft.SharePoint.Linq.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
      <HintPath>..\..\Binaries\SharePoint\Microsoft.SharePoint.Publishing.dll</HintPath>
    </Reference>
    ...
  </ItemGroup>

Fix:
I removed the highlighted parts of the *.csproj above (version, culture, public key token and processor architecture), ending up with this:
  <ItemGroup>
    <Reference Include="Microsoft.SharePoint.Linq">
      <HintPath>..\..\Binaries\SharePoint\Microsoft.SharePoint.Linq.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.SharePoint.Publishing">
      <HintPath>..\..\Binaries\SharePoint\Microsoft.SharePoint.Publishing.dll</HintPath>
    </Reference>
    ...
  </ItemGroup>

FIX: 'XSLT compile error' on host-named site collection

Scenario:
On your host-named site collection you are trying to reference an XSLT file hosted in a SharePoint Library.
Assuming you have already checked that the xslt file is where it is expected to be.

Your code could look like this:

XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = CredentialCache.DefaultCredentials;

XmlTextReader stylesheet = new XmlTextReader(xslLink);
stylesheet.XmlResolver = resolver;

XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(stylesheet);

On the last line you are getting this error:
XSLT compile error.
   at System.Xml.Xsl.Xslt.XsltLoader.LoadStylesheet(XmlReader reader, Boolean include)
   at System.Xml.Xsl.Xslt.XsltLoader.Load(Compiler compiler, Object stylesheet, XmlResolver xmlResolver)
   at System.Xml.Xsl.Xslt.Compiler.Compile(Object stylesheet, XmlResolver xmlResolver, QilExpression& qil)
   at System.Xml.Xsl.XslCompiledTransform.CompileXsltToQil(Object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver)
   at System.Xml.Xsl.XslCompiledTransform.LoadInternal(Object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver)
   at System.Xml.Xsl.XslCompiledTransform.Load(XmlReader stylesheet)

Fix:
On the SharePoint server, add the host-name and IP in the "hosts" file (%systemroot%\system32\drivers\etc\hosts). Your new entry should look like:
10.10.10.190 SharePointTest.microsoft.com 
10.10.10.190 is the server's public IP address
SharePointTest.microsoft.com is your site collection host-name

Cause:
SharePoint is trying to access the XSLT file using a URL like:
http://SharePointTest.microsoft.com/Styles/MyStyleFile.XSLT
and it cannot reach the named address http://SharePointTest.microsoft.com

Note: The change will not take effect immediately. You can wait a few minutes or try this command:
ipconfig /flushdns

Add custom DLL to deployment package

Scenario:
You have a custom (helper) DLL that you need to include in your deployment. As this is not a SharePoint solution you cannot deploy the same way you would to with a webpart for example.

Solution:
In Visual Studio, open your solution package:

Select the Advanced tab:

Add your DLL in the dialog:

Tooltip style notification

Scenario:
You want to show a brief status message to the user. The notification will slide in and the out to the right side of the window.


Java Script:
SP.UI.Notify.addNotification('<img src="/_layouts/images/loadingcirclests16.gif" style="vertical-align: top;"/>Loading ...', false);

If you want your notification to stay on the screen until the process finishes you can use a couple of functions like:

function AddNotification() {
  notifyId = SP.UI.Notify.addNotification("Loading ...", true);
}

function RemoveNotification() {
  SP.UI.Notify.removeNotification(notifyId);
  notifyId  = '';
}
Notes:
The second parameter (set to true above) sets the stickiness of the note.
The notifyId variable, set when creating the notification, is used again when hiding it.

More about it on MSDN:
http://msdn.microsoft.com/en-us/library/ee658473(v=office.14).aspx

FIX: Duplicate field in list view form

Scenario:
One or more list fields appear twice on the forms associated to a list (new, edit and view). There are no duplication in the list columns. The list is using a custom content type.

For example the Answer field shows twice on the New FAQ form:


Things to look for:
Check that the field/column is not declared twice in the list settings page.

Cause:
I have seen this happening in 2 cases:
1. when changing and re-deploying the underlying content type
2. when migrating lists from one site to the other (using PowerShell in my case)

Fix:
Browse to the list settings page (on the List Tools - List ribbon click on the List Settings icon)

In the Content Types section click on the content type link

Remove the duplicated column

FIX: The operation could not be completed because item was removed from the gallery

Scenario:
You attempt to add a custom web part to a webpage fails with this message:
The operation could not be completed because item was removed from the gallery

Fix:
1. Remove the web part from the web part gallery:
http://site:port/_catalogs/wp/Forms/AllItems.aspx

2. Disable and the re-enable the feature containing the web part (at the web or the site collection level) to add the web part back to the gallery.


Find all list templates used in a website


Scenario:
You need to determine the template used to create a list (or a library).

PowerShell script:

$web = get-spweb http://site:port/web
$web.lists | Format-Table -Property Title, BaseType, BaseTemplate -auto

Note:
The above script will list all BaseTypes and BaseTemplates used in the web

FIX: The site is not valid. The 'Pages' document library is missing

Scenario:
Trying to create a new page fails with this error:

Microsoft.SharePoint.Publishing.InvalidPublishingWebException: The site is not valid. The 'Pages' document library is missing.    
at Microsoft.SharePoint.Publishing.PublishingWeb.GetPublishingListWithCleanup(PublishingListType list, Boolean throwExceptionOnInvalidWeb)     
at Microsoft.SharePoint.Publishing.Internal.CodeBehind.BasePageSettingsPage.get_PageListRoot()     
at Microsoft.SharePoint.Publishing.Internal.CodeBehind.BasePageSettingsPage.SetParentUrlLabel()   
at Microsoft.SharePoint.Publishing.Internal.CodeBehind.BasePageSettingsPage.LoadValues()     
at Microsoft.SharePoint.Publishing.Internal.CodeBehind.CreatePagePage.LoadValues()     
at Microsoft.SharePoint.Publishing.Internal.CodeBehind.BasePageSettingsPage.OnLoad(EventArgs e)     
at Microsoft.SharePoint.Publishing.Internal.CodeBehind.CreatePagePage.OnLoad(EventArgs e)     
at System.Web.UI.Control.LoadRecursive()     
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Fix: runt this PowerShell script:
$web = get-spweb http://site:port/web
$newId = $web.Lists["Pages"].ID
$web.AllProperties["__PagesListId"] = $newId.ToString()
$web.Update()

Upgrade SharePoint 2007 content database to SharePoint 2010

Scenario
You want to upgrade one or more SharePoint 2007 web sites to SharePoint 2010

How to
Create a copy of your SharePoint 2007 content database.

Run PowerShell script

Mount-SPContentDatabase -Name DBName -WebApplication http\\site:port -DatabaseServer DBServer -ClearChangeLog 

Note
You cannot add the content database through

Technet link:
http://technet.microsoft.com/en-us/library/ff607581.aspx

Delete all personal site collections

Scenario:
To save space, you want to delete all "personal" site collections from your local copy of the production content database.

PowerShell script:

 get-spsite -Limit ALL | where {$_.url -match "/personal/"} | ForEach-Object {Remove-SPSite -Identity $_.ID -Confirm:$false –GradualDelete}  

Note:
You can change the URL pattern to something else by replacing "/personal/" with your pattern.