Walkthrough: Creating a Site Column Project Item with a Project Template, Part 1

SharePoint projects are containers for one or more SharePoint project items. You can extend the SharePoint project system in Visual Studio 2010 by creating your own SharePoint project item types and then associating them with a project template. In this walkthrough, you will define a project item type for creating a site column, and then you will create a project template that can be used to create a new project that contains a site column project item.

This walkthrough demonstrates the following tasks:

  • Creating a Visual Studio extension that defines a new type of SharePoint project item for a site column. The project item type includes a simple custom property that appears in the Properties window.

  • Creating a Visual Studio project template for the project item.

  • Building a Visual Studio Extension (VSIX) package to deploy the project template and the extension assembly.

  • Debugging and testing the project item.

This is a stand-alone walkthrough. After you complete this walkthrough, you can enhance the project item by adding a wizard to the project template. For more information, see Walkthrough: Creating a Site Column Project Item with a Project Template, Part 2.

Note

You can download a sample that contains the completed projects, code, and other files for this walkthrough from the following location: https://go.microsoft.com/fwlink/?LinkId=191369.

Prerequisites

You need the following components on the development computer to complete this walkthrough:

Knowledge of the following concept is helpful, but not required, to complete the walkthrough:

Creating the Projects

To complete this walkthrough, you need to create three projects:

  • A VSIX project. This project creates the VSIX package to deploy the site column project item and the project template.

  • A project template project. This project creates a project template that can be used to create a new SharePoint project that contains the site column project item.

  • A class library project. This project that implements a Visual Studio extension that defines the behavior of the site column project item.

Start the walkthrough by creating the projects.

To create the VSIX project

  1. Start Visual Studio.

  2. On the File menu, point to New, and then click Project.

  3. In the combo box at the top of the New Project dialog box, make sure that .NET Framework 4 is selected.

  4. In the New Project dialog box, expand the Visual C# or Visual Basic nodes, and then click the Extensibility node.

    Note

    The Extensibility node is available only if you install the Visual Studio 2010 SDK. For more information, see the prerequisites section earlier in this topic.

  5. Click the VSIX Project template.

  6. In the Name box, type SiteColumnProjectItem.

  7. Click OK.

    Visual Studio adds the SiteColumnProjectItem project to Solution Explorer.

To create the project template project

  1. In Solution Explorer, right-click the solution node, point to Add, and then click New Project.

    Note

    In Visual Basic projects, the solution node appears in Solution Explorer only when the Always show solution check box is selected in the General, Projects and Solutions, Options Dialog Box.

  2. In the combo box at the top of the Add New Project dialog box, make sure that .NET Framework 4 is selected.

  3. In the Add New Project dialog box, expand the Visual C# or Visual Basic nodes, and then click the Extensibility node.

  4. In the list of project templates, select C# Project Template or Visual Basic Project Template.

  5. In the Name box, type SiteColumnProjectTemplate.

  6. Click OK.

    Visual Studio adds the SiteColumnProjectTemplate project to the solution.

  7. Delete the Class1 code file from the project.

  8. If you created a Visual Basic project, also delete the following files from the project:

    • MyApplication.Designer.vb

    • MyApplication.myapp

    • Resources.Designer.vb

    • Resources.resx

    • Settings.Designer.vb

    • Settings.settings

To create the extension project

  1. In Solution Explorer, right-click the solution node, point to Add, and then click New Project.

  2. In the combo box at the top of the Add New Project dialog box, make sure that .NET Framework 4 is selected.

  3. In the Add New Project dialog box, expand the Visual C# or Visual Basic nodes, and then click Windows.

  4. Select the Class Library project template.

  5. In the Name box, type ProjectItemTypeDefinition.

  6. Click OK.

    Visual Studio adds the ProjectItemTypeDefinition project to the solution and opens the default Class1 code file.

  7. Delete the Class1 code file from the project.

Configuring the Extension Project

Add code files and assembly references to configure the extension project.

To configure the project

  1. In the ProjectItemTypeDefinition project, add a new code file called SiteColumnProjectItemTypeProvider.

  2. On the Project menu, click Add Reference.

  3. On the .NET tab, press CTRL and then click the following assemblies, and then click OK:

    • Microsoft.VisualStudio.SharePoint

    • System.ComponentModel.Composition

Defining the New SharePoint Project Item Type

Create a class that implements the ISharePointProjectItemTypeProvider interface to define the behavior of the new project item type. Implement this interface whenever you want to define a new type of project item.

To define the new SharePoint project item type

  1. In the ProjectItemTypeDefinition project, open the SiteColumnProjectItemTypeProvider code file.

  2. Replace the code in this file with the following code and then save the file.

    Imports System
    Imports System.Diagnostics
    Imports System.ComponentModel
    Imports System.ComponentModel.Composition
    Imports Microsoft.VisualStudio.SharePoint
    
    Namespace Contoso.SharePointProjectItems.SiteColumn
    
        ' Export attribute: Enables Visual Studio to discover and load this extension.
        ' SharePointProjectItemType attribute: Specifies the ID for the new project item type. This string must match the value of the 
        '     Type attribute of the ProjectItem element in the .spdata file for the project item.
        ' SiteColumnProjectItemTypeProvider class: Defines a new type of project item.
        <Export(GetType(ISharePointProjectItemTypeProvider))> _
        <SharePointProjectItemType("Contoso.SiteColumn")> _
        Partial Friend Class SiteColumnProjectItemTypeProvider
            Implements ISharePointProjectItemTypeProvider
    
            Private WithEvents projectItemTypeDefinition As ISharePointProjectItemTypeDefinition
    
            ' Configures the behavior of the project item type.
            Private Sub InitializeType(ByVal projectItemTypeDefinition As ISharePointProjectItemTypeDefinition) _
                Implements ISharePointProjectItemTypeProvider.InitializeType
    
                projectItemTypeDefinition.SupportedDeploymentScopes = _
                    SupportedDeploymentScopes.Site Or SupportedDeploymentScopes.Web
                projectItemTypeDefinition.SupportedTrustLevels = SupportedTrustLevels.All
                Me.projectItemTypeDefinition = projectItemTypeDefinition
            End Sub
    
            ' Creates a custom property for this project item.
            Private Sub ProjectItemPropertiesRequested(ByVal Sender As Object,
                ByVal e As SharePointProjectItemPropertiesRequestedEventArgs) _
                Handles projectItemTypeDefinition.ProjectItemPropertiesRequested
    
                Dim properties As SiteColumnProperties = Nothing
    
                ' If the properties object already exists, get it from the project item's annotations.
                If False = e.ProjectItem.Annotations.TryGetValue(properties) Then
                    ' Otherwise, create a new properties object and add it to the annotations.
                    properties = New SiteColumnProperties(e.ProjectItem)
                    e.ProjectItem.Annotations.Add(properties)
                End If
                e.PropertySources.Add(properties)
            End Sub
        End Class
    
        Friend Class SiteColumnProperties
            Private projectItem As ISharePointProjectItem
            Private Const TestPropertyId As String = "Contoso.SiteColumnProperty"
            Private Const PropertyDefaultValue As String = "Default custom property value."
    
            Friend Sub New(ByVal projectItem As ISharePointProjectItem)
                Me.projectItem = projectItem
            End Sub
    
            'The property gets or sets a simple string value. 
            <DisplayName("Example Property")> _
            <DescriptionAttribute("This is an example property for site column project items.")> _
            <DefaultValue(PropertyDefaultValue)> _
            Public Property ExampleProperty As String
                Get
                    Dim propertyValue As String = Nothing
    
                    ' Get the current property value if it already exists; otherwise, return a default value.
                    If False = projectItem.ExtensionData.TryGetValue(TestPropertyId, propertyValue) Then
                        propertyValue = PropertyDefaultValue
                    End If
                    Return propertyValue
                End Get
                Set(ByVal value As String)
                    If value <> PropertyDefaultValue Then
                        ' Store the property value in the ExtensionData property of the project item.
                        ' Data in the ExtensionData property persists when the project is closed.
                        projectItem.ExtensionData(TestPropertyId) = value
                    Else
                        ' Do not save the default value.
                        projectItem.ExtensionData.Remove(TestPropertyId)
                    End If
                End Set
            End Property
        End Class
    End Namespace
    
    using System;
    using System.Diagnostics;
    using System.ComponentModel;
    using System.ComponentModel.Composition;
    using Microsoft.VisualStudio.SharePoint;
    
    namespace Contoso.SharePointProjectItems.SiteColumn
    {
        // Enables Visual Studio to discover and load this extension.
        [Export(typeof(ISharePointProjectItemTypeProvider))]
    
        // Specifies the ID for the new project item type. This string must match the value of the 
        // Type attribute of the ProjectItem element in the .spdata file for the project item.
        [SharePointProjectItemType("Contoso.SiteColumn")]
    
        // Defines a new type of project item.
        internal class SiteColumnProjectItemTypeProvider : ISharePointProjectItemTypeProvider
        {
            // Implements IProjectItemTypeProvider.InitializeType. Configures the behavior of the project item type.
            public void InitializeType(ISharePointProjectItemTypeDefinition projectItemTypeDefinition)
            {
                projectItemTypeDefinition.SupportedDeploymentScopes =
                   SupportedDeploymentScopes.Site | SupportedDeploymentScopes.Web;
                projectItemTypeDefinition.SupportedTrustLevels = SupportedTrustLevels.All;
    
                // Handle event to create a custom property for this project item.
                projectItemTypeDefinition.ProjectItemPropertiesRequested +=
                    projectItemTypeDefinition_ProjectItemPropertiesRequested;
            }
    
            // Creates a custom property for this project item.
            void projectItemTypeDefinition_ProjectItemPropertiesRequested(object sender,
                SharePointProjectItemPropertiesRequestedEventArgs e)
            {
                SiteColumnProperties properties = null;
    
                // If the Properties object already exists, get it from the project item's annotations.
                if (!e.ProjectItem.Annotations.TryGetValue(out properties))
                {
                    // Otherwise, create a new Properties object and add it to the annotations.
                    properties = new SiteColumnProperties(e.ProjectItem);
                    e.ProjectItem.Annotations.Add(properties);
                }
    
                e.PropertySources.Add(properties);
            }
        }
    
        internal class SiteColumnProperties
        {
            // This class defines the property behavior.
            private ISharePointProjectItem projectItem;
            private const string propertyId = "Contoso.SiteColumnProperty";
            private const string propertyDefaultValue = "Default custom property value.";
    
            internal SiteColumnProperties(ISharePointProjectItem projectItem)
            {
                this.projectItem = projectItem;
            }
    
            // The property gets or sets a simple string value. 
            [DisplayName("Example Property")]
            [DescriptionAttribute("This is an example property for site column project items.")]
            [DefaultValue(propertyDefaultValue)]
            public string ExampleProperty
            {
                get
                {
                    string propertyValue;
    
                    // Get the current property value if it already exists; otherwise, return a default value.
                    if (!projectItem.ExtensionData.TryGetValue(propertyId, out propertyValue))
                    {
                        propertyValue = propertyDefaultValue;
                    }
                    return propertyValue;
                }
                set
                {
                    if (value != propertyDefaultValue)
                    {
                        // Store the property value in the ExtensionData property of the project item. 
                        // Data in the ExtensionData property persists when the project is closed.
                        projectItem.ExtensionData[propertyId] = value;
                    }
                    else
                    {
                        // Do not save the default value.
                        projectItem.ExtensionData.Remove(propertyId);
                    }
                }
            }
        }
    }
    

Creating a Visual Studio Project Template

To enable other developers to create a new SharePoint project that contains a site column project item, create a project template. A SharePoint project template includes files required for all projects in Visual Studio, such as .csproj or .vbproj and .vstemplate files, and files that are specific to SharePoint projects. For more information, see Creating Item Templates and Project Templates for SharePoint Project Items.

In this procedure, create an Empty SharePoint project to generate the files that are specific to SharePoint projects, and then add these files to the SiteColumnProjectTemplate project so that they will be included in the template that is generated from this project. Also configure the SiteColumnProjectTemplate project file to specify where the project template appears in the Add New Project dialog box.

To create the files for the project template

  1. Start a second instance of Visual Studio with administrator privileges.

  2. Create a new Empty SharePoint Project named BaseSharePointProject. Do not select the Deploy as a farm solution option in the SharePoint Customization Wizard.

  3. Add an Empty Element item to the project. Name the item Field1.

  4. Save the project and then close the second Visual Studio instance.

  5. In the instance of Visual Studio that has the SiteColumnProjectItem solution open, right-click the SiteColumnProjectTemplate project node in Solution Explorer.

  6. On the Add menu, click Existing Item.

  7. In the Add Existing Item dialog box, click the drop-down list of file extensions and select All Files (*.*).

  8. Navigate to the directory that contains the BaseSharePointProject project. In this folder, select key.snk, and then click Add.

    Note

    In this walkthrough, the project template you create uses the same key.snk file to sign each project that is created by using the template. To learn how to expand this sample to create a new key.snk file for each project instance, see Walkthrough: Creating a Site Column Project Item with a Project Template, Part 2.

  9. Repeat steps 5-8 to add the following files from the specified subfolders in the BaseSharePointProject directory:

    • \Field1\Elements.xml

    • \Field1\SharePointProjectItem.spdata

    • \Features\Feature1\Feature1.feature

    • \Features\Feature1\Feature1.Template.xml

    • \Package\Package.package

    • \Package\Package.Template.xml

    Add these files directly to the SiteColumnProjectTemplate project; do not recreate the Field1, Features, or Package subfolders in the project. For more information about these files, see Creating Item Templates and Project Templates for SharePoint Project Items.

To configure how developers discover the project template in the Add New Project dialog box

  1. In Solution Explorer, right-click the SiteColumnProjectTemplate project node and click Unload Project. If you are prompted to save changes to any files, click Yes.

  2. Right-click the SiteColumnProjectTemplate node again and click Edit SiteColumnProjectTemplate.csproj or Edit SiteColumnProjectTemplate.vbproj.

  3. Locate the following VSTemplate element in the project file.

    <VSTemplate Include="SiteColumnProjectTemplate.vstemplate">
    
  4. Replace this VSTemplate element with the following XML.

    <VSTemplate Include="SiteColumnProjectTemplate.vstemplate">
      <OutputSubPath>SharePoint\SharePoint14</OutputSubPath>
    </VSTemplate>
    

    The OutputSubPath element specifies additional folders in the path under which the project template is created when you build the project. The folders specified here ensure that the project template will be available only when customers click the 2010 node under the SharePoint node in the Add New Project dialog box.

  5. Save and close the file.

  6. In Solution Explorer, right-click the SiteColumnProjectTemplate project, and then click Reload Project.

Editing the Project Template Files

Edit the following files in the SiteColumnProjectTemplate project to define the behavior of the project template:

  • AssemblyInfo.cs or AssemblyInfo.vb

  • Elements.xml

  • SharePointProjectItem.spdata

  • Feature1.feature

  • Package.package

  • SiteColumnProjectTemplate.vstemplate

  • ProjectTemplate.csproj or ProjectTemplate.vbproj

In the following procedures you will add replaceable parameters to some of these files. A replaceable parameter is a token that begins and ends with the dollar sign ($) character. When a user uses this project template to create a new project, Visual Studio automatically replaces these parameters in the new project with specific values. For more information, see Replaceable Parameters.

To edit the AssemblyInfo.cs or AssemblyInfo.vb file

  1. In the SiteColumnProjectTemplate project, double-click the AssemblyInfo.cs or AssemblyInfo.vb file in Solution Explorer.

  2. Add the following statement to the top of this file.

    Imports System.Security
    
    using System.Security;
    

    When the Sandboxed Solution property of a SharePoint project is set to True, Visual Studio adds the System.Security.AllowPartiallyTrustedCallersAttribute to the AssemblyInfo code file. However, the AssemblyInfo code file in the project template does not import the System.Security namespace by default. You must add this using or Imports statement to prevent compile errors.

  3. Save and close the file.

To edit the Elements.xml file

  1. In the SiteColumnProjectTemplate project, double-click the Elements.xml file in Solution Explorer.

  2. Replace the contents of the file with the following XML.

    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="https://schemas.microsoft.com/sharepoint/">
      <Field ID="{$guid5$}" 
          Name="$safeprojectname$" 
          DisplayName="$projectname$" 
          Type="Text" 
          Group="Custom Columns">
      </Field>
    </Elements>
    

    The new XML adds a Field element that defines the name of the site column, its base type, and the group in which to list the site column in the gallery. For more information about the contents of this file, see Field Definition Schema.

  3. Save and close the file.

To edit the SharePointProjectItem.spdata file

  1. In the SiteColumnProjectTemplate project, double-click the SharePointProjectItem.spdata file in Solution Explorer.

  2. Replace the contents of the file with the following XML.

    <?xml version="1.0" encoding="utf-8"?>
    <ProjectItem Type="Contoso.SiteColumn" DefaultFile="Elements.xml" 
                 xmlns="https://schemas.microsoft.com/VisualStudio/2010/SharePointTools/SharePointProjectItemModel">
      <Files>
        <ProjectItemFile Source="Elements.xml" Target="$safeprojectname$\" Type="ElementManifest" />
      </Files> 
    </ProjectItem>
    

    The new XML makes the following changes to the file:

    • It changes the Type attribute of the ProjectItem element to the same string that is passed to the SharePointProjectItemTypeAttribute on the project item definition (the SiteColumnProjectItemTypeProvider class you created earlier in this walkthrough).

    • It removes the SupportedTrustLevels and SupportedDeploymentScopes attributes from the ProjectItem element. These attribute values are unnecessary because the trust levels and deployment scopes are specified in the SiteColumnProjectItemTypeProvider class in the ProjectItemTypeDefinition project.

    For more information about the contents of .spdata files, see SharePoint Project Item Schema Reference.

  3. Save and close the file.

To edit the Feature1.feature file

  1. In the SiteColumnProjectTemplate project, double-click the Feature1.feature file in Solution Explorer.

  2. Replace the contents of the file with the following XML.

    <?xml version="1.0" encoding="utf-8"?>
    <feature xmlns:dm0="https://schemas.microsoft.com/VisualStudio/2008/DslTools/Core" dslVersion="1.0.0.0" Id="$guid4$" featureId="$guid4$" 
             imageUrl="" solutionId="00000000-0000-0000-0000-000000000000" title="Site Column Feature1" version=""
             deploymentPath="$SharePoint.Project.FileNameWithoutExtension$_$SharePoint.Feature.FileNameWithoutExtension$"
             xmlns="https://schemas.microsoft.com/VisualStudio/2008/SharePointTools/FeatureModel">
      <projectItems>
        <projectItemReference itemId="$guid2$" />
      </projectItems>
    </feature>
    

    The new XML makes the following changes to the file:

    • It changes the values of the Id and featureId attributes of the feature element to $guid4$.

    • It changes the values of the itemId attribute of the projectItemReference element to $guid2$.

    For more information about .feature files, see Creating Item Templates and Project Templates for SharePoint Project Items.

  3. Save and close the file.

To edit the Package.package file

  1. In the SiteColumnProjectTemplate project, double-click the Package.package file in Solution Explorer.

  2. Replace the contents of the file with the following XML.

    <?xml version="1.0" encoding="utf-8"?>
    <package xmlns:dm0="https://schemas.microsoft.com/VisualStudio/2008/DslTools/Core" dslVersion="1.0.0.0" 
             Id="$guid3$" solutionId="$guid3$" resetWebServer="false" name="$safeprojectname$" 
             xmlns="https://schemas.microsoft.com/VisualStudio/2008/SharePointTools/PackageModel">
      <features>
        <featureReference itemId="$guid4$" />
      </features>
    </package>
    

    The new XML makes the following changes to the file:

    • It changes the values of the Id and solutionId attributes of the package element to $guid3$.

    • It changes the values of the itemId attribute of the featureReference element to $guid4$.

    For more information about .package files, see Creating Item Templates and Project Templates for SharePoint Project Items.

  3. Save and close the file.

To edit the SiteColumnProjectTemplate.vstemplate file

  1. In the SiteColumnProjectTemplate project, double-click the SiteColumnProjectTemplate.vstemplate file in Solution Explorer.

  2. Replace the contents of the file with one of the following sections of XML. If you are creating a Visual C# project template, use the following XML.

    <?xml version="1.0" encoding="utf-8"?>
    <VSTemplate Version="3.0.0" xmlns="https://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
      <TemplateData>
        <Name>Site Column</Name>
        <Description>Creates a new site column in SharePoint</Description>
        <FrameworkVersion>3.5</FrameworkVersion>
        <ProjectType>CSharp</ProjectType>
        <CreateNewFolder>true</CreateNewFolder>
        <CreateInPlace>true</CreateInPlace>
        <ProvideDefaultName>true</ProvideDefaultName>
        <DefaultName>SiteColumn</DefaultName>
        <LocationField>Enabled</LocationField>
        <EnableLocationBrowseButton>true</EnableLocationBrowseButton>
        <PromptForSaveOnCreation>true</PromptForSaveOnCreation>
        <NumberOfParentCategoriesToRollUp>1</NumberOfParentCategoriesToRollUp>
        <Icon>SiteColumnProjectTemplate.ico</Icon>
        <SortOrder>1000</SortOrder>
      </TemplateData>
      <TemplateContent>
        <Project TargetFileName="SharePointProject1.csproj" File="ProjectTemplate.csproj" ReplaceParameters="true">
          <ProjectItem ReplaceParameters="true" TargetFileName="Properties\AssemblyInfo.cs">AssemblyInfo.cs</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Features\Feature1\Feature1.feature">Feature1.feature</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Features\Feature1\Feature1.Template.xml">Feature1.template.xml</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Package\Package.package">Package.package</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Package\Package.Template.xml">Package.Template.xml</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Field1\SharePointProjectItem.spdata">SharePointProjectItem.spdata</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Field1\Elements.xml" OpenInEditor="true">Elements.xml</ProjectItem>
          <ProjectItem ReplaceParameters="false" TargetFileName="key.snk">key.snk</ProjectItem>
        </Project>
      </TemplateContent>
    </VSTemplate>
    

    If you are creating a Visual Basic project template, use the following XML.

    <?xml version="1.0" encoding="utf-8"?>
    <VSTemplate Version="3.0.0" xmlns="https://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
      <TemplateData>
        <Name>Site Column</Name>
        <Description>Creates a new site column in SharePoint</Description>
        <FrameworkVersion>3.5</FrameworkVersion>
        <ProjectType>VisualBasic</ProjectType>
        <CreateNewFolder>true</CreateNewFolder>
        <CreateInPlace>true</CreateInPlace>
        <ProvideDefaultName>true</ProvideDefaultName>
        <DefaultName>SiteColumn</DefaultName>
        <LocationField>Enabled</LocationField>
        <EnableLocationBrowseButton>true</EnableLocationBrowseButton>
        <PromptForSaveOnCreation>true</PromptForSaveOnCreation>
        <NumberOfParentCategoriesToRollUp>1</NumberOfParentCategoriesToRollUp>
        <Icon>SiteColumnProjectTemplate.ico</Icon>
        <SortOrder>1000</SortOrder>
      </TemplateData>
      <TemplateContent>
        <Project TargetFileName="SharePointProject1.vbproj" File="ProjectTemplate.vbproj" ReplaceParameters="true">
          <ProjectItem ReplaceParameters="true" TargetFileName="My Project\AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Features\Feature1\Feature1.feature">Feature1.feature</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Features\Feature1\Feature1.Template.xml">Feature1.template.xml</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Package\Package.package">Package.package</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Package\Package.Template.xml">Package.Template.xml</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Field1\SharePointProjectItem.spdata">SharePointProjectItem.spdata</ProjectItem>
          <ProjectItem ReplaceParameters="true" TargetFileName="Field1\Elements.xml" OpenInEditor="true">Elements.xml</ProjectItem>
          <ProjectItem ReplaceParameters="false" TargetFileName="key.snk">key.snk</ProjectItem>
        </Project>
      </TemplateContent>
    </VSTemplate>
    

    The new XML makes the following changes to the file:

    • It sets the Name element to the value Site Column (this is the name that appears in the Add New Project dialog box).

    • It adds ProjectItem elements for each of the files that are included in each project instance.

    For more information about the contents of .vstemplate files, see Visual Studio Template Schema Reference.

  3. Save and close the file.

To edit the ProjectTemplate.csproj or ProjectTemplate.vbproj file

  1. In the SiteColumnProjectTemplate project, double-click the ProjectTemplate.csproj file or ProjectTemplate.vbproj file in Solution Explorer.

  2. Replace the contents of the file with one of the following sections of XML. If you are creating a Visual C# project template, use the following XML.

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="https://schemas.microsoft.com/developer/msbuild/2003">
      <PropertyGroup>
        <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
        <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
        <SchemaVersion>2.0</SchemaVersion>
        <ProjectGuid>{$guid1$}</ProjectGuid>
        <OutputType>Library</OutputType>
        <AppDesignerFolder>Properties</AppDesignerFolder>
        <RootNamespace>$safeprojectname$</RootNamespace>
        <AssemblyName>$safeprojectname$</AssemblyName>
        <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
        <FileAlignment>512</FileAlignment>
        <ProjectTypeGuids>{BB1F664B-9266-4fd6-B973-E1E44974B511};{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
        <DebugSymbols>true</DebugSymbols>
        <DebugType>full</DebugType>
        <Optimize>false</Optimize>
        <OutputPath>bin\Debug\</OutputPath>
        <DefineConstants>DEBUG;TRACE</DefineConstants>
        <ErrorReport>prompt</ErrorReport>
        <WarningLevel>4</WarningLevel>
        <UseVSHostingProcess>false</UseVSHostingProcess>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
        <DebugType>pdbonly</DebugType>
        <Optimize>true</Optimize>
        <OutputPath>bin\Release\</OutputPath>
        <DefineConstants>TRACE</DefineConstants>
        <ErrorReport>prompt</ErrorReport>
        <WarningLevel>4</WarningLevel>
      </PropertyGroup>
      <PropertyGroup>
        <SignAssembly>true</SignAssembly>
        <AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile>
      </PropertyGroup>
      <ItemGroup>
        <Reference Include="System" />
        <Reference Include="System.Core" />
        <Reference Include="System.Data" />
        <Reference Include="System.Data.DataSetExtensions" />
        <Reference Include="System.Web" />
        <Reference Include="System.Xml" />
        <Reference Include="System.Xml.Linq" />
        <Reference Include="Microsoft.SharePoint" />
        <Reference Include="Microsoft.SharePoint.Security" />
      </ItemGroup>
      <ItemGroup>
        <Compile Include="Properties\AssemblyInfo.cs" />
      </ItemGroup>
      <ItemGroup>
        <None Include="Field1\SharePointProjectItem.spdata">
          <SharePointProjectItemId>{$guid2$}</SharePointProjectItemId>
        </None>
        <None Include="Field1\Elements.xml" />
      </ItemGroup>
      <ItemGroup>
        <None Include="key.snk" />
        <None Include="Package\Package.package">
          <PackageId>{$guid3$}</PackageId>
        </None>
        <None Include="Package\Package.Template.xml">
          <DependentUpon>Package.package</DependentUpon>
        </None>
        <None Include="Features\Feature1\Feature1.feature">
          <FeatureId>{$guid4$}</FeatureId>
        </None>
        <None Include="Features\Feature1\Feature1.Template.xml">
          <DependentUpon>Feature1.feature</DependentUpon>
        </None>
      </ItemGroup>
      <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
      <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\SharePointTools\Microsoft.VisualStudio.SharePoint.targets" />
    </Project>
    

    If you are creating a Visual Basic project template, use the following XML.

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="https://schemas.microsoft.com/developer/msbuild/2003">
      <PropertyGroup>
        <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
        <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
        <ProductVersion>
        </ProductVersion>
        <SchemaVersion>
        </SchemaVersion>
        <ProjectGuid>{$guid1$}</ProjectGuid>
        <OutputType>Library</OutputType>
        <RootNamespace>$safeprojectname$</RootNamespace>
        <AssemblyName>$safeprojectname$</AssemblyName>
        <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
        <FileAlignment>512</FileAlignment>
        <ProjectTypeGuids>{BB1F664B-9266-4fd6-B973-E1E44974B511};{D59BE175-2ED0-4C54-BE3D-CDAA9F3214C8};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>
        <OptionExplicit>On</OptionExplicit>
        <OptionCompare>Binary</OptionCompare>
        <OptionStrict>Off</OptionStrict>
        <OptionInfer>On</OptionInfer>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
        <DebugSymbols>true</DebugSymbols>
        <DebugType>full</DebugType>
        <DefineDebug>true</DefineDebug>
        <DefineTrace>true</DefineTrace>
        <OutputPath>bin\Debug\</OutputPath>
        <WarningLevel>4</WarningLevel>
        <UseVSHostingProcess>false</UseVSHostingProcess>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
        <DebugType>pdbonly</DebugType>
        <DefineDebug>false</DefineDebug>
        <DefineTrace>true</DefineTrace>
        <Optimize>true</Optimize>
        <OutputPath>bin\Release\</OutputPath>
        <UseVSHostingProcess>false</UseVSHostingProcess>
      </PropertyGroup>
      <PropertyGroup>
        <SignAssembly>true</SignAssembly>
        <AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile>
      </PropertyGroup>
      <ItemGroup>
        <Reference Include="System" />
        <Reference Include="System.Core" />
        <Reference Include="System.Data" />
        <Reference Include="System.Data.DataSetExtensions" />
        <Reference Include="System.Xml" />
        <Reference Include="System.Xml.Linq" />
        <Reference Include="Microsoft.SharePoint" />
        <Reference Include="Microsoft.SharePoint.Security" />
      </ItemGroup>
      <ItemGroup>
        <Import Include="Microsoft.VisualBasic" />
        <Import Include="System" />
        <Import Include="System.Collections" />
        <Import Include="System.Collections.Generic" />
        <Import Include="System.Data" />
        <Import Include="System.Diagnostics" />
        <Import Include="System.Linq" />
        <Import Include="System.Xml.Linq" />
        <Import Include="Microsoft.SharePoint" />
        <Import Include="Microsoft.SharePoint.Security" />
      </ItemGroup>
      <ItemGroup>
        <Compile Include="My Project\AssemblyInfo.vb" />
      </ItemGroup>
      <ItemGroup>
        <AppDesigner Include="My Project\" />
      </ItemGroup>
      <ItemGroup>
        <None Include="Features\Feature1\Feature1.feature">
          <FeatureId>{$guid4$}</FeatureId>
        </None>
        <None Include="Field1\SharePointProjectItem.spdata">
          <SharePointProjectItemId>{$guid2$}</SharePointProjectItemId>
        </None>
        <None Include="key.snk" />
        <None Include="Package\Package.package">
          <PackageId>{$guid3$}</PackageId>
        </None>
        <None Include="Package\Package.Template.xml">
          <DependentUpon>Package.package</DependentUpon>
        </None>
      </ItemGroup>
      <ItemGroup>
        <None Include="Features\Feature1\Feature1.Template.xml">
          <DependentUpon>Feature1.feature</DependentUpon>
        </None>
        <None Include="Field1\Elements.xml" />
      </ItemGroup>
      <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
      <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\SharePointTools\Microsoft.VisualStudio.SharePoint.targets" />
    </Project>
    

    The new XML makes the following changes to the file:

    • It changes the TargetFrameworkVersion element to specify the .NET Framework 3.5.

    • It adds SignAssembly and AssemblyOriginatorKeyFile elements to sign the project output.

    • It adds new Reference elements for assembly references used by SharePoint projects.

    • It adds new elements for each of the default files in the project, such as Elements.xml and SharePointProjectItem.spdata.

  3. Save and close the file.

Creating a VSIX Package to Deploy the Project Template

To deploy the extension, use the VSIX project in the SiteColumnProjectItem solution to create a VSIX package. First, configure the VSIX package by modifying the source.extension.vsixmanifest file that is included in the VSIX project. Then, create the VSIX package by building the solution.

To configure and create the VSIX package

  1. In Solution Explorer, double-click the source.extension.vsixmanifest file in the SiteColumnProjectItem project.

    Visual Studio opens the file in the manifest editor. The source.extension.vsixmanifest file is the basis for the extension.vsixmanifest file that is required by all VSIX packages. For more information about this file, see VSIX Extension Schema Reference.

  2. In the Product Name box, type Site Column.

  3. In the Author box, type Contoso.

  4. In the Description box, type A SharePoint project for creating site columns.

  5. In the Content section of the editor, click the Add Content button.

  6. In the Add Content dialog box, click the Select a content type drop-down box and then select Project Template.

    Note

    This value corresponds to the ProjectTemplate element in the extension.vsixmanifest file. This element identifies the subfolder in the VSIX package that contains the project template. For more information, see ProjectTemplate Element (VSX Schema).

  7. Under Select a source, click the Project radio button, and select SiteColumnProjectTemplate in the list box next to it.

  8. Click OK.

  9. Click the Add Content button again.

  10. In the Add Content dialog box, in the Select a content type list box, select MEF Component.

    Note

    This value corresponds to the MefComponent element in the extension.vsixmanifest file. This element specifies the name of an extension assembly in the VSIX package. For more information, see MEFComponent Element (VSX Schema).

  11. Under Select a source, select the Project radio button, and select ProjectItemTypeDefinition in the list box next to it.

  12. Click OK.

  13. On the Build menu, click Build Solution. Make sure that the project compiles without errors.

Testing the Project Template

You are now ready to test the project template. First, start debugging the SiteColumnProjectItem solution in the experimental instance of Visual Studio. Then, test the Site Column project in the experimental instance of Visual Studio. Finally, build and run the SharePoint project to verify that the site column works as expected.

To start debugging the solution

  1. Restart Visual Studio with administrator privileges and open the SiteColumnProjectItem solution.

  2. Open the SiteColumnProjectItemTypeProvider code file, and add a breakpoint to the first line of code in the InitializeType method.

  3. Press F5 to start debugging.

    Visual Studio installs the extension to %UserProfile%\AppData\Local\Microsoft\VisualStudio\10.0Exp\Extensions\Contoso\Site Column\1.0 and starts an experimental instance of Visual Studio. You will test the project item in this instance of Visual Studio.

To test the project in Visual Studio

  1. In the experimental instance of Visual Studio, on the File menu, point to New, and then click Project.

  2. Expand Visual C# or Visual Basic (depending on the language your project template supports), expand SharePoint, and then click 2010.

  3. In the list of project templates, select Site Column.

  4. In the Name box, type SiteColumnTest.

  5. Click OK. A new project appears in Solution Explorer with a project item named Field1.

  6. Verify that the code in the other instance of Visual Studio stops on the breakpoint that you set earlier in the InitializeType method. Press F5 to continue to debug the project.

  7. In Solution Explorer, click the Field1 node and press F4. The Properties window opens.

  8. Verify that the property Example Property appears in the properties list.

To test the site column in SharePoint

  1. In Solution Explorer, click the SiteColumnTest node.

  2. In the Properties window, click the text box next to the Site URL property and type https://localhost. This specifies the local SharePoint site on the development computer that you want to use for debugging.

    Note

    The Site URL property is empty by default because the Site Column project template does not provide a wizard for collecting this value when the project is created. To learn how to add a wizard that asks the developer for this value and then configures this property in the new project, see Walkthrough: Creating a Site Column Project Item with a Project Template, Part 2.

  3. Press F5. The site column is packaged and deployed to the SharePoint site specified by the Site URL property of the project. The Web browser opens to the default page of this site.

    Note

    If the Script Debugging Disabled dialog box is displayed, click Yes to continue to debug the project.

  4. On the Site Actions menu, click Site Settings.

  5. Under Galleries, click Site columns.

  6. In the list of site columns, verify that there is a Custom Columns group that contains a column named SiteColumnTest.

  7. Close the Web browser.

Cleaning up the Development Computer

After you finish testing the project, remove the project template from the experimental instance of Visual Studio.

To clean up the development computer

  1. In the experimental instance of Visual Studio, on the Tools menu, click Extension Manager.

    The Extension Manager dialog box opens.

  2. In the list of extensions, click Site Column, and then click Uninstall.

  3. In the dialog box that appears, click Yes to confirm that you want to uninstall the extension.

  4. Click Restart Now to complete the uninstallation.

  5. Close both instances of Visual Studio (the experimental instance and the instance of Visual Studio that has the SiteColumnProjectItem solution open).

Next Steps

After you complete this walkthrough, you can add a wizard to the project template. When a user creates a Site Column project, the wizard asks the user for the site URL to use for debugging and whether the new solution is sandboxed, and the wizard configures the new project with this information. The wizard also collects information about the column (such as the base type and the group in which to list the column in the site column gallery) and adds this information to the Elements.xml file in the new project. For more information, see Walkthrough: Creating a Site Column Project Item with a Project Template, Part 2.

See Also

Tasks

Walkthrough: Creating a Site Column Project Item with a Project Template, Part 2

Concepts

Defining Custom SharePoint Project Item Types

Creating Item Templates and Project Templates for SharePoint Project Items

Saving Data in Extensions of the SharePoint Project System

Associating Custom Data with SharePoint Tools Extensions