SharePoint error when editing a wiki page: Sys.WebForms.PageRequestManagerServerException: An unexpected error has occurred

I’ve had an ongoing problem where some users, when clicking the Edit Page button on a SharePoint 2010 wiki page, get the following error:

Sys.WebForms.PageRequestManagerServerException: An unexpected error has occurred

I found a couple blog posts about this suggesting a permissions issue (which made sense, as users in other groups could successfully edit pages):

Both sites suggested that an Access Denied message should appear in the ULS logs. However, no such message appeared in relation to my errors.

ULS entry:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.SharePoint.Publishing.WebControls.MediaWebPart.get_WebPartAdderId()
at Microsoft.SharePoint.Publishing.WebControls.InsertMediaRibbonButton.RegisterRequiredScripts()
at Microsoft.SharePoint.Publishing.WebControls.InsertMediaRibbonButton.OnPreRender(EventArgs e)
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint... 1317dffd-b607-4f1c-9145-b4adc1d364ba

The MediaWebPart. SharePoint 2010 added a video/audio insertion feature on the ribbon, and the error occurred when trying to add the button.

It turns out, the permissions to the Web Part Gallery had been customized (i.e. broken inheritance from the parent site collection), and some groups who had permission to edit wiki pages did not have read permission for the Web Part Gallery (and, consequently, the MediaWebPart). Adding Restricted Read access for the group in question (to either the MediaWebPart or to the Web Part Gallery) solved this problem.

I don’t imagine this will be a common problem for other people, but I thought it worth mentioning.

Displaying numeric fields in SharePoint 2010 without commas

A common request is to display number fields in SharePoint 2010 lists without commas. For example, if you had a list of books that included PublicationYear column, it would format the values as:

  • 2,001
  • 1,998
  • 2,011

This is confusing to the viewer, as values no longer look like years.

The most frequent suggestion is to create an additional field that calculates a value based on the Number field and ignores all non-numeric parts. This is relatively straightforward, and can be accomplished entirely within the browser:

=TEXT([MyNumericData], "0")

Or, in a case where you’d like to retain two digits after the decimal:
=TEXT([MyNumericData], "0.00")

SharePoint appears to store the data in its numeric format in a another column, hidden to the browser but visible in SharePoint Designer. It’s [column name] followed by a period. For example, I created a field called MyNumericData, so the hidden field is MyNumericData. Again:

  • MyNumericData
  • MyNumericData.

Adding this to a view via SharePoint Designer is non-obvious. Here are the steps I used:

  1. Click on a data item in Design mode until you see a tab labeled xsl:value-of:
    SharePoint Designer 2010 Design Mode
  2. Right-click the item and select Edit Formula
  3. Remove the current XPath expression
  4. Add the MyNumericData. row from the fields pane
  5. Add the format-number function from the Math / Number functions
  6. Add the appropriate format pattern (e.g. ‘#’)

The appropriate format pattern depends on how you wish to display the data:

  • Display integer value:
    format-number($thisNode/@MyNumericData.,'#')
  • Always display two digits after the decimal:
    format-number($thisNode/@MyNumericData.,'0.00')
  • Display up to 2 digits after the decimal:
    format-number($thisNode/@MyNumericData.,'#.##')

If you look at the code view after making these changes, you will see that SharePoint Designer added a hefty chunk of XSL to the XsltListViewWebPart.

Is there any advantage to this method over adding a calculated field? Not as far as I can tell–but it’s interesting to note that there is more than one overly-complicated solution to what seems like a trivial problem.

Updating a SharePoint page’s Page Layout using PowerShell

Earlier today I tried to update the page layout on a SharePoint 2010 site via the browser, which produced an error. I looked up the error’s correlation ID in the ULS logs and found this:
GetFileFromUrl: ArgumentException when attempting get file Url https://oldsitename/webname/_catalogs/masterpage/Block.aspx Value does not fall within the expected range.

I couldn’t change the page layout via the browser. I couldn’t change the page layout via SharePoint Designer.

Fortunately, I found Patrick Lamber’s helpful post, How to programmatically change the page template in Moss 2007, which basically described the same error and described applying a new page layout via the object model.

For whatever reason, I thought I could do it just as easily via PowerShell. I started following Jason Grimme’s post, Update SharePoint List Item(s) with Powershell, but I was unable to check-out/check-in the page or access the PublishingPageLayout property.

Liam Cleary’s reply on a TechNet post (Using PowerShell to Checkout and Checkin a file) tipped me off that I needed to use SPFile (rather than SPListItem) in order to perform the necessary operations. Here are the commands I ended up using:

$spWeb = Get-SPWeb("http://currentsitename/webname")
$spFile = $spWeb.GetFile("http://currentsitename/webname/Pages/Test-Page.aspx")
$spFile.CheckOut("Online",$null)
$spFile.Properties["PublishingPageLayout"] = "/_catalogs/masterpage/Block.aspx, Block"
$spFile.Update()
$spFile.CheckIn("Update page layout via PowerShell",[Microsoft.SharePoint.SPCheckinType]::MajorCheckIn)
$spWeb.Dispose()

I visited the page and…another error! This one telling me there wasn’t a valid page layout. Funny, it worked in development.

It turns out, when I compared it to the PublishingPageLayout property of a working page, I had missed the space character after the comma.

Doesn’t work:
"/_catalogs/masterpage/Block.aspx,Block"

Works:
"/_catalogs/masterpage/Block.aspx, Block"

Once I applied the proper path, I was also able to change the page layout via the browser again.

Monitoring web server status with a shell script

Recently, my VPS (Virtual Private Server) ran into some issues where it exceeded the maximum amount of RAM allotted under my subscription. When this happens, the web server software shuts down and does not restart until I manually restart it.

This is bad. I’m not always visiting my own web site, so it could be down for days without me knowing. Although I really need to identify what is using all the RAM, in the meantime I’ll settle for a monitoring system that will notify me when the server is down.

#!/bin/bash
if curl -s --head http://osric.com/ | grep "200 OK" > /dev/null
  then 
    echo "The HTTP server on osric.com is up!" > /dev/null
  else
    echo "The HTTP server on osric.com is down!"
fi

cURL will let you retrieve a URL via the command line, and provides more options than Wget for a single URL. In this case, I used the silent switch to eliminate the status/progress output, and the head switch to retrieve only the document headers. The document header is then piped to Grep, which searches for the string “200 OK” (the HTTP status message for a successful request).

I send the result of that to /dev/null so that the output doesn’t appear on the screen.

If grep does find 200 OK, then I send a success message to /dev/null. This is largely unnecessary, but it is nice to leave in to test the script in a successful case–just remove the > /dev/null. If it doesn’t find 200 OK, then there is a problem. It might not mean, necessarily, that the web server is down, but it definitely indicates there is a problem that needs to be identified.

I added a call to this script to a crontab to run every 5 minutes. If there is no output, nothing happens. If there is output, the output is sent to me via e-mail, which, assuming I am checking my e-mail religiously, should reduce server downtime.

CFFTP Transfers a Zero-Byte File and Throws a Timeout Error

Although I’ve used ColdFusion for 7+ years now, I’ve never used the cfftp tag before. Yesterday, I found a reason to try it out. I figured it would be as simple as cfhttp–and it was, with one exception (no pun intended).

Here is my sample code:

<cfftp action="open" 
    connection="test"
    server="ftp.osric.com"
    username="chris"
    password="********************"
    timeout="60"
    stoponerror="yes">
<cfftp  
    connection = "test" 
    action = "getFile"  
    name = "downloadFile"  
    transferMode = "binary"  
    localFile = "S:\chris\handlebar-moustache.jpg"  
    remoteFile = "handlebar-moustache.jpg"
    timeout="60">

Here’s the error message it produced:
An error occurred during the FTP getFile operation.
Error: getFile operation exceeded timeout.

However, the local file was still created (as a zero-byte file).

The solution, in my case, was to turn on passive mode (add attribute passive="yes" to the cfftp tag).

Active FTP vs. Passive FTP, a Definitive Explanation has a brief explanation of the differences between active and passive FTP.

Importing Data into a SharePoint List

SharePoint Joel’s recent post, Managing Large Lists in SharePoint for Users and Site Admins got me interested in testing the 5000 list view item limit.

It also gave me a good opportunity to put fakenamegenerator.com to the test. The site quickly provided me with a list of 6000 random names.

Now, how to get them into a SharePoint list? Continue reading Importing Data into a SharePoint List

CSS Sprites and Accessibility

Yahoo’s Best Practices for Speeding Up Your Web Site lists minimizing HTTP requests as the very first recommendation. One of the ways they suggest doing that is by using CSS sprites (which I mentioned previously in Clever Ways to Save Bandwidth).

I recently applied this technique to a series of social media icons. Here’s an example:
http://osric.com/chris/css-sprites-social-media-icons-example.html

The example page uses a single image to display 8 separate icons from the following single image:

CSS sprites of social media icons

Be careful when using background images as links. Continue reading CSS Sprites and Accessibility

SharePoint user control to display a random image

The master page of a SharePoint site I work on loaded 7 photographic images, all over 50 kB each, to display at random as a banner adjacent to the site logo. The way it loaded the images was very inefficient: a default image was loaded in the HTML, and Javascript on the page created 7 image objects and returned one at random to overwrite the default. I decided to find a C# way to solve the problem.
Continue reading SharePoint user control to display a random image

WordPress Manual Update Instructions

One of the great things about WordPress is the one-click upgrade procedure. It’s particularly convenient, because WordPress has frequent upgrades and security updates. Without an easy way of upgrading, many users would complain of upgrade fatigue, or would continue running older versions with security flaws.

Of course, not everyone can use the one click upgrade: My host is not configured properly, so I need to upgrade manually. Fortunately, a manual upgrade is relatively painless. Although it is described in some detail at Upgrading WordPress: Manual Update, I’m listing my specific procedures (using the Bash shell) here.

  1. Download the latest version to your home directory:
    wget http://wordpress.org/latest.tar.gz
  2. Remove any old WordPress directory before unpacking the latest:
    rm -r ./wordpress
  3. Unpack the latest version:
    tar -xf wordpress-3.2.tar.gz
  4. Backup the database:
    mysqldump --add-drop-table -h localhost -u [username] -p [database name] | bzip2 -c > [site name].[dd-MMM-yyyy].bak.sql.bz2
  5. Disable plugins. You can do this via the admin interface, or the database:
    UPDATE wp_options SET option_value = 'a:0:{}' WHERE option_name = 'active_plugins';
  6. Remove the wp-admin and wp-includes directories:
    rm -r ./path/to/your/wordpress/wp-admin ./path/to/your/wordpress/wp-includes
  7. Copy only the updated files over to the WordPress install:
    cp -ru ./wordpress/* ./path/to/your/wordpress/
  8. Visit the admin page (which may prompt a database upgrade).
  9. Re-enable any plugins.

Step 6 may seem unnecessary in light of step 7, but in my experience merely updating the wp-admin and wp-includes directories is not enough: there may be old files that are not present in the latest version, but that will cause problems if they still exist.

I’ve found that my reCAPTCHA plugin doesn’t retain its API keys, but you can look them up again on the reCAPTCHA site. Other plugins may have similar issues.

Thanks to Perishable Press for the tip on disabling WordPress plugins via MySQL.

SQL Injection Goes Mainstream

Note to the web development world: even a mainstream media source like Time Magazine knows about SQL injection. Don’t you think it’s time you protected your web applications against it?

Last week’s issue of Time featured an article that focused on LulzSec‘s activities. In Hack Attack, author Bill Saporito went a step beyond most journalists covering web security by mentioning an actual technique: SQL injection.

SQL injection is a subclass of injection attacks, wherein a malicious user manipulates input so as to insert (or inject) a tag-along command into the application code. It’s #1 on OWASP’s Top Ten Vulnerabilities for 2010, in part because such vulnerabilities are:

  • Common
  • Easy to exploit
  • Have a huge payoff (i.e. devastating impact)

Because it is so common and easy-to-exploit, there are a lot of automated tools that malicious users (often by way of compromised machines) use to scan sites and test them for vulnerabilities. If a vulnerability is found, the application may be targeted for further attacks. Basically, attackers are on the lookout for low-hanging fruit in the same way that thieves look for valuables sitting in plain sight in a parked car. Don’t take the car analogy too far, though: if someone breaks into your car, there will be broken glass and your iPod will be gone. If someone exploits a SQL injection vulnerability on your site, they may have all your user data (and more), with hardly a trace: entries in your access logs and error logs, which are too-often completely ignored.

As the joke goes, you don’t have to outrun the bear to avoid being mauled and eaten–you just have to outrun the other guy. One of the best ways to make sure your web application is not targeted for further attacks is to make sure the relatively simple SQL injection scanners don’t find any vulnerabilities.

SQL injection is fairly simple to defend against using parameterized input, and your development language of choice should have documentation on how to do this. OWASP also offers a SQL Injection Prevention Cheat Sheet. There are also automated tools to you can use to check your code for SQL injection flaws (such as QueryParam Scanner for ColdFusion), or test your site for vulnerabilities–also known as penetration testing or pen testing–such as the (currently out-of-date) SQL Inject Me add-on for Firefox.

Checking your web applications for SQL injection vulnerabilities is the first thing you should do, but it is hardly the last. Although fending off automated SQL injection attempts is definitely a good thing, there are many other categories of vulnerabilities, and a determined attacker will find them. Stay informed, and make sure you know what attackers are up to before you read about it in Time.