4.5. Web Parts

A Web Part is a user interface component similar to the familiar controls we see on ordinary web pages, such as text boxes and buttons. However, in addition to providing "canned" UI functionality, Web Parts can also participate in SharePoint's personalization infrastructure. That is, individual users can add, remove, and configure their own custom view of a SharePoint site by manipulating the Web Parts available to them. Users, of course, have this privilege only if the SharePoint administrator grants it to them. Also, while web controls typically provide simple UI functionality such as text boxes, Web Parts are often complex UI elements that can connect to back-end data providers or business processes.

In WSS 3.0 the Web Part infrastructure is built entirely on top of the ASP.NET 2.0 Web Part classes. This means that with very little additional training, an ASP.NET developer can build Web Parts that will also run in the SharePoint environment. Web Parts can be used to perform a myriad of tasks. They can connect to a SQL Server database, connect to an Active Directory, or access SQL Server Reporting Services among other things. Almost anything you can do with custom code, you can do within a Web Part. Web Part development is relatively easy and is a powerful way to extend SharePoint and ASP.NET sites.

The following nonexhaustive list borrowed from the SDK, demonstrates some of the ways in which you can use custom Web Parts:

  • Creating custom properties, you can display and modify in the user interface and access via the code in your Web Parts.

  • Improving performance and scalability. A compiled custom Web Part runs faster than a script.

  • Implementing proprietary code without disclosing the source code.

  • Securing and controlling access to content within the Web Part. Built-in Web Parts allow any users with appropriate permissions to change content and alter Web Part functionality. With a custom Web Part, you can determine the content or properties to display to users, regardless of their permissions.

  • Making your Web Part connectable, allowing Web Parts to provide or access data from other connectable Web Parts.

  • Interacting with the object models that are exposed in WSS v3. For example, you can create a custom Web Part to save documents to a WSS document library.

  • Controlling the cache for the Web Part by using built-in cache tools. For example, you can use these tools to specify when to read, write, or invalidate the Web Part cache.

  • Benefiting from a rich development environment with debugging features that are provided by tools such as Visual Studio 2005.

  • Creating a base class for other Web Parts to extend. For example, to create a collection of Web Parts with similar features and functionality, create a custom base class from which multiple Web Parts can inherit. This reduces the overall cost of developing and testing subsequent Web Parts.

  • Controlling the implementation of the Web Part. For example, you can write a custom server-side Web Part that connects to a back-end database, or you can create a Web Part that is compatible with a broader range of Web browsers.

4.5.1. Web Part Infrastructure

The WSS 3.0 Web Part infrastructure is built on top of the Microsoft ASP.NET 2.0 Web Part infrastructure. This topic could span multiple chapters, but in the interest of space we are only going to scratch the surface and discuss the topics needed to design, deploy, and debug a simple WSS v3 Web Part. What follows is a crash course, if you will, on developing a simple WSS v3 Web Part. After reading the following section, you should be able to move forward and solve all kinds of different business problems you may have for which you think a custom Web Part would be able to provide a solution. Keep in mind that you will be working in a very familiar environment, Visual Studio 2005, and with very familiar languages, C# or VB.Net. Remember, aside from interacting with the WSS v3 object model (if necessary), most of the code required to create a Web Part is most likely code you are already very familiar with writing. The following sections cover some of the best practices for designing a Web Part, the steps needed to deploy a Web Part manually, and how to debug a Web Part.

4.5.1.1. ASP.NET Web Part Infrastructure

The ASP.NET Web Part infrastructure is based on a WebPartManager class that manages the lifetime of Web Part instances at runtime. Each ASP.NET web page that uses Web Part controls must contain the following two items, remembering that WSS v3 pages are just ASP.NET pages.

  • Exactly one WebPartManager object that tracks which Web Parts have been added to each particular zone, and stores and retrieves data about how each Web Part has been customized and personalized.

  • One or more WebPartZone objects, into which Web Parts are placed.

Web Parts that require dynamic characteristics (such as retaining customization and personalization data) must be created within Web Part zones—in ASP.NET, Web Parts cannot be placed outside of a Web Part zone.

4.5.1.2. WSS v3 Web Part Infrastructure

The WSS v3 Web Part infrastructure uses many of the controls in the ASP.NET Web Part control set and also introduced a number of its own controls that inherit from the ASP.NET base classes and provide some additional functionality.

4.5.1.2.1. WSS v3 SPWebPartManager Class vs. ASP.NET WebPartManagerClass

Instead of using the WebPartManager (System.Web.UI.WebControls.WebParts.WebPartManager) class, WSS v3 uses the SPWebPartManager (Microsoft.SharePoint.WebPartPages.SPWebPartManager) class, that inherits from the former. Any page in WSS v3 that contains Web Parts on it must have an instance of the SPWebPartManager class on the page to manage the Web Parts. This object is used to track which zone each of the Web Parts is in, connection informa-tion related to Web Parts, and personalization settings. The SPWebPartManager object is also responsible for raising the Web Part events that occur during a Web Parts lifetime.

The SDK tells us that the default master page that is provided with the Windows SharePoint Services technology includes an instance of SPWebPartManager, so this control is automatically included with all of your WSS v3 content pages, assuming that you are using the default master page.

4.5.1.2.2. WSS v3 WebPartZone Class vs. ASP.NET WebPartZone Class

The WebPartZone (Microsoft.SharePoint.WebPartPages.WebPartZone) class used by WSS v3 is not to be confused with the WebPartZone (System.Web.UI.WebControls.WebParts.WebPartZone) class used by the ASP.NET Web Part framework. The WSS v3 version inherits from the ASP.NET version and is primarily responsible for maintaining a consistent look and feel across Web Part controls. The WebPartZone and SPWebPartManager classes are the magic behind the persistence mechanism provided by Web Parts. Together, they handle the serialization of data associated with Web Parts into the appropriate WSS v3 content database.

4.5.1.2.3. WSS v3 WebPart Class vs. ASP.NET WebPart Class

Unlike the previous two classes, in which SharePoint-specific classes were created (SPWebPartManager and WebPartZone) that inherit from their ASP.NET counterparts, the WebPart class that is used in SharePoint is the same WebPart class that is used in ASP.NET. This is possible because WSS v3 is built directly on ASP.NET. Although it is still possible to build a Web Part and derive it from the WebPart class contained in the Microsoft.SharePoint.WebPartPages namespace or the WebPart class contained in the System.Web.UI.WebControls.WebParts namespace, Microsoft highly recommends inheriting from the WebPart class contained in the System.Web.UI.WebControls.WebParts namespace unless any of the following requirements are present:

  • Cross-page connections

  • Connections between Web Parts that are outside a Web Part zone

  • Client-side connections

  • Use of the data-caching infrastructure (provided by SharePoint, not ASP.NET)

  • Multiple providers for a single consumer with respect to connectable Web Parts

4.5.2. Web Part Design

As with any other component you may choose to design, whether it be a user control in a web application or maybe even a custom server control, a good design in the beginning will most likely save you from a great number of potential problems down the road. Keep in mind that not everyone starts out as an expert Web Part developer. Web part design and development, although still classified as specialized by some, is by and large becoming more and more mainstream in today's development community. As the adoption rate for SharePoint increases, Web Part developers will no longer find themselves few and far between. On the contrary, with the entire Web Part platform being transformed into what is essentially a superset of the ASP.NET 2.0 platform, Web Part design and development not only becomes easier for the masses but also becomes more appealing and accessible.

Following some best practices will also make life a little easier for developers down the road, whether they are adding enhancements or possibly trying to fix a potential bug (yes, we all have bugs in our code). In addition to a plethora of best practices that carry over from the .NET development world, such as variable naming, spacing, casing, and many others, there are a few additional items to keep in mind when developing Web Parts. This list is by no means all inclusive and a more exhaustive list can be viewed at the following URL (http://msdn2.microsoft.com/en-us/library/ms916817.aspx) in the SDK. This list was originally created for WSS v2, but most of the concepts and ideas still apply.

  • Handle exceptions appropriately by making good use of try... catch blocks—Catching exceptions and presenting the user with a clean message makes the user experience much better.

  • Check Permissions before rendering your Web Part—For example, displaying a Save button to a user who does not have permission to save would not produce a very good user experience. Remember, you have access to all of the user's permissions when rendering the Web Part's user interface.

  • Validate properties before saving—Since Web Part properties can be modified in a number of places, for example in the tool pane, in the .webpart or .dwp file among others, validation code should be called in the properties' Set accessor method. This is not commonly done; however, in most cases, this is the last chance you will have to validate its value.

  • Validate all user input—All user input should be validated before performing any operations with that input. There are many reasons for this including preventing SQL injection, cross-site scripting, buffer overflow, and so on. The appropriate use of validators as well as server-side error handling is always a good practice and strongly encouraged.

  • HTMLEncode all user input rendered to the client—Try not to emit HTML manually at all if possible. Make use of the rendering capabilities of the System.Web.UI.HtmlControls and System.Web.UI.WebControls namepaces. They exist to provide the correct markup to the many devices that access your SharePoint site. A label rendered in Internet Explorer will have very different HTML markup than a label rendered on a mobile phone.

The most important take away here is to be mindful of performance, error handling, and of course the end-user experience. If end users have a lousy experience, they will most likely not come back.

4.5.3. Creating and Deploying a Web Part

The process of creating a custom Web Part, although not terribly complex, does involve a series of steps that must be performed in order for the Web Part to function properly within the WSS v3 environment. These steps may seem like a lot a first, but as you design and develop an increasingly large number of Web Parts, they will eventually become second nature. All of the code used to run a Web Part needs to be contained inside an assembly. Signing Web Part assemblies is not required, but it is most certainly a best practice and encouraged. Signing, however, is required if the assembly is to be deployed to the Global Assembly Cache (GAC). It also aids in enforcing code access security. Traditionally, this (GAC deployment) may not be something that a developer has much control over in production, so signing the assembly will allow this process to proceed if it is needed. The security policy that is being used by the site on which the Web Part is deployed must trust the Web Part's code. Having the trust level in the web.config set to Full is not recommended. Instead, the recommended best practice is to make a copy of the WSS_Minimal security policy and to add to it the appropriate permissions as new Web Parts are developed and added to the system. The complete detailed process of creating a custom code access security file is outside the bounds of this book; however, there are a few good examples online. Again, we remind you that the easiest way to learn how to do a lot of tasks outlined in this chapter in particular is to look at how Microsoft has done them within SharePoint. Go ahead and make a copy of the wss_minimaltrust.config security file located at [WSS]CONFIG and take a look at it. In order for the Web Part to run within a WSS v3 site, a SafeControl entry must also exist in the site's web.config file. As mentioned, this process will become second nature as you develop more and more Web Parts. Most importantly, remember that security is a good thing.

Your custom Web Part is going to be very simple. Once you understand the fundamentals of creating and deploying a Web Part, you will be able to extend this example to perform many other tasks. It will accept a string from the user and return that string converted to the standard Pig Latin form as defined by Wikipedia (http://en.wikipedia.org/wiki/Pig_latin). It will contain a text box for the input, a button to initiate the conversion, and a literal control to display the result. You will also give the user the ability to bold the result by changing one of the Web Part's custom properties.

4.5.3.1. Create the Web Part Class

You begin Web Part creation by creating a WebPart class:

  1. Create a new project by clicking Project under the New option from the File menu.

  2. Under Project types, select the Class Library template under Windows in the language of your choice (C# is used in this example).

  3. In the Location text box, browse to C:Documents and SettingsAdministratorMy DocumentsVisual Studio 2005projects and click Open.

  4. Uncheck the Create directory for solution check box.

  5. Give your Web Part project a meaningful name such as PigLatin, and click OK.

  6. Add a reference to System.Web.

  7. Delete the Class1.cs file.

  8. Add a new class file, naming it PigLatinWebPart.cs.

    At this point, you will have an empty class that essentially has no functionality, nor is it a Web Part. It needs to inherit from one of the two WebPart classes discussed earlier in this section. Since you don't need any of the functionality specific to the WSS v3 Web Part, you should have it inherit from the ASP.NET Web Part class.

  9. Have it inherit from the System.Web.UI.WebControls.WebParts.WebPart class.

    Since you are going to be creating a couple of user interface components for your Web Part you need to add a couple of using statements to your class to reduce the amount of code that you will have to type. You also will be using some ASP.NET attributes located in the System.Web.UI.WebControls.WebParts namespace; so add a using statement for that namespace as well.

  10. Add using statements for the System.Web.UI, System.Web.UI.HtmlControls, System.Web.UI.WebControls, and System.Web.UI.WebControls.WebParts namespaces.

  11. Build your project.

4.5.3.2. Add AllowPartiallyTrustedCallers Attribute To Assembly

Microsoft states that since the bin directory is a partial trust location, your Web Part does not automatically grant full trust code permissions when it is executed. Because the code that calls into your Web Part will be granted only partial trust permissions, your Web Part needs to have the AllowPartialTrustedCallers attribute set on it. You can set this attribute at the assembly level using the following steps:

  1. Click the plus sign next to the Properties node in your project.

  2. Open the AssemblyInfo.cs file and add the following attribute at the bottom of this file.

    [assembly: System.Security.AllowPartiallyTrustedCallers()]

  3. Build your project.

NOTE

The SDK states that marking an assembly as safe to AllowPartiallyTrustedCallers puts a lot of responsibility for safe implementation on the developers.

4.5.3.3. Create the Web Part User Interface Properties

It is time to decide how the Web Part will look. We determined earlier that your Web Part will consist of a text box for input, a button for initiating the conversion process, and a literal control to display the result. A common way to display these controls is to place them into a table.

It is generally accepted as a best practice to not emit HTML directly through your Web Part code but instead to let the .NET framework handle this process. It knows how to emit a button control on a variety of platforms. By leveraging this built-in capability provided by Microsoft, you drastically reduce the chances that your HTML will be rendered incorrectly across different browsers, as it might if you were to write it yourself. This concept will be demonstrated shortly.

Place the text box and the button in one row of the table, each in its own column, and place the literal control in the second row, spanning the two columns. Give the table a width of 100%.

  1. Declare the protected member variables that will represent your user interface elements, both visible (text box, button) and nonvisible (table, rows, columns):

    protected HtmlTable _MainTable = null;
    protected HtmlTableRow _Row1 = null;
    protected HtmlTableCell _Column11 = null;
    protected HtmlTableCell _Column12 = null;

    protected HtmlTableRow _Row2 = null;
    protected HtmlTableCell _Column21 = null;
    protected TextBox _InputTextBox = null;
    protected Button _ConvertButton = null;
    protected Literal _OutputLiteral = null;

  2. Declare a private Boolean field to determine whether or not to bold the result string.

  3. Add code for the public property and private member field that will be used to determine whether or not to bold the result string when it is rendered:

    private bool _BoldResult = false;
    
    [Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    System.ComponentModel.Category("User Interface"),
    WebDisplayName("Bold Result"),
    WebDescription("Check to bold the output.")]
    public bool BoldResult
    {
      get { return _BoldResult; }
      set { _BoldResult = value; }
    }

There are a few things to note in the above property. Note that it is decorated with multiple attributes. The Personalizable attribute is used to determine if the property can be set on a user-by-user basis (PersonalizationScope.User) or on a shared basis (PersonalizationScope.Shared). The Category attribute specifies the name of the category in which to group this property when displayed in the tool pane. The WebBrowsable attribute is used to determine if this particular Web Part property is displayed in the tool pane when the properties of the Web Part are modified. The WebDisplayName defines the friendly name for this property, and the WebDescription attribute defines the string value to use as a tooltip for this property.

4.5.3.4. Render the Web Part User Interface Components

The next step is to override the CreateChildControls method of the WebPart base class. This method, as described in the SDK, is called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering. It is here that you will create instances of your controls, including the table, rows, columns, text box, button, and literal controls; define any properties; and hook up any event handlers. You will include error handling in the form of a try . . . catch block. If an exception were to occur, it would simply clear out the controls collection of the Web Part and add a literal control to the table to display the error. You may want to change this before going to production to display a more user-friendly error, but for development purposes, this will suffice. Having this type of error handling in place now will be beneficial down the road as the user interface of your Web Part gets more and more complex and error prone.

  1. Override the CreateChildControls method in your class by adding the following code to it:

    protected override void CreateChildControls()
    {
      try
      {

    // create the main table
        _MainTable = new HtmlTable();
        _MainTable.Style.Add(HtmlTextWriterStyle.Width, "100%");
    
        // create row 1
        _Row1 = new HtmlTableRow();
    
        // create column 1
        _Column11 = new HtmlTableCell();
        _Column11.Style.Add(HtmlTextWriterStyle.Width, "70%");
    
        // create the input textbox
        _InputTextbox = new TextBox();
        _InputTextbox.ID = "InputTextbox";
    
        // add the textbox into column 1
        _Column11.Controls.Add(_InputTextbox);
    
        // add column 1 into row 1
        _Row1.Controls.Add(_Column11);
    
        // create column 2
        _Column12 = new HtmlTableCell();
        _Column12.Style.Add(HtmlTextWriterStyle.Width, "30%");
    
        // create the button
        _ConvertButton = new Button();
        _ConvertButton.ID = "ConvertButton";
        _ConvertButton.Text = "Convert";
        _ConvertButton.Click += new EventHandler(ConvertButton_Click);
    
        // add the button into column 2
        _Column12.Controls.Add(_ConvertButton);
    
        // add column 2 into row 1
        _Row1.Controls.Add(_Column12);
    
        // add row 1 into the main table
        _MainTable.Controls.Add(_Row1);
    
        // create row 2
        _Row2 = new HtmlTableRow();
    
        // create column 1
        _Column21 = new HtmlTableCell();
        _Column21.Attributes.Add("colspan", "2");
    
        // create the output literal
        _OutputLiteral = new Literal();
        _OutputLiteral.ID = "OutputLiteral";
    
        // add the literal into column 1
        _Column21.Controls.Add(_OutputLiteral);

    // add column 2 into row 2
        _Row2.Controls.Add(_Column21);
    
        // add row 2 into the main table
        _MainTable.Controls.Add(_Row2);
    
        // add the table to this Web Part's control collection
        this.Controls.Add(_MainTable);
      }
      catch (Exception ex)
      {
        Literal _ErrorMessageLiteral = new Literal();
        _ErrorMessageLiteral.Text = ex.Message;
    
        this.Controls.Clear();
        this.Controls.Add(_ErrorMessageLiteral);
      }
    }

    If you try and build your project at this point, the build will fail. If you look closely at the above code, you will see that you have wired up an event handler but have yet to define it. Go ahead and stub out your event handler, so your code will compile.

  2. Add the following event handler code stub to your WebPart class:

    protected void ConvertButton_Click(object sender, EventArgs e)
    {
    }

    If you have followed the steps so far, the class you have created is not decorated with the public access modifier. In C#, the default class access modifier is internal; therefore, your Web Part will not be visible outside this assembly, nor will you be able to add it to a page.

  3. Add a public access modifier to the PigLatinWebPart class:

    public PigLatinWebPart : System.Web.UI.WebParts.WebPart
    {
      ...
    }

  4. Build your project.

4.5.3.5. Sign the Assembly

As discussed earlier in this chapter, it would be a good idea to deploy your Web Part at this point. Once the Web Part is successfully deployed, you can then come back and implement the code necessary to convert the input string to Pig Latin. If you encounter problems during the deployment of your Web Part now, it will be much easier to debug if there is no custom code being executed. Once you successfully manage to deploy the Web Part, you can then concentrate on developing and debugging the business rules and other logic.

Before you deploy your Web Part, you should sign the assembly. The following steps guide you through the process of signing your assembly.

  1. Right-click on the project node and select Properties from the context menu.

  2. Click the Signing tab.

  3. Check the Sign the assembly check box.

  4. Select <New...> from the "Choose a strong name key file" drop-down list.

  5. Enter PigLatin in the Key file name text box.

  6. Uncheck the Protect my key file with a password check box.

  7. Click OK.

  8. Save your changes and build the project.

Now that your assembly is signed, you need to add a SafeControl entry to your web application's web.config file. Before you are able to add the SafeControl entry to your web.config, you need to extract the public key token from your compiled assembly using the following steps.

4.5.3.6. Extract Public Key Token

The following steps guide you though the process of extracting the public key token from your signed assembly using the .NET Framework Strong Name Utility command-line tool. Take note of the public key token; you will need it in the next step.

  1. Open a Visual Studio 2005 Command Prompt window by clicking on Start Programs Microsoft Visual Studio 2005 Visual Studio Tools Visual Studio 2005 Command Prompt.

  2. Type sn -T <assembly> where <assembly> is the complete path to the Web Part's assembly within your project. If this path contains spaces, place it within double quotation marks. The command window should look similar to Figure 4-24.

4.5.3.7. Add Safe Control Entry

The following steps walk you through the process of adding a SafeControl entry to the web.config file of your web application. Without this entry your Web Part will not run.

  1. Navigate to the physical folder that represents the web application that you plan on deploying the Web Part to. If the default settings were used, the path should be something like this:

    C:InetpubwwwrootwssVirtualDirectoriesDevelopment80

    The name of the folder in the directory (C:InetpubwwwrootwssVirtualDirectories) that contains the web application is determined by the name you gave the web application as well as the port number used during its creation.

  2. Open the web.config file.

    Figure 4.24. Figure 4-24

    Take a moment to locate the SafeControls element. Notice that there are several SafeControl elements already defined in your web.config file. Also notice that the entries each contain the complete signature of the assembly that they represent, including the version and the public key token. Because you signed your assembly with a private key in prior steps, you will need the public key you extracted in the previous set of steps.

  3. Make a copy of one of the SafeControl entries in the web.config file. Update the Assembly attribute of the copy to the fully qualified name of your Web Part's assembly and the Namespace attribute to the Web Part's namespace. Your SafeControl entry should resemble the following snippet. Make sure that the public key token in your entry matches the public key token you extracted in the previous set of steps.

    <SafeControl
      Assembly="PigLatin, Version=1.0.0.0, Culture=neutral,
    PublicKeyToken=969570b2ee20066e"
      Namespace="PigLatin"
      TypeName="*"
      Safe="True"
      AllowRemoteDesigner="True" />

4.5.3.8. Deploy the Assembly

You now need to place the assembly into the appropriate location, namely the bin folder of the web application that you plan on deploying the Web Part to. Do this by using a post-build event in your project.

  1. Right-click on the project node and select Properties from the context menu.

  2. Click the Build Events tab.

  3. Enter the following command in the "Post-build event command line" text box to copy the PigLatin.dll file to the correct location:

    xcopy PigLatin.dll "C:InetpubwwwrootwssVirtualDirectories
    Development80in" /y

    The trailing slash in the above path will ensure that the bin folder is created if it does not exist. Be sure to update the path to be the correct folder for your web application.

  4. Save your changes and build the project.

4.5.3.9. Create Web Part Definition File

In order to import your Web Part onto a page, you need to create a .webpart file. This file, once uploaded, is stored in the content database and tells SharePoint the information it needs to find the Web Part code. It can also be used to set default values for any of your Web Part's properties. Alternatives to this approach are discussed later.

  1. Add an XML file to your project, and name it PigLatinWebPart.webpart.

  2. Add the following code to the PigLatinWebPart.webpart file and save the file. Make sure that the public key token in your file matches the public key token extracted in previous steps. Also notice that you are able to set default values for many of the built-in properties as well as any of the public properties defined in your WebPart class. You are setting default values for both the Title and the Description properties below.

    <webParts>
      <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
        <metaData>
          <type name="PigLatin.PigLatinWebPart, PigLatin, Version=1.0.0.0,
    Culture=neutral, PublicKeyToken=969570b2ee20066e" />
          <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
        </metaData>
        <data>
          <properties>
            <property name="Title" type="string">Pig Latin Converter</property>
            <property name="Description" type="string">This Web Part will convert an
    input string to its Pig Latin equivalent.</property>
          </properties>
        </data>
      </webPart>
    </webParts>

4.5.3.10. Deploy Web Part Definition File

You now need to place the .webpart file into the appropriate location, namely the wpcatalog folder of the web application to which you will deploy the Web Part. Do this by using a post-build event.

  1. Right-click on the project node, and select Properties from the context menu.

  2. Click the Build Events tab.

  3. Enter the following command in the "Post-build event command line" text box to copy the PigLatinWebPart.webpart file to the correct location.

    xcopy ....PigLatinWebPart.webpart "C:InetpubwwwrootwssVirtualDirectoriesDevelopment80wpcatalog" /y

    The trailing slash in the above path will ensure that the wpcatalog folder is created if it does not exist. Be sure to update the path to be the correct folder for you web application.

  4. Save your changes and build the project.

4.5.3.11. Add the Web Part to a Page

The final step in your deployment involves informing SharePoint of the Web Part's existence. There are a few ways to accomplish this task. Keep in mind that if you had deployed this Web Part via a WSS v3 Solution, all of this work would have been done for you. The ways in which you could inform SharePoint of the Web Part are:

  • Since we copied the .webpart file to the wpcatalog folder, it will automatically appear in the Web Part gallery when we attempt to add a new Web Part via the links at the top of your Web Part zones when editing a page.

  • Had you not copied the .webpart file to the wpcatalog folder, you could manually import the .webpart file to any page within your site.

  • Had you not copied the .webpart file to the wpcatalog folder, you could have browsed to the Web Part gallery and added it by clicking on New when viewing the Web Part gallery's Web Parts. SharePoint is smart enough to find your Web Part and display it as an option to add to the gallery. This is possible because of the public access modifier decorating the Web Part class within the assembly (which is in the bin folder).

  1. Browse to the WSS v3 site and click on Edit Page under Site Actions.

  2. Click in Add a Web Part in one of the two default Web Part zones.

  3. Select the Pig Latin Converter Web Part, and click Add. Your Web Part should be rendered on the page. Click Exit Edit Mode under the Site Action link.

You can now see your Web Part in its full glory (see Figure 4-25), including your text box and button. You can also click on the button and see that it does indeed post back as you would expect. Remember that you have not added any code to the button click event handler, so nothing is really happening yet. It is up to you to implement the code to convert the input string to Pig Latin. You should know where to find the requirements!

Figure 4.25. Figure 4-25

4.5.4. Testing and Debugging a Web Part

Any developer, novice or experienced, will of course understand the need to test and debug their code. There are a handful of ways to do this. Because there is no design-time experience for developing Web Parts, and you cannot "run" a Web Part in the traditional sense of running a project, as you can with a web application or a WinForms application, you need to "Attach to Process" to debug your Web Part. The process in this case is the IIS worker process in which the Web Part is running. Regardless of the process used to debug the Web Part, these steps assume that the assembly is in the bin folder of the web application hosting the Web Part, which incidentally is also a best practice. If you plan on deploying the Web Part assembly to the GAC, additional steps need to be performed to get the Visual Studio debugger to successfully debug your assembly. Working under the assumption that you have a Web Part created and have set a breakpoint somewhere in the code that you would like to pause execution on, the steps to debug in this way are as follows. Keep in mind that if your Web Part does not contain any references to WSS v3 objects, it may be easier to debug the Web Part by debugging the web site in which it is hosted.

  1. Open up a Visual Studio 2005 project containing the Web Part you wish to debug.

  2. Select Attach to Process from the Debug menu in Visual Studio 2005.

  3. Select the appropriate w3wp.exe process in the Attach to Process window. If you see more than one w3wp.exe process, simply attach to all of them by holding down the Ctrl key and clicking on all of them one by one, or if you know the correct process, select it.

  4. Click the Attach button.

  5. Click Attach in the Attach Security Warning dialog box that appears for each process that you are attaching to.

  6. Ensure that a break point exists somewhere in your code.

  7. Browse to a page containing your Web Part.

  8. Perform an action that will enable you to reach the breakpoint. Execution will stop, and you should be able to debug your code as you would any other application.

  9. To stop debugging, click the Stop button in the Debug toolbar, press Shift+F5, or select Stop Debugging from the Debug menu.

Although you do not have the luxury of the design-time experience, you do still have all of the rich debugging features that Visual Studio 2005 has to offer available.

4.5.5. Additional Web Part Features

We have only scraped the surface in discussing what Web Parts can do. There are other development options available, but this section briefly discusses only two of those options. Two of the additional available options are:

  • Connected Web Parts

  • Custom verbs

4.5.5.1. Connected Web Parts

Connected Web Parts allow you to have two Web Parts that can exchange information with one another at runtime. A connection between two Web Parts requires that one Web Part be a provider and that the other Web Part be a consumer. The provider Web Part provides some data to the consumer. Think of any type of master-detail scenario as an example. One such example could be a provider Web Part listing some invoices and the details associated with all of the items on each invoice, such as address and total. The provider Web Part would provide the invoice number to the consumer Web Part. The consumer Web Part might list all of the items on the selected invoice. Selecting an invoice in the provider Web Part would automatically display the items on the invoice in the consumer Web Part. More information on the steps required to implement connected Web Parts can be located at http://msdn2.microsoft.com/en-us/library/ms469765.aspx.

4.5.5.2. Custom Verbs

Custom verbs allow you to add items to the menu supplied within each Web Part (see Figure 4-26). By default, you see menu items for Minimize, Close, Delete, Modify Shared Web Part, Connections, and Export. You can add items to this menu quite easily by simply overriding the Verbs property of the WebPart class.

Figure 4.26. Figure 4-26

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.240.230