Walkthrough: Creating a Custom Deployment Step for SharePoint Projects

Walkthrough: Creating a Custom Deployment Step for SharePoint Projects

When you deploy a SharePoint project, Visual Studio 2010 executes a series of deployment steps in a specific order. Visual Studio includes many built-in deployment steps, but you can also create your own.

In this walkthrough, you will create a custom deployment step to upgrade solutions on a SharePoint server. Visual Studio includes built-in deployment steps for many tasks, such retracting or adding solutions, but it does not include a deployment step for upgrading solutions. By default, when you deploy a SharePoint solution, Visual Studio first retracts the solution (if it is already deployed) and then redeploys the entire solution. For more information about the built-in deployment steps, see Deploying SharePoint Solution Packages.

This walkthrough demonstrates the following tasks:

  • Creating a Visual Studio extension that performs two main tasks:

    • It defines a custom deployment step to upgrade SharePoint solutions.

    • It creates a project extension that defines a new deployment configuration. A deployment configuration is a set of deployment steps that are executed for a given project. The new deployment configuration includes the custom deployment step and several built-in deployment steps.

  • Creating two custom SharePoint commands that are called by the extension assembly. SharePoint commands are methods that can be called by extension assemblies to use APIs in the SharePoint server object model. For more information, see Calling into the SharePoint Object Models.

  • Building a Visual Studio Extension (VSIX) package to deploy both of the assemblies.

  • Testing the new deployment step.

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

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

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

  • A VSIX project to create the VSIX package to deploy the extension.

  • A class library project that implements the extension. This project must target the .NET Framework 4.

  • A class library project that defines the custom SharePoint commands. This project must target the.NET Framework 3.5.

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 New Project dialog box, expand the Visual C# or Visual Basic nodes, and then click Extensibility.

    NoteNote

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

  4. In the combo box at the top of the dialog box, select .NET Framework 4.

  5. Click the VSIX Project template.

  6. In the Name box, type UpgradeDeploymentStep.

  7. Click OK.

    Visual Studio adds the UpgradeDeploymentStep project to Solution Explorer.

To create the extension project

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

    NoteNote

    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 New Project dialog box, expand the Visual C# or Visual Basic nodes, and then click Windows.

  3. In the combo box at the top of the dialog box, select .NET Framework 4.

  4. Select the Class Library project template.

  5. In the Name box, type DeploymentStepExtension.

  6. Click OK.

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

  7. Delete the Class1 code file from the project.

To create the SharePoint command project

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

    NoteNote

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

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

  3. Click the Class Library project template.

  4. In the combo box at the top of the dialog box, select .NET Framework 3.5.

  5. In the Name box, type SharePointCommands.

  6. Click OK.

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

  7. Delete the Class1 code file from the project.

Before you write code to create the custom deployment step, you have to add code files and assembly references, and configure the projects.

To configure the DeploymentStepExtension project

  1. In the DeploymentStepExtension project, add two code files called:

    • UpgradeStep

    • DeploymentConfigurationExtension

  2. On the Project menu, click Add Reference.

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

    • Microsoft.VisualStudio.SharePoint

    • System.ComponentModel.Composition

To configure the SharePointCommands project

  1. In the SharePointCommands project, add a code file called Commands.

  2. In Solution Explorer, click the SharePointCommands project node.

  3. On the Project menu, click Add Reference.

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

    • Microsoft.SharePoint

    • Microsoft.VisualStudio.SharePoint.Commands

Create a class that defines the upgrade deployment step. To define the deployment step, the class implements the IDeploymentStep interface. Implement this interface whenever you want to define a custom deployment step.

To define the custom deployment step

  1. In the DeploymentStepExtension project, double-click the UpgradeStep code file.

  2. Paste the following code into this file.

    NoteNote

    After adding this code, the project will have some compile errors. These errors will go away when you add code in later steps.

    
    using System;
    using Microsoft.VisualStudio.SharePoint;
    using Microsoft.VisualStudio.SharePoint.Deployment;
    using System.ComponentModel.Composition;
    
    namespace Contoso.DeploymentSteps.Upgrade
    {
        // Enables Visual Studio to discover and load this deployment step.
        [Export(typeof(IDeploymentStep))]
    
        // Specifies the ID for this new deployment step.
        [DeploymentStep("Contoso.DeploymentSteps.UpgradeSolution")]
    
        // Defines a new deployment step that can be used to upgrade a solution on a SharePoint site.
        internal class UpgradeStep : IDeploymentStep
        {
            private string solutionName;
            private string solutionFullPath;
    
            // Implements IDeploymentStep.Initialize.
            public void Initialize(IDeploymentStepInfo stepInfo)
            {
                stepInfo.Name = "Upgrade solution";
                stepInfo.StatusBarMessage = "Upgrading solution...";
                stepInfo.Description = "Upgrades the solution on the local machine.";
            }
    
            // Implements IDeploymentStep.CanExecute. Specifies whether the solution can be upgraded.
            public bool CanExecute(IDeploymentContext context)
            {
                // SharePoint returns all the installed solutions names in lower case.
                solutionName = (context.Project.Package.Model.Name + ".wsp").ToLower();
                solutionFullPath = context.Project.Package.OutputPath;
                bool solutionExists = context.Project.SharePointConnection.ExecuteCommand<string, bool>(
                    "Contoso.Commands.IsSolutionDeployed", solutionName);
    
                // Throw exceptions in error cases because deployment cannot proceed.
                if (context.Project.IsSandboxedSolution)
                {
                    string sandboxMessage = "Cannot upgrade the solution. The upgrade deployment configuration " +
                        "does not support Sandboxed solutions.";
                    context.Logger.WriteLine(sandboxMessage, LogCategory.Error);
                    throw new InvalidOperationException(sandboxMessage);
                }
                else if (!solutionExists)
                {
                    string notDeployedMessage = string.Format("Cannot upgrade the solution. The IsSolutionDeployed " +
                        "command cannot find the following solution: {0}.", solutionName);
                    context.Logger.WriteLine(notDeployedMessage, LogCategory.Error);
                    throw new InvalidOperationException(notDeployedMessage);
                }
    
                // Execute step and continue with deployment.
                return true;
            }
    
            // Implements IDeploymentStep.Execute.
            public void Execute(IDeploymentContext context)
            {
                context.Logger.WriteLine("Upgrading solution: " + solutionName, LogCategory.Status);
                context.Project.SharePointConnection.ExecuteCommand("Contoso.Commands.UpgradeSolution",
                    solutionFullPath);
            }
        }
    }
    
    
    

Create a project extension for the new deployment configuration. The deployment configuration includes several built-in deployment steps and the new upgrade deployment step. This deployment configuration makes it easy for SharePoint developers to use the upgrade deployment step in SharePoint projects.

To create the deployment configuration, the class implements the ISharePointProjectExtension interface. Implement this interface whenever you want to create a SharePoint project extension.

To create the deployment configuration

  1. In the DeploymentStepExtension project, double-click the DeploymentConfigurationExtension code file.

  2. Paste the following code into this file.

    
    using Microsoft.VisualStudio.SharePoint;
    using Microsoft.VisualStudio.SharePoint.Deployment;
    using System.ComponentModel.Composition;
    
    namespace Contoso.DeploymentSteps.Upgrade
    {
        // Enables Visual Studio to discover and load this project-level extension.
        [Export(typeof(ISharePointProjectExtension))]
    
        // Defines a project-level extension. The extension creates a new deployment configuration that includes the
        // upgrade deployment step.
        internal class DeploymentConfigurationExtension : ISharePointProjectExtension
        {
            // Implements ISharePointProjectExtension.Initialize.
            public void Initialize(ISharePointProjectService projectService)
            {
                projectService.ProjectInitialized += ProjectInitialized;
            }
    
            // Creates the new deployment configuration.
            private void ProjectInitialized(object sender, SharePointProjectEventArgs e)
            {
                string[] deploymentSteps = new string[] 
                {
                    DeploymentStepIds.PreDeploymentCommand,
                    DeploymentStepIds.RecycleApplicationPool,
                    "Contoso.DeploymentSteps.UpgradeSolution",
                    DeploymentStepIds.PostDeploymentCommand 
                };
    
                string[] retractionSteps = new string[] 
                {
                    DeploymentStepIds.RecycleApplicationPool,
                    DeploymentStepIds.RetractSolution                
                };
    
                IDeploymentConfiguration configuration = e.Project.DeploymentConfigurations.Add(
                    "Upgrade", deploymentSteps, retractionSteps);
                configuration.Description = "This is the upgrade deployment configuration";
            }
        }
    }
    
    
    

Create two custom commands that call into the SharePoint server object model. One command determines whether a solution is already deployed; the other command upgrades a solution.

To define the SharePoint commands

  1. In the SharePointCommands project, double-click the Commands code file.

  2. Paste the following code into this file.

    
    using System;
    using System.IO;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;
    using Microsoft.VisualStudio.SharePoint.Commands;
    
    namespace Contoso.DeploymentSteps.Upgrade
    {
        internal class Commands
        {
            // Determines whether the specified solution has been deployed to the local SharePoint server.
            [SharePointCommand("Contoso.Commands.IsSolutionDeployed")]
            private bool IsSolutionDeployed(ISharePointCommandContext context, string solutionName)
            {
                SPSolution solution = SPFarm.Local.Solutions[solutionName];
                return solution != null;
            }
    
            // Upgrades the specified solution to the local SharePoint server.
            [SharePointCommand("Contoso.Commands.UpgradeSolution")]
            private void UpgradeSolution(ISharePointCommandContext context, string fullWspPath)
            {
                SPSolution solution = SPFarm.Local.Solutions[Path.GetFileName(fullWspPath)];
    
                if (solution == null)
                {
                    throw new InvalidOperationException("The solution has not been deployed.");
                }
    
                solution.Upgrade(fullWspPath);
            }
        }
    }
    
    
    

At this point in the walkthrough, all the code for the custom deployment step and the SharePoint commands are now in the projects. Build the solution to make sure that both projects compile without errors.

To build the solution

  • On the Build menu, select Build Solution.

To deploy the extension, use the VSIX project in your 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, under the UpgradeDeploymentStep project, double-click the source.extension.vsixmanifest file.

    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 Upgrade Deployment Step for SharePoint Projects.

  3. In the Author box, type Contoso.

  4. In the Description box, type Provides a custom upgrade deployment step that can be used in SharePoint projects.

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

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

    NoteNote

    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).

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

  8. Click OK.

  9. In the manifest editor, click the Add Content button again.

  10. In the Add Content dialog box, in the Select a content type list box, select Custom Extension Type.

    NoteNote

    This value corresponds to the CustomExtension element in the extension.vsixmanifest file. This element specifies a custom extension that you want to include in the Visual Studio extension. For more information, see CustomExtension Element (VSX Schema).

  11. In the Type text box, type SharePoint.Commands.v4.

    NoteNote

    This value corresponds to the Type attribute of the CustomExtension element in the extension.vsixmanifest file. The value Sharepoint.Commands.v4 is required for all custom extension assemblies that contain custom SharePoint commands.

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

  13. Click OK.

  14. On the Build menu, click Build Solution. Make sure that the solution compiles without errors.

  15. Open the build output folder for the UpgradeDeploymentStep project. Make sure that this folder now contains the UpgradeDeploymentStep.vsix file.

    By default, the build output folder is the ..\bin\Debug folder under the folder that contains your project file.

To test the upgrade deployment step, you must first deploy a sample solution to the SharePoint site. Start by debugging the extension in the experimental instance of Visual Studio. Then, create a list definition and list instance to use to test the deployment step, and then deploy them to the SharePoint site. Next, modify the list definition and list instance and redeploy them to see how the default deployment process overwrites solutions on the SharePoint site.

Later in this walkthrough, you will modify the list definition and list instance, and then upgrade them on the SharePoint site.

To start debugging the extension

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

  2. In the DeploymentStepExtension project, open the UpgradeStep code file and add a breakpoint to the first line of code in the CanExecute and Execute methods.

  3. Press F5 to start debugging.

  4. Visual Studio installs the extension to %UserProfile%\AppData\Local\Microsoft\VisualStudio\10.0Exp\Extensions\Contoso\Upgrade Deployment Step for SharePoint Projects\1.0 and starts an experimental instance of Visual Studio. You will test the upgrade deployment step in this instance of Visual Studio.

To create the list definition and list instance

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

  2. In the New Project dialog box, expand Visual C#, expand SharePoint, and then click 2010.

  3. In the combo box at the top of the dialog box, make sure that .NET Framework 3.5 is selected. Projects for Microsoft SharePoint Foundation 2010 and Microsoft SharePoint Server 2010 require this version of the .NET Framework.

  4. In the list of project templates, click List Definition.

  5. In the Name box, type EmployeesListDefinition.

  6. Click OK.

  7. In the SharePoint Customization Wizard, type the URL of the site that you want to use for debugging.

  8. Under What is the trust level for this SharePoint solution, click Deploy as a farm solution.

    NoteNote

    The upgrade deployment step does not support sandboxed solutions.

  9. Click Next.

  10. In the Choose List Definition Settings page, under What is the display name of the list definition?, type Employees List.

  11. Under What is the type of the list definition?, select Contacts.

  12. Make sure that the Add a list instance for this list definition check box is selected.

  13. Click Finish.

    Visual Studio creates the project and opens the Elements.xml file for the list definition in the editor.

  14. In Solution Explorer, right-click the EmployeesListDefinition project node and click Properties.

  15. On the SharePoint tab of the project properties, clear the Auto-retract after debugging check box.

  16. In Solution Explorer, expand the ListDefinition1 node, and expand the child ListInstance1 node.

  17. Double-click the Elements.xml file that is a child of the ListInstance1 node. The Elements.xml file opens in the editor.

  18. Replace the default XML in this file with the following XML. This XML changes the name of the list to Employees. It also adds an item for an employee named Jim Hance.

    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <ListInstance Title="Employees"
                    OnQuickLaunch="TRUE"
                    TemplateType="10000"
                    Url="Lists/Employees"
                    Description="Simple list to test upgrade deployment step">
        <Data>
          <Rows>
            <Row>
              <Field Name="Title">Hance</Field>
              <Field Name="FirstName">Jim</Field>
              <Field Name="Company">Contoso</Field>
            </Row>
          </Rows>
        </Data>
      </ListInstance>
    </Elements>
    

To deploy the list definition and list instance

  1. In Solution Explorer, click the EmployeesListDefinition project node.

  2. In the Properties window, make sure that the Active Deployment Configuration property is set to Default.

  3. Press F5.

  4. Verify that the project builds successfully, that the SharePoint site opens to the new Employees list, and that the list includes an entry for Jim Hance.

  5. Close the Web browser.

To modify the list definition and list instance and redeploy them

  1. In the EmployeesListDefinition project, double-click the Elements.xml file that is a child of the ListInstance1 project item.

  2. Remove the Data element and its children to remove the entry for Jim Hance from the list. When you are finished, the file should contain the following XML.

    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <ListInstance Title="Employees"
                    OnQuickLaunch="TRUE"
                    TemplateType="10000"
                    Url="Lists/Employees"
                    Description="Simple list to test upgrade deployment step">
      </ListInstance>
    </Elements>
    
  3. Double-click the Schema.xml file that is a child of the ListDefinition1 project item.

  4. Search in this file for the string BaseViewID="1". This string is an attribute for a View element that you will modify in the next steps.

  5. Under this View element, locate the child ViewFields element.

  6. Under the ViewFields element, remove the two child FieldRef elements that have the Name attribute set to Attachments and HomePhone. This action removes these fields from the default view of the Employees list on the SharePoint site. When you are finished, the ViewFields element should have the following contents.

    <ViewFields>
      <FieldRef Name="LinkTitle" />
      <FieldRef Name="FirstName" />
      <FieldRef Name="Company" />
      <FieldRef Name="WorkPhone" />
      <FieldRef Name="Email" />
    </ViewFields>
    
  7. Press F5. Verify that the Deployment Conflicts dialog box appears. This dialog box appears when Visual Studio tries to deploy a solution (the list instance) to a SharePoint site that already has that solution deployed.

    Later in this walkthrough, you will notice that this dialog box does not appear when you execute the upgrade deployment step.

  8. Click Resolve Automatically. Visual Studio deletes the list instance on the SharePoint site, deploys the list item in the project, and then opens the SharePoint site to the Employees list.

  9. Verify the following details:

    • The Attachments and Home Phone columns do not appear in this view of the list.

    • The list is now empty. When you used the Default deployment configuration to redeploy the solution, the Employees list was replaced with the new empty list in your project.

You are now ready to test the upgrade deployment step. First, add an item to the list instance in SharePoint. Then, change the list definition and list instance, and then upgrade them on the SharePoint site to confirm that the upgrade deployment step does not overwrite the new item.

To manually add an item to the list

  1. In the Ribbon on the SharePoint site, click the Items tab.

  2. In the New group, click New Item.

  3. In the Last Name field, type Ruth.

  4. In the First Name field, type Andy.

  5. In the Company field, type Contoso.

  6. Click Save. Verify that the new item appears in the list. Later in this walkthrough, you will use this item to verify that the upgrade deployment step does not overwrite the contents of this list.

  7. Close the Web browser.

To test the upgrade deployment step

  1. In the experimental instance of Visual Studio, in Solution Explorer, click the EmployeesListDefinition project node.

  2. In the Properties window, set the Active Deployment Configuration property to Upgrade. This is the custom deployment configuration that includes the new upgrade deployment step.

  3. Double-click the Schema.xml file that is a child of the ListDefinition1 project item.

  4. Locate the ViewFields element that you modified earlier.

  5. Under the ViewFields element, remove the two child FieldRef elements that have the Name attribute set to WorkPhone and Email. This action removes these fields from the default view of the Employees list on the SharePoint site. When you are finished, the ViewFields element should have the following contents.

    <ViewFields>
      <FieldRef Name="LinkTitle" />
      <FieldRef Name="FirstName" />
      <FieldRef Name="Company" />
    </ViewFields>
    
  6. Press F5. Verify that the code in the other instance of Visual Studio stops on the breakpoint that you set earlier in the CanExecute method.

  7. Press F5 again. Verify that the code stops on the breakpoint that you set earlier in the Execute method.

  8. Press F5 a final time. The SharePoint site to the Employees list.

  9. In the Quick Launch area, click the Employees list.

  10. Verify the following details:

    • The Andy Ruth item you manually added earlier is still in the list.

    • The Business Phone and E-mail Address columns are not displayed in this view of the list.

    The Upgrade deployment configuration modifies the existing Employees list instance on the SharePoint site. If you used the Default deployment configuration instead of the Upgrade configuration, you would encounter a deployment conflict. Visual Studio would resolve the conflict by replacing the Employees list, and the Andy Ruth item would be deleted.

After you finish testing the upgrade deployment step, remove the list instance and list definition from the SharePoint site, and remove the deployment step extension from Visual Studio.

To remove the list instance from the SharePoint site

  1. Open the Employees list on the SharePoint site, if it is not already open.

  2. In the Ribbon on the SharePoint site, click the List tab.

  3. On the List tab, in the Settings group, click List Settings.

  4. Under Permissions and Management, click Delete this list. Click OK to confirm that you want to send the list to the recycle bin.

  5. Close the Web browser.

To remove the list definition from the SharePoint site

  • In the experimental instance of Visual Studio, on the Build menu, select Retract.

    Visual Studio retracts the list definition from the SharePoint site.

To uninstall the extension

  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 Deployment Step for SharePoint Projects, 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 UpgradeDeploymentStep solution open).

Community Additions

ADD
Show:
© 2016 Microsoft