SharePoint 2007 Deployment: Site Content Type Features

Summary

This post is about developing features to create site content types in a SharePoint site. Check the first post SharePoint 2007 Deployment: Overview for an introduction and the series index.

Package Structure

As I mentioned previously in the post SharePoint 2007 Deployment: Creating and Using Features, to build a feature you need to create the following files:

  • The feature manifest file (which must be named feature.xml)
  • One or more element manifest files

The feature manifest file contains the generic information about the feature package, and the element manifest files contain the information about each specific type of element that makes up the feature. Since I already explained all the possible contents of the feature manifest file in the above mentioned post, I will focus this one the element manifest that allows the creation of site content types in a SharePoint site.

You can then place these two files inside a Solution following the instructions in the post SharePoint 2007 Deployment: Creating Solutions, to provide an easy way to deploy the feature (or upgrade it).

Site Content Types

A Content Type is a definition of the metadata and behavior of a SharePoint list item. In short, it specifies a type of list item based on:

  • The columns that compose the list item;
  • The document template used to create a new item (if it’s a document content type);
  • The information management policies associated with it;
  • The workflows associated with it.

Content types have a hierarchic structure, which means that each content type has a parent content type from which it inherits all the definitions. These definitions can be overriden in the child content type.

Each list can have one or more associated content types. Each content type associated to a specific list is called List Content Type. However, any List Content Type must be based on a Site Content Type, which is a content type definition that is not associated to a specific list.

A Site Content Type exists in the context of a web site (organized in groups, in the site content type gallery) and can be associated with any lists of that web site or child web sites.

One can create new site content types or edit the existing ones following the steps below:

  • Site Actions (press the button)
  • Site Settings
  • Site Content Types (in the Galleries option group)

Allowed Scopes

The scopes to which a feature can be deployed, are dictated by the types of elements included in it. A feature with site content type elements can only be deployed to a Site Collection scope, even though you can create a site content type in a non-root web site.

Attempting to install a feature of another scope that contains site content type elements, will result in an error.

Feature Manifest

I will only present a simple feature manifest, since the additional options were presented in the above mentioned post.

<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
         Id="5DFD12AF-D0AA-4c63-8FB8-C49DB1191083"
         Title="My Site Content Type Feature"
         Description="Adds my Content Types."
         Scope="Site"
         Version="1.0.0.0">
    <ElementManifests>
        <ElementManifest Location="ContentTypes.xml"/>
    </ElementManifests>
</Feature>

Notes about this feature manifest:

  • The title of the feature is My Site Content Type Feature.
  • It will be deployed as a Site Collection feature, since it’s Scope value is Site.
  • It references a single element manifest file: ContentTypes.xml.

Element Manifest

The element manifest file can have any name you wish (in this example it’s called ContentTypes.xml), but it’s root element must be <Elements>. Inside this root element, you can place any number of feature element descriptions. In this example I will present the use of the <ContentType> element which is used to deploy Site Content Types.

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
   <ContentType
      ID="0x0100C5647A362F236548B218C15302286758"
      Name="My Content Type"
      Description="Simple Custom Content Type"
      ReadOnly="FALSE"
      Hidden="FALSE"
      Sealed="FALSE"
      FeatureId="5DFD12AF-D0AA-4c63-8FB8-C49DB1191083"
      Group="Custom Content Types">
      <FieldRefs>
         <RemoveFieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" 
Name="Title"/> <FieldRef ID="{b402db15-ee44-4ec4-89e3-23e10a8fc64c}"
Name="My_x0200_Field" /> <FieldRef ID="{538c71e4-8650-4ce7-b021-920effa66346}"
Name="Status" /> </FieldRefs> </ContentType> </Elements>

This example creates a site content type named My Content Type with two custom site columns. Here is a short explanation of the attributes of the <ContentType> element:

  • ID – The ID of the new content type. This ID bears information about the content type hierarchy and, for that reason, cannot be randomly generated. More about this below.
  • Name – The name of the content type.
  • Description – (optional) A descriptive text about the content type.
  • ReadOnly – (optional) Specifies if the content type is read-only, which means its definition cannot be changed. The default value is FALSE.
  • Hidden – (optional) Specifies if the content type is hidden, which means SharePoint will not show it in the New button in the list toolbar. The default value is FALSE.
  • Sealed – (optional) Specifies if the content type is sealed, which means that it cannot have child content types. Only a site collection administrator can unseal a content type. The default value is FALSE.
  • FeatureId – (optional) ID of the feature in which the content type is included.
  • Group – (optional) Name of the content type group to which this content type is assigned.

The <ContentType> element has three optional child elements, one of which is shown in the sample above: the <FieldRefs> element. The other two are <XmlDocuments> and <DocumentTemplate>.

The FieldRefs Element

The <FieldRefs> element is used to specify which site columns are part of the site content type. This element has two possible child elements: <FieldRef> and <RemoveFieldRef>.

The <FieldRef> element specifies a site column that belongs to the content type, and <RemoveFieldRef> specifies a site column that belongs to the parent content type but will be removed from this content type. Both these elements have a mandatory ID attribute that uniquely identify the site column and can have several additional optional attributes (which are a subset of those presented in the previous post for the <Field>; element).

The XmlDocuments Element

Although not used very often, this element allows you to include custom information in the content type in the form of XML nodes. These nodes are represented by a <XmlDocument> element placed inside the <XmlDocuments> element. The contents of the <XmlDocument> element can conform to any schema, sufficing that they are valid XML.

The DocumentTemplate Element

This element is only used if you’re defining a document content type. It allows you to specify the path to the document template that is used to create new items of this content type in a document library. It has a single attribute, TargetName, which is the path (either absolute or relative) to the document template.

Content Type IDs

The content type ID uniquely identifies a content type and encapsulates the content type’s hierarchy. That is, the ID of a certain content type includes the ID of its parent content type.

To create a new ID for a content type you can follow one of two possible conventions:

  • [parent content type ID] + two hexadecimal values (different from "00")
  • [parent content type ID] + "00" + hexadecimal GUID

Usually the first convention is used by SharePoint for the default content types included in SharePoint.

Example:

  • 0x (System)
  • 0x01 (Item Content Type)
  • 0x0101 (Document Content Type, child of Item Content Type)
  • 0x0120 (Folder Content Type, child of Item Content Type)

The second convention is used by SharePoint when

  • You create a new content type based on an existing one
  • A site content type is copied to a list (becoming a list content type)

You should use this convention whenever you create a new content type based on a content type you didn’t create. If you’re creating a content type based on another content type you have create, then you can use the first approach.

Example:

  • 0x01 (Item Content Type)
  • 0x0100C5647A362F236548B218C15302286758 (Custom Content Type based on the Item Content Type)
  • 0x0100C5647A362F236548B218C1530228675801 (Custom Content Type based on the previous content type)

One final note about Content Type IDs is that they have a maximum length of 512 bytes which can hold 1024 hexadecimal characters. The above conventions will help you keep below this limit while ensuring that no one creates a new content type with the same ID.

SharePoint 2007 Deployment: Site Column Features

Summary

This post is about developing features to create site columns in a SharePoint site. Check the first post SharePoint 2007 Deployment: Overview for an introduction and the series index.

Package Structure

As I mentioned previously in the post SharePoint 2007 Deployment: Creating and Using Features, to build a feature you need to create the following files:

  • The feature manifest file (which must be named feature.xml)
  • One or more element manifest files

The feature manifest file contains the generic information about the feature package, and the element manifest files contain the information about each specific type of element that makes up the feature. Since I already explained all the possible contents of the feature manifest file in the above mentioned post, I will focus this one the element manifest that allows the creation of site columns in a SharePoint site.

You can then place these two files inside a Solution following the instructions in the post SharePoint 2007 Deployment: Creating Solutions, to provide an easy way to deploy the feature (or upgrade it).

Site Columns

Just to keep everything clear, I’m going to give a brief explanation about the concept of site columns. Site columns are reusable column definitions, which means that they are exactly the same as a regular list column but do not belong to any single list. A site column exists in the context of a web site (organized in groups, in the site column gallery) and can be used in lists and content types in that web site or its child web sites.

One can create new site columns or edit the existing ones following the steps below:

  • Site Actions (press the button)
  • Site Settings
  • Site Columns (in the Galleries option group)

Allowed Scopes

The scopes to which a feature can be deployed, are dictated by the types of elements included in it. A feature with site column elements can only be deployed to Site Collection or Web Site scopes.

Feature Manifest

I will only present a simple feature manifest, since the additional options were presented in the above mentioned post.

<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
         Id="5DFD12AF-D0AA-4c63-8FB8-C49DB1191083"
         Title="My Site Columns Feature"
         Description="Adds My Site Columns."
         Scope="Site"
         Version="1.0.0.0">
    <ElementManifests>
        <ElementManifest Location="SiteColumns.xml"/>
    </ElementManifests>
</Feature>

Notes about this feature manifest:

  • The title of the feature is My Site Columns Feature.
  • It will be deployed as a Site Collection feature, since it’s Scope value is Site.
  • It references a single element manifest file: SiteColumns.xml.

Element Manifest

The element manifest file can have any name you wish (in this example it’s called SiteColumns.xml), but it’s root element must be <Elements>. Inside this root element, you can place any number of feature element descriptions. In this example I will present the use of the <Field> element which is used to deploy Site Columns.

Since the <Field> element can have a very large number of attributes I will only show a subset with the most common ones.

<Elements xmlns = "http://schemas.microsoft.com/sharepoint/">
    <Field 
    ID="{b402db15-ee44-4ec4-89e3-23e10a8fc64c}"
    Type="Text"
    Title="TextField"
    Name="TextField"
    StaticName="TextField"
    DisplayName="TextField"
    Description="My Text Field."
    Required="FALSE" 
    MaxLength="255"
    Hidden="FALSE"
    ReadOnly="FALSE"
    ShowInDisplayForm="TRUE"
    ShowInEditForm="TRUE"
    ShowInListSettings="TRUE"
    ShowInNewForm="TRUE"
    ShowInVersionHistory="TRUE"
    ShowInViewForms="TRUE"
    Group="Custom Columns">        
    </Field>
</Elements>

This example creates a site column, named TextField, of type Single Line of Text. See below a short explanation of the used attributes:

  • ID – This is the unique identifier of this site column. It will be used to reference this site column when including it in a content type or attaching it to a list.
  • Type – This attribute specifies the type of data stored in the site column. It can have one of the following values:
    • AllDayEvent: All day event flag, used in calendar lists.
    • Attachments: Stores the URL of attachments.
    • Boolean: Specifies a Yes/No field.
    • Calculated: Specifies that this field’s value is calculated based on other columns’ values.
    • Choice: Specifies a Choice (menu to choose from) field with a pre-defined set of values.
    • Computed: Specifies a field whose value depends on another field’s value.
    • ContentTypeId: Contains a Content Type ID value.
    • Counter: Used to hold the internal ID’s for each item.
    • Currency: Specifies a field that stores a currency value (its format depends on the locale).
    • DateTime: Specifies a Date and Time field.
    • File: Contains a file (used in document libraries).
    • GridChoice: Specifies a rating scale (used in surveys).
    • Guid: Specifies a field that holds a unique identifier.
    • Integer: Specifies a number field that holds integer values only.
    • Lookup: Specifies a Lookup field, which is similar to the Choice field except the available choices are retrieved from another list.
    • LookupMulti: Specifies a Lookup field that allows multiple selections.
    • ModStat: Specifies a field that contains content approval status.
    • MultiChoice: Specifies a Choice field that allows multiple selections.
    • Note: Specifies a Multiple Lines of Text field.
    • Number: Specifies a Number field, that can hold floating-point values.
    • PageSeparator: Specifies a page separator (used in surveys).
    • Recurrence: Used to mark an event as recurrent in a calendar list.
    • Text: Specifies a Single Line of Text field.
    • ThreadIndex: Specifies the correlation ID in a threaded conversation (used in discussion lists).
    • Threading: Used in the creation and display of threaded discussion-like views.
    • URL: Specifies a Hyperlink or Picture field.
    • User: Specifies a Person or Group field.
    • UserMulti: Specifies a Person or Group field that allows multiple selections.
    • WorkflowEventType: Contains the type of workflow history event (used in workflow history list).
    • WorkflowStatus: Contains the workflow status (used in lists that have associated workflows).
  • Title – This is the name of the field shown in the interface, and it can be changed by the user.
  • Name – (optional) This is the internal name of the field, and is guaranteed to never change during the lifetime of the field. It is automatically generated from the display name of the field, and the spaces and special characters are escaped.
  • StaticName – (optional) This is automatically set to the same value as the internal name, but can be changed programmatically (not through the interface though).
  • DisplayName – (optional) This is the same as the Title property.
  • Description – (optional) This is the description for the field. SharePoint displays this text in new/edit forms below the data entry control.
  • Required – (optional) Specifies if the field is mandatory. Default value is FALSE.
  • MaxLength – (optional) Specifies the maximum number of characters allowed for this field.
  • Hidden – (optional) Specifies that the field should be completely hidden from the interface. If TRUE, this field will not be shown on views or forms. Default value is FALSE.
  • ReadOnly – (optional) Specifies that the field should be read-only, which means it appears in views but will be hidden from new/edit forms. Default value is FALSE.
  • ShowInDisplayForm – (optional) Specifies that the field should be shown in display forms. Default value is TRUE.
  • ShowInEditForm – (optional) Specifies that the field should be shown in edit forms. Default value is TRUE.
  • ShowInListSettings – (optional) Specifies that the field should be shown in the list settings screen. Default value is TRUE.
  • ShowInNewForm – (optional) Specifies that the field should be shown in new forms. Default value is TRUE.
  • ShowInVersionHistory – (optional) Specifies that the field should be shown in the version history of an item. Default value is TRUE.
  • ShowInViewForms – (optional) Specifies that the field should be shown in view forms. Default value is TRUE.
  • Group – (optional) Specifies the name of the group that contains the site column.

Additional Samples

Because there are so many types of fields, I will include some additional samples and notes to show some of the other attributes used to specify a field.

The Choice Field

    <Field 
    ID="{538c71e4-8650-4ce7-b021-920effa66346}"
    Type="Choice"
    Name="Publishing_x0020_Status"
    StaticName="Publishing_x0020_Status"
    DisplayName="Publishing Status"
    Required="FALSE"  
    Format="Dropdown"
    FillInChoice="FALSE"
    Group="Custom Columns">
        <Default>Not Published</Default>
        <CHOICES>
            <CHOICE>Not Published</CHOICE>
            <CHOICE>Pending</CHOICE>
            <CHOICE>Published</CHOICE>
            <CHOICE>Error</CHOICE>
        </CHOICES>
    </Field>

The Choice field has a few specific issues that are worth mentioning:

  • The Type attribute must be set to Choice.
  • The Format attribute is used for several purposes, but in choice fields, it defines the type of control used to select the option. Possible values are Dropdown (default) and RadioButtons.
  • The attribute FillInChoice specifies if the user can add choices to the column.
  • The <Default> child element specifies which of the choices is pre-selected in the control as default.
  • The <CHOICES> child element contains all the possible value options, each in its own <CHOICE> child element. Beware that you must use capital letters for these elements, otherwise the field will not contain any of the choices.

The Multiple Lines of Text Field

  <Field 
    ID="{5b79f1f1-b14f-489b-9bd5-a76897db93b9}"
    Type="Note"
    Name="My_x0020_Comments"
    StaticName="My_x0020_Comments"
    DisplayName="My Comments"
    Required="FALSE"
    UnlimitedLengthInDocumentLibrary="TRUE"
    NumLines="10"
    RichText="FALSE"
    Sortable="FALSE"
    Group="Custom Columns">
  </Field>

The Multiple Lines of Text field also has some specific attributes:

  • The Type attribute must be set to Note.
  • The UnlimitedLengthInDocumentLibrary attribute specifies that there will be no limitation to the contents of this field when used in document libraries.
  • The NumLines attribute defines the number of lines shown in the data entry control (textarea HTML control).
  • The RichText attribute specifies if the field accepts formatted text or only plain text.
  • The Sortable attribute specifies if the field can be used to sort a list. Note fields always have the Sortable attribute set to FALSE.

The Number Field

  <Field
    ID="{5b7934e1-b14f-489b-9bd5-a76837da92b4}"
    Type="Number"
    Name="My_x0020_Number"
    StaticName="My_x0020_Number"
    DisplayName="My Number"
    Required="FALSE"
    Min="0"
    Max="100"
    Decimals="0"
    Percentage="FALSE"
    Group="Custom Columns">
  </Field>

The Number field has the following additional attributes:

  • The Type attribute must be set to Number.
  • The Min and Max attributes specify the minimum and maximum values that this field can contain. Both attributes are optional.
  • The Decimals attribute specifies the number of decimal places of the number stored in the field.
  • The Percentage attribute specifies if the number is to be shown as a percentage. Default value is FALSE.

The Lookup Field

The Lookup field is the only field type that cannot be created with a simple feature such as this one. The cause for this is the fact that this type of field references a column of a list using the list’s ID, and a list’s ID is dynamically generated when a list is created.

This means that there is no way one can predict what will be the ID of the list referenced by the Lookup field when the feature is developed. This value is only known when the feature is activated in a specific web site.

For that reason, the steps to create a feature for this type of site column will be the subject of one of the next posts of the series.

TechDays 2008

Terminou na passada sexta-feira, 14 de Março, a terceira edição do TechDays. Durante 3 dias, várias centenas de participantes assistiram a conferências técnicas dadas por 120 oradores, e trocaram experiências entre si. Esta edição foi bastante maior do que as anteriores, e contou com a participação de muito mais empresas no salão de exposições. Podem consultar todos os detalhes em http://www.techdays.pt.

Infelizmente este ano apenas pude estar presente nos últimos dois dias. No entanto, foi um evento especial para mim, já que me deram a oportunidade de apresentar uma sessão. Aqui fica o meu agradecimento à Microsoft pelo convite.

Em relação à sessões a que assisti, aqui fica o meu testemunho:

  • INT04: Qual é o Contexto desta Conversação? Activando Conversações Longas em Serviços de Workflow. Serviços "Duráveis" – Sessão muito interessante sobre Workflow Services, dada pelo Zé Tó da Microsoft. Para quem não conhece o conceito, trata-se do resultado de integrar serviços WCF com workflows WF e permite resolver problemas como a manutenção de estado entre chamadas a serviços.
  • ARC01: Software + Services: The Convergence of SaaS, SOA and Web 2.0 – Excelente sessão, dada pelo Beat Schwegler da Microsoft, sobre S+S. Tratou-se de uma sessão mais teórica mas não demasiado complexa, e o Beat conseguiu passar muito bem a mensagem e a visão da Microsoft sobre o tema. Deu alguns exemplos claros de implementações do conceito, como o Eve Online ou o Amazon S3.
  • INT06: Viagem ao Centro da Núvem – O Internet Service Bus (ISB) e os BizTalk Services – Não podia faltar à Sessão do Jota não só por ser amigo e colega, mas porque o tema é muito interessante. O Jota conseguiu desafiar a audiência e eficazmente levantar o véu sobre os BizTalk Services e o que poderão vir a representar num futuro próximo. Apesar de se tratar de uma tecnologia ainda num estádio precoce, o seu potencial é enorme e poderá revolucionar a forma como as aplicações comunicam entre si. A ideia é capitalizar sobre o investimento feito pela Microsoft em tecnologias como o MSN Messenger e o Groove, que conseguem adaptar-se às configurações de segurança existentes e estabelecer ligações através de firewalls.
  • DEV02: Linguagens Dinâmicas na Plataforma .NET (Iron Python e IronRuby) – Como developer não poderia deixar de assistir a uma das sessões desta track. Esta em particular versou sobre duas novas linguagens do mundo .Net, o IronPython e o IronRuby, baseadas em Python e Ruby, respectivamente. Trata-se de linguagens interpretadas, com uma sintaxe bastante mais simples e mais natural que o C# mas com expressividade idêntica. Foi uma sessão introdutória mas bastante interessante, dada pelo Alcides Fonseca, Microsoft Student Partner.
  • COL07: Microsoft Search Server 2008 – Introdução e Apresentação de Novas Funcionalidades – Apresentação de um novo produto da Microsoft, derivado do Office SharePoint Server for Search, com algumas melhorias no motor de pesquisa e na sua interface de configuração. O Bruno Valente e o Luís Calado Sousa, da Microsoft, conseguiram explicar as melhorias e os impactos deste novo produto no mercado e nas organizações. É certamente um produto a manter debaixo de olho, para quem se movimenta no mercado SharePoint.
  • WEB05: ASP.NET Futures – Dynamic Data Controls and Astoria Services – Esta foi a primeira de duas sessões do Matt Gibbs (Microsoft) sobre a próxima versão do ASP.NET. O foco principal foram os Dynamic Data Controls que integrarão o próximo pacote de extensões do ASP.NET e que conseguem obter o schema da base de dados em tempo real adaptando-se automaticamente (mais informações aqui).
  • VST03: Hardcore Debuging e Profiling de Aplicações .NET – Assisti a esta sessão mais por curiosidade e, apesar de ser relativamente complexo, gostei bastante de conhecer algumas das técnicas e ferramentas de debuging usadas pelo suporte da Microsoft: MDbg, WinDbg, SOS e Hawkeye são apenas algumas delas. Esta sessão foi apresentada pelo Filipe Prezado e pelo João Loureiro, ambos da Microsoft.
  • WEB04: MVC Framework on Future ASP.NET – A segunda sessão do Matt Gibbs (Microsoft) sobre a próxima versão do ASP.NET, desta vez focada na implementação do padrão MVC, pela Microsoft. Eu já tinha assistido a uma sessão semelhante há alguns meses atrás, na Microsoft, pelo Dino Esposito, sobre o MVC. Trata-se de uma alternativa ao desenvolvimento ASP.NET clássico (e não uma substituição do existente) em que o desenvolvimento é feito em Modelos, Controladores e Vistas, e no qual o URL passa a ter um papel central. Deixa de existir code-behind e o developer passa a ter maior controlo sobre o markup gerado pelos controlos.

Relativamente à sessão que apresentei, COL04: Desenvolvimento de Aplicações Sofisticadas com Microsoft Office SharePoint Designer 2007, o objectivo era mostrar como se pode construir uma aplicação sobre SharePoint 2007, usando o SharePoint Designer 2007, sem código. Baseei-me num dos site templates da Microsoft (os fantásticos 40), ao qual adicionei algumas funcionalidades através de Data Views e Workflows, e mostrei como se fazia.

A sala estava cheia e penso que no geral correu bem, mas tenho consciência que há muito a melhorar e a aprender. A todos os que estiveram presentes, obrigado 🙂