Using Event Receivers in SharePoint Foundation 2010

I have been working with Nick Gattuccio on authoring a two-part MSDN article about using event receivers in SharePoint 2010. The first part provides a thorough explanation of what events are and how they can be developed and deployed in SharePoint. The second part provides practical examples using Visual Studio 2010.

Title: Using Event Receivers in SharePoint Foundation 2010 (Part 1 of 2)

Title: Using Event Receivers in SharePoint Foundation 2010 (Part 2 of 2)

Let me know how useful this is to you.

SharePoint Detector – Chrome Extension

Ever wondered whether a site is built on top of SharePoint? Now, there is an easy way to find out. Install the “SharePoint Detector” Chrome extension located at, and you will get the SharePoint icon displayed in Chrome’s address bar every time you browse to a SharePoint site. You can then click on the SharePoint icon and choose to share the site by email, on your WordPress blog, LinkedIn, Twitter, Facebook and\or StumbleUpon.

For example, here is what happens when you browse to

If you decide to share on Twitter, you will get the following popup.

You can edit it as you like then post to your Twitter account. Same goes for all the other different methods of sharing..

Enjoy sharing SharePoint!

Content DB Attach using PowerShell

In this post, I’ll talk about how to attach\mount a SharePoint content database to a SharePoint web application after it has been restored\attached to the SQL server. See my previous post for details on how to restore a database using PowerShell.

SharePoint provides a cmdlet to do the content db attach. This cmdlet is called Mount-SPContentDatabase. I will create a script block wrapper for this cmdlet and show how to call it remotely. The script block below adds the SharePoint PowerShell snapin if it’s not already added, selects a web application in the farm, then calls the Mount-SPContentDatabase to do the content db attach.

[ScriptBlock] $global:AttachSPContentDB =
    param([string] $dbName, [string] $dbServer)

        # Load the Sharepoint Cmdlets
        Write-Host "Loading SharePoint PowerShell Snapin"
        $spSnapin = Get-PSSnapin | where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}
        if($spSnapin -eq $null)
            Add-PSSnapin Microsoft.SharePoint.PowerShell
            Write-Host -ForegroundColor "Green" -Object "SharePoint PowerShell Snapin loaded"
            Write-Host -ForegroundColor "Gray" -Object "SharePoint PowerShell Snapin already loaded"

        # Get  web applciation url
        Write-Host "Selecting a web application in the farm"
        $webAppUrl = (Get-SPWebApplication | select -Index 0).Url

        # Mount the database at the specified SQL server to the web application
        Write-Host "Mounting database '$dbName' at SQL server '$dbServer' to web application '$webAppUrl'"
        $newDB = Mount-SPContentDatabase $dbName -DatabaseServer $dbServer -WebApplication $webAppUrl -AssignNewDatabaseId
        Write-Host -ForegroundColor "Green" -Object "Database mounted successfully with ID: " + ($newDB.Id)

        # Return content DB Id
        return $newDB.Id.ToString()
    catch [Exception]
        Write-Host -ForegroundColor "Red" -Object $_.Exception

        return $null

To call this script block, pass the name of the Sql server and the name of the content database. Make sure that the content database is already restored\attached to the SQL server.

.$AttachSPContentDB "ContentDBName" "SqlServerName"

To call the script block on a remote SharePoint WFE, you can simply run

Invoke-Command -ComputerName "WFEName" -ScriptBlock { .$AttachSPContentDB "ContentDBName" "SqlServerName" }

Note that the New-SPContentDatabase cmdlet has the same effect as Mount-SPContentDatabase. The only difference is that New-SPContentDatabase creates a new SQL database if there is no database with the same name already available on the SQL server.

SharePoint Foundation 2010 on Windows 7

This MSDN article describes in detail how to install SharePoint Foundation 2010 for development purposes on Windows Vista, Windows 7 and Windows Server 2008. The purpose of this post is to focus on the SharePoint installation on Window 7 only and clear out all the details for the other operating systems.

  1. Download SharePoint Foundation 2010 x64 for free. Note that there is no x86 version of SharePoint Server, so don’t bother setting it up if you have a 32-bit machine.
  2. Create a new folder “C:\SharePointFiles” and copy “SharePointFoundation.exe” to it.
  3. Start command prompt, change directory to C:\SharePointFiles and run the following command to extract the “SharePointFoundation.exe” to C:\SharePointFiles
    SharePointFoundation.exe /extract:C:\SharePointFiles
  4. Open C:\SharePointFiles\files\Setup\config.xml, add a new <Setting> tag under the <Configuration> element, then save the file. Make sure you copy the below element as is since all of the text in the configuration file is case-sensitive.
    <Setting Id=”AllowWindowsClientInstall” Value=”True”/>
  5. Install the following Prerequisites:
  6. Enable the required windows features by running this batch file:
  7. Restart your computer to complete the changes that you made to Windows Features.
  8. Install SharePoint 2010
    • Run Setup.exe under C:\SharePointFiles
    • Select standalone (Windows 7 can’t be used for production deployments of SharePoint 2010 and it’s recommended that you use Standalone only)
    • After the installation is complete, you will be prompted to start the SharePoint Products and Technologies Configuration Wizard.
  9. After a SharePoint solution (.wsp file) is deployed, it recycles the application pool. To improve the initial page load times, set the optimizeCompilations property of the <compilation> tag in your web.config file (C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config) to true.
    <compilation optimizeCompilations=”true”>

SharePoint Designer 2010 is also free and can help you better design your SharePoint site(s). You can download it here.

Visual Studio 2010 & SharePoint Server Code

You have downloaded Visual Studio 2010 RC and SharePoint 2010 Beta and now you’d like to use VS to develop on top of SharePoint. You can use one of the following approaches:

Approach Extension Usage VS Project Type
Solution Wsp Add functionality on top of SharePoint. Anything under the SharePoint template node (Web Part, List Definition, Content Type, etc…)
Client Application Exe, dll, xap End User Windows\Silverlight apps, Assemblies Anything that uses SharePoint Client OM, Web Services, RPCs
Server Application Exe, dll Admin tools Anything that uses SharePoint Server OM (Ex: referencing Microsoft.SharePoint.dll)

The point behind this blog post is to ensure that you have the right Visual Studio 2010 settings for compiling and running SharePoint Server applications or assemblies.

Compile Issue

Warning 1 The referenced assembly “Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL” could not be resolved because it has a dependency on “System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” which is not in the currently targeted framework “.NETFramework,Version=v4.0,Profile=Client”. Please remove references to assemblies not in the targeted framework or consider retargeting your project.


SharePoint 2010 is built on top of .Net Framework 3.5. So make sure you have it as your targeted framework in VS. Go to project properties and change the target framework to “.Net Framework 3.5”.
Run Issue
The Web application at <url> could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.
You have an x64 version of SharePoint Server installed, but VS 2010 is building your code as x86. So go to project properties \ Build and change platform target from x86 to x64.

SPList Image and SPFile Icon

If you ever wanted to create a WinForms app for SharePoint that displays or interacts with lists, document libraries and files, then taking advantage of the SPList.ImageUrl and SPFile.IconUrl would help improve the user experience for your app.

Below is an app that displays all the webs, lists, document libraries and files in a selected site collection.

We can improve this a little bit by adding icons (taken from TEMPLATE\IMAGES frolder on a SharePiont installation) for some of the nodes, as follows:

However, this is not good enough since we’ll have all lists with the same icon, all doc libs with the same icon and so on… Here is the same app taking advantage of the list image url and file icon url.

For the list or document library, this is done by using the SPList.ImageUrl attribute. Here is howthe tree node was added:

TreeNode listNode = parentNode.Nodes.Add(list.Title);
listNode.SelectedImageIndex = listNode.ImageIndex = GetImage(GetImageFullPath(list.ImageUrl));

For the file, this is done by using the SPFile.IconUrl attribute. Here is howthe tree node was added:

TreeNode fileNode = parentNode.Nodes.Add(file.Name);
fileNode.SelectedImageIndex = fileNode.ImageIndex = GetImage(GetImageFullPath(file.IconUrl));

The GetImageFullPath method simply gets the full path of the image:

/// <summary>
/// Gets the SharePoint full path from the relative path
/// </summary>
/// <param name="relativePath"></param>
/// <returns></returns>
private static string GetImageFullPath(string relativePath)
    //  Get image name
    string imageName = Path.GetFileName(relativePath);

    //  Get SharePoint IMAGES folder path
    string fullPath = SPUtility.GetGenericSetupPath(@"TEMPLATE\IMAGES");

    return Path.Combine(fullPath, imageName);

Given that now we have the full file system path to the image, all we have to do now is create an image from the file path then add it to the ImageList of the TreeView. The GetImage() method below does the job.

/// <summary>
/// Gets the image of the sp element from specified url
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private int GetImage(string url)
    //  Get image index from the Image List
    int imageIndex = spImageList.Images.IndexOfKey(url);

    //  Image is not in the list, so add it
    if (imageIndex == -1)
        //  Get the image from specified path
        Image image = Image.FromFile(url);

        //  Add the image to the image list
        spImageList.Images.Add(url, image);

        //  Get its index
        imageIndex = spImageList.Images.Count - 1;

    return imageIndex;

Here is how the final app looks like. Click on the image below to download the src and exe.