Export (0) Print
Expand All

Walkthrough: Calling into the SharePoint Client Object Model in a Server Explorer Extension

This walkthrough demonstrates how to call the SharePoint client object model from an extension for the SharePoint Connections node in Server Explorer. For more information about using the SharePoint client object model, see Calling into the SharePoint Object Models.

This walkthrough demonstrates the following tasks:

  • Creating a Visual Studio extension that extends the SharePoint Connections node of Server Explorer in the following ways:

    • It adds a new Web Part Gallery node under each SharePoint site node in Server Explorer. This new node contains child nodes that represent each Web Part in the Web Part gallery on the site.

    • It defines a new type of node that represents a Web Part instance. This new node type is the basis for the child nodes under the new Web Part Gallery node. The new Web Part node type displays information in the Properties window about the Web Part that it represents.

  • Building a Visual Studio Extension (VSIX) package to deploy the extension.

  • Debugging and testing the extension.

NoteNote

The extension you create in this walkthrough resembles the extension that you create in Walkthrough: Extending Server Explorer to Display Web Parts. However, whereas that walkthrough uses the SharePoint server object model, this walkthrough accomplishes the same tasks by using the client object model.

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 two projects:

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

  • A class library project that implements the Server Explorer extension.

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. SharePoint tools extensions require features in this version of the .NET Framework.

  5. Click the VSIX Project template.

  6. In the Name box, type WebPartNode.

  7. Click OK.

    Visual Studio adds the WebPartNode 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 WebPartNodeExtension.

  6. Click OK.

    Visual Studio adds the WebPartNodeExtension 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 extension, you have to add code files and assembly references to your project, and update the default namespace.

To configure the project

  1. In the WebPartNodeExtension project, add two code with the following names:

    • SiteNodeExtension

    • WebPartNodeTypeProvider

  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.SharePoint.Client

    • Microsoft.SharePoint.Client.Runtime

    • Microsoft.VisualStudio.SharePoint

    • System.ComponentModel.Composition

    • System.Windows.Forms

  4. On the Project menu, select WebPartNodeExtension Properties.

    The Project Designer opens.

  5. Click the Application tab.

  6. In the Default namespace box (C#) or Root namespace box (Visual Basic), type ServerExplorer.SharePointConnections.WebPartNode.

Create two icons for the Server Explorer extension: an icon for the new Web Part Gallery node, and another icon for each child Web Part node under the Web Part Gallery node. Later in this walkthrough, you will write code that associates these icons with the nodes.

To create icons for the nodes

  1. In the Project Designer for the WebPartNodeExtension project, click the Resources tab.

  2. Click This project does not contain a default resources file. Click here to create one.

    Visual Studio creates a resources file and opens it in the designer.

  3. At the top of the designer, click the drop-down arrow on the Add button, and click Add New Icon.

  4. Type WebPartsNode for the new icon name, and click Add.

    The new icon opens in the Image Editor.

  5. Edit the 16x16 version of the icon so that it has a design you can easily recognize.

  6. Click the 32x32 version of the icon.

  7. On the Image menu, click Delete Image Type.

  8. Repeat steps 3 through 7 to add a second icon to the project resources. Name this icon WebPart.

  9. In Solution Explorer, under the Resources folder for the WebPartNodeExtension project, select WebPartsNode.ico.

  10. In the Properties window, click the drop-down next to Build Action and select Embedded Resource.

  11. Repeat the last two steps for WebPart.ico.

Create a class that adds the new Web Part Gallery node to each SharePoint site node. To add the new node, the class implements the IExplorerNodeTypeExtension interface. Implement this interface whenever you want to extend the behavior of an existing node in Server Explorer, such as adding a new child node to a node.

To add the Web Part Gallery node to Server Explorer

  1. In the WebPartNodeExtension project, double-click the SiteNodeExtension 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.Collections.Generic;
    using System.ComponentModel.Composition;
    using Microsoft.SharePoint.Client;
    using Microsoft.VisualStudio.SharePoint;
    using Microsoft.VisualStudio.SharePoint.Explorer;
    
    namespace ServerExplorer.SharePointConnections.WebPartNode
    {
        // Enables Visual Studio to discover and load this extension.
        [Export(typeof(IExplorerNodeTypeExtension))]        
    
        // Indicates that this class extends SharePoint site nodes in Server Explorer.
        [ExplorerNodeType(ExplorerNodeTypes.SiteNode)]
    
        // Represents an extension of SharePoint site nodes in Server Explorer.
        internal class SiteNodeExtension : IExplorerNodeTypeExtension
        {
            private System.Uri siteUrl = null;
    
            public void Initialize(IExplorerNodeType nodeType)
            {
                // The NodeChildrenRequested event is raised when the user expands the
                // SharePoint site node in Server Explorer.
                nodeType.NodeChildrenRequested += NodeChildrenRequested;
            }
    
            // Creates the new Web Part Gallery node with the specified icon.
            private void NodeChildrenRequested(object sender, ExplorerNodeEventArgs e)
            {
                // Get the site URL so that it can be used later to access the site
                // by using the SharePoint client object model.
                siteUrl = e.Node.Context.SiteUrl;
    
                // The CreateWebPartNodes argument is a delegate that Visual Studio calls 
                // to create the child nodes under the Web Part Gallery node.
                e.Node.ChildNodes.AddFolder("Web Part Gallery", Properties.Resources.WebPartsNode.ToBitmap(), 
                    CreateWebPartNodes);
            }
    
            // Creates individual Web Part nodes under the new Web Part Gallery node.
            private void CreateWebPartNodes(IExplorerNode parentNode)
            {
                // Use the SharePoint client object model to get items from the Web Part gallery.
                ClientContext context = new ClientContext(siteUrl.AbsoluteUri);
                List webPartsGallery = context.Web.GetCatalog((int)ListTemplateType.WebPartCatalog);
                ListItemCollection webParts = webPartsGallery.GetItems(new CamlQuery());
    
                // Request the FieldValuesAsText property values with the Web Part items.
                context.Load(webParts, listItems => listItems.Include(i => i.FieldValuesAsText));
                context.ExecuteQuery();
    
                if (webParts != null)
                {
                    foreach (ListItem webPart in webParts)
                    {
                        // Create a new annotation object to store the current Web Part item with the new node.
                        var annotations = new Dictionary<object, object>() 
                        { 
                            { typeof(ListItem), webPart } 
                        };
    
                        // Create the new node for the current Web Part item.
                        parentNode.ChildNodes.Add(WebPartNodeTypeProvider.WebPartNodeTypeId,
                            webPart.FieldValuesAsText.FieldValues["Title"], annotations);
                    }
                }
            }
        }
    }
    
    
    

Create a class that defines a new type of node that represents a Web Part. This new node type is used by Visual Studio to display child nodes under the Web Part Gallery node. Each of these child nodes represents a single Web Part on the SharePoint site.

To define the new node type, the class implements the IExplorerNodeTypeProvider interface. Implement this interface whenever you want to define a new type of node in Server Explorer.

To define the Web Part node type

  1. In the WebPartNodeExtension project, double-click the WebPartNodeTypeProvider code file.

  2. Paste the following code into this file.

    
    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using System.ComponentModel.Composition;
    using Microsoft.SharePoint.Client;
    using Microsoft.VisualStudio.SharePoint;
    using Microsoft.VisualStudio.SharePoint.Explorer;
    
    namespace ServerExplorer.SharePointConnections.WebPartNode
    {
        // Enables Visual Studio to discover and load this extension.
        [Export(typeof(IExplorerNodeTypeProvider))]
    
        // Specifies the ID for this new node type.
        [ExplorerNodeType(WebPartNodeTypeProvider.WebPartNodeTypeId)]
    
        // Defines a new node type that represents a Web Part on a SharePoint site.
        internal class WebPartNodeTypeProvider : IExplorerNodeTypeProvider
        {
            internal const string WebPartNodeTypeId = "Contoso.WebPart";
    
            public void InitializeType(IExplorerNodeTypeDefinition typeDefinition)
            {
                typeDefinition.DefaultIcon = Properties.Resources.WebPart.ToBitmap();
                typeDefinition.IsAlwaysLeaf = true;
    
                typeDefinition.NodePropertiesRequested += NodePropertiesRequested;
                typeDefinition.NodeMenuItemsRequested += NodeMenuItemsRequested;
            }
    
            // Retrieves properties that are displayed in the Properties window when
            // a Web Part node is selected.
            private void NodePropertiesRequested(object sender,
                ExplorerNodePropertiesRequestedEventArgs e)
            {
                var webPart = e.Node.Annotations.GetValue<ListItem>();
                object propertySource = e.Node.Context.CreatePropertySourceObject(
                    webPart.FieldValuesAsText.FieldValues);
                e.PropertySources.Add(propertySource);
            }
    
            private void NodeMenuItemsRequested(
                object sender, ExplorerNodeMenuItemsRequestedEventArgs e)
            {
                e.MenuItems.Add("Display Message").Click += MenuItemClick;
            }
    
            private void MenuItemClick(object sender, MenuItemEventArgs e)
            {
                IExplorerNode parentNode = e.Owner as IExplorerNode;
    
                if (parentNode != null)
                {
                    var webPart = parentNode.Annotations.GetValue<ListItem>();
                    MessageBox.Show("You clicked the context menu for the following Web part: " +
                        webPart.FieldValuesAsText.FieldValues["Title"] + ".", "Web Part Menu Command");
                }
            }
        }
    }
    
    
    

At this point in the walkthrough, all the code for the Web Part Gallery node is now in the project. Build the solution to make sure that the project compiles 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 project. Then, create the VSIX package by building the solution.

To configure the VSIX package

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

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

  2. In the Product Name box, type Web Part Gallery Node for Server Explorer.

  3. In the Author box, type Contoso.

  4. In the Description box, type Adds a custom Web Part Gallery node to the SharePoint Connections node in Server Explorer.

  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 WebPartNodeExtension in the list box next to it.

  8. Click OK.

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

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

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

You are now ready to test the new Web Part Gallery node in Server Explorer. First, start debugging the extension project in an experimental instance of Visual Studio. Then, use the new Web Parts node in the experimental instance of Visual Studio.

To start debugging the extension

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

  2. In the WebPartNodeExtension project, open the SiteNodeExtension code file and add a breakpoint to the first lines of code in the NodeChildrenRequested and CreateWebPartNodes methods.

  3. Press F5 to start debugging.

    Visual Studio installs the extension to %UserProfile%\AppData\Local\Microsoft\VisualStudio\10.0Exp\Extensions\Contoso\Web Part Gallery Node Extension for Server Explorer\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 extension

  1. In the experimental instance of Visual Studio, on the View menu, click Server Explorer.

  2. Verify that the SharePoint site that you want to use for testing appears under the SharePoint Connections node in Server Explorer. If it is not listed, follow these steps:

    1. Right-click SharePoint Connections and click Add Connection.

    2. In the Add SharePoint Connection dialog box, enter the URL for the SharePoint site that you want to connect to. To specify the SharePoint site on your development computer, type http://localhost.

    3. Click OK.

  3. Expand the site connection node (the node that displays the URL of your site), and then expand a child site node (for example, Team Site).

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

  5. In the experimental instance of Visual Studio, verify that a new node named Web Part Gallery appears under the top-level site node. Expand the Web Part Gallery node.

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

  7. In the experimental instance of Visual Studio, verify that all the Web Parts on the connected site appear under the Web Part Gallery node in Server Explorer.

  8. Right-click one of the Web Parts, and click Properties.

  9. Verify that details about the Web Part appear in the Properties window.

  10. In Server Explorer, right-click the same Web Part again, and click Display Message.

    Verify that a message box appears. Click OK in the message box.

After you finish testing the extension, uninstall the extension from Visual Studio.

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 Web Part Gallery Node Extension for Server Explorer, 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. The project item is also uninstalled.

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

Community Additions

ADD
Show:
© 2015 Microsoft