All about Microsoft Office SharePoint Server Content Type – Part 4

In the part 1 of the article we covered

  • What is a content type
  • How content types work
  • In the part 2 of the article we covered

  • Extending content types
  • Attaching workflows to a content type
  • Attaching event handlers to a content type
  • In the part 3 of the article we will cover

  • How to create a Content Type programmatically using SharePoint object model
  • Significance of Content Type ID
  • Creating Content Types using Visual Studio Extensions for WSS
  • Deployment of Content Types as Features
  • In this part 4 (final part) of the article we will cover

    • Solution Package Editing in VS 2008 / WSP view
    • Adding content type to a list definition

     

    Solution Package Editing in VS 2008 / WSP view:

    Using Visual Studio 2008 and VSeWSS 1.2 you can create SharePoint projects. It also provides a developer friendly WSP view / Solution Package Editing option. Lets run through this option to see how it helps developers to quickly create the WSP and and the Deployment Package.

    Pre Requisites:

    VS 2008

    VSeWSS 1.2

    • Start up your Visual Studio 2008.
    • File->New->Project choose SharePoint under Visual C# project types
    • Select ‘Empty’ project.
    • Right Click the project –>Add->New Item choose SharePoint under Visual C# categories and select ‘Content Type’
    • Give it a name for example ‘MyNewContentType’
    • Choose ‘Item’ as the base content type.
    • Edit the ‘MyNewContentType.xml’ and un comment the Field schema definition (We are going to use the default fields generated for this demo)
    • <?xml version="1.0" encoding="utf-8"?>
      <Elements Id="ca5ae715-cdb6-4454-b581-a5c3b968fc7c"
          xmlns="http://schemas.microsoft.com/sharepoint/">
        <ContentType ID="0x01000cd55cdd7f634cc6aa237f152e1a1875"
                     Name="MyNewContentType"
                     Group="Development"
                     Description="Developing Content Type"
                     Version="0">
          <FieldRefs>
            <FieldRef
              ID="{2986f56e-9b87-426a-b7ee-989758c88533}"
              Name="MyNewContentTypeField" />
          </FieldRefs>
        </ContentType>
        <Field ID="{2986f56e-9b87-426a-b7ee-989758c88533}"
               Type="Text"
               Name="MyNewContentTypeField"
               DisplayName="MyNewContentType Field"
               StaticName="MyNewContentTypeField"
               Hidden="FALSE"
               Required="FALSE"
               Sealed="FALSE" />
      </Elements>
    • In the Solution Explorer window you will find a tab ‘WSP View’

    image

    • Let us look at this TAB and see what we got there. If it does not show the contents hit the ‘Refresh’ button

    image

    • This has the virtual view of the solution package our VSeWSS is putting together for us.
    • Here you can edit the feature.xml and update the name, display properties.
    • This gives more control to the developers and also it provides a easy way to deploy to the local SharePoint box for testing
    • Right Click the project select properties and choose Debug tab. Set the URL to the desired Site Collection where the feature needs to be deployed.

    image

    • Now you can either press F5 or Right Click Project and Select ‘Deploy’ option.
    • This will create the deployment package, deploy the solution and activate the feature for the selected site collection.

    Adding a Content Type to a List Definition:

    In this walk through I am going to create a new List Definition and add the ‘MyDerivedContentType’ that I created earlier (refer to Part – 3)

    • Start up your Visual Studio 2008.
    • File->New->Project choose SharePoint under Visual C# project types
    • Select ‘List Definition’

    image

    • Once selected it will create a project structure similar to the one shown below

    image

    • Open the Schema.xml. Insert the ContentTypeRef node inside the ContentTypes tag

    <ContentTypeRef ID=”0x010044AFF40E174C4F7D89861FF89CEE1D15003824D8E586F44E54AC7049578A0100E5“/>

    <ContentTypes>
      <ContentTypeRef ID="0x01">
        <Folder TargetName="Item"/>
      </ContentTypeRef>
      <ContentTypeRef ID="0x0120"/>
      <ContentTypeRef
        ID="0x010044AFF40E174C4F7D89861FF89CEE1D15003824D8E586F44E54AC7049578A0100E5"/>
    </ContentTypes>
    • The tricky thing is we have to now add all the fields that we want as part of this list instance of the ContentType. If we do not add the fields and update the views we will not get those columns even though it is part of the ContentType. I think it is kept this way in order to have the flexibility of creating an instance of the existing content type with the desired columns.
    • Under the Fields node add all the Fields that are part of the ‘MyDerivedContentType’ including the one in the base content type,
    <Fields>
          <Field ID="{71ED4BE5-B83F-47e4-866E-08D226709522}"
           Name="Project Status"
           Type="Choice"
           DisplayName="Project Status"
           Group="Custom Columns"
           Format="Dropdown">
            <CHOICES>
              <CHOICE>Not Started</CHOICE>
              <CHOICE>In Progress</CHOICE>
              <CHOICE>Completed</CHOICE>
            </CHOICES>
          </Field>
          <Field ID="{5623b931-2e9e-4dc6-81b6-c8a151f37418}"
            Name="Team Member"
            Type="User"
            List='UserInfo'
            UserSelectionMode="1"
                UserSelectionScope="1"
            DisplayName="Team Member"
            Group="Custom Columns"
            SourceID="http://schemas.microsoft.com/sharepoint/v3"
            ShowAddressBookButton="TRUE">
          </Field>
          <Field ID="{9b39033a-4f1c-4a0f-9deb-73fecdbc3b5d}"
            Name="Project Type"
            Type="Choice"
            DisplayName="Project Type"
            Group="Custom Columns"
            Format="Dropdown">
            <CHOICES>
              <CHOICE>Internal</CHOICE>
              <CHOICE>External</CHOICE>
            </CHOICES>
          </Field>
    </Fields>
    • Under the ‘ViewFields’ node add the fields that we want to see in the New and Edit forms.
    <ViewFields>
      <FieldRef Name="LinkTitleNoMenu">
      </FieldRef>
      <FieldRef Name="Project Type">
      </FieldRef>
      <FieldRef Name="Project Status">
      </FieldRef>
      <FieldRef Name="Team Member">
      </FieldRef>
    </ViewFields>
    • Set the debug URL to the site collection you want this list definition to be deployed and press F5 or choose ‘Deploy’ option when you right click the Project in the solution explorer.
    • Once deployed go to the Site Collection. Create a new List and choose your new ‘List Definition1’ instead of the Custom List option.

    image

    • This will create a list with the desired site columns from the content type. If you enable management of Content Types in this list you can see lineage of the columns.

    image

    This concludes the four part series on Content Types.

    Useful Links:

    Part – 1 , Part – 2 , Part – 3 , Part – 4

    Advertisements

    All about Microsoft Office SharePoint Server Content Type – Part 3

    In the part 1 of the article we covered

  • What is a content type
  • How content types work
  • In the part 2 of the article we covered

  • Extending content types
  • Attaching workflows to a content type
  • Attaching event handlers to a content type
  • In this part 3 of the article we will cover

  • How to create a Content Type programmatically using SharePoint object model
  • Significance of Content Type ID
  • Creating Content Types using Visual Studio Extensions for WSS
  • Deployment of Content Types as Features
  •  In the part 4 (final part) of the article we will cover

    • Solution Package Editing in VS 2008 / WSP view
    • Adding content type to a list definition

    How to create a Content Type programmatically using SharePoint object model:

  • Lets try and add a content type called “NewSpec” that inherits from another custom content type called “Spec” . Make sure you add the content type to the web before you call the update method of the content type. 
    using (SPSite site = new SPSite("http://vslearnmoss/sites/sitecoll1"))
    {
        using (SPWeb web = site.OpenWeb())
        {
            SPContentType contentType = new SPContentType
             (web.AvailableContentTypes["Spec"],web.ContentTypes, "NewSpec");
            web.ContentTypes.Add(contentType);
            web.Fields.Add("SpecColumn1", SPFieldType.Text, true);
            SPFieldLink fieldLink = new SPFieldLink(web.Fields["SpecColumn1"]);
            contentType.FieldLinks.Add(fieldLink);
            contentType.Update();
        }
    }

     

    Significance of Content Type ID:

    Content type IDs uniquely identify the content type. Content type IDs are designed to be recursive. The content type ID encapsulates that content type’s “lineage”, or the line of parent content types from which the content type inherits. Each content type ID contains the ID of the parent content type, which in turn contains the ID of that content type’s parent, and so on, ultimately back to and including the System content type ID. By parsing the content type ID, you can determine which content types the content type inherits, and how two content types are related.

    Windows SharePoint Services V3 uses this information to determine the relationship between content types, and for push down operations.

    You can construct a valid content type ID using one of two conventions:

    · Parent content type ID + two hexadecimal values

    · Parent content type ID + “00” + hexadecimal GUID

    There is one special case, that of the System content type, which has the content type ID of “0x”. The System content type is the sealed content type from which all other content types ultimately inherit.

    For all other content types, you must use one of the above methods for constructing a valid content type ID.

    Note that if you use the first method, the two hexadecimal values cannot be “00”.

    A content type ID must be unique within a site collection.

    Content type IDs have a maximum length of 512 bytes. Because two hexadecimal characters can fit in each byte, this gives each content type ID an effective maximum length of 1024 characters.

    …more info on Andrew May’s web log

    SPContentType.ID property is a read only property. When you create Content Types programmatically the ID creation is taken care of. If you are creating your content type using features then you will have to define the content types.

     

    Creating Content Types using Visual Studio Extensions for WSS:

    Dev Environment – VS 2008 Professional Edition with VSeWSS 1.2

    • Open Visual Studio, choose File->New->Project
    • Select SharePoint project templates under Visual C#, choose ‘Empty’ project template.

    image

    • Select SharePoint project templates under Visual C#, choose ‘Empty’ project template.
    • Type in your name for the Project and Select the Project Location and click OK
    • After the project structure is created. Right click the project and choose Add-> New Item and select Content Type under SharePoint category.

    image

    • When you add this new item, you will be prompted to choose the Base Content Type. Choose ‘Item’. You can choose other base content types depending upon the need.

    image

    • It will generate an XML file with a dummy field references as well. The file generated follows the Content Type definition schema and Field definition schema.
    • The ContentType ID generated is “0x010044aff40e174c4f7d89861ff89cee1d15”. Here 0x01 denotes ‘Item’ base content type and it is followed by 2 zeros and then the GUID of the new content type 0x010044aff40e174c4f7d89861ff89cee1d15.
    • Let us assume that we want to create 2 site columns. One field of type User and another of type Choice column. Edit the ‘MyBaseContentType.xml’ and include the following.
    • <?xml version="1.0" encoding="utf-8"?>
      <Elements Id="5d7dfb50-7693-4f6f-aa61-0a3cfedca39a"
           xmlns="http://schemas.microsoft.com/sharepoint/">
       
        <Field ID="{5623b931-2e9e-4dc6-81b6-c8a151f37418}"
              Name="Team Member"
              Type="User"
              List='UserInfo'
              UserSelectionMode="1"
                  UserSelectionScope="1"
              DisplayName="Team Member"
              Group="Custom Columns"
              SourceID="http://schemas.microsoft.com/sharepoint/v3"
              ShowAddressBookButton="TRUE">
        </Field>
        <Field ID="{9b39033a-4f1c-4a0f-9deb-73fecdbc3b5d}"
            Name="Project Type"
            Type="Choice"
            DisplayName="Organization"
            Group="Custom Columns"
            Format="Dropdown">
          <CHOICES>
            <CHOICE>Internal</CHOICE>
            <CHOICE>External</CHOICE>
          </CHOICES>
        </Field>
        <ContentType ID="0x010044aff40e174c4f7d89861ff89cee1d15"
                     Name="MyBaseContentType"
                     Group="Development"
                     Description="Developing Content Type"
                     Version="0">
          <FieldRefs>
            <FieldRef ID ="{5623b931-2e9e-4dc6-81b6-c8a151f37418}"
               Name ="Team Member"
               Required="TRUE">
            </FieldRef>
            <FieldRef ID ="{9b39033a-4f1c-4a0f-9deb-73fecdbc3b5d}"
               Name ="Project Type"
               Required="TRUE">
            </FieldRef>
          </FieldRefs>
        </ContentType>
      </Elements>
    • Build the solution. Right Click the Project in the Visual Studio Solution Explorer and Choose ‘Deploy’ option. This Content Type will be packaged as a feature and deployed globally and the feature will be activated.
    • Go To Site Collection->Site Actions->Site Settings->Site Content Types you will see ‘MyBaseContentType’ under the Development as we chose the group name as ‘Development’

    image

    • Go To Site Settings->Site Collection Features you will see the MyBaseContentType feature activated.

    image

    We have now created a new content type and deployed it from the familiar Visual Studio environment. If you want to derive this content type and create a new content type. Follow the below mentioned steps.

    • Create a new Visual Studio project similar to the one described above. Name it as MyDerivedContentType. Choose ‘Item’ as the base content type.
    • Edit the MyDerivedContentType.xml and include field definition for an additional field for representing project status. Refer to the code below.
    <?xml version="1.0" encoding="utf-8"?>
    <Elements Id="84e70bc9-5444-4634-a256-96e0caf8dce6"
           xmlns="http://schemas.microsoft.com/sharepoint/">
      <Field ID="{71ED4BE5-B83F-47e4-866E-08D226709522}"
          Name="Project Status"
          Type="Choice"
          DisplayName="Project Status"
          Group="Custom Columns"
          Format="Dropdown">
        <CHOICES>
          <CHOICE>Not Started</CHOICE>
          <CHOICE>In Progress</CHOICE>
          <CHOICE>Completed</CHOICE>
        </CHOICES>
      </Field>
      <ContentType
          ID="0x010044aff40e174c4f7d89861ff89cee1d15003824d8e586f44e54ac7049578a0100e5"
                   Name="MyDerivedContentType"
                   Group="Development"
                   Description="Developing Content Type"
                   Version="0">
        <FieldRefs>
          <FieldRef ID ="{71ED4BE5-B83F-47e4-866E-08D226709522}"
             Name ="Project Status"
             Required="TRUE">
          </FieldRef>
        </FieldRefs>
      </ContentType>
    </Elements>
    • Update the ContentType ID in the following fashion
      • Item + 00 + BaseContentType + 00 + NewGUID
      • image
    • Add the fields as required. In this example I have added ‘Project Status’ .
    • Build and Deploy the project as explained above.
    • Go To Site Actions->Site Settings->Site Collection Features and Activate the My Derived Content Type Feature.
    • Go to the Site Settings->Site Content Types gallery. You will see the new content type added. image

    Deployment of Content Types as Features:

    Let us go through the steps for creating a WSP file using the MakeCab utility. We will make this as part of the build events and generate the WSP from within Visual Studio environment.

     

    Follow the steps mentioned in Creating Content Types using Visual Studio Extensions for WSS section above for creating a content type project

    I have re used the MyDerivedContentType project.

    • Create a new text file with a name Package.ddf. This will contain the definition for the MakeCab utility. This will include the path for the manifest file, feature.xml and the elements.xml (In our project the element file is named as MyDerivedType.xml)
    ;*** MakeCab Directive file
    ;
    .OPTION Explicit ; Generate errors
    .Set CompressionType=MSZIP
    .Set UniqueFiles=Off
    .Set Cabinet=On
    .Set DiskDirectory1=Package
    .Set CabinetNameTemplate=MyDerivedContentType.cab
    ;
    ; \
    ;**************************************************
     
    manifest.xml
     
    .Set DestinationDir=MyDerivedContentType
    MyDerivedContentType\Feature.xml
    MyDerivedContentType\MyDerivedContentType.xml
    ;
    ;***End
    • Create a new XML file with the name manifest.xml and place it in the project folder. This manifest file will have reference to the Feature manifest(feature.xml) and the Resource (MyDerivedType.xml) location.
    <Solution SolutionId="C8109F9E-6551-4c5b-94CF-E187FEF85712"
          xmlns="http://schemas.microsoft.com/sharepoint/">
     
      <FeatureManifests>
        <FeatureManifest Location="MyDerivedContentType\Feature.xml"/>
      </FeatureManifests>
     
      <Resources>
        <Resource Location ="MyDerivedContentType\MyDerivedContentType.xml"/>
      </Resources>
    </Solution>
    • Create a new XML file and place it in the MyDerivedType folder. The feature.xml will have reference to the elements xml file(MyDerivedType.xml).
    <Feature
        Title="My Derived Content Type Feature"
        Id="850DEEC6-D53D-4aeb-8C60-E4C66CF9FCE4"
        Scope="Site"
        Description="Adds a content type based on the My Base Content type"
        Version="1.0.0.0"
        Hidden="FALSE"
        DefaultResourceFile="core"
        xmlns="http://schemas.microsoft.com/sharepoint/" >
     
      <ElementManifests>
        <!-- Calling Element file to load Custom Column, Webpart and Site Template-->
        <ElementManifest Location="MyDerivedContentType.xml" />
      </ElementManifests>
     
    </Feature>
    • After adding the package.ddf, manifest.xml and the feature.xml the folder structure will look like this

    image

    • Once you are done Right Click the Project and choose properties, Go to Build Events tab and add the following post build commands

    image

    cd "$(ProjectDir)"
    makecab.exe /F Package.ddf
    ren Package\MyDerivedContentType.cab MyDerivedContentType.wsp
    • This command will use the makecab utility after a successful build to create a CAB file as per the package.ddf directive file included. And will rename it to .wsp that can be used for the deployment.
    • In addition it will also create a solution folder which also includes this WSP and the setup.bat to help with the deployment. You can also use STSADM command line utility to ‘ADD’, ‘DEPLOY’ and ‘ACTIVATE’ the feature as required.

    Useful Links:

    Part – 1 , Part – 2 , Part – 3 , Part – 4

    Create GUID disabled in Visual Studio 2008

    Just when I wanted to create a GUID i found that the ‘Create GUID’ menu was disabled in the Tools menu.

    image

     

    Found that I have to copy over the following files from “Program Files\Microsoft SDKs\Windows\v6.0A\Bin” folder to the “Microsoft Visual Studio 9.0\Common7\Tools” folder.

    1. guidgen.exe
    2. uuidgen.exe

    I am not sure why the files were missing, may be there was an issue while installing Visual Studio 2008.

    I found this workaround solution at : http://forums.asp.net/t/1209461.aspx

    also check this http://social.msdn.microsoft.com/Forums/en-US/vssetup/thread/5a9efc16-5cb3-42f5-871b-1f7cc2386e28/

    Error : An unhandled exception occurred in the user interface.Exception Information: OSearch

    You might receive this error if you have not qualified the user account with the domain name

    I received this error while I was setting up Search Service on a MOSS machine.

    image

    I fixed it by setting the farm search service account qualified with a domain name.

    image

    All about Microsoft Office SharePoint Server Content Type – Part 2

    In the part 1 of the article we covered

  • What is a content type
  • How content types work In this part 2 of the article I will cover the following
  • Extending content types
  • Attaching workflows to a content type
  • Attaching event handlers to a content type
  •  

    Extending Content Types :

    You can create site content types based on other site content types. To do this, the site on which you are creating your new content type must be in scope for the site content type from which you are deriving the new content type.

    In this way you can create a general site content type, which contains attributes common to several types of content, and then derive more specific site content types from it. This is exactly what Windows SharePoint Services does in its own built-in content type hierarchy. All content types ultimately derive from the System content type.

     

    Lets take the following hierarchy as an example. A parent site has a base content type called DocumentX. In the same site 2 other content types Spec and Memo inherits from DocumentX content type.

    A content type in a sub site ProductXSpec inherits from Spec content type. A list in that site uses ProductXSpec from the sub site and Memo from the parent site.

     

    image

     

    First I created a content type by name DocumentX from List Content Type group item as the base. (Refer to Part 1 of this article to find out more about creating a new content type) Then I created Spec and Memo content types choosing Custom Content Type group and DocumentX as the parent from the dropdown.

    image

     

    In the child site I created a new content type ProductXSpec that inherits from Spec content type.

    image

    then I created a list called ProductSpec which has content types enabled. In this list I associated the content type ProductXSpec and Memo.

    image

    Now I can enter content relating to ProductXSpec and Memo. The list content types ProductXSpec and Memo inherits from the parent but allows you to customize and the scope is limited to this list. I can now add a new column that becomes part of both ProductXSpec and Memo as well. Make sure that you choose “Add to all content types”

    The scope of this column is within this list content type and does not affect the site content type from which the list content type derives from.

    image

     

    Attaching workflows to a content type:

    The availability of a workflow within a site varies, depending on where it is added:

    • If you add a workflow directly to a list or library, it is available only for items in that list or library.
    • If you add a workflow to a list content type (an instance of a site content type that was added to a specific list or library), it is available only for items of that content type in the specific list or library with which that content type is associated.
    • If you add a workflow to a site content type, that workflow is available for any items of that content type in every list and library to which an instance of that site content type was added. If you want a workflow to be widely available across lists or libraries in a site collection for items of a specific content type, the most efficient way to achieve this result is by adding that workflow directly to a site content type.

    You can add a workflow to a content type and ensure that all content types inheriting from this base content type will also get the workflow attached.

    • Click Add a workflow and choose from the available default workflows out of the box or any custom workflow that is available in that site collection.
    • To ensure that all inheriting content types get this workflow select “Add this workflow to all content types that inherit from this content type? “

    image

    image

     

     

    Attaching event handler to a content type:

    You can attach event handler to a content type. I created a list in the ProjectXYZ subsite using a content type called ‘Spec’ created earlier.

    Then I created a EventHandler using the simple code displayed below.

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint;
     
    namespace ProductSpec.EventHandlers
    {
        class HandleDelete : SPItemEventReceiver
        {
     
     
            public override void ItemDeleting(SPItemEventProperties properties)
            {
                    properties.Cancel = true;
                    properties.ErrorMessage = "This is a readonly item 
    
    therefore you cannot delete it.";
     
            }
        }
    }

     

    I registered the event handler to the content type ‘Spec’ using the EventHandlerExplorer tool from U2U.

    image

     

    Once associated. I created a new list based on the ‘Spec’  content type. I added an entry into the list. When I try to delete I get this nice little message that I have added in the ‘ItemDeleting’ event.

    image

    * Note : To be continued in Part 3

    Useful Links:

    Part – 1 , Part – 2 , Part – 3 , Part – 4

    All about Microsoft Office SharePoint Server Content Type – Part 1

    In this article I would like touch upon the following areas.

    • What is a content type
    • How content types work
    • Extending content types
    • Attaching Workflows to a content type
    • Attaching event handlers to a content type
    • Deploying a content type as a feature

    What is a Content Type:

    A content type is a reusable settings that describe the shared behaviors for a specific type of content. or in other words Content types enables us to manage the metadata and behavior of a document or a list item type in a centralized manner, that is reusable.

    Content types can be defined for documents, list items, folders. Content types can be used organize content across multiple lists and libraries across the site collection. Also a list or a library can contain references to multiple Content types.

    How Content types work:

    Content Type Terminologies:

    • Site Content type – Content types are created at the site level and they act as a template which can be instantiated in a list under a sub site.
    • List Content type – The instance of the Site content type is called a list content type. When we add a site content type to a list SharePoint creates a copy of the Site content type  onto the list.
    • Content type scope – The scope depends on the site where the content type is created. The content type is then available to all the sub sites.
    • Parent content type – All the content types follow a hierarchy. The following image(Fig – Base content type hierarchy) shows the relationship between the different content types. Ultimately all the content types inherit from System content type.
    • Groups – Categorizing content types into groups to make it easier for users to find them.(Fig – Content Type Groups)

    Base content type hieararchy

    Fig – Base Content type hierarchy

    image

    Fig – Content Type Groups

     

    Creating a new List Content Type :

    In this example we are going to create a new content types called Project Task

    • Go to the Site or Site Collection top level site where you want to create the content type.
    • On the Site Actions menu click Site Settings
    • In the Galleries column select Site content types

    image

     

    • This opens the gallery listing all the existing site content types, click Create
    • Enter the Content type name as ‘Project Task’ and choose ‘List Content Types’ group and ‘Item’ as the Parent Content Type and click OK.

      image

    • The content type gets saved and navigates to the admin page of the content type. Go to Columns section and click ‘Add from new site column’. We will now create new site columns to be added to this content type.

    image

     

    • Add 2 columns Project Task – Single line of text, Project Details – Multiple lines of text.

    image

    image

    • Go to the custom list to which we are going to associate this new content type.
    • Click Settings->List Settings->Choose Advanced settings from the General Settings section.
    • Make sure that the ‘Allow management of content types’ is selected.

    image

    image

    • Get back to the settings page and select ‘Add from existing site content types’

    image

    • Choose the ‘Project Task’ from the list box and click ‘Add’ and click OK.
    • Now we are done with associating a content type with the list.

    image

    • Now when you click ‘New’ from the list’s all items view page you will see an option ‘Project Task’

    image

    • This opens a new item page with the columns that we associated with the content type.

    image

    • At this point the list has instantiated a copy of ‘Project Task’ content type. Lets see how it behaves when we update the content type. Let us add a new column called ‘Task Owner’.  Go To Site Actions->Site Settings->Site Content Types->Select the ‘Project Task’ content type->Go to columns Section and click ‘Add from new site column’.

    image

    image

    • Enter ‘Task Owner’ in the column name and choose ‘Person or Group’ and make sure the ‘Update all content types inheriting form this type’ is selected.(default selection)
    • Go back to the Project Tasks list which uses the ‘Project Task’ content type->Click New Project Task. Here you will see the newly updated column Task Owner appearing in the form.

    image

    Creating a new Document Content Type :

    In this example we are going to create 2 new document content types called Project Proposal and Technical Design and associate it with a document library named Project Documents 

    • Go to the Site or Site Collection top level site where you want to create the content type.
    • On the Site Actions menu click Site Settings
    • In the Galleries column select Site content types
    • This opens the gallery listing all the existing site content types, click Create
    • Enter Project Proposal as the name of the content type and choose Document under the Document Content Types group. Click OK.

    image

    • The content type gets saved and navigates to the admin page of the content type. Go to Settings section and click ‘Advanced Settings’. We can associate a document template that is available in the site or can associate a document template from your local computer. In this case I have chosen to associate a .dotx template i have in my local drive.

    image

    image

    • Repeat the above steps and add a new content type called ‘Technical Design
    • Go to the ‘Project Documents’ document library to which we are going to associate the content types. Click Settings->Document Library Settings->Advance Settings->Make sure that the Allow Management of content types is selected.

    image

    • From the content types section choose ‘Add from existing site content types’
    • Select ‘Project Proposal’ and ‘Technical Design’ from the Available site content types. Click OK

    image

    • Remove the default document content type.
    • Go to the Project Documents library and now you will have 2 options in the ‘New’ menu option.

    image

    Creating a new Folder Content Type :

    Now imagine that we should have 2 folders, one for the Project Proposal Documents and one for the Technical Design Documents. And those folders should host only the respective type of documents.

    • Go to the Site or Site Collection top level site where you want to create the content type.
    • On the Site Actions menu click Site Settings
    • In the Galleries column select Site content types
    • This opens the gallery listing all the existing site content types, click Create
    • Enter ‘Proposal Documents’ as the name of the content type and choose Folder under the Folder Content Types group. Click OK.
    • Create another folder content type with another name ‘Proposal Documents’

    image

    • Go to the Project Documents library->Document Library Settings->Under the content types click ‘Add from existing site content types’.
    • Select ‘Design Documents’ and ‘Proposal Documents’ and click OK

    image

    • Go back to the Project Documents library->Document library settings->Advanced Settings->Set the Display ‘New Folder’ to No.
    • Go back to the Project Documents library and click ‘New’ you will now see the 2 new folder content types.

    image

    image

    • Create a new Folder for Design Documents. Lets say we name it as ‘Design Docs – 2009
    • Select ‘Change New Button Order’ option from the folder context menu.

    image

    • Choose ‘Technical Design’ (document content type we added earlier. refer to the creating a document content type in this same article) and unselect all other content types

    image

    • Now when we click ‘New’  in the Design Docs – 2009 folder you will see the ‘Technical Design’ document as the only option.

    image

    * To be continued in Part 2 of the post

    Useful Links:

    Part – 1 , Part – 2 , Part – 3 , Part – 4

    Querying SharePoint Calendar for Recurring Events using CAML Query

    Calendar items in SharePoint fall into several categories. Single events are those which don’t repeat and only appear once on the calendar, while recurring events may show up any number of times depending on the recurrence pattern selected by a user.

     

    Recurring event pattern is set using the options presented when the ‘Make this a repeating event’ checkbox is selected.

    image

     

    Querying SharePoint Calendar list is a bit tricky. Let me run through the following query scenarios:

    • Querying for all the events that has the start or end date matching current date.
    • Querying for all the events that happens in the same week of a given date.
    • Querying for all the events that happens in the same month of a given date.
    • Querying for all the events that happens in the same year of a given date.

    I created a repeating event starting from Jan 1, 2009 with no end date.

    Querying for all the events that has the start or end date matching current date :

     
    Code :
    using (SPSite oSPSite = new SPSite("http://myserver/sites/Events"))
                {
                    using (SPWeb oSPWeb = oSPSite.OpenWeb())
                    {
                        tSPList = oSPWeb.Lists["EventsCalendar"];
                        CalDate = new DateTime(2009,2,1);
                        oQuery.ExpandRecurrence = true;
                        oQuery.Query = "<Where><DateRangesOverlap>;
    <FieldRef Name='EventDate' /><FieldRef Name='EndDate' />
    <FieldRef Name='RecurrenceID' /><Value Type='DateTime'><Today />
    </Value></DateRangesOverlap></Where>"
                        oQuery.CalendarDate = CalDate;
                        tSPListItems = tSPList.GetItems(oQuery);
                    }
                }

    In the above snippet note that the value is sent as “Today” and the date set as Calendar date is Feb 1, 2009

     

    <Value Type='DateTime'><Today /></Value>

     

    This will result in fetching all the events that has the start or end date coinciding with today’s date.

    The result bound to the grid will look like this

     

    image

    It shows all the events happening on Feb 1, 2009

     

    Querying for all the events that happens in the same week of a given date :

     
    Code :
     
    using (SPSite oSPSite = new SPSite("http://myserver/sites/Events"))
    {
        using (SPWeb oSPWeb = oSPSite.OpenWeb())
        {
            tSPList = oSPWeb.Lists["EventsCalendar"];
            CalDate = new DateTime(2009,2,1);
            oQuery.ExpandRecurrence = true;
            oQuery.Query = "<Where><DateRangesOverlap><FieldRef Name='EventDate' />;
            <FieldRef Name='EndDate' /><FieldRef Name='RecurrenceID' />
            <Value Type='DateTime'><Week /></Value>
            </DateRangesOverlap></Where>"
            oQuery.CalendarDate = CalDate;
            tSPListItems = tSPList.GetItems(oQuery);
        }
    }

    In the above snippet note that the value is sent as “Week” and the date set as Calendar date is Feb 1, 2009

     

    <Value Type='DateTime'><Week /></Value>

    This will result in fetching all the events that has the start or end date coinciding with that week The result bound to the grid will look like this

    image

    It shows all the events starting from Feb 1, 2009 till Feb 8,2009 (Sunday to Sunday) . It is actually picking all the days from the current week and also one extra day from the next week !. The result remains the same for input dates starting Feb 1 through Feb 7.

     

    Querying for all the events that happens in the same month of a given date :

     
    Code :
     
    using (SPSite oSPSite = new SPSite("http://myserver/sites/Events"))
    {
        using (SPWeb oSPWeb = oSPSite.OpenWeb())
        {
            tSPList = oSPWeb.Lists["EventsCalendar"];
            CalDate = new DateTime(2009,2,1);
            oQuery.ExpandRecurrence = true;
            oQuery.Query = "<Where><DateRangesOverlap><FieldRef Name='EventDate' />;
            <FieldRef Name='EndDate' /><FieldRef Name='RecurrenceID' />
            <Value Type='DateTime'><Month /></Value>
            </DateRangesOverlap></Where>"
            oQuery.CalendarDate = CalDate;
            tSPListItems = tSPList.GetItems(oQuery);
        }
    }

    In the above snippet note that the value is sent as “Month” and the date set as Calendar date is Feb 1, 2009

     

    <Value Type='DateTime'><Month /></Value>

     

    The results that are fetched with this query is a little confusing !!!

    image

    image

    image

     

    It gets the events that occurred in the last 7 days from the Jan, 2009 and the entire month from Feb , 2009 and last five days from March , 2009.

    Querying for all the events that happens in the same year of a given date :

     
    Code :
     
    using (SPSite oSPSite = new SPSite("http://myserver/sites/Events"))
    {
        using (SPWeb oSPWeb = oSPSite.OpenWeb())
        {
            tSPList = oSPWeb.Lists["EventsCalendar"];
            CalDate = new DateTime(2009,2,1);
            oQuery.ExpandRecurrence = true;
            oQuery.Query = "<Where><DateRangesOverlap><FieldRef Name='EventDate' />;
            <FieldRef Name='EndDate' /><FieldRef Name='RecurrenceID' />
            <Value Type='DateTime'><Year /></Value>
            </DateRangesOverlap></Where>"
            oQuery.CalendarDate = CalDate;
            tSPListItems = tSPList.GetItems(oQuery);
        }
    }

    In the above snippet note that the value is sent as “Year” and the date set as Calendar date is Feb 1, 2009

     

    <Value Type='DateTime'><Year /></Value>

     

    The results that are fetched with this query continues to baffle me !!!

    image

    image

     

    It gets all the events that occurs starting from today Feb 20, 2009 all the way through Feb 19, 2011.

     

     

    I have no clue why the Month and Year filters did not work as someone would expect…