Updating content types using SharePoint Web Services (SPServices)

When you deploy an updated content type which is created from code and have new fields, your changes won’t automatically be pushed to children that inherit from your content type. This is only the case when you have created your content type using code. In the sandbox solution, I’m using the SharePoint Web Services to add new fields to content types that inherit from the updated content type.

Why the web services? With the push from Microsoft to go more and more client side, I found it a challenge to not do something with simply a farm solution or a server-side script. During the development of the web part, I’ve found 2 annoyances by using the SPServices library and jQuery/SharePoint:

  1. SPServices says every method name is unique. This is not true. There’s a method “UpdateContentType” for both the Lists.asmx and the Webs.asmx. Due to this overlooked bug, the call will always be directed to the Webs.asmx web service. I’ve modified the SPServices js file to comment out the WSops.UpdateContentType method for Webs.
  2. jQuery will always put your generated attributes to lower case. The web services are case-sensitive as you can see from the following screenshot (taken from STSSOAP.DLL, decompiled with ILSpy)
    caseSensitive

The web part itself is pretty straight forward. You’ll get a list of content types with update links.

content type updater webpart

When using firebug or another web dev tool, you can track all the calls that are made to the Webs.asmx & Lists.asmx

content type updater console window

I’ve deployed a custom content type to my site, created a list with that content type and then made an update to the site content type. As you can see there’s a column missing from the list content type:

site content type

list content type

After I click on “Update” next to “CustomContentType”, the script will detect a difference between these two and update accordingly:

soap call new fields

And the updated list content type:

updated list content type

All in all I’m pretty happy with the result. You can do a lot with just the web services from SharePoint, but they take some time to get used to. Also the documentation isn’t always great as for instance they mention to use <FieldRefs> while in the source code of the web service itself there’s only a parse of the <Fields> tag.

For the full source, or if you want to download and test the web part itself, you can go to CodePlex.

Get the content types associated with lists for a SharePoint site

I received the question if it was possible to check which content types are associated to which lists inside a SharePoint site. Instead of looking at every list separately, which is pretty dull, I quickly wrote a script that will list the output in a table sorted by content type:

function run
{
	param ($siteName)
	clear
	if ( (Get-PSSnapin -Name Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null )
	{
	    Add-PsSnapin Microsoft.SharePoint.Powershell
	}
	$web = Get-SPWeb -Identity $siteName
	foreach ($list in $web.Lists)
	{
		if ($list.AllowContentTypes)
		{
			foreach ($contenttype in $list.ContentTypes)
			{
				$result = New-Object PSObject -Property @{
					ContentType = $contenttype.Name
					ListName = $list.Title
				}
				$result
			}
		}
	}
	$web.Dispose()
}
$output = run "http://sharepoint" | Sort-Object ContentType
$output | Format-Table ContentType, ListName

Which results in the following output:

powershell output

Happy scripting!

Add an event receiver to a specific list programmatically

Creating an event receiver allows you to catch events for specific list types. Such as custom lists, document libraries, announcements, … When we want to catch an event for a specific list, the standard procedure for creating an event receiver changes a bit.

There’s an article on MSDN which describes a method by editing the elements.xml file of an event receiver project. However, the same result can be achieved with code.

Basically, an event receiver template will create a feature file which holds a reference to the elements.xml file from the event receiver project. Inside this elements.xml file, the properties of the event receiver are defined, such as the type of list it will be bound to. We want to bypass the elements.xml file and manually attach the event receiver to a specific list’s event receivers. The binding itself will be written in a feature event receiver.

Start out with creating a new SharePoint 2010 project and select the Event Receiver template. Fill in any desired properties and click on OK:

new event receiver project

Next, fill in the site where the list is at you want to attach the event receiver. Also choose “farm solution” as the desired trust level.

link farm solution

Click next, choose the event receiver settings. I’ve chosen for “List Item Events” where “An item was added” should be handled. The event source isn’t important, since we’ll override the binding:

event receiver settings

When finish is clicked, Visual Studio will create the files based on the template and the chosen settings. A feature will be created with a reference to the EventReceiver1 project. Inside this project an elements.xml file and a code file will be created. The elements.xml file holds the settings of the event receiver. The code file holds the code that will be executed:

event receiver solution explorer

Whenever you want to add more events that have to be captured, click on the EventReceiver1 project and look at the properties window. Here you can enable or disable events that have to be captured. Note that when you disable an already enabled event, the code inside the code file will not be removed. This is a safety built-in for when you accidentally disable an event:

event receiver properties

The next step is removing the connection between the feature and the event receiver project. By doing this we avoid that the elements.xml file is used to bind the event receiver. Double click on the feature file, select the EventReceiver1 project and click on the “<” arrow to remove the project from the feature:

remove event receiver from feature

Save the modification, and right-click the feature file to add a feature event receiver:

add event receiver

If it’s not already open, double-click the feature event receiver code file to open it up. Next, uncomment both FeatureActivated and FeatureDeactivating code blocks.

First, declare two constants in your feature class to keep constancy:

        const string _listName = "test";
        const SPEventReceiverType _eventType = SPEventReceiverType.ItemAdded;

Next, write the following code in the FeatureActivated block:

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb oWeb = (SPWeb)properties.Feature.Parent;
            oWeb.Lists[_listName].EventReceivers.Add(_eventType, Assembly.GetExecutingAssembly().FullName, "EventReceiverProject1.EventReceiver1.EventReceiver1");
        }

You’ll notice that the Assembly namespace isn’t recognized so add the following line in your using statements:

using System.Reflection;

The last parameter of the Add() function can be found in the elements.xml file of the EventReceiver1 project. When you open this file you will see the 2 tags that are also referenced here in our code:

        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>EventReceiverProject1.EventReceiver1.EventReceiver1</Class>

$SharePoint.Project.AssemblyFullName$ is replaced by Assembly.GetExecutingAssembly().FullName in the code.

The following code will remove the event receiver that was added:

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb oWeb = (SPWeb)properties.Feature.Parent;

            SPList oList = oWeb.Lists[_listName];
            for (int i = oList.EventReceivers.Count - 1; i >=0 ; i--)
            {
                if (oList.EventReceivers[i].Type.Equals(_eventType))
                {
                    try
                    {
                        oList.EventReceivers[i].Delete();
                    }
                    catch (Exception e)
                    {
                        // Write to logs
                    }
                }
            }
        }

Updating a list item field using its internal name

While looking up examples of eventreceivers for updating list item fields, I noticed a high usage of display names. List fields were often referenced using their display name, like:

properties.ListItem["Title"] = "something";

It works, but, when there are multiple languages used on the SharePoint site, it might get broken. A solution to this is using the internal field name. This can be obtained by GetFieldByInternalName(). By using the internal field name, SharePoint will never be confused by changes. Imagine someone changing the name of a column and breaking your code. That’s not good. The internal field name will always stay the same, unless someone changes it programmatically of course 😉

I used the following code snippet to add text to the title of a list item:

       public override void ItemAdded(SPItemEventProperties properties)
       {
           base.ItemAdded(properties);
           Guid oId = properties.ListItem.Fields.GetFieldByInternalName("Title").Id;
           properties.ListItem[oId] += " and something added to the title field";
           properties.ListItem.Update();
       }

Finding the internal field name is pretty simple. By using Visual Studio 2010’s server explorer, we can access almost all the information of our SharePoint site.

Open up the Server Explorer by going to view and clicking the Server Explorer:

open server explorer

With the Server Explorer view open click on the Add SharePoint Connection button and add your site:

add sharepoint connection

Now we have access to our site properties within Visual Studio 2010. Please note that everything here is read only.

Expand the Explorer View to a desired list field and click on it:

server explorer expanded

The Properties window will now show the associated properties of the field. Here we can find back the internal field name:

list field properties

Other useful information like the GUID of the field can also be found here.