Click to Rate and Give Feedback
MSDN
MSDN Library
Web Development
Server Technologies
SDK Documentation
General Reference
 Walkthrough: Creating a Basic Share...
Walkthrough: Creating a Basic SharePoint Web Part

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

NoteImportant:

Beginning with Windows SharePoint Services 3.0, the Windows SharePoint Services 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 Windows SharePoint Services. 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 Windows SharePoint Services in the Windows SharePoint Services Software Development Kit (SDK). For more information about ASP.NET Web Parts, see the Web Parts Control Set Overview in the ASP.NET documentation.

Microsoft Visual Studio 2005

Windows SharePoint Services 3.0

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.

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.

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:

    C#
    [assembly: AssemblyVersion(“1.0.*”)]
    
    Visual Basic
    <Assembly: AssemblyVersion(“1.0.*”)>
    

    so that it reads:

    C#
    [assembly: AssemblyVersion(“1.0.0.0”)]
    
    Visual Basic
    <Assembly: AssemblyVersion(“1.0.0.0”>
    
  3. Add the following line to the top of the file:

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

    C#
    [assembly: AllowPartiallyTrustedCallers]
    
    Visual Basic
    <Assembly: AllowPartiallyTrustedCallers()>
    

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:

    C#
    namespace SimpleWebPart
    

    so that it reads:

    C#
    namespace MyWebParts
    
  3. For Visual Basic, right-click on the 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

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:

    C#
    using Microsoft.SharePoint.WebPartPages;
    
    Visual Basic
    Imports Microsoft.SharePoint.WebPartPages
    

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:

    C#
    public class SimpleWebPart : WebControl
    
    Visual Basic
    Public Class SimpleWebPart
       Inherits WebControl
    

    with this line:

    C#
    public class SimpleWebPart : WebPart
    
    Visual Basic
    Public Class SimpleWebPart
       Inherits WebPart
    

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:

    C#
    protected override void Render(HtmlTextWriter output)
    
    Visual Basic
    Protected Overrides Sub RenderContents(ByVal output as HtmlTextWriter)
    

    with this line:

    C#
    protected override void RenderWebPart(HtmlTextWriter output)
    
    Visual Basic
    Protected Overrides Sub RenderWebPart(ByVal output as HtmlTextWriter)
    

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.

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

    C#
    public void saveTitle_click(object sender, EventArgs e)
    {
         this.Title = newTitle.Text;
         try
         {
              this.SaveProperties = true;
         }
         catch (Exception ex)
         {
              this.Title = "Error: " + ex.Message;
         }
    }
    
    Visual Basic
    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.

    C#
    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);
    }
    
    Visual Basic
    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);
    }
    Visual Basic
    Protected Overrides Sub RenderWebPart(ByVal output as HtmlTextWriter)
        RenderChildren(output)
    End Sub
    

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 Windows SharePoint Services and also Related Topics at the end of this walkthrough.

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.

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.

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.

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 Windows SharePoint Services 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.

Note

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 Windows SharePoint Services 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.

    Xml
    <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

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
<?xml version="1.0"?>
<WebPart xmlns="http://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
    <?xml version="1.0"?>
    <WebPart xmlns="http://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>
    NoteImportant:

    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.

To use and test your Web Part, import it into a Web Part page on a server that is running Windows SharePoint Services 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.

    NoteNote:

    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.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
This page needs revision      larsw ... ch15patel   |   Edit   |  

It contains references to .NET 1.1 / Visual Studio .NET 2003.
I couldn't find the Microsoft.Sharepoint assembly in the .NET tab of the Add Reference dialog box either, even if I installed WSS3.0 together with VS2005.

When you try to add reference dont look for Microsoft.Sharepoint name in Add Reference Dialog box, Look for Microsoft Windows Sharepoint Services in it.

Flag as ContentBug
Ditto on 'Revision'      GtlBearFL   |   Edit   |  
Although the references are outdated, the content cannot be followed successfully. Please check content for accuracy prior to posting.
Tags What's this?: Add a tag
Flag as ContentBug
Please comment on the needed revisions      CRSCoder   |   Edit   |  

I was able to do this "successfully". Here are some of the things I did that were different than above:

First - common sense - in the section Defining the logic and rendering of your webpart . Make sure to remove all of the <b> and </b> tags...OK that's a bit of entertainment as well.

If you attempt to build and see several errors "Caption is deprecated..." etc. check your "Using" directives and make sure they match the ones in the example. It may be overkill, but here are the contents of my file:

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.HtmlControls;


namespace MyWebParts
{

[Guid("60487385-c231-4274-8536-64e5be432bd5")]
//public class SimpleWebPart : System.Web.UI.WebControls.WebParts.WebPart
[XmlRoot(Namespace="MyWebParts")]
public class SimpleWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{

private const string defaultText = "hello";
private string text = defaultText;

// Declare variables for HtmlControls user interface elements.
HtmlButton _mybutton;
HtmlInputText _mytextbox;


// Event handler for _mybutton control that sets the
// Title property to the value in _mytextbox control.
public void _mybutton_click(object sender, EventArgs e)
{
this.Title = _mytextbox.Value;
try
{
this.SaveProperties = true;
}
catch
{
//Caption = "Error... Could not save property.";
this.ToolTip = "Error... Could not save property.";

}
}

// Override the ASP.NET Web.UI.Controls.CreateChildControls
// method to create the objects for the Web Part's controls.
protected override void CreateChildControls()
{
// Create _mytextbox control.
_mytextbox = new HtmlInputText();
_mytextbox.Value = "";
Controls.Add(_mytextbox);

// Create _mybutton control and wire its event handler.
_mybutton = new HtmlButton();
_mybutton.InnerText = "Set Web Part Title";
_mybutton.ServerClick += new EventHandler(_mybutton_click);
Controls.Add(_mybutton);
}

[Browsable(true), Category("Miscellaneous"),
DefaultValue(defaultText),
WebPartStorage(Storage.Personal),
FriendlyName("Text"), Description("Text Property")]
public string Text
{
get
{
return text;
}

set
{
text = value;
}
}


//protected override void Render(HtmlTextWriter writer)
protected override void RenderWebPart(HtmlTextWriter writer)
{
// TODO: add custom rendering code here.
// writer.Write("Output HTML");
RenderChildren(writer);
// Securely write out HTML
writer.Write("<BR>Text Property: " + SPEncode.HtmlEncode(Text));

}
}
}

To register a Web Part assembly as a SafeControl

When following the WebPart Library template instructions there are several options for ensuring the control is seen by WSS 3.0 as "safe". I initially edited the web.config in the root c:\inetpub\wwwroot directory - as it says in the instructions. When I imported the web part the import was successful (it showed up as an option on the import page), but dropping the webpart on the web part page failed with the message:

"Unable to add selected web part(s). A Web Part or Web Form Control on this Page cannot be displayed or imported. The type is not registered as safe." Here's a good description of how to make a control "safe" in Sharepoint's eyes. http://msdn2.microsoft.com/en-us/library/ms916848.aspx

So, I edited the web.Config at the root of my site, C:\Inetpub\wwwroot\wss\VirtualDirectories\5219, for example using the XML provided in the example:

<SafeControl
Assembly="SimpleWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def148956c61a16b" Namespace="MyWebParts"
TypeName="*" Safe="True" />

.... repeated the import and was then able to drop the web part on the webpart page. IT WORKED! And I could use it to change the 'Title" of the Web Part itself. Cool!

There are likely some elements of the file (above), for example in the "using" directives, that may not be quite kosher for WSS 3.0. I'm new to web parts and WSS 3.0 so I do not know (yet) what these are.

I hope this helps.

Tags What's this?: Add a tag
Flag as ContentBug
Inconsistencies in the article - IS there an actual web part library template for VS.NET 2005?