Freigeben über


Understanding Field Controls and Web Parts in SharePoint Server 2007 Publishing Sites

Summary: Learn the details of Microsoft Office SharePoint Server 2007 field controls and Web Parts and how they differ, and best practices for when to use each type of control. (17 printed pages)

Andrew Connell, Critical Path Training, LLC (Microsoft MVP)

March 2009

Applies to: Microsoft Office SharePoint Server 2007

Contents

  • Introduction to Understanding Field Controls and Web Parts

  • Web Parts

  • SharePoint Field Controls

  • Important Differences Between Field Controls and Web Parts

  • Content Editor Web Part vs. Publishing HTML Field Control

  • Best Practices: When to Use Field Controls vs. Web Parts in SharePoint Server Publishing Sites

  • Conclusion

  • Additional Resources

Download the code samples that accompany this article:Windows SharePoint Services 3.0 Content Editor Web Part Link Fixup and Prohibit Content Editor Web Part.

Introduction to Understanding Field Controls and Web Parts

Microsoft Office SharePoint Server 2007 publishing sites empower content owners to manage content on a site without involving IT staff in the day-to-day management of the site. Content owners can use one of two tools provided by developers—field controls or Web Parts—to manage content on a page.

Office SharePoint Sever 2007 introduced to the SharePoint Server platform the capability to create content managed sites. This capability, known as Web Content Management (WCM), enables organizations to separate the content management of the site from the site implementation elements such as pages, code, branding, and business rules that facilitate the controlled publishing aspects. SharePoint Server WCM sites, also known as publishing sites, give organizations significant control over the content, structure, and branding of a site without having to be involved in the day-to-day management and oversight of content owners.

Developers and designers create page templates for content owners to provide one or more rendering options for content pages on the site. These templates, known as page layouts, contain two types of controls that allow content owners to edit and manage the content on the page: Web Parts and field controls.

Unfortunately, many developers are not familiar with the intricacies of each component or their specific advantages and disadvantages. For example, the Content Editor Web Part is often used instead of the Publishing HTML field control. Although this might seem like a subtle choice, it can have a dramatic effect on the site. The selection of the wrong control can introduce significant challenges to the deployment of publishing sites that can be difficult to resolve.

It is critical that every developer who works on SharePoint Server publishing sites understands the intricacies and implications of using field controls or Web Parts in page layouts. This article addresses the details of how Web Parts and field controls work, the differences between the two types of controls, and the advantages and disadvantages of each. The article also provides some best practices for when each should or should not be used.

The examples in this article use the Adventure Works Travel sample publishing site, as shown in Figure 1.

Figure 1. Adventure Works Travel Sample publishing site

Adventure Works Travel Sample publishing site

The site has the following two Web applications and alternate access mappings, as shown in Figure 2:

  • http://authoring.adventure-works.com, which is available only to authenticated users for content authoring

  • https://www.adventure-works.com, available to anonymous users

Figure 2. Adventure Works Travel Sample publishing site implementation

Adventure Works Travel Sample site implementation

Web Parts

Most SharePoint Server developers are familiar with Web Parts because they are the easiest and most common way to customize pages within SharePoint sites. In Windows SharePoint Services 2.0 and Microsoft Office SharePoint Portal Server 2003, Web Parts were provided by Windows SharePoint Services. However, beginning with Windows SharePoint Services 3.0 and Office SharePoint Server 2007, the ASP.NET 2.0 Web Part framework manages all of this on behalf of Windows SharePoint Services. This means that Windows SharePoint Services no longer controls which Web Parts are on the page or their locations on the page, and does not manage the content stored in the Web Parts. The content and configuration data for Web Parts, known as personalization data, is stored in the ASP.NET 2.0 personalization data store. In Windows SharePoint Services 3.0 sites, this personalization data store is kept in the SharePoint content database.

Although Windows SharePoint Services includes many useful, built-in Web Parts, developers can also create custom Web Parts and custom Editor Parts. Editor Parts are the sections within the tool pane that appears on the side of the page when a user clicks the Modify [Shared | My] Web Part menu command on the Web Part's Verbs menu that is used to modify the Web Parts configuration and display settings. Custom Editor Parts enable developers to create customized configuration experiences for users, such as adding more intuitive and useful controls and providing client-side data entry validation.

It is important to understand how Web Parts work within ASP.NET 2.0 and Windows SharePoint Services 3.0 sites. When a Web Part is added to a page in a SharePoint site, ASP.NET 2.0 inserts a block of XML into the Web Part zone that notifies ASP.NET 2.0 about which Web Part to load and what data to assign to all of the Web Part's public properties. When the page is requested, the ASP.NET 2.0 Web Part framework examines this XML to find the Web Part to load (by assembly and class), loads the control, and sets the values of all the public properties. Finally, the page rendering process renders the Web Part.

The following example shows what this block of XML looks like for an Image Web Part.

<WebPart xmlns="https://schemas.microsoft.com/WebPart/v2" xmlns:iwp="https://schemas.microsoft.com/WebPart/v2/Image">
  <Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
  <TypeName>Microsoft.SharePoint.WebPartPages.ImageWebPart</TypeName>
  <FrameType>None</FrameType>
  <Title>Sample Image Web Part</Title>
  <iwp:ImageLink>/_layouts/images/GEARS_AN.GIF</iwp:ImageLink>
</WebPart> 

This XML data is stored in the ASP.NET 2.0 personalization data store—not with the page itself. This means the personalization data is tied to the page's URL and user context, not to the page or version of the current page (as in a SharePoint Server publishing site).

Developers and designers can also use Web Parts within Office SharePoint Server 2007 publishing sites. They add Web Part zones to page layouts, which are used to define rendering templates for content pages. After these Web Part zones are added to the page, content owners can manage which Web Parts are in those zones and modify the content within the Web Parts. Developers can also add Web Parts to the Web Part zones in the page layout, which will be added to new content pages. After a new page is created and saved, the Web Part content and configuration data is saved into the personalization data store. Future changes to the page layout that the content page is configured to use for rendering will affect only new pages, not existing pages.

Office SharePoint Server 2007 publishing sites have three special Web Parts that are available only to sites that have the Publishing Features activated. The Table of Contents Web Part and Content Query Web Part are both used for aggregating content, and the Summary Links Web Part is used to show an arbitrary list of links with additional formatting options. These publishing Web Parts are optimized for content aggregation and provide advanced customization and rending options for developers. However, they are just Web Parts so they have the same characteristics as do all other ASP.NET 2.0 Web Parts. For example, their configuration data is stored in the ASP.NET 2.0 personalization data store.

Note

The Adventure Works Travel site does not use the Web Part zones within page layouts. Instead, Web Parts that are used, such as the Content Query Web Part, are placed statically on the page so content owners cannot add, remove, or modify them on the page. Figure 3 shows how a Web Part zone with a Web Part already added looks to a content owner. Notice the blue box, which represents the Web Part zone, with the orange Add a Web Part button at the top.

Figure 3. Web Part zone with Web Part already added

Web Part zone with Web Part already added

SharePoint Field Controls

Publishing site developers are not limited to using just Web Parts to create the editable content regions on page layouts. Another option for developers is to use field controls in page layouts. Field controls are very different from Web Parts. Before using them, it is important to understand how publishing pages work.

All content pages, stored in their respective site's Pages library, conform to a specific content type. The content type defines the content fields on the page such as the title, subtitle, date, page body, and page image. The page layout, which conforms to a content type, defines how the page should render. Essentially, field controls act as little windows into each of the content fields on the page. In edit mode, they show the content that is currently stored in the field, and when the page is saved, the changes are saved into the page list item in the Pages library. In display mode, the field control simply renders the content stored in the field of the page list item. Therefore, unlike Web Parts, where the content is stored in the ASP.NET 2.0 personalization data store, the data in field controls is stored with the actual page.

Developers and designers are responsible for adding field controls to the page layout ASPX file by using a tool such as Microsoft Office SharePoint Designer 2007 or by editing the ASPX file deployed by using a Feature. (For information about creating page layouts, see Approaches to Creating Master Pages and Page Layouts in SharePoint Server 2007). Only developers and designers can specify the placement, settings, and rules on field controls in the page layout's ASPX file.

For example, certain content authoring capabilities can be disabled in the Rich Text Editor field control so content owners cannot add tables, links, images, or freeform formatting to the content. Instead, you can configure the field control to allow only CSS styles to be available for formatting the content. These things cannot be changed by content owners through the browser. Therefore, field controls provide developers and designers a higher level of control over content pages than Web Parts do. Content owners can only add and manage content within field controls. They cannot move field controls on the page or override the settings set by developers.

Although SharePoint Server includes many built-in field controls for publishing sites, developers can create custom field controls. Custom field controls are useful when the content authoring or display experience does not meet the needs of a particular project. Consider, for example, a page that should show a list of the last five items from an RSS feed. The complete RSS feed, including the items, should not be stored in the page; only the RSS feed's URL needs to be retained. The hyperlink field control would work for this in edit mode, but in display mode it would show only the URL of the feed. A developer could create a custom field control that takes the URL, retrieves the contents of the RSS feed, and renders hyperlinked titles to the most recent five posts in the feed that meet the project requirements. By using the edit mode panel, the built-in hyperlink field control can be rendered when the page is in edit mode to edit the URL of the feed; another edit mode panel configured to render its contents in display mode could contain the custom field control.

As previously discussed, the Adventure Works Travel site uses field controls for almost all content in all page layouts used on the site. The easy way to spot a field control is by the thin border surrounding it, complete with a gray tab at the top with the field's name, as shown in Figure 4.

Figure 4. Field control

Field control

Important Differences Between Field Controls and Web Parts

The differences between field controls and Web Parts and their use in publishing sites might seem subtle, but the options are very different and can have a dramatic effect on the success of a publishing site's implementation.

Field controls differ from Web Parts in two fundamental ways: who ultimately controls the content, and where the content is stored. Table 1 summarizes the previous discussion about differences between field controls and Web Parts.

Table 1. Comparing field controls and Web Parts

Area of Comparison Field Controls Web Parts

Content storage

Content is stored in fields within the page's list item in the Pages library.

Within the Web Part data in the page, which is stored separately from the page in the ASP.NET 2.0 personalization data store.

Who has ultimate control?

Page developer or designer controls the placement, settings, and rules on the page. Content owner controls the content.

Page developer or designer controls locations of Web Part zones, but content owners have ultimate control over which Web Parts are in the Web Part zone and what content is within the Web Parts.

The following sections explore the more important differences between field controls and Web Parts within publishing sites.

Content Storage

Field controls differ significantly from Web Parts in where content is stored. Field controls do not store content; instead, they act as windows to the content that is actually stored within the page in the Pages library. When a page is edited, SharePoint Server automatically creates a new version of the page. This means that the use of field controls enables SharePoint Server to create new versions and yet retain historical versions of the page.

This is very different from Web Parts. As previously mentioned, the content within Web Parts is not stored within the Web Part itself or in the page that the Web Part is on. Instead, the content is stored within the ASP.NET 2.0 personalization data store. Because the content is not stored with the page, it is not versioned each time the page is edited. Therefore if a page layout is created by using only Web Parts, the history of the page versions only information such as the page title, page layout selected, publication schedule, and contact person fields that all pages retain by default. The advantage to using Web Parts for content is that you can personalize the content on a user-by-user basis if the publishing site has a way to uniquely identify users, such as by requiring a logon.

Who Has Control?

Another major difference between using field controls and Web Parts is who has ultimate control over the page. There are two aspects to this: who has control over the layout and structure of the page, and who has control over the content on the page.

Control of Page Layout and Structure

Consider who has ultimate control over the layout and structure of the page. When developers or designers add field controls to a page layout's ASPX file at design time, they specify placement of the controls and any settings information, such as whether tables are allowed in the rich text editor. However, when content authors try to create or edit the page, they can enter and manage content only within the field controls and must abide by the settings established on the controls by the developers and designers. Content owners cannot move field controls on the page, add different field controls to the page, or break the rules established by the developers or designers. As a result, the developers and designers have ultimate control over the page layout, content presentation, and structure.

Using Web Parts in page layouts has very different implications for who has ultimate control. Developers and designers add Web Part zones to the page layouts. Optionally, they can also add Web Parts to the Web Part zones that are added by default when the page is first created by a content owner. Therefore, developers and designers control where Web Parts can be added to the page layout, but not which Web Parts are added to the Web Part zones or the content within the Web Parts.

Control of Page Content

Now consider who has control of the content within a page. When field controls are used to facilitate the management of the content within a page layout, the content owners can add and manage content only in the field controls that are provided. Some field controls enable developers and designers to specify rules for the content; for example, they can specify the rich text editor to prohibit content owners from performing freeform content formatting, and instead make only CSS classes available for formatting. Content owners can manage the content only within the field controls that are provided by the developers and designers.

Conversely, when developers implement Web Part zones in page layouts, content owners have significantly more freedom in the creation of the page. Content owners can add Web Parts to or remove Web Parts from the Web Part Zones, reorder the Web Parts within the Web Part zones, and manage all the content within the Web Parts on the page. Therefore, when Web Parts are used, content owners have a great amount of freedom to select which Web Parts to add to the page and what content to use within those Web Parts.

Multilingual Sites and Site Variations

SharePoint Server 2007 publishing sites include functionality known as variations that is used to facilitate multilingual solutions. Variations help the site owners manage multiple copies of the site collection, or a section of the site collection, to implement one or more translations of the content. Each copy represents a separate language and one copy is flagged as the source label, or the language that all the others are based on. When a content owner publishes a new major version of a page in the source label, the variation infrastructure creates a copy of the page in each of the other variation labels in the variation hierarchy in the site collection. These copies are not references to the source page; they are exact copies. In the future, if the source page changes and is republished, the associated copies are refreshed with the updated content and must then be retranslated.

When configuring a variation hierarchy, the site collection owner can choose to not recopy the Web Part data on future updates of the page after it is published as version 1.0. One reason the site collection owner might choose this is that the built-in list-based Web Parts pull their contents directly from a list by the list's identifier or GUID. Therefore, when the page is copied from the English site to the Spanish site, the Spanish version of the page will show content from the English list. The Spanish site owner would likely modify this Web Part on the initial copy to pull data from a different list. However, the site collection owner has chosen to not overwrite the Web Part data when pages are republished at a later date.

The implication here is that if Web Parts are used to store content on the site, they may or may not be replicated to other variation labels if the publishing site is using variations to implement multilingual versions of the site. Field controls do not have this same issue because their content, stored in the page's list item itself, is always copied to the variation labels.

Content Deployment

SharePoint Sever 2007 also includes the capability to have an internal content authoring or staging SharePoint Server farm that is not accessible to the public, and that on a schedule takes all newly published content and deploys it to another SharePoint farm that is accessible to users with read-only access. This capability is known as content deployment. Content deployment moves all content from one site collection to another site collection. This includes the content contained in field controls (which is actually in the page's list item) and in Web Parts. However, one Web Part, the Content Editor Web Part, stores links as absolute links when content is edited with the rich text editor. As a result, if the Content Editor Web Part is on a page in the authoring site that contains a link to a resource in the same site collection, when the next content deployment job runs, the contents of the Content Editor Web Part on the destination site collection will point back to the URL of the authoring site, which is likely not accessible to external users.

The following section contains more information on the Content Editor Web Part, how it stores hyperlinks, and how to address these issues.

Content Editor Web Part vs. Publishing HTML Field Control

In addition to the general comparison between field controls and Web Parts, one specific case warrants more discussion: using the Content Editor Web Part instead of the Publishing HTML field control. The Content Editor Web Part is frequently considered a more flexible and less strict option than the Publishing HTML field control. However, not only are there important differences between the two because one is a Web Part and the other is a field control, there are also specific nuances of the Content Editor Web Part that are not immediately obvious until issues arise well after a project is deployed. The Content Editor Web Part is commonly used in publishing sites for many reasons, such as the following:

  • Content Editor Web Parts are much easier to prototype with a customer or with management when showing the content management capabilities of SharePoint Server. They can quickly demonstrate how content owners can easily manage the content on a page without the involvement of IT staff. These prototypes often make it into production without additional work.

  • The Publishing HTML field control has a common point of frustration with developers, designers, and content owners: it will not allow inline ECMAScript such as JavaScript to be stored in the content. However, the Content Editor Web Part allows content owners to enter JavaScript on the page. This is a point of controversy because many organizations that deploy publishing sites do not want content owners to be able to add JavaScript to pages; content owners should manage only the content on the page, not the functionality.

  • The Content Editor Web Part enables content owners to add content areas and remove existing content areas or move them around on a page when in edit mode. This added flexibility is something that content owners like, because developers or designers must add the Publishing HTML field control to the page layout's ASPX file and it cannot be moved or removed in edit mode.

Most customers who implement publishing sites, especially publishing sites that are Internet-facing, are usually interested in two very important issues:

  • Centrally managed (usually by the IT group) branding or a user interface that content owners cannot alter. The corporate brand of a site is usually strictly controlled by the company IT staff to maintain a consistent experience on their company Web site. Content owners are expected to maintain only the content on the site, not the formatting of the content. In addition to controlling the brand, many organizations also want to control the location of content on the page and the types of content that can exist on the page.

  • Retention of historical versions of all content on the site. Some industries must adhere to strict guidelines and regulations in different laws across countries that require them to retain historical versions of content on an Internet-facing site. In addition to legal requirements, the organization might need historical versions of content for other reasons.

The decision to use Content Editor Web Parts, the Publishing HTML field control, or some combination of the two can have a significant and lasting effect on a publishing site's implementation. Many people do not realize that the content stored in the Content Editor Web Part is not versioned when the page is edited. For example, a site implemented with no field controls and only Content Editor Web Parts for content will have no historical versions of the content; only the latest content entered into the Content Editor Web Part is available. However, because the Content Editor Web Part's content is stored in the ASP.NET 2.0 personalization data store that is kept in the SharePoint site's content database, database backups can be used to retrieve old content. The other option, the Publishing HTML field control, does not have this historical version issue because all content is versioned with the page.

Another issue with using the Content Editor Web Part in publishing sites is that the site developers and designers have absolutely no control over the formatting choices made by the content owners at edit time. The Content Editor Web Part does not provide any controls to limit what formatting controls are available to content owners. Therefore, content owners can use formatting that can cause inconsistency issues with the rest of the site's branding. Conversely, the Publishing HTML field control does provide controls to restrict different formatting options in edit mode.

The Content Editor Web Part and Publishing HTML field control also differ in how they handle hyperlinks. Based on how the content is entered within the Content Editor Web Part, hyperlinks to content within the current site are stored either as relative (/Pages/default.aspx) or absolute (https://www.adventure-works.com/Pages/default.aspx) links.

The Content Editor Web Part provides three ways to edit content: using a rich text editor, editing the source HTML directly, or editing the source HTML by linking to an existing HTML page. The most common of these is using the rich text editor because it requires no knowledge of HTML markup and also provides a WYSIWYG experience so the content owner can see the formatting results in real time.

In the Content Editor Web Part's rich text editor, the content author can enter a link as an absolute link or a relative link either manually or by using the Browse button, as shown in Figure 5. When picking a link in the existing site by using the Browse button, the top-level (root) relative link to the target is shown in the Selected URL text box.

Figure 5. Content Editor Web Part Edit Hyperlink dialog box

Content Editor Web Part Edit Hyperlink dialog box

Although the dialog box implies that the relative URL is saved, the Content Editor Web Part actually saves an absolute URL. This can cause various issues when the site can be accessed through multiple URLs (as in the case of the Adventure Works Travel site with two extended Web applications) or when the content is deployed to another SharePoint farm (as in the case when content deployment is used to deploy a site within an authoring or staging farm to a read-only farm). Figure 6 and Figure 7 demonstrate the issue. The same page is shown in the authoring site (Figure 6) and in the read-only version of the site (Figure 7).

Figure 6. Adventure Works Travel authoring site

Adventure Works Travel authoring site

Figure 7. Adventure Works Travel read-only site

Adventure Works Travel read-only site

Figure 8 shows the rendered HTML source with the absolute URL.

Figure 8. Rendered HTML source with the absolute URL

Rendered HTML source with the absolute URL

Unfortunately, it is not possible to force the Content Editor Web Part to always store relative links instead of absolute links. You can address this by simply not using the Content Editor Web Part for content and instead using the Publishing HTML field control, which does not store absolute links. For some organizations, however, that might be a large or unreasonable task to replace all existing Content Editor Web Parts with the Publishing HTML field control and then to migrate all content from the Web Parts to the field controls. And some organizations might want to use the Content Editor Web Part for managing content. Another option is to edit all Content Editor Web Part source code by using the source code option instead of the rich text editor, and then remove all absolute links. However, for those organizations with many Content Editor Web Parts in their publishing sites, this can also be an unreasonable task.

In these cases, there is a workaround. Developers can create a custom ASP.NET 2.0 control adapter to change the rendering process of all Content Editor Web Parts within the current Web application. ASP.NET 2.0 control adapters enable developers to inject a custom rendering process for a specific Web control. The custom control adapter examines each URL in the Content Editor Web Part's content area and finds any absolute links that match specific URLs. The URLs it seeks are those that match any of the alternate access mappings for the current site, which the control adapter can determine at run time by enumerating through all the alternate access mappings when rendering the Content Editor Web Part. This works when the publishing site is not being deployed, using content deployment, to another farm because the destination farm is not connected to the source farm in content deployment. Thus, code cannot easily walk through the source farm's alternate access mappings. In this case, the control adapter should be fed a list of URLs that are candidates to convert from absolute to relative links.

The following code shows how to create a control adapter that dynamically enumerates through all alternate access mappings for the current site, as in the case of the Adventure Works Travel sample publishing site.

Note

If content deployment is employed, the control adapter must be modified to get a list of all URLs to change from absolute to relative links.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.Adapters;
using Microsoft.SharePoint.Administration;

namespace MSDN.SharePoint.Samples {
  public class ContentEditorWebPartUrlFixupAdapter : ControlAdapter {
    private const string CEWP_ALT_URLS_CACHE = "CEWP_FIXUP_URLS";

    /// <summary>
    /// Modify the rendered output of the Content Editor Web Part by replacing specific
    /// absolute URLs with a relative reference.
    /// </summary>
    protected override void Render (System.Web.UI.HtmlTextWriter writer) {
      // Get the built-in Content Editor Web Part rendering.
      StringBuilder sb = new StringBuilder();
      HtmlTextWriter htmlWriter = new HtmlTextWriter(new StringWriter(sb));
      base.Render(htmlWriter);
      string preUrlFixupMarkup = sb.ToString();

      // Loop though list of alternate URLs and replace all found with relative links.
      string postUrlFixupMarkup = preUrlFixupMarkup;
      foreach (Uri uri in AlternateUrls) {
        postUrlFixupMarkup = postUrlFixupMarkup.Replace(uri.ToString(), "/");
      }
      
      // Write out fixed-up HTML.
      writer.Write(postUrlFixupMarkup);
    }

    /// <summary>
    /// Get a list of all URLs that should be converted from absolute links
    /// to relative links either by dynamically walking through the SharePoint
    /// API (when content deployment is not employed) or from a static list
    /// (when content deployment is employed).
    /// </summary>
    private List<Uri> AlternateUrls {
      get {
        // Try to pull list from cache... 
        List<Uri> alternateUrls = HttpContext.Current.Cache[CEWP_ALT_URLS_CACHE] as List<Uri>;
        
        if (alternateUrls == null) {
          alternateUrls = new List<Uri>();
        
          // Get reference to current SharePoint Web application.
          SPWebApplication currentWebApp = SPWebApplication.Lookup(HttpContext.Current.Request.Url);

          // Add all alternate access mapping URLs to collection.
          foreach (SPAlternateUrl aamUrl in currentWebApp.AlternateUrls) {
            alternateUrls.Add(aamUrl.Uri);
          }
          
          /* NOTE: if using content deployment, replace the previous code in the
           * IF statement with a routine that looks at a list of URLs 
           * provided in some way other than a dynamic lookup.
           */

          // Cache for five minutes.
          HttpContext.Current.Cache.Add(CEWP_ALT_URLS_CACHE, alternateUrls, 
           null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, 
           CacheItemPriority.Normal, null);

        }
        
        return alternateUrls;
      }
    }

  }
}

Sign this assembly and then deploy it to either the Web application's \BIN folder or the global assembly cache. If the assembly is deployed to the \BIN folder, you must create a custom code access security policy to grant this assembly more security than just WSS_Minimal or WSS_Medium. Deploying to the global assembly cache gives the assembly full trust and therefore you do not have to create a custom policy.

After deployment, the next step is to modify the compat.browser file within the Web application's \App_Browser folder, parallel to the Web application's \BIN folder. Within this file, add a new <browser> node to register the custom control adapter with all Content Editor Web Parts in the Web application.

<browser refID="Default">
  <controlAdapters>
    <adapter controlType="Microsoft.SharePoint.WebPartPages.ContentEditorWebPart"
             adapterType="MSDN.SharePoint.Samples.ContentEditorWebPartUrlFixupAdapter,
             MSDN.SharePoint.Samples.ContentEditorWebPartUrlFixupAdapter, 
             Version=1.0.0.0, Culture=neutral, PublicKeyToken=642dcc68e389cf61" />
  </controlAdapters>
</browser>

If a <browser refID="Default" /> already exists, just add the <adapter /> node as a child to its <controlAdapters /> node instead of creating a new <browser /> node. Next, recycle the application pool that is hosting the Web application, or just recycle Internet Information Services (IIS) to reload the browser compatibility file. With all the changes implemented, reload one of the pages that previously contained absolute links and that should now contain relative links. Notice how the URL in the https://www.adventure-works.com site now points to the correct domain (see Figure 9) and that, when examining the rendered HTML source of the page, the link is now relative (see Figure 10).

Figure 9. Adventure Works Travel read-only site

Adventure Works Travel read-only site

Figure 10. Rendered HTML source with the relative URL

Rendered HTML source with the relative URL

Prohibiting the Use of the Content Editor Web Part on SharePoint Server Publishing Sites

Some developers and designers who implement publishing sites may decide that they do not want content owners to have access to the Content Editor Web Part. Instead, all content should be managed within field controls. Web Part zones might be included in some page layouts to provide functionality and content aggregation or rollup capabilities. However, content owners should not have the option to add a Content Editor Web Part to these Web Part zones. One way to address this is to remove the Content Editor Web Part from the site collection's Web Part Gallery because it is added by default to all SharePoint sites. However, this does not prohibit sophisticated content owners from importing Content Editor Web Parts into the Web Part zones through the browser.

To address this issue, developers can add a new <SafeControl /> entry to the Web application's web.config file that marks the Content Editor Web Part as an unsafe control by using the following XML.

<SafeControl Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, 
  PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.WebPartPages" 
  TypeName="ContentEditorWebPart" Safe="False" />

This can be done manually or by using a custom Web application scoped Feature that contains a Feature receiver, which either applies or removes this change as shown in the following code.

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace MSDN.Samples.ProhibitContentEditorWebPart {
  public class FeatureReceiver : SPFeatureReceiver {
    private ModificationEntry[] _modEntries;

    public override void FeatureInstalled (SPFeatureReceiverProperties properties) { }
    public override void FeatureUninstalling (SPFeatureReceiverProperties properties) { }

    public FeatureReceiver () {
      _modEntries = new ModificationEntry[] {
        new ModificationEntry("SafeControl[@Namespace='Microsoft.SharePoint.WebPartPages']
           [@TypeName='ContentEditorWebPart'][@Safe='False']",
            "configuration/SharePoint/SafeControls",
            "<SafeControl Assembly=\"Microsoft.SharePoint, Version=12.0.0.0, 
            Culture=neutral, PublicKeyToken=71e9bce111e9429c\" 
            Namespace=\"Microsoft.SharePoint.WebPartPages\" 
            TypeName=\"ContentEditorWebPart\" Safe=\"False\" />",
            SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode)
      };
    }

    public override void FeatureActivated (SPFeatureReceiverProperties properties) {
      SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
      if (webApp == null)
        throw new ArgumentNullException("Unable to get reference to current 
        Web application. Likely activating from Feature that isn't Web 
        Application scoped.");

      foreach (ModificationEntry modificationEntry in _modEntries) {
        webApp.WebConfigModifications.Add(this.CreateModification(modificationEntry));
      }

      webApp.WebService.ApplyWebConfigModifications();
    }

    public override void FeatureDeactivating (SPFeatureReceiverProperties properties) {
      SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
      if (webApp == null)
        throw new ArgumentNullException("Unable to get reference to current 
        Web application. Likely activating from Feature that isn't Web 
        Application scoped.");

      foreach (ModificationEntry modificationEntry in _modEntries) {
        webApp.WebConfigModifications.Remove(this.CreateModification(modificationEntry));
      }

      webApp.WebService.ApplyWebConfigModifications();
      webApp.Update();
    }

    private SPWebConfigModification CreateModification (ModificationEntry entry) {

      SPWebConfigModification mod = new SPWebConfigModification(entry.Name, entry.Path);
      mod.Owner = "ProhibitConentEditorWebPart";
      mod.Sequence = 0;
      mod.Type = entry.ModType;
      mod.Value = entry.Value;

      return mod;
    }

    public struct ModificationEntry {
      public string Name;
      public string Path;
      public string Value;
      public SPWebConfigModification.SPWebConfigModificationType ModType;

      public ModificationEntry (string name, string path, string value, 
      SPWebConfigModification.SPWebConfigModificationType modType) {
        Name = name;
        Path = path;
        Value = value;
        ModType = modType;
      }
    }
  }
}

After deploying and activating the Feature, even if a content owner gets a Content Editor Web Part onto the page by using the Web Part framework's import option, the Web Part is reported as an unsafe control as shown in Figure 11.

Figure 11. Results of marking Content Editor Web Part as unsafe control

Content Editor Web Part as unsafe control

Best Practices: When to Use Field Controls vs. Web Parts in SharePoint Server Publishing Sites

After developers and designers understand the differences between Web Parts and field controls in SharePoint Sever 2007 publishing sites, the next question is when to use them. The following table summarizes a few of the factors to consider and which option is best suited for the specific scenario.

Table 2. When to use field controls or Web Parts in publishing sites

Scenario Field Controls Web Parts

Centrally controlled site branding and user experience

X

Content owner responsible only for content, not presentation

X

Content owners need freedom to modify the layout of the page

X

Versioning of all content in site for historical or regulatory reasons

X

Personalization of content

X

Implementation of functionality (aggregating content from other sites or from same site)

X

If the success of the publishing site depends on maintaining a consistent branding experience while enabling content owners to manage content, use field controls. Web Parts are not good options in this scenario because the developers and designers have little to no control over the Web Parts that are put on the pages, and the content or the formatting of the content within these Web Parts.

If the structure, placement, and formatting of the content is important, use field controls to provide content owners with the capability to manage the content, but not to change its presentation.

If some sort of functionality is required, such as the ability to aggregate content from the same site or from external sites, or to implement something such as a stock ticker, use Web Parts. In this case, there is no content to save or version as it relates to functionality, only configuration information that the Web Part needs to implement the functionality.

If any of the publishing site's page layouts contain Web Part zones and the Content Editor Web Part is available to content owners, consider implementing a custom ASP.NET 2.0 control adapter to address absolute URLs that the Content Editor Web Part's rich text editor always saves.

Consider removing the Content Editor Web Part from the site collection's Web Part Gallery and prohibiting it from running in the Web application by marking it as an unsafe control when a publishing site is using field controls for content, but the page layouts in the site contain some Web Part zones.

Conclusion

Office SharePoint Server 2007 publishing sites are used to implement a Web content management solution for organizations that want to put the day-to-day management of the site content into the hands of those who need it: the content owners. This frees the organization's IT staff from having to make frequent content updates to their company Web site. Publishing sites also enable developers and designers to enforce a consistent user experience and brand throughout the site, while giving content owners the freedom to manage and update the content when needed without any involvement from the IT group.

Developers and designers are provided two options for creating editable regions in pages where the content owners can manage the content: Web Parts and field controls. Both options have advantages and disadvantages that should be considered in the early phase of the implementation of a new publishing site. Unfortunately, the easier approach for managing content areas, the Content Editor Web Part, has some challenging aspects many do not realize until the project implementation is well underway or already deployed. Specifically, the content stored in a Content Editor Web Part is not versioned with the page and the most common way to edit content within it, using the rich text editor, saves all links as absolute references… even if relative references are entered by the content owner.

This article addressed in detail the characteristics of field controls and Web Parts and the advantages and disadvantages of each. It also discusses the challenges associated with the Content Editor Web Part, including options for addressing or mitigating these issues. Finally, some best practices are offered for when to use field controls and Web Parts within Office SharePoint Server 2007 publishing sites and how to address the use of the Content Editor Web Part within these sites.

Additional Resources

For more information, see the following resources: