Partager via


Walkthrough: Creating a Basic SharePoint Web Part

[Cet article doit être considéré comme une documentation préliminaire, susceptible d'être modifiée dans les versions futures. Certains liens peuvent être en anglais ou mener à des articles en anglais.]

This programming task includes the steps for creating a basic custom SharePoint Foundation Web Part. It is a simple Web Part that allows you to change the Web Part’s Title property, which is a SharePoint FoundationWebPart base class property that sets the text in the title bar of the Web Part.

Important

Beginning with Windows SharePoint Services 3.0, the SharePoint Foundation Web Part infrastructure is built on top of the Microsoft ASP.NET 2.0 Web Part infrastructure and Web Parts that derive from the ASP.NET WebPart class are completely supported in SharePoint Foundation. You should create ASP.NET Web Parts whenever possible.

For more information about choosing the best Web Part base class from which to derive, see Developing Web Parts in SharePoint Foundation in the SharePoint Foundation Software Development Kit (SDK). For more information about ASP.NET Web Parts, see the Web Parts Control Set Overview in the ASP.NET documentation.

Conditions requises

Microsoft Visual Studio 2005

Windows SharePoint Services 3.0

Step 1: Create a Web Control Library project

Web Parts are based on ASP.NET Web Form Controls. You create Web Parts in Microsoft Visual C# or Microsoft Visual Basic by using the ASP.NET Web Control Library template.

To create a new Web Control Library project

  1. Start Visual Studio 2005.

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

  3. In the New Project dialog box, click Visual C# Projects or Visual Basic Projects, and then select the Web Control Library template.

  4. Type SimpleWebPart as the name and specify the location for the project files, and then click OK.

Step 2: Add a Reference to Microsoft.SharePoint.dll

To create a Web Part, you need to add a reference to the Microsoft.SharePoint assembly (Microsoft.SharePoint.dll) in your Web Control Library project.

To add a reference to Microsoft.SharePoint.dll

  1. On the Project menu, click Add Reference.

  2. On the .NET tab, double-click Windows SharePoint Services.

  3. Click OK.

Step 3: Set the Version Number and set up partially trusted callers

By default, the AssemblyVersion property of your project is set to increment each time you recompile your Web Part. A Web Part page identifies a Web Part with the version number that is specified in the web.config file. With the AssemblyVersion property set to increment, if you recompile your Web Part after importing it into a Web Part page, the Web Part framework will look for the version number you specified in the web.config file. If the version number does not match, an error will occur. To prevent the version number of your Web Part from incrementing each time you recompile, you need to set the version number in the AssemblyInfo file.

Since you are creating signed code, you must also tell your assembly to allow partially trusted code calls. By default, any strong-named assembly that does not explicitly opt in to its use by partially trusted code will be callable only by other assemblies that are granted full trust by security policy.

To set the version number and allow partially trusted callers

  1. In Solution Explorer, double-click the AssemblyInfo file

  2. Edit the line:

    [assembly: AssemblyVersion("1.0.*")]
    
    <Assembly: AssemblyVersion("1.0.*")>
    

    so that it reads:

    [assembly: AssemblyVersion("1.0.0.0")]
    
    <Assembly: AssemblyVersion("1.0.0.0">
    
  3. Add the following line to the top of the file:

    using System.Security;
    
    Imports System.Security;
    
  4. Add the following line to the bottom of the file:

    [assembly: AllowPartiallyTrustedCallers]
    
    <Assembly: AllowPartiallyTrustedCallers()>
    

Step 4: Rename the Class and Namespace

If you are creating multiple Web Parts, you should generally use the same namespace across all of your Web Parts. By default, the Web Control Library assigns the namespace the same name as your project. For this example, we are using the arbitrary namespace of MyWebParts for the WebPart class. After you create the project, a blank class file is displayed. You can change the default class name of WebCustomControl to easily identify your new Web Part.

To rename the class and namespace

  1. Rename the default class by selecting WebCustomControl1 in Solution Explorer, right-click, click Rename, and type SimpleWebPart as the file name.

  2. For C#, change the Web Part namespace by editing the line:

    namespace SimpleWebPart
    

    so that it reads:

    namespace MyWebParts
    
  3. For Visual Basic, right-click the SimpleWebPart project in the Solution Explorer and click Properties. Replace the text in the Assembly name and Root namespace text boxes to MyWebParts.SimpleWebPart

Step 5: Add a Namespace Directive

To make it easier to write a basic WebPart class, you should use the using directive in C# or the Imports directive in Visual Basic to reference the following namespace in your code:

To add a namespace directive

  • Add the following using or Imports directive near the top of your code:

    using Microsoft.SharePoint.WebPartPages;
    
    Imports Microsoft.SharePoint.WebPartPages
    

Step 6: Inherit from the Web Part Class

By default, the Web Control Library template creates a custom control that inherits from the System.Web.UI.Control class (a parent class of both the ASP.NET and SharePoint WebPart classes). To create a SharePoint Web Part, you should inherit from the Microsoft.SharePoint.WebPartPages.WebPart base class.

To inherit from the Web Part base class.

  • Replace this line of code:

    public class SimpleWebPart : WebControl
    
    Public Class SimpleWebPart
       Inherits WebControl
    

    with this line:

    public class SimpleWebPart : WebPart
    
    Public Class SimpleWebPart
       Inherits WebPart
    

Step 7: Use the RenderWebPart Method

The WebPart base class seals the Render method of System.Web.UI.Control because the Web Part infrastructure needs to control rendering the contents of a Web Part. For this reason, custom Web Parts must override the RenderWebPart method of the WebPart base class.

To use the RenderWebPart method.

  • Replace this line of code:

    protected override void Render(HtmlTextWriter output)
    
    Protected Overrides Sub RenderContents(ByVal output as HtmlTextWriter)
    

    with this line:

    protected override void RenderWebPart(HtmlTextWriter output)
    
    Protected Overrides Sub RenderWebPart(ByVal output as HtmlTextWriter)
    

Step 8: Define the Logic and Rendering of your Web Part

After you complete the previous steps, you can define the logic and rendering for your Web Part. For this part, we will write some basic ASP.NET code to create two controls: a text box and a button that will set the Title property of the Web Part.

To define the logic and rendering of your Web Part

  1. Create two user interface objects by adding the following code near the top of the SimpleWebPart file.

    Button saveTitle;
    TextBox newTitle;
    
    Public saveTitle as Button
    Public newTitle as TextBox
    
  2. Create the button handling event by adding the following code inside the class.

    public void saveTitle_click(object sender, EventArgs e)
    {
         this.Title = newTitle.Text;
         try
         {
              this.SaveProperties = true;
         }
         catch (Exception ex)
         {
              this.Title = "Error: " + ex.Message;
         }
    }
    
    Public Sub saveTitle_Click(ByVal sender As Object, ByVal e As EventArgs)
        Me.Title = newTitle.Text
        Try
            Me.SaveProperties = True
        Catch ex As Exception
            Me.Title = "Error: " & ex.Message
        End Try
    End Sub
    
  3. Override the CreateChildControls() method by adding the following code inside the class.

    protected override void CreateChildControls()
    {
         //Create text box
         newTitle = new TextBox();
         newTitle.Text = "";
         Controls.Add(newTitle);
    
         //Create button
         saveTitle = new Button();
         saveTitle.Text = "Set Web Part Title";
         saveTitle.Click += new EventHandler(saveTitle_click);
         Controls.Add(saveTitle);
    }
    
    Protected Overrides Sub CreateChildControls()
        'Create text box
        newTitle = New TextBox()
        newTitle.Text = ""
        Controls.Add(newTitle)
    
        'Create button
        saveTitle = New Button()
        saveTitle.Text = "Set Web Part Title"
        AddHandler saveTitle.Click, AddressOf saveTitle_Click
        Controls.Add(saveTitle)
    End Sub
    
  4. Replace the RenderWebPart method with the following line of code.

    protected override void  RenderWebPart(HtmlTextWriter output)
    {
         RenderChildren(output);
    }
    
    Protected Overrides Sub RenderWebPart(ByVal output as HtmlTextWriter)
        RenderChildren(output)
    End Sub
    

Step 9: Create a Valid Strong Name for the Assembly

Web Parts are designed to be distributed over the Internet or an intranet. For security reasons, when you create a custom Web Part, you should give it a strong name to ensure that the Web Part can be trusted by your users. For more information about strong naming, see Deploying Web Parts in SharePoint Foundation and also Assembly Signing Frequently Asked Questions.

To assign a strong name to an assembly

  1. In Solution Explorer, right-click on the SimpleWebPart project and click Properties.

  2. In the SimpleWebPart properties, click the Signing tab on the left side.

  3. On the Signing tab, check the Sign the assembly checkbox.

  4. Select New in the Choose a strong name key file drop-down menu.

  5. In the Create Strong Name Key dialog, type SimpleWebPartKey and uncheck Protect my key file with a password.

  6. Now, the assembly will be signed when it is built.

Step 10: Build Your Web Part

After you add all of the preceding code, you can build your sample Web Part.

To build your Web Part

  • On the Build menu, click Build Solution.

Step 11: Copy Your DLL to the Bin Directory

After the Web Part is built, you must copy the resulting DLL to the bin directory.

To copy your DLL to the bin directory

  1. On the file system, locate the SimpleWebPart.dll file. The default location for Visual Studio 2005 is C:\Documents and Settings\UserName\My Documents\Visual Studio 2005\Projects\SimpleWebPart\SimpleWebPart\bin\Debug.

  2. Copy the SimpleWebPart.dll file from the output directory to the Web application root bin directory. The default location of the Web application root for is C:\Inetpub\wwwroot\wss\VirtualDirectories\PortNumber\bin.

    For more information, see How to: Find the Web Application Root.

Step 12: Increase the Default Trust Level and Add a SafeControl Entry for your Web Part

provides a SafeControls list to prevent users from arbitrarily adding server-side code within ASPX pages. The SafeControls list is a list of approved controls and Web Parts specific to your SharePoint site that you have designated as safe for invocation on any ASPX page within your site. This list is contained in the web.config file in your Web application root. The local path contains the physical location of the web.config file.

By default, the trust level for this server is WSS_Minimal, which does not allow access to the SharePoint Foundation object model. For this Web Part to set the SaveProperties property, you must perform one of the following three actions:

  • Create a custom policy file for your assembly, or

  • Install your assembly in the global assembly cache, or

  • Increase the trust level for the entire virtual server.

In this example, you will increase the default trust from WSS_Minimal to WSS_Medium in the web.config file.

Notes

The web.config file is located in the folder where the virtual directory for the Web site runs. It is usually located in the following directory: c:\inetpub\wwwroot\wss\VirtualDirectories\PortNumber, but your administrator may have set up your directory differently and this may not be the location of the file.

You can find the location of your web.config file by using the Internet Information Services (IIS) snap-in. The IIS snap-in is an administration tool for IIS that has been integrated with other administrative functions. To launch the IIS snap-in and locate the web.config file:

  1. Click Start, point to Programs, point to Administrative Tools, and click Internet Information Services (IIS) Manager.

  2. Expand the node that is the name of your computer, and expand the Web Sites item in the tree.

  3. Locate the web site that is running your SharePoint Foundation installation (often it is Default Web Site).

  4. Right-click and select Properties.

  5. Select the Home Directory tab.

To increase the default trust level and add a SafeControl entry for your Web Part

  1. Open the web.config file in the Web application root.

  2. In the level attribute of the trust section, change WSS_Minimal to WSS_Medium.

  3. In the SafeControls section of your web.config file, add a SafeControl entry for your custom assembly as follows.

    <SafeControl Assembly="SimpleWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=PublicKeyToken" Namespace="MyWebParts" TypeName="SimpleWebPart" Safe="True"/>
    
  4. Replace the PublicKeyToken with the actual value for your Web Part's assembly. To determine the correct PublicKeyToken for your Web Part, use the sn.exe command-line utility.

    sn.exe -T C:\inetpub\wwwroot\wss\VirtualDirectories\PortNumber\bin\SimpleWebPart.dll
    

Step 13: Create a DWP File to Deploy your Web Part

A Web Part definition file (.dwp) is a simple XML file that contains property settings for a single Web Part. To import your Web Part into a Web Part page, simply upload the .dwp file. After uploading the Web Part, you can display the Web Part by dragging it into one of the zones of the Web Part page.

Two properties are required in the .dwp file: Assembly and TypeName. However, to display a default name and description for the Web Part after it is imported, you should also include the Title and Description properties. If you want to set other Web Part properties during import, you can also define them in a .dwp file. A .dwp file takes the following form.

<?xml version="1.0"?>
<WebPart xmlns="https://schemas.microsoft.com/WebPart/v2">
   <Assembly>AssemblyName(with no .dll extension),
     Version=VersionNumber, Culture=Culture,
     PublicKeyToken=PublicKeyToken</Assembly>
   <TypeName>WebPartNameSpace.WebPartClassName</TypeName>
   <Title>DefaultWebPartTitle</Title>
   <Description>WebPartDescription</Description>
</WebPart>

To create a DWP file

  1. Copy and paste the following XML into a new text file.

    <?xml version="1.0"?>
    <WebPart xmlns="https://schemas.microsoft.com/WebPart/v2">
       <Assembly>SimpleWebPart, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=PublicKeyToken</Assembly>
       <TypeName>MyWebParts.SimpleWebPart</TypeName>
       <Title>My Simple Web Part</Title>
       <Description>A simple Web Part</Description>
    </WebPart>
    

    Important

    You must replace PublicKeyToken in the XML above with the public key token of your assembly.

  2. Save this file as SimpleWebPart.dwp in the bin directory of the Web application root.

Step 14: Import your Web Part into a Web Part Page

To use and test your Web Part, import it into a Web Part page on a server that is running SharePoint Foundation or Microsoft Office SharePoint Server 2007.

To import your Web Part

  1. Navigate to the page on your SharePoint site where you want the Web Part to be accessible.

  2. In the Web Part page, click Site Actions, and select Site Settings.

  3. On the Site Settings page, click Web Parts under the Galleries heading.

  4. On the toolbar in the Web Part gallery, click Upload.

  5. On the Upload Web Part page, click Browse and select the .dwp file that you created.

    Notes

    This should be in C:\inetpub\wwwroot\wss\VirtualDirectories\PortNumber\bin\.

    Click OK.

  6. Navigate back to the Web Part page. In the Web Part page, click Site Actions, and select Edit Page.

  7. In your preferred zone, click Add a Web Part and check the box next to My Simple Web Part in the dialog box. Click Add.

  8. After the Web Part is added to the zone, type some text in the text box and click Set Web Part Title to test the Web Part.