SharePoint 4 Developers

Additional reference guide in .NET / SharePoint Development

SharePoint 2010 Content Type Hub

In this article we will check out a new feature in SharePoint Server 2010 called Content Type Hub, which allows the Content Types centralisation and sharing through the Metadata Service Application. You will understand how it works, how to configure it, how to publish and consume Content Types and some troubleshooting.

Hi folks,

In this article we will check out a new feature in SharePoint Server 2010 called Content Type Hub, which allows the centralisation and sharing of Content Types through the Metadata Service Application. You will understand how it works, how to configure it, how to publish and consume Content Types and also some troubleshooting.

How it works

Widely discussed when using MOSS 2007, the Content Type Sharing was always problematic, because once the Content Types are created in a single Site Collection, they cannot be shared among other Site Collections (there is no OOTB resource for that).

This new feature is available through the Metadata Services Application, which maps the Site Collection in which the Content Types are shared, working like a Hub.

The Figure 1 below displays how a Content Type Hub works:

 MSA
Figure 1 – The operation of a Content Type Hub (Publisher x Subscribers)

The concept of its operation is very simple, basically the Content Type Hub publishes the Content Types and through the Metadata Service Application they are replicated to the Subscribers. These subscribers can be Site Collections that are in different Web Applications even in different Farms (if you wish it).

Content Types Synchronism is done by 2 Timer Jobs that are executed in the background. They are:

  • Content Type Hub – Responsible for managing the Content Types to be published.
  • Content Type Subscriber – Responsible for publishing the Content Types from the Hub to the Content Type Gallery of the Site Collection.

Configuration

Site Collection (Content Type Hub)

A Site Collection needs to be created firstly to serve as the Content Type Hub, in order to do that go to the Central Administration > Application Management > Create Site Collections and create a new Site Collection, according the Figure 2:

 sitecol
Figure 2 – Site Collection Creation

Shortly after that, enable the Feature Content Type Syndication Hub for the Site Collection in the Site Actions > Site Settings > Site collection features, according the Figure 3:

 feature1
Figure 3 – Feature Activation - Content Type Syndication Hub

Note: At the moment this Feature is activated the Site Collection is provisioned as the Content Type Hub.

Metadata Service Application

The Metadata Application Service is a service for sharing metadata, whose main feature is the storage of keywords and term sets (which is not discussed in this paper) and as optional feature to serve as a Hub for Content Types.

In the Farm is possible to have zero or more Metadata Service Applications and this criterion depends entirely on the Design of your solution. In this approach we need only one running service application whose connection will consume only one Content Type Hub. In order to consume more than one Content Type Hub, you need to create another service application for that. This is applicable in case you want to create different scopes for Content Types, e.g. the separation of Content Type Hubs for consumption in an Intranet Web Site and the other one in an Internet Web Site.

Here we are addressing only the planning of the Metadata Application Service as a Hub for Content Types, but if you're interested in exploring more about this service application, see the references in this article.

The Metadata Service Application can be created through Central Administration > Application Management > Manage Service Applications > New > Managed Metadata Service. The Figures 4 and 5 display the necessary data for that:

 metadata3
Figure 4 – Creating a new Metadata Service Application (1/2)

 metadata4
Figure 5 – Creating a new Metadata Service Application (2/2)

Note: An important point to be commented is that once the URL Configuration for the Content Type Hub is set, this cannot be changed by the user interface. If you want to change it after the Service Application is created, use this approach for updating the Metadata Service Application.

As we will not use the Metadata Service Application for storing keywords and term sets, disable the default storage location of this service application in Central Administration > Application Management > Manage Service Applications by selecting the Managed Metadata Service Connection and clicking Properties, according the Figure 6:

 metadataconn
Figure 6 – Settings of the Metadata Service Connection (1/2)

Shortly after that, uncheck the checkboxes according the Figure 7:

metadataconn2
Figure 7 – Settings of the Metadata Service Connection (2/2)

OBS: Only one default storage location for keywords and term sets is allowed in a Web Application, thus let these options available until you decide to use them.

Publishing

The Site Columns and Content Types referenced in the posts Creating Site Columns Programmatically via XML and Creating Content Types Programmatically via XML are going to be used in the Hub, because they will serve us as examples of Content Types to be published.

Note: Just deploy the Site Columns using the script provided. Use another approach for deploying the Content Types, according to this post SharePoint Lesson Series – Lesson 2 – Content Types – Part I.

Once these objects are created, start publishing the Content Types. This task can be done manually or programmatically. I'll show you both.

It is worth remembering that, only for purposes of understanding, Content Type Syndication is the definition to the way that Content Types are organized and shared between Lists and Libraries, which is precisely what we are doing with their publishing using the Content Type Hub.

Manual

In this type of publishing go to Site Actions > Site Settings > Site Content Types and for each Content Type created, under the Settings go to Manage publishing for this content type as shown in the Figure 8 below:

publishing
Figure 8 – Manual Publishing of Content Types (1/2)

Shortly after that, one of the options for publishing is available, according the Figure 9:

publishing2  
Figure 9 – Manual Publishing of Content Types (2/2)

Note: Because we are publishing it for the first time, only the Publish option is available. If you have already published the Content Type, the other two options are available and the current disabled.

Just for clarification, I am commenting on the publishing options:

  • Publish – The Content Type is delivered for being consumed in other Site Collections that reference it.
  • Unpublish – The Content Type is retracted. Its copy remains in the other Site Collections, however its status changes to be no longer Read-Only.
  • Republish – Redo the Content Type Publishing. It should be applied in cases where there was some change in it.

Coding

If you prefer to automate the publishing process (especially if you have multiple Content Types), use the code below for this task.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using CommonLibrary;
  7. using Microsoft.SharePoint;
  8. using Microsoft.SharePoint.Taxonomy;
  9. using Microsoft.SharePoint.Taxonomy.ContentTypeSync;
  10. using System.Configuration;
  11.  
  12. namespace PublishingContentTypes
  13. {
  14.     public class Program
  15.     {
  16.         public static void Main()
  17.         {
  18.             try
  19.             {
  20.                 string url = ConfigurationManager.AppSettings["Url"].ToString();
  21.                 bool publish = bool.Parse(ConfigurationManager.AppSettings["Publish"].ToString());
  22.  
  23.                 using (SPSite site = new SPSite(url))
  24.                 {
  25.                     using (SPWeb web = site.RootWeb)
  26.                     {
  27.                         string contentTypeXml = Path.GetFullPath("ContentTypes.xml");
  28.  
  29.                         List<string> list = XMLHelper.ReadXML(contentTypeXml);
  30.  
  31.                         foreach (string item in list)
  32.                         {
  33.                             SPContentType ctype = web.ContentTypes[item];
  34.                             if (ctype != null)
  35.                             {
  36.                                 if (publish)
  37.                                 {
  38.                                     // Publishing
  39.                                     ContentTypeHelper.ContentTypePublish(site, ctype);
  40.                                 }
  41.                                 else
  42.                                 {
  43.                            ��        // Unpublishing
  44.                                     ContentTypeHelper.ContentTypeUnPublish(site, ctype);
  45.                                 }
  46.                             }
  47.                         }
  48.                     }
  49.                 }
  50.             }
  51.             catch (Exception ex)
  52.             {
  53.                 Console.WriteLine(ex.ToString());
  54.             }
  55.         }
  56.     }
  57. }

Note: Be aware of the utilisation of the namespace Microsoft.SharePoint.Taxonomy, which refers to the assembly Microsoft.SharePoint.Taxonomy.dll, which is only available in SharePoint Server 2010 (directory 14\ISAPI).

I have also created some libraries to facilitate the publishing, as you can see it in the solution below:

 script
Figure 10 – Content Types Publishing Solution

The code below refers to the class ContentTypeHelper.cs and shows the details for publishing and unpublishing Content Types:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Microsoft.SharePoint;
  6. using Microsoft.SharePoint.Taxonomy;
  7. using Microsoft.SharePoint.Taxonomy.ContentTypeSync;
  8.  
  9. namespace CommonLibrary
  10. {
  11.     public static class ContentTypeHelper
  12.     {
  13.         public static void ContentTypePublish(SPSite hubSite, SPContentType ctype)
  14.         {
  15.             // Check to see whether the site is a valid hub site.
  16.             if (ContentTypePublisher.IsContentTypeSharingEnabled(hubSite))
  17.             {
  18.                 ContentTypePublisher publisher = new ContentTypePublisher(hubSite);
  19.  
  20.                 Console.WriteLine("Publishing the content type: " + ctype.Name);
  21.  
  22.                 // Check to see whether this content type has been published.
  23.                 if (publisher.IsPublished(ctype))
  24.                 {
  25.                     Console.WriteLine(ctype.Name + " is a published content type.");
  26.                 }
  27.  
  28.                 publisher.Publish(ctype);
  29.             }
  30.             else
  31.             {
  32.                 // The provided site is not a valid hub site.
  33.                 Console.WriteLine("This site is not a valid hub site");
  34.             }
  35.         }
  36.  
  37.         public static void ContentTypeUnPublish(SPSite hubSite, SPContentType ctype)
  38.         {
  39.             if (ContentTypePublisher.IsContentTypeSharingEnabled(hubSite))
  40.             {
  41.                 ContentTypePublisher publisher = new ContentTypePublisher(hubSite);
  42.  
  43.                 Console.WriteLine("Unpublishing the content type: " + ctype.Name);
  44.  
  45.                 // Check to see whether this content type has been published.
  46.                 if (!publisher.IsPublished(ctype))
  47.                 {
  48.                     Console.WriteLine(ctype.Name + " is not a published content type.");
  49.                 }
  50.                 else
  51.                 {
  52.                     publisher.Unpublish(ctype);
  53.                 }
  54.             }
  55.             else
  56.             {
  57.                 // The provided site is not a valid hub site.
  58.                 Console.WriteLine("This site is not a valid hub site");
  59.             }
  60.         }
  61.     }
  62. }

Download the solution here.

How to consume Content Types

In order to consume the Content Types of the Content Type Hub, make sure you are referencing the Metadata Service Application that offers the service application. This applies only if you are using another Web Application as Hub, otherwise you're already entitled to use it within your Web Application.

Make sure you have referenced the service application in the Central Administration > Application Management > Configure service application associations. The Figure 11 displays the scenario that I have just commented:

 association
Figure 11 – Configuring the service application association

Note: Notice that I have two Web Applications, the 81 serves as Publisher and the 80 as Subscriber. Both use the same service Managed Metadata Service.

In the beginning of this article I quickly commented on the Timer Jobs that are responsible for the Content Types Synchronism, now just exploring a little more, if you want to trigger them after publishing or unpublishing Content Types for a quick check, go to the Central Administration > Monitoring > Check job status and select the desired job definition according the Figures 12 and 13:

 jobdefinition
Figure 12 – Triggering Timer Jobs (1/2)

 jobdefinition2
Figure 13 – Triggering Timer Jobs (2/2)

Note: By forcing the execution of the Timer Jobs above, always trigger the Content Type Hub (Publisher) first and then the Subscribers. The execution is asynchronous, so despite the status changes quickly after triggering the job, probably it will still be running.

Note that there are two Subscribers consuming the Content Types (port 80 and 81) even though the Hub is on port 81, just because other Site Collections within the same Web Application can take advantage of Content Types.

After the asynchronous execution, you have the option to check at the Site Collection Subscribers whether the Content Types were successfully replicated. One possible way is to access the Content Types via Site Actions> Site Settings> Site content types (Group Galleries) and check whether the Content Type is there, according Figure 14:

 happyend
Figure 14 – Content Types published :)

Another possible way is exemplified in the section “Troubleshooting” below.

Troubleshooting

Nothing is perfect, you will always face problems that appear in the middle of the road. Welcome to the Real World!

In order to check the publishing errors there are two ways, both can be checked at the Publisher or at the Subscriber sides, the first way is available on the Hub Site in Site Actions> Site Settings> Content type service application error log (Site Collection Administration group) according Figure 15 below:

 errorpublisher
Figure 15 – Checking the publishing errors at the Publisher side

The second way is available at the Site Collections Subscribers side in Site Actions > Site Settings > Content Type Publishing (Site Collection Administration group) according Figure 16:

errorsubscriber1
Figure 16 – Checking the publishing errors at the Subscriber side (1/2)

NOTE: The figure above shows a successful outcome, because all the Content Types were published correctly (what should happen in your environment). This figure is only used to display where to find the possible publishing errors.

Another point to be reviewed is regarding the Refresh of all the Content Types published. If you wish to force an update of the Subscriber, which has changed for some reason, leave this option selected. This will overwrite the current Content Types with the version of the Publisher.

Visit the link for the publishing error log, there you can also see the publishing errors (the same as the Publisher) as shown in Figure 17:

 errorsubscriber2
Figure 17 – Checking the publishing errors at the Subscriber side (2/2)

Tip of the day

***UPDATED in 29/08/2011***
Features can be used to deploy content types in the Hub. They are always the best practice. Just be aware that this will create a dependency on them with a FeatureId, and by doing this, when you publish the content types, the same Feature on the Site Collections Subscribers will be required, so you can get the content types published.

Other option is to use a Powershell script or Console Application. In this case, when you publish the content types, there is no need to activate any feature in the Site Collections Subscribers.

I hope it clarifies the options you have when deploying and publishing content types. :)

Conclusion

In the version of SharePoint Server 2010, the Service Metadata Application enables the sharing of Content Types, which promotes the Content Type Syndication in different Site Collections from different Web Applications, and even in different Farms!

Enjoy this feature to create a new Design sharing Content Types!

References:
http://www.wictorwilen.se/Post/Plan-your-SharePoint-2010-Content-Type-Hub-carefully.aspx
http://www.chakkaradeep.com/post/SharePoint-2010-Content-Type-Hubs
http://msdn.microsoft.com/en-us/library/ff394469.aspx
http://technet.microsoft.com/en-us/library/ee424403.aspx
http://technet.microsoft.com/en-us/library/ee519603.aspx


Cheers,

Marcel Medina

Click here to read the same content in Portuguese.

Creating Content Types Programmatically via XML

In this post I demonstrate how to create Content Types Programatically via XML (Quick Note)

Hi folks,

Here we go with one more quick note, the approach now is creating content types programmatically via XML. This approach is not usual, because it requires Reflection to use some Internal methods of the SPContentType class (Microsoft.SharePoint namespace).

It is possible to create Content Types using XML in case a Feature is created for that, however if you have a XML and don’t want to create a Feature, the only way is using Reflection as solution.

Consider the following XML:

Code Snippet
  1. <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  2.   <ContentType ID="0x0100BEBD79039D12B646B28237616422B927"
  3.                Name="Team"
  4.                Group="World Cup 2010 ContentTypes"
  5.                Version="1">
  6.     <Folder TargetName="_cts/Team" />
  7.     <XmlDocuments>
  8.       <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
  9.         <FormTemplates xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
  10.           <Display>ListForm</Display>
  11.           <Edit>ListForm</Edit>
  12.           <New>ListForm</New>
  13.         </FormTemplates>
  14.       </XmlDocument>
  15.     </XmlDocuments>
  16.     <FieldRefs>
  17.       <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" Required="TRUE" />
  18.       <FieldRef ID="{05a571ad-f9d1-4aab-a703-1af3ae393fbf}" Name="Country" Required="TRUE" />
  19.     </FieldRefs>
  20.   </ContentType>
  21.   <ContentType ID="0x0100BEBD79039D12B646B28237616422B92701"
  22.                Name="Team Player"
  23.                Group="World Cup 2010 ContentTypes"
  24.                Version="1">
  25.     <Folder TargetName="_cts/Team Player" />
  26.     <XmlDocuments>
  27.       <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
  28.         <FormTemplates xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
  29.           <Display>ListForm</Display>
  30.           <Edit>ListForm</Edit>
  31.           <New>ListForm</New>
  32.         </FormTemplates>
  33.       </XmlDocument>
  34.     </XmlDocuments>
  35.     <FieldRefs>
  36.       <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" Required="TRUE" />
  37.       <FieldRef ID="{05a571ad-f9d1-4aab-a703-1af3ae393fbf}" Name="Country" Required="TRUE" />
  38.       <FieldRef ID="{04555083-ec04-4c20-a609-42a283428374}" Name="PlayerName" Required="TRUE" />
  39.       <FieldRef ID="{2f2abeb9-ed3d-41d9-bbde-03d1150396a1}" Name="PlayerAge" Required="FALSE" />
  40.       <FieldRef ID="{ea4b814a-a18b-403a-a33a-8ea5436cb540}" Name="Position" Required="TRUE" />
  41.     </FieldRefs>
  42.   </ContentType>
  43.   <ContentType ID="0x0100BEBD79039D12B646B28237616422B92702"
  44.                Name="Team Venue"
  45.                Group="World Cup 2010 ContentTypes"
  46.                Version="1">
  47.     <Folder TargetName="_cts/Team Venue" />
  48.     <XmlDocuments>
  49.       <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
  50.         <FormTemplates xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
  51.           <Display>ListForm</Display>
  52.           <Edit>ListForm</Edit>
  53.           <New>ListForm</New>
  54.         </FormTemplates>
  55.       </XmlDocument>
  56.     </XmlDocuments>
  57.     <FieldRefs>
  58.       <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" Required="TRUE" />
  59.       <FieldRef ID="{05a571ad-f9d1-4aab-a703-1af3ae393fbf}" Name="Country" Required="TRUE" />
  60.       <FieldRef ID="{af008077-3a7e-41d9-aaca-2b0997bb5e25}" Name="HostCity" Required="TRUE" />
  61.       <FieldRef ID="{9910fa0d-c7e8-464a-9607-caba1502b7dc}" Name="Arrival" Required="FALSE" />
  62.     </FieldRefs>
  63.   </ContentType>
  64. </ Elements >

 

In order to add the Content Types above, the code snippet below must be used:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml;
  6. using System.IO;
  7. using Microsoft.SharePoint;
  8. using CommonLibrary;
  9.  
  10. namespace ContentTypes
  11. {
  12.     class Program
  13.     {
  14.         static void Main(string[] args)
  15.         {
  16.             using (SPSite site = new SPSite("http://localhost"))
  17.             {
  18.                 using (SPWeb web = site.RootWeb)
  19.                 {
  20.                     XmlDocument xmlDoc = new XmlDocument();
  21.  
  22.                     xmlDoc.Load(Path.GetFullPath("ContentTypes.xml"));
  23.  
  24.                     foreach (XmlElement fieldNode in xmlDoc.DocumentElement.ChildNodes)
  25.                     {
  26.                         SPContentType ct = ContentTypesHelper.CreateEmptyContentType();
  27.  
  28.                         XmlTextReader xmlReader = new XmlTextReader(fieldNode.OuterXml, XmlNodeType.Element, new XmlParserContext(xmlDoc.NameTable, null, "en", XmlSpace.Default));
  29.  
  30.                         ContentTypesHelper.LoadContentTypeFromXml(ct, xmlReader);
  31.  
  32.                         ContentTypesHelper.SetContentTypeScope(ct, web);
  33.  
  34.                         site.RootWeb.ContentTypes.Add(ct);
  35.  
  36.                         site.RootWeb.Update();
  37.                     }
  38.                 }
  39.             }
  40.         }
  41.     }
  42. }

 

When analising the code above, it is possible to note that the methods CreateEmptyContentType, LoadContentTypeFromXml and SetContentTypeScope are resposible for the Content Types creation, and are contained in the class ContentTypesHelper. These methods use Reflection and were created by Robert Fridén in his blog few years ago, now I am reusing them.

Through the .NET Reflector it is possible to identify Internal methods of the Microsoft.SharePoint.SPContentType class, according the Figure below:

reflector  Figure 1 – SPContentType class visualised through the .NET Reflector


Check out the code of the ContentTypesHelper class:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;
  6. using System.Xml;
  7. using Microsoft.SharePoint;
  8.  
  9. namespace CommonLibrary
  10. {
  11.     public class ContentTypesHelper
  12.     {
  13.         /// <summary>
  14.         /// Creates an Empty Content Type
  15.         /// </summary>
  16.         public static SPContentType CreateEmptyContentType()
  17.         {
  18.             ConstructorInfo constructor = (typeof(SPContentType)).GetConstructor(
  19.                 BindingFlags.NonPublic | BindingFlags.Instance,
  20.                 null,
  21.                 Type.EmptyTypes,
  22.                 null);
  23.  
  24.             SPContentType ctype = (SPContentType)constructor.Invoke(new object[0]);
  25.  
  26.             return ctype;
  27.         }
  28.  
  29.         /// <summary>
  30.         /// Loads Content Type from XML
  31.         /// </summary>
  32.         public static void LoadContentTypeFromXml(SPContentType ctype, XmlTextReader xmlReader)
  33.         {
  34.             MethodInfo loadMethod = ctype.GetType().GetMethod("Load",
  35.                 BindingFlags.NonPublic | BindingFlags.Instance,
  36.                 null,
  37.                 new Type[] { typeof(XmlReader) },
  38.                 null);
  39.  
  40.             loadMethod.Invoke(ctype, new object[] { xmlReader });
  41.         }
  42.  
  43.         /// <summary>
  44.         /// Sets Content Type from XML
  45.         /// </summary>
  46.         public static void SetContentTypeScope(SPContentType ctype, SPWeb web)
  47.         {
  48.             string scope = web.ServerRelativeUrl.TrimStart('/');
  49.  
  50.             MethodInfo setCTScopeMethod = ctype.GetType().GetMethod(
  51.               "SetScope",
  52.               BindingFlags.NonPublic | BindingFlags.Instance,
  53.               null,
  54.               new Type[] { typeof(string) },
  55.               null);
  56.  
  57.             setCTScopeMethod.Invoke(ctype, new object[] { scope });
  58.  
  59.             PropertyInfo fieldLinksScopeProperty = ctype.FieldLinks.GetType().GetProperty(
  60.               "Scope",
  61.               BindingFlags.NonPublic | BindingFlags.Instance,
  62.               null,
  63.               typeof(string),
  64.               Type.EmptyTypes,
  65.               null);
  66.  
  67.             fieldLinksScopeProperty.SetValue(ctype.FieldLinks, scope, new object[0]);
  68.  
  69.             PropertyInfo contentTypeWebProperty = ctype.GetType().GetProperty(
  70.               "Web",
  71.               BindingFlags.NonPublic | BindingFlags.Instance,
  72.               null,
  73.               typeof(SPWeb),
  74.               Type.EmptyTypes,
  75.               null);
  76.  
  77.             contentTypeWebProperty.SetValue(ctype, web, new object[0]);
  78.         }
  79.     }
  80. }

 

In the end the Content Types will be created according the Figure below:

cttypes  Figure 2 – Content Types Creation


Download the solution here.

Considerations

  • The Site Columns are not inherited automatically in this approach. Note that the Content Types of the XML are listing all the columns, which wouldn’t be necessary if the inheritance was working properly.
  • The addition of the property Inherits=TRUE does not change this behaviour.

References:
http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx
http://www.15seconds.com/issue/050602.htm
http://vspug.com/bobsbonanza/2007/12/17/deploying-site-columns-and-content-types-to-sharepoint-webs
http://www.red-gate.com/products/reflector


Cheers,

Marcel Medina

Click here to read the same content in Portuguese.

Creating Site Columns Programmatically via XML

In this post I demonstrate how to create Site Columns Programatically via XML (Quick Note)

Hi folks,

From now on I will also post some quick notes of SharePoint development. I believe they are going to be very useful in our daily activities.

In this post I demonstrate how to create Site Columns programatically via XML.

Consider the following Site Columns XML:

Code Snippet
  1. <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  2.   <Field Type="Choice" Description="List of countries" Required="TRUE" Format="Dropdown" FillInChoice="FALSE" Group="World Cup 2010 Columns" ID="{05A571AD-F9D1-4aab-A703-1AF3AE393FBF}" StaticName="Country" Name="Country" DisplayName="Country" Version="1">
  3.     <CHOICES>
  4.       <CHOICE>Algeria</CHOICE>
  5.       <CHOICE>Argentina</CHOICE>
  6.       <CHOICE>Australia</CHOICE>
  7.       <CHOICE>Brazil</CHOICE>
  8.       <CHOICE>Cameroon</CHOICE>
  9.       <CHOICE>Chile</CHOICE>
  10.       <CHOICE>Côte d'Ivoire</CHOICE>
  11.       <CHOICE>Denmark</CHOICE>
  12.       <CHOICE>England</CHOICE>
  13.       <CHOICE>France</CHOICE>
  14.       <CHOICE>Germany</CHOICE>
  15.       <CHOICE>Ghana</CHOICE>
  16.       <CHOICE>Greece</CHOICE>
  17.       <CHOICE>Honduras</CHOICE>
  18.       <CHOICE>Italy</CHOICE>
  19.       <CHOICE>Japan</CHOICE>
  20.       <CHOICE>Korea DPR</CHOICE>
  21.       <CHOICE>Korea Republic</CHOICE>
  22.       <CHOICE>Mexico</CHOICE>
  23.       <CHOICE>Netherlands</CHOICE>
  24.       <CHOICE>New Zealand</CHOICE>
  25.       <CHOICE>Nigeria</CHOICE>
  26.       <CHOICE>Paraguay</CHOICE>
  27.       <CHOICE>Portugal</CHOICE>
  28.       <CHOICE>Serbia</CHOICE>
  29.       <CHOICE>Slovakia</CHOICE>
  30.       <CHOICE>Slovenia</CHOICE>
  31.       <CHOICE>South Africa</CHOICE>
  32.       <CHOICE>Spain</CHOICE>
  33.       <CHOICE>Switzerland</CHOICE>
  34.       <CHOICE>Uruguay</CHOICE>
  35.       <CHOICE>USA</CHOICE>
  36.     </CHOICES>
  37.   </Field>
  38.   <Field Type="Choice" Description="List of host cities" Required="TRUE" Format="Dropdown" FillInChoice="FALSE" Group="World Cup 2010 Columns" ID="{AF008077-3A7E-41d9-AACA-2B0997BB5E25}" StaticName="HostCity" Name="HostCity" DisplayName="City" Version="1">
  39.     <Default>Johannesburg</Default>
  40.     <CHOICES>
  41.       <CHOICE>Cape Town</CHOICE>
  42.       <CHOICE>Durban</CHOICE>
  43.       <CHOICE>Johannesburg</CHOICE>
  44.       <CHOICE>Mangaung/Bloemfontein</CHOICE>
  45.       <CHOICE>Nelson Mandela Bay/Port Elizabeth</CHOICE>
  46.       <CHOICE>Nelspruit</CHOICE>
  47.       <CHOICE>Polokwane</CHOICE>
  48.       <CHOICE>Rustenburg</CHOICE>
  49.       <CHOICE>Tshwane/Pretoria</CHOICE>
  50.     </CHOICES>
  51.   </Field>
  52.   <Field Type="Choice" Description="List of players" Required="TRUE" Format="Dropdown" FillInChoice="FALSE" Group="World Cup 2010 Columns" ID="{EA4B814A-A18B-403a-A33A-8EA5436CB540}" StaticName="Position" Name="Position" DisplayName="Position" Version="1">
  53.     <CHOICES>
  54.       <CHOICE>Defensive Midfielder</CHOICE>
  55.       <CHOICE>Forward</CHOICE>
  56.       <CHOICE>Goalkeeper</CHOICE>
  57.       <CHOICE>Left Back</CHOICE>
  58.       <CHOICE>Left Midfielder</CHOICE>
  59.       <CHOICE>Right Back</CHOICE>
  60.       <CHOICE>Right Midfielder</CHOICE>
  61.       <CHOICE>Stopper</CHOICE>
  62.       <CHOICE>Striker</CHOICE>
  63.       <CHOICE>Sweeper</CHOICE>
  64.     </CHOICES>
  65.   </Field>
  66.   <Field Type="Text" Description="The name of the player" Required="TRUE" MaxLength="255" Group="World Cup 2010 Columns" ID="{04555083-EC04-4c20-A609-42A283428374}" StaticName="PlayerName" Name="PlayerName" DisplayName="Player Name"></Field>
  67.   <Field Type="Number" Description="The age of the player" Required="FALSE" Decimals="0" Group="World Cup 2010 Columns" ID="{2F2ABEB9-ED3D-41d9-BBDE-03D1150396A1}" StaticName="PlayerAge" Name="PlayerAge" DisplayName="Player Age"></Field>
  68.   <Field Type="DateTime" Description="The date of arrival" Required="FALSE" Format="DateOnly" Group="World Cup 2010 Columns" ID="{9910FA0D-C7E8-464a-9607-CABA1502B7DC}" StaticName="Arrival" Name="Arrival" DisplayName="Arrival" />
  69. </Elements>

 

In order to add the Site Columns above, the code snippet below must be used:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml;
  6. using System.IO;
  7. using Microsoft.SharePoint;
  8.  
  9. namespace SiteColumns
  10. {
  11.     public class Program
  12.     {
  13.         public static void Main(string[] args)
  14.         {
  15.             using (SPSite site = new SPSite("http://localhost/"))
  16.             {
  17.                 XmlDocument xmlDoc = new XmlDocument();
  18.  
  19.                 xmlDoc.Load(Path.GetFullPath("SiteColumns.xml"));
  20.  
  21.                 foreach (XmlElement fieldNode in xmlDoc.DocumentElement.ChildNodes)
  22.                 {
  23.                     site.RootWeb.Fields.AddFieldAsXml(fieldNode.OuterXml);
  24.                 }
  25.             }
  26.         }
  27.     }
  28. }

 

In the end the Site Columns will be created according the Figure below:


Figure 1 – Creating Site Columns

Download the solution here.

Cheers

Marcel Medina

Click here to read the same content in Portuguese.