Friday, March 30, 2012

Long Running Operations

The problem:

I have a long-running operation that is supposed to transfer to an error page in case of an error.

This code is perfectly valid. However, the error page (SPUtility.ErrorPage, which is just a synonym for error.aspx) it transfers to is too generic ("An error has occurred on the server") and cannot be customized with a more informative error message.


The solution:

You don't have to call the End() method for the long operation; if the result is erroneous, make a transfer to the error page using SPUtility.TransferToErrorPage, which takes an error message as a parameter. This code does the trick. Note also that it catches ThreadAbortException.

Thursday, March 1, 2012

Adding a Positive Integer Column To a List Via PowerShell

The problem:

I need to add a column to my list via PowerShell; this column must be a positive integer.

The solution:

Here is a simple script to accomplish this:

$site = Get-SPSite "http://my_site_collection"
$web = $site.OpenWeb("my_site")
$list = $web.Lists["my_list"]
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Integer

#The new field is not required, so the value of the third parameter is 0
$spFieldName = "PositiveNo"
$list.Fields.Add($spFieldName, $spFieldType, 0)
$list.Update()

#Now that we created a new field, let's change it so that it has a minimal value of 1 and no decimal places
$spField = $list.Fields.GetField($spFieldName)
$spField.MinimumValue = 1
$spField.DisplayFormat = "0"
$spField.Update()

#Need to add the new column to the list
$views = $list.Views["All Items"]
$views.ViewFields.Add($spFieldName)
$views.Update()