Adding an item of a specific contenttype to a list

August 6th, 2006 by tonstegeman

This previous post shows how you can create content types in code. The code in this post will show you how you add an item to a list and set the contenttype for that item. An SPItem object has a property called ContentType, but you cannot use that, because it is readonly.

The code to do this looks like this:

            SPSite site = new SPSite("http://myportal/testsite");
            SPWeb web = site.OpenWeb();
            SPList list = web.Lists["ContentTypeTest"];
 
            // We first check if the contenttype is available and then use the id.            
            SPContentType contentType = web.AvailableContentTypes["Proposal"];
            if (contentType != null)
            {
                SPListItem item2 = list.Items.Add();
                item2["ContentTypeId"] = contentType.Id;
                item2["Title"] = Custom contenttype, set from code!”;
                item2.Update();
            }

First we open the site and get an SPList object of the list we want to add the item to. In my sample the list is called “ContentTypeTest”. The next step is to get an object of the SPContentType type from the available contenttypes for the web. If it exists, we can add an item to the list and set the value of the “ContentTypeId” field for our item. The contenttype in my sample is called “Proposal”.

File not found message in SharePoint 2007 when logged on as a reader

July 21st, 2006 by tonstegeman

Just a quick one this time. When you create a custom masterpage for your SharePoint environment and upload that into the masterpage gallery, you will have to publish it before readers will be able to access the portal. Otherwise they will get a “File not found” message when trying to access a page. The masterpage gallery itself is a SharePoint document library with versioning and approvals enabled. When you first upload a masterpage, the status is “Draft” and therefore only visible for administrators.

Something that is very obvious afterwards, but took me (and other people) some time to realize.

Creating ContentTypes in SharePoint 2007 by using a feature

July 19th, 2006 by tonstegeman

In one of the previous posts I showed how you can add sitecolumns to a SharePoint 2007 site by using features. It is also possible to deploy content types using features. In this post I will describe how to do that. We will create 3 contenttypes; the first is called “Company Document” and has 2 fields: Region and Industry. The contenttypes “Proposal” and “Whitepaper” inherit from this “Company Document”. Proposal has 1 extra column called ClientName and Whitepaper has and extra column to store the publication date.

One warning: SharePoint 2007 isn’t very informative in case you do something wrong in your sitecolumns or contenttypes. It simply does not appear in the list, leaving you wondering what is wrong. Be warned!

Step 1 – Create the SiteColumns
The first step is to create the site columns. Fields cannot be added directly to contenttypes, they have to be a sitecolumn. I will not describe how to deploy these columns (you can find that here). The feature xml looks like this:

    1 <?xml version="1.0" encoding="utf-8" ?>
    2 <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    3   <Field ID="{7d2aeebd-ad31-43f2-9f9f-72d76759dd36}" 
    4       Name="Region" DisplayName="Region" StaticName="Region" Group="Company Metadata Model"
    5       Type="Choice" Sealed="TRUE" AllowDeletion="FALSE"
    6       SourceID="http://schemas.microsoft.com/sharepoint/v3/fields"
    7       Description="Identifies the region this document applies to">
    8     <CHOICES>
    9       <CHOICE>EMA</CHOICE><CHOICE>ASPAC</CHOICE><CHOICE>Americas</CHOICE>
   10     </CHOICES>
   11     <Default>EMA</Default>
   12   </Field>
   13   <Field ID="{05d891f3-5f35-41aa-bce0-40e37d08c2e3}" 
   14     Name="Industry" DisplayName="Industry" StaticName="Industry" Group="Company Metadata Model"
   15     Type="Choice" Sealed="TRUE" AllowDeletion="FALSE" FillInChoice="FALSE"
   16     SourceID="http://schemas.microsoft.com/sharepoint/v3/fields"
   17     Description="Identifies the industry that the document applies to" >
   18     <CHOICES>
   19       <CHOICE>Auto Dealerships</CHOICE><CHOICE>Auto Manufacturers</CHOICE>
   20     </CHOICES>
   21   </Field>
   22   <Field ID="{a898bf6c-bb0b-4451-b0f3-b6aa27223865}"
   23       Name="CustomerName" DisplayName="Customer Name" StaticName="CustomerName" Group="Company Metadata Model"
   24       Type="Text" Sealed="TRUE" AllowDeletion="FALSE"
   25       SourceID="http://schemas.microsoft.com/sharepoint/v3/fields"
   26       Description="Identifies the client for whom the document was prepared" />
   27   <Field ID="{b3c3f26e-a0c6-4607-8f45-5465c8fd67cb}"
   28       Name="PublicationDate" DisplayName="Publication Date" StaticName="PublicationDate" Group="Company Metadata Model"
   29       Type="Text" Sealed="TRUE" AllowDeletion="FALSE"
   30       SourceID="http://schemas.microsoft.com/sharepoint/v3/fields"
   31       Description="The official publication date for the document" />
   32 </Elements>

You will need to give you sitecolumns a unique id (a GUID). These ID’s are used to reference the fields from the contenttype XML.
I am still trying to figure out why we now have a Name and a StaticName for a field. If you know this, please let me know!

Step 2 – Create a ContentType feature

  • Create a new subfolder “companycontenttypes” in folder “C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12TEMPLATEFEATURES”.
  • Add a new file to this folder called “feature.xml”
  • The contents of this file look like this:
        1 <?xml version="1.0" encoding="utf-8" ?>
        2 <!-- _lcid="1033" _version="12.0.4017" _dal="1" -->
        3 <!-- _LocalBinding -->
        4 <Feature  Id="c36321e0-0107-43fa-85bf-5729f23963fc"
        5           Title="Company Content Types"
        6           Description="Company Content Types"
        7           Version="1.0.0.0"
        8           Scope="Site"
        9           xmlns="http://schemas.microsoft.com/sharepoint/">
       10   <ElementManifests>
       11     <ElementManifest Location="companycontenttypeswss.xml" />
       12   </ElementManifests>
       13 </Feature>

    Make sure you create a new unique ID for the feature. Please note the feature is scoped at the site level.

  • The element manifest is the name of the file in which we will create our contenttypes.

 Step 3 – Create the contenttypes

  • Create a new file in the same folder, with the value of the Location attribute of the ElementManifest element in the feature xml of ste 2.
  • In my case this xml looks like this:
        1 <?xml version="1.0" encoding="utf-8" ?>
        2 <!-- _lcid="1033" _version="12.0.4017" _dal="1" -->
        3 <!-- _LocalBinding -->
        4 <!--
        5 -->
        6 <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
        7   <ContentType ID="0x01010D"
        8       Name="Company Document"
        9       Group="Company Metadata Model"
       10       Description="Company document"
       11       Version="0">
       12     <FieldRefs>
       13       <FieldRef ID="{7d2aeebd-ad31-43f2-9f9f-72d76759dd36}" Name="Region" Required="TRUE"/>
       14       <FieldRef ID="{05d891f3-5f35-41aa-bce0-40e37d08c2e3}" Name="Industry" Required="TRUE"/>
       15     </FieldRefs>
       16   </ContentType>
       17   <ContentType ID="0x01010D0D"
       18       Name="Proposal"
       19       Group="Company Metadata Model"
       20       Description="Company proposal"
       21       Version="0">
       22     <FieldRefs>
       23       <FieldRef ID="{a898bf6c-bb0b-4451-b0f3-b6aa27223865}" Name="CustomerName" Required="TRUE"/>
       24     </FieldRefs>
       25   </ContentType>
       26   <ContentType ID="0x01010D0E"
       27       Name="Whitepaper"
       28       Group="Company Metadata Model"
       29       Description="Company whitepaper"
       30       Version="0">
       31     <FieldRefs>
       32       <FieldRef ID="{b3c3f26e-a0c6-4607-8f45-5465c8fd67cb}" Name="PublicationDate" Required="TRUE"/>
       33     </FieldRefs>
       34   </ContentType>
       35 </Elements>

    In this xml the 3 contenttypes are defined. One thing to be aware of is the ID of a contenttype. An ID has to be unique, and by using the correct syntax, you can set the inheritance of a contenttype. The ID of our base contenttype is “0×01010D”. This means that our contenttype inherits from “0×0101”, which is the out of the box SharePoint Document contenttype. Our Proposal inherits from our Company Document and therefore the ID starts with “0×01010D” followed by a unique identifier this Proposal.
    By setting the “Required” attribute, the fields will be required for a user to fill in when the contenttype is used in a list.

Step 3 – Register and Activate the feature

  • Register the feature by using this command:
        stsadm -o installfeature -filename companycontenttypesfeature.xml
  • Activate the feature by using this command:
        stsadm" -o activatefeature -filename companycontenttypesfeature.xml -url http://companyintranetPlease note that the contenttypes will be avaible in the site that is set with the -url parameter. They are available in the site and all it’s subsites.

Step 4 – Test the contenttypes

  • Create a new document library in your site
  • Switch “Allow management of content types?” on in the advanced settings
  • Add the Proposal and Whitepaper contenttypes to the library
  • The “Columns” section of your document library should now look like this:
    Contenttypes

Activating Features in a site definition in SharePoint 2007

July 19th, 2006 by tonstegeman

In previous posts about sitecolumns and contenttypes I described how to create features to deploy sitecolumns and contenttypes to a site. The last step of this process is always to activate the feature using the STSADM activatefeature command. In my case I wanted to activate this feature automatically when I create a new site. The <Configuration> element of a site definition (onet.xml) contains 2 new elements: SiteFeatures and WebFeatures. Because my features have a “Site”  scope, I added them to the SiteFeatures.

This is configured like this:

    1 <Configuration ID="0" Name="Publishing">
    2   <Lists>
    3   </Lists>
    4   <SiteFeatures>
    5     <!-- Activate SiteColumns -->
    6     <Feature ID="37b693b8-e650-44dd-88bb-497dc78de1f6" ></Feature>
    7     <!-- Activate ContentTypes -->
    8     <Feature ID="c36321e0-0107-43fa-85bf-5729f23963fc" ></Feature>
    9   </SiteFeatures>
   10   <WebFeatures>
   11   </WebFeatures>
   12 </Configuration>

Please make sure that you activate the sitecolumns before the contenttypes!! A better way is to use the ActivationDependencies, but I haven’t figured that out yet.

After an iisreset and creating a new site, I have the new contenttypes and sitecolumns available in that site. Because I added this to the site definition of a toplevel site in a site collection, they are automatically available in all subsites. Of course you can also activate the features for every subsite, but in my case it didn’t make sense to do it in every subsite separately.

Now I never have to wonder if a new site collection will get my default site columns and content types. It is as easy as that!

SiteDefinitions in SharePoint 2007

July 16th, 2006 by tonstegeman

MOSS 2007 still uses site definitions, as in SharePoint 2003 technologies. The basic structure of these site definitions is still the same, although there have been a lot of changes. In this post I will decribe a number of these changes.

Features
A lot of the options of a site are now added to the sitedefinition by activating features. This makes the onet.xml and the filestructure of the site definition much cleaner. Registering ListTemplates in a site definition for example, only requires a specific feature to be activated from the onet.xml. The <Configuration> element in onet.xml now contains an element <WebFeatures>. Registering the listtemplate for the Document Library is now done by adding this line to this element:
<Feature ID="00BFEA71-E717-4E80-AA17-D0C71B360101" >
In SharePoint 2003, the schema files for the list had to be in the LISTS folder in every site definition, and the ListTemplate had to be registered in every onet.xml. Now you register schema of the list and the registration are part of a feature, that you activate from onet. Much cleaner, because there is only 1 place where the list is defined and registered.

“Virtual” Site Definitions
In SharePoint 2003, a sitedefinition is a folder named “SPS[your_name]” in the SPS folder 60TEMPLATE1033 and a registration in webtempsps.xml (or any other file called “webtemp*”. In SharePoint 2007, the folders for site definitions have moved to a special folder called “SiteTemplates”. Their name no longer needs to start with “SPS”. Apart from that you can now have ‘virtual’ site definitions. Such site definitions are a registration of a number of webs that will be provisioned the the site definitions is used. The “Corporate Intanet Site” and the “Internet Presence Web Site” are examples of such a site definition. They do not point to a specific folder, but to a manifest file (which is set in the “ProvisionData” attribute).
In case of the Corporate Intranet Portal, this is a reference to the file called “PortalWebManifest.xml”. This file contains xml like the sample below:

<portal xmlns="PortalTemplate.xsd">
    <web
 name="Home"
 siteDefinition="SPS"
 displayName="$Resources:spscore,PortalManifest_Home_DisplayName;"  description="$Resources:spscore,PortalManifest_Home_Description;">
        <webs>
            <web name="News" siteDefinition="SPSNHOME"   displayName="$Resources:spscore,PortalManifest_News_DisplayName;"   description="$Resources:spscore,PortalManifest_News_Description;" />
        </webs>
    </web>
</portal>

When this site definition is used, a site called “Home” is created, and for this site the subsites that are referenced in the <webs> element will be created. Nice way of packaging a number of sites into 1 single site definitions.

ASPX pages

The aspx pages in a site definition no longer contain code/HTML. They use SharePoint masterpages and page layouts. So instead of changing a lot of aspx pages on the file system, you just make your changes to the page layout or the masterpage. Nice! 

Adding site columns to Office SharePoint Server by using Features

June 30th, 2006 by tonstegeman

As described in the previous item, one of the ways to deploy a site columns is by using Features. Features are another important new feature J in MOSS 2007. They are an easy way to deploy changes to a SharePoint environment. You can deploy site columns, content types, assemblies, webpart, menu items and a lot more. This article will not talk about features, but is using features to deploy a site column.

 

Please note that the code samples you will see are based on a beta version of SharePoint 2007. The actual syntax can be different in later builds of the product.

 

Features are deployed as files on the server. The can be found in the “FEATURES” folder, which is a subfolder of the “TEMPLATE” folder. In this FEATURES folder, I have created a new subfolder called “fieldstst”. In this folder are a number of files.

 

Feature.xml

The feature.xml file is a general description of the feature and looks like this:

 

<Feature  Id="CA7BD552-10B1-4563-85B9-5ED1D39C073B"
  Title="TSTFields"
  Description="Fields added through features by Ton Stegeman"
  Version="12.0.0.0"
  Scope="Site"
  xmlns=http://schemas.microsoft.com/sharepoint/>
  <ElementManifests>
    <ElementManifest Location="fieldstst.xml"/>
  ElementManifests>
Feature>

 

The most important setting here are the Scope, that sets the scope for the feature. This Scope determines the availability of the feature. I have set it to “Site”, which makes my sitecolumns available at the site level. The Location attribute of the ElementManifest element is a reference to the file that has the actual definition of my site column.

 

Site column feature xml

The file fieldtst.xml looks like this:

 

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Field ID="{1DAB9B48-2D1A-47b3-878C-8E84F0D322CB}"
    Name="RegionFromFeature"
    Group="TST_Columns"
    Type="Choice"
    DisplayName="Region"
    SourceID=http://schemas.microsoft.com/sharepoint/v3/fields
    StaticName="RegionFromFeature"
    FillInChoice="FALSE">
    <CHOICES>
      <CHOICE>GlobalCHOICE>
      <CHOICE>EuropeCHOICE>
    CHOICES>
    <Default>GlobalDefault>
  Field>
Elements>

 

I think this XML does not need a very detailed explanation. If you are used to working with site definitions and list templates in SharePoint/WSS 2003, you will recognize the syntax.

 

Installation

The actually use the site column, the feature must be installed and activated. This is done in 2 steps by using STSADM:

 

The first step is to install the feature. In my case this will be like this:

 

stsadm -o installfeature -filename fieldststfeature.xml

 

The second step is to activate the feature:

 

stsadm -o activatefeature -filename fieldststfeature.xml -url http://tonportal

 

After activating, you need to do an IISRESET, and the site column should be available. In my case it is only available in the “tonportal” portal.

 

CMS and SharePoint together in MOSS 2007: using SharePoint metadata in webcontent.

June 30th, 2006 by tonstegeman

In Microsoft Office SharePoint Server 2007, CMS is now integrated into SharePoint. I really like the way that has been done. Webpages are basically documents in a document library. This document library is called “Pages” and is available in every Office Server (not WSS) site definition. This document library contains a number of different contenttypes. They add something like 20 columns to the document library. All content in the webpages is stored in these columns. You can easily see this by creating a new site and add some content to the page. Then click on the “Pages” link in the breadcrumb. This takes you to the document library that contains an item “default.aspx” (see screenshot below).

This is just a normal SharePoint item that has the normal dropdown to take you to “View Properties”. This page shows you all the metadata of the default.aspx document, including the content you entered. Nice!!!

What I also like is that it is now very easy to mix “CMS”  placeholders with “SharePoint” webpartzones in the same page. You do this in the PageLayout.

Because the “Pages” library is just a normal SharePoint list, you can do easily add your own metadata to that list. In the steps below, I will show how you then can add webcontrols to the PageLayout. By doing this your content editors can edit the metadata for the page, while they are editing the content for the page.

Step 1 – Add metadata
I have created 2 sitecolumns at the Homepage of the portal. One of them (industry) is a multivalued lookup to a list called “Industries”. The other is a choicefield. I have created them as sitecolumns, but you can also use contenttypes, or add them directly to the “Pages” library. The image below shows the columns on my Pages library, including my custom fields.

Step 2 – Create a new Page Layout

  • Start SharePoint Designer and open your site.
  • Navigate to “_catalogs” and then to “masterpage”. This is the Master Page Gallery that has the master pages and all Page Layouts.
  • Copy one of the exiting Page Layouts. (I used ArticleLeft.aspx)
  • Rename the new PageLayout and give it a proper description
  • Open the page layout in SharePoint Designer
    The placeholder named “PlaceHolderMain” in my case already had 2 webcontrols for adding metadata to the page, ArticleStartDate and ArticleByLine. I added 2 extra webcontrols just below these controls, to show the Industry and Region fields. The Industry field (which is a multi value lookup) is added like this:

    <SharePointWebControls:MultipleLookupField runat="server" id="IndustriesField" FieldName="Industry"/>

    And the region field is added using this line:

     <SharePointWebControls:DropDownChoiceField runat="server" id="RegionField" FieldName="Region"/>

    In the WSS3 SDK you can find more information about these  WebControls and all the others that are available.You can put them in any placeholder in the page layout. I put them here, because readers who access the page then see the values we have selected at the top of the page. The Title field is an example of a control that is placed in a different placeholder in the same page.

  • Save the Page Layout (and don’t forget to publish and approve it if you want to make it available to all content editors.)

Step 3 – Create a new page

  • Navigate to a Site (not based on any WSS site template)
  • Select Site Actions and Create Page
  • Select the page layout we just created.
  • Your page now should look like this:
  • After editing content and saving the page, it should look like this:

As we have seen it is very easy to use custom metadata in your webpages. I think this is very powerful. It makes it very easy for content editors to maintain metadata on their webpages. And if you run a keyword search for content about a specific industry, the search will now return both documents and webpages. Combined with SiteColumns and ContentTypes, this make content management a lot easier.

Setting site properties in a SharePoint 2007 site definition by using a feature

June 28th, 2006 by tonstegeman

In SharePoint 2007 ‘features’ are new. They are a great way to add all sorts of things to your SharePoint environment. You can use them for example to create content types or site columns (see my previous post). It is also possible to activate a feature from the site definition. I have used this to create a feature that stores properties for the site in the properties (SPPropertyBag) of the site. We can now set these properties while creating the site, directly from the site definition. And the good news: it is extremely easy!

 

Please note the code below is tested on MOSS 2007 beta2. It is not guaranteed to work on later builds.

 

Step 1 – Create a SPFeatureReceiver

·         Create a class library project in Visual Studio 2005.

·         Add a reference to the assembly Microsoft.SharePoint.

·         Sign the assembly.

·         Add a class to the project and let it inherit from SPFeatureReceiver (in the Microsoft.SharePoint namespace)

·         Implement these methods:

o   FeatureActivated

o   FeatureDeactivating

o   FeatureInstalled

o   FeatureUninstalling

·         In my receiver I have only implemented FeatureActivated. This method gets a parameter of the SPFeatureReceiverProperties  type. This parameter has a reference to the site (SPWeb) that you are creating in the Feature.Parent property (see code sample below). The code then simply walks through the properties of the feature and adds them to the propertybag.

public override void FeatureActivated(SPFeatureReceiverProperties properties)

{

    SPWeb web = (SPWeb)properties.Feature.Parent;

    bool updated = false;

    foreach (SPFeatureProperty featureProperty in properties.Feature.Properties)

    {

        if ((!string.IsNullOrEmpty(featureProperty.Name)) && (!string.IsNullOrEmpty(featureProperty.Value)))

        {

            if (web.Properties.ContainsKey(featureProperty.Name))

            {

                web.Properties[featureProperty.Name] = featureProperty.Value;

            }

            else

            {

                web.Properties.Add(featureProperty.Name, featureProperty.Value);

                updated = true;

            }

        }

    }

    if (updated) web.Properties.Update();

}

·         Build the assembly

·         Add the assembly to the GAC

 

Step 2 – Create and install a new feature

·         Create a new folder for your new feature in the folder “C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12TEMPLATEFEATURES”. I called this folder “SiteProperties”.

·         Add a feature.xml file to this folder, and configure your feature:

o   Make sure it has a unique ID (a guid)

o   Set the title and description

o   Make sure the scope is “Web”. This feature can only be used in a web, and not in other scopes.

o   Set the references to your assembly and receiver class from step 1.

o   My xml looks like this:

<Feature

  Id="C15B7790-A6B7-444D-BACF-5C797A4E1F33"

  Title="Site Properties"

  Description="Set per-site properties in the property bag of the site."

  Version="1.0.0.0"

  Scope="Web"

  Hidden="TRUE"

  ReceiverAssembly="Eog.OfficeServer.Features, Version=1.0.0.0, Culture=neutral, PublicKeyToken=fef402cb2da0e9fa"

  ReceiverClass="Eog.OfficeServer.Features.SiteProperties"

  xmlns="http://schemas.microsoft.com/sharepoint/">

</Feature>

·         Install your feature using STSADM:

stsadm -o installfeature -filename sitepropertiesfeature.xml

 

Step 3 – Create a Site Definition

To create a new Site Definition, I started with a copy of the “Publising and Team Collaboration Site” template:

·         Copy the folder PUBLISHING in “C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12TEMPLATESiteTemplates”, and give it a new name.

·         Register the new site template in WEBTEMPSPS.XML (in folder “C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12TEMPLATE1033XML”). This is the same process as registering a new site definition in SharePoint 2003.

·         Do an IISRESET and test if you can create a new site based on the new site definition (at the moment it is just a copy, to make sure we registered it properly)

 

Step 4 – Activate your feature from the site definition.

The last step is to activate your feature from the definition:

·         Open the ONET.XML file in your site definition

·         One of the “Configuration” sections contains a XML node called “WebFeatures”.

·         Add a new “Feature” childnode to that node and set the properties. This ID for the feature is the same as the “Id” in the feature.xml file. This is my xml:

<Feature ID="C15B7790-A6B7-444D-BACF-5C797A4E1F33">

  <Properties xmlns="http://schemas.microsoft.com/sharepoint/">

    <Property Key="NavigationParent" Value="http://tst2007/Reports"/>

    <Property Key="NavigationExpand" Value="3"/>

  </Properties>

</Feature>

·         Save the XML file and do an IISRESET

 

Step 5 – Test

When you create a new site based on this site definition, this site will have 2 extra properties stored in the property bag. I have created a very simple webpart that just reads these 2 properties and writes them in the page. And here’s the result:

 

Adding and using site columns and content types from code in Office SharePoint Server 2007

May 27th, 2006 by tonstegeman

As described in the previous post, sitecolumns are an interesting new feature of Office SharePoint Server 2007. There are 3 ways you can create these sitecolumns:

1.      By using the user interface (see previous item)

2.      By using the object model.

3.      By using SharePoint Features.

 

This item is about the second option. Please note that the code samples you will see are based on a beta version of SharePoint 2007. The actual syntax can be different in later builds of the product.

 

Add a new site column

Sitecolumns can be added to a SPWeb object, which is exactly the same as adding fields to a list. Both SPList and SPWeb now have a “Fields” property. Adding fields these SPFieldCollection object is the same as in SharePoint 2003. The sample below adds a new choicefield to the “Topics” site in my testportal.

 

SPSite site = new SPSite("http://tonportal");

SPWeb web = site.OpenWeb("/Topics");

 

string newFieldName = web.Fields.Add("RegionFromCode",

SPFieldType.Choice, true);

 

SPFieldChoice regionField = (SPFieldChoice)web.Fields[newFieldName];

regionField.Choices.Add("Global");

regionField.Choices.Add("Europe");

regionField.DefaultValue = "Europe";

regionField.Update();

 

This nice thing about a sitecolumn is that when you make changes to them , these changes are pushed to all instances that use the site column. From code you can do this by using the “pushChangesToLists” parameter of the Update method of the SPField:

 

regionField.Update(true);

 

Add site column to a list

When you want to add a site column to a list from code, you can do that by using the “AvailableFields” property of the SPWeb. By using AvailableFields you do not have to worry about the scope of your sitecolumn. Of course it must be available in your site, but you don’t have to figure out if the field is in the current web, or one if it’s parent webs. In the sample below, the site column we create above will be used in one of the subsites of the Topics site. It is added to the “Shared Documents” document library.

 

SPSite site = new SPSite("http://tonportal");

SPWeb web = site.OpenWeb("/Topics/MOSS2007");

SPList list = web.Lists["Shared Documents"];

 

SPField regionField = web.AvailableFields["RegionFromCode"];

list.Fields.Add(regionField);

 

 

 

Content Types

As described in this post by Martin Kearn, content types are another important new feature of MOSS. It is very easy to add site columns to a contenttype. You simply add a new SPFieldLink object to the FieldLinks collection of the contenttype. The code snippet below adds a new content type to the Topics site, and adds the region column we just created to that content type. The content type will inherit from the out of the box SharePoint ‘Document’ content type.

 

SPSite site = new SPSite("http://tonportal");

SPWeb web = site.OpenWeb("/Topics");

 

// Create new content type

SPContentType documentContentType = web.AvailableContentTypes["Document"];

SPContentType newContentType = new SPContentType(documentContentType, web.ContentTypes, "Ton Document");

web.ContentTypes.Add(newContentType);

newContentType = web.ContentTypes[newContentType.Id];

 

// Add FieldLink to content type

SPField regionField = web.AvailableFields["RegionFromCode"];

SPFieldLink fieldLink = new SPFieldLink(regionField);

newContentType.FieldLinks.Add(fieldLink);

newContentType.Update(false);

 

The Update method of a content type has a parameter “UpdateChildren”. If this is true, it will update all content types that inherit from this content type.

 

Use content type

The last step in this post is to add the new content type to a document library. Please not that these steps do not only apply to document libraries, but to all SharePoint lists and content types. To add a contenttype to a list, the list must support contenttypes. You can switch this on by using the ContentTypesEnabled property.

 

SPSite site = new SPSite("http://tonportal");

SPWeb web = site.OpenWeb("/Topics");

SPList list = web.Lists["Document Library"];

 

SPContentType documentContentType = web.AvailableContentTypes["Ton Document"];

list.ContentTypesEnabled = true;

list.ContentTypes.Add(documentContentType);

 

To summarize the steps we have done in this post:

·        Create a new site column

·        Use the site column to a list

·        Create a new content type

·        Add our new site column to the new contenttype

Use the new contenttype in a list

Sitecolumns in Office SharePoint Server 2007

May 26th, 2006 by tonstegeman

One of the many new features in Office SharePoint Server 2007 is the availability of sitecolumns. Sitecolumns are SharePoint list fields, that are defined at the site level. They are a general definition of a column, that can be re-used throughout the site, and it’s subsites. This is an important improvement, because you probably all remembered adding a choicefield “Region” to your lists/libraries in SPS2003. Just after you finished adding this choicefield to all lists, you found out there was a new region that had to be added to all the dropdowns…..
This is where sitecolumns in MOSS help you. Another great thing is that you can now create a “Customer” lookup column, and re-use that throughout all your sites. This way all “Customer” lookups use the same list that holds the customer data. Nice!! These lookups also have a nice new feature: “Allow multiple values”. 

The following is a brief description of how to create site columns. The first step is to create the site column. In any site, go to Site Settings in any site and click “Site columns” in the Galleries section, and click “Create”.

 O_Sitecolumns_1(Click for a larger version)

An important thing to remember is that site columns have a “scope”. The availability of your sitecolumns in the portal/sitecollection depends on this scope. Site columns (this also applies to content types) are available in the site where you create them, and all it’s subsites. Site columns that should be available in every site, should be created at the root level (Home). After you create the site column, you can use that column in all your lists and document libraries (or even better, in content types).

The next step is to add the site columns to a list or document library. Go to the settings menu of your list and click the “Add from existing site columns” link:

O_sitecolumns_3   

When you make an update to the select list, the changes are automatically pushed to all instances, when you select “Update all list columns based on this site column?”  

      O_sitecolumns_2

For each instance of a site column in a list, you can override settings (like “required” or the default value). Please note that when you make changes to the site columns itself, and update all the lists, these changes at the list level will be overridden.