This documentation is archived and is not being maintained.

ImportCatalogPart Class

Imports a description file for a WebPart control (or other ASP.NET server control used as a WebPart control), so that users can add the control to a Web page with pre-defined settings. This class cannot be inherited.

Namespace: System.Web.UI.WebControls.WebParts
Assembly: System.Web (in system.web.dll)

Public NotInheritable Class ImportCatalogPart
	Inherits CatalogPart
Dim instance As ImportCatalogPart

public final class ImportCatalogPart extends CatalogPart
public final class ImportCatalogPart extends CatalogPart
Not applicable.

The ImportCatalogPart control enables users to import a description file that describes settings on a WebPart control or server control that a user wants to add to a WebPartZoneBase zone.

After a user imports a description file, the WebPart control referenced in the file appears within the ImportCatalogPart control, and a user can add the control to the page.

The description file is not the same as the control itself. It is an XML file that ends with a .WebPart extension and contains name/value pairs--mostly property values--that describe the state of the control. The description file is created according to a specified XML format, as described in the topic Web Parts Control Description Files.

As for the control that the description file refers to, it can either be compiled into an assembly, or it can be a user control defined in an .ascx file. In either case, the control referenced in an imported description file must exist on the Web server that hosts the page that is attempting to import the control. The description file references the control name and the assembly (or file) that contains the control, and the description file contains settings that affect the control's property values, appearance, and behavior.

The ImportCatalogPart control enables users to share settings on controls. A complex control can have many properties and settings. For example, in a typical intranet site within a large company, a custom WebPart control might contain a number of properties that hold values specific to the users' environment, such as their database connections, departmental information, and so on. The control might also contain a number of properties that affect its appearance. One user could personalize the control on a particular site and get it working properly, export a description file for the control, and then share the description file with other users, who could import the file to add the fully configured control to other intranet sites that they are allowed to personalize. As long as the compiled assembly or user control file containing the control exists on the Web server that is hosting their site, users can add the control to other Web sites.

The mechanism by which users import a description file (and hence its associated server control) into a Web page is the ImportCatalogPart control, which a page developer must add to a Web page. When a user switches the page to catalog display mode, the ImportCatalogPart control appears, and the user can user this control to browse to the .WebPart description file corresponding to the server control they want to import. Following the UI and instructions provided by the ImportCatalogPart control, a user is able to add the desired server control into the Web page, with its appearance and properties fully configured as specified in the imported description file.

Before a WebPart control's description file can be imported, a user must first create (export) the file based on an existing WebPart control. A description file can be exported for a control if the following conditions are met:

  • The control has properties marked with the Personalizable attribute.

  • The Web.config file has the enableExport attribute value set to true on the <webParts> element.

  • A developer sets the value of the ExportMode property on the control to a value other than the default value of None, which prohibits export. If the ExportMode property value is set to NonSensitiveData, any property that contains an IsSensitive parameter with a Personalizable attribute is not exported when a user exports a description file. This enables control developers to prevent sensitive data, such as connection strings, from being exported in certain situations.

A user can export a control that has been enabled for export by clicking the export verb that appears in the verbs menu of the control, and following the instructions to save a .WebPart description file for the control. Other users can then import this file to configure their own instances of the control.

The ImportCatalogPart class contains several properties. The BrowseHelpText property contains text with instructions for users when they browse to locate the description file. The ImportedPartLabelText property contains text that serves as a label for the imported control as it appears within the ImportCatalogPart control. The PartImportErrorLabelText contains text that is displayed if an error occurs when a control description is being imported. The Title property overrides the base property to assign a default title for an ImportCatalogPart control if the developer does not assign a title. The UploadButtonText property contains the text for the button that the user clicks to upload the description file, and the UploadHelpText property contains the instructions for the upload process.

The ImportCatalogPart class also contains several unique methods. The GetAvailableWebPartDescriptions method retrieves a WebPartDescription object for each WebPart control in the catalog, which enables an ImportCatalogPart control to display information about each server control without having to create an instance of it. The GetWebPart method gets an instance of a particular WebPart control, based on the description passed to the method.

There are some inherent risks associated with using the ImportCatalogPart control. One example is the possibility of importing malicious data into your Web application through the description files used for importing. If someone has placed malicious script code as the value of a string property in the description file, then that script could potentially be executed when a user imports the description file and adds the referenced server control to a Web page. To minimize the risk of importing description files with malicious data, server controls that have string-typed properties should always encode the property data. Another risk involves importing types through description files (see Web Parts Control Description Files). A malicious user could submit requests to load many assemblies into the AppDomain, resulting in an excessive amount of memory being consumed.

To avoid the risks associated with import, you can disable the feature altogether by not using the import feature or the ImportCatalogPart control. Or you can limit what users have access to the control. You could do this programmatically, using role management (see Managing Authorization Using Roles). For instance, when the page loads, you could test to see whether a user is in a certain role, such as the administrator role. If the user is in the role, you could programmatically add the ImportCatalogPart control to the page for that user. You could also use a declarative approach to limit the set of users that can use the ImportCatalogPart control. Within your web page that contains a catalog, you could place two CatalogZone controls: one for users who can import, and one for those who cannot. The zone for users who can import would contain the ImportCatalogPart control. The zone itself could be placed inside of a LoginView control, which would enable you to limit use of the control in the zone to only those authenticated users or roles that you specify.

How to: Set the Display Mode of a Web Parts PageBuilding ASP .NET Web Applications
How to: Export Web Parts Control SettingsBuilding ASP .NET Web Applications
How to: Set the Display Mode of a Web Parts PageBuilding ASP .NET Web Applications
How to: Export Web Parts Control SettingsBuilding ASP .NET Web Applications

The following code example demonstrates how to use the ImportCatalogPart control declaratively and programmatically on a Web page. The example has four parts:

  • A user control that enables you to change display modes on a Web Parts page.

  • A Web page that contains a CatalogZone control and an ImportCatalogPart control.

  • A source code file that contains two custom WebPart controls.

  • An explanation of how the example works when you load the page in a browser.

The first part of this code example is the user control that enables users to change display modes on a Web page. You should place the following source code in a file and name it Displaymodemenucs.ascx or Displaymodemenuvb.ascx (depending on which language you are using). For details about display modes and a description of the source code in this control, see Walkthrough: Changing Display Modes on a Web Parts Page.

<%@ control language="vb" classname="DisplayModeMenuVB"%>
<script runat="server">
  ' Use a field to reference the current WebPartManager.
  Dim _manager As WebPartManager

  Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
    AddHandler Page.InitComplete, AddressOf InitComplete
  End Sub

  Sub InitComplete(ByVal sender As Object, ByVal e As System.EventArgs)
    _manager = WebPartManager.GetCurrentWebPartManager(Page)
    Dim browseModeName As String = WebPartManager.BrowseDisplayMode.Name
    ' Fill the dropdown with the names of supported display modes.
    Dim mode As WebPartDisplayMode
    For Each mode In _manager.SupportedDisplayModes
      Dim modeName As String = mode.Name
      ' Make sure a mode is enabled before adding it.
      If mode.IsEnabled(_manager) Then
        Dim item As New ListItem(modeName, modeName)
      End If
    Next mode
    ' If shared scope is allowed for this user, display the scope-switching
    ' UI and select the appropriate radio button for the current user scope.
    If _manager.Personalization.CanEnterSharedScope Then
      Panel2.Visible = True
      If _manager.Personalization.Scope = PersonalizationScope.User Then
        RadioButton1.Checked = True
        RadioButton2.Checked = True
      End If
    End If
  End Sub

  ' Change the page to the selected display mode.
  Sub DisplayModeDropdown_SelectedIndexChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    Dim selectedMode As String = DisplayModeDropdown.SelectedValue   
    Dim mode As WebPartDisplayMode = _
    If Not (mode Is Nothing) Then
      _manager.DisplayMode = mode
    End If

  End Sub
  ' Set the selected item equal to the current display mode.
  Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)
    Dim items As ListItemCollection = DisplayModeDropdown.Items
    Dim selectedIndex As Integer = _
    DisplayModeDropdown.SelectedIndex = selectedIndex

  End Sub

  ' Reset all of a user's personalization data for the page.
  Protected Sub LinkButton1_Click(ByVal sender As Object, _
    ByVal e As EventArgs)
  End Sub

  ' If not in User personalization scope, toggle into it.
  Protected Sub RadioButton1_CheckedChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    If _manager.Personalization.Scope = PersonalizationScope.Shared Then
    End If

  End Sub
  ' If not in Shared scope, and if user is allowed, toggle the scope.
  Protected Sub RadioButton2_CheckedChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    If _manager.Personalization.CanEnterSharedScope AndAlso _
      _manager.Personalization.Scope = PersonalizationScope.User Then
    End If

  End Sub

  <asp:Panel ID="Panel1" runat="server" 
    Font-Names="Verdana, Arial, Sans Serif" >
    <asp:Label ID="Label1" runat="server" 
      Text="&nbsp;Display Mode" 
    <asp:DropDownList ID="DisplayModeDropdown" runat="server"  
      OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
    <asp:LinkButton ID="LinkButton1" runat="server"
      Text="Reset User State" 
      ToolTip="Reset the current user's personalization data for the page."
      OnClick="LinkButton1_Click" />
    <asp:Panel ID="Panel2" runat="server" 
      GroupingText="Personalization Scope"
      Visible="false" >
      <asp:RadioButton ID="RadioButton1" runat="server" 
        GroupName="Scope" OnCheckedChanged="RadioButton1_CheckedChanged" />
      <asp:RadioButton ID="RadioButton2" runat="server" 
        OnCheckedChanged="RadioButton2_CheckedChanged" />

The second part of the code example is the Web page. At the top of the page are two register directives, one for the user control and one for the compiled component that contains the two custom WebPart controls. Notice that the page has a declarative reference to the ImportCatalogPart control, nested within the proper hierarchy of declarative elements. Notice also that several property values are assigned declaratively on the <asp:importcatalogpart> element. Also, the Button1_Click method updates a number of property values on the ImportCatalogPart control.

In the page's WebPartZone control, the two custom WebPart controls are declared. The <aspSample:userinfowebpart> control has an exportmode="all" attribute on it. This attribute is required to enable users to export a description file for the control, which can then be imported by other users who wish to import the control using the description file.


To enable users of a Web Parts application to export a description file for WebPart controls, you must also enable the export feature in the Web application by adding an enableExport="true" attribute to the <webParts> element (which is a child of the <system.web> element) in the Web.config file. Export is disabled by default, so if you have not yet enabled export for your application, edit the Web.config file and do it now.

<%@ page language="VB" %>
<%@ register TagPrefix="uc1" 
  Src="DisplayModeMenuVB.ascx" %>
<%@ register tagprefix="aspSample" 
  Namespace="Samples.AspNet.VB.Controls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

<script runat="server">

  Protected Sub Button1_Click(ByVal sender As Object, _
    ByVal e As EventArgs)
      ImportCatalogPart1.Title = "Import Server Controls"
      ImportCatalogPart1.BrowseHelpText = "Enter the path to a " _
        & "description file."
      ImportCatalogPart1.UploadButtonText = "Upload Description"
      ImportCatalogPart1.UploadHelpText = "Upload a description file."
      ImportCatalogPart1.ImportedPartLabelText = "Imported Controls"
      ImportCatalogPart1.PartImportErrorLabelText = "An error occured " _
        & "during the import process."
  End Sub

  Protected Sub Page_Load(ByVal sender As Object, _
    ByVal e As EventArgs)
      Button1.Visible = false
  End Sub

  Protected Sub ImportCatalogPart1_PreRender(ByVal sender As Object, _
    ByVal e As EventArgs)
      Button1.Visible = true
  End Sub

<html xmlns="" >
  <head runat="server">
      ImportCatalogPart Control
    <form id="form1" runat="server">
      <asp:webpartmanager id="WebPartManager1" runat="server"  />
      <uc1:DisplayModeMenuVB ID="DisplayModeMenu1" runat="server" />
      <asp:webpartzone id="zone1" runat="server" >
        <PartTitleStyle BorderWidth="1" 
          Font-Names="Verdana, Arial"
          BackColor="LightBlue" />
            title = "Text Display WebPart" /> 
          <aspsample:userinfowebpart id="userinfo1" runat="server" 
            Title="User Information" exportmode="all" />
      <asp:EditorZone ID="EditorZone1" runat="server">
          <asp:PropertyGridEditorPart ID="PropertyGridEditorPart1" 
            runat="server" />
      <asp:CatalogZone ID="CatalogZone1" runat="server">
          <asp:ImportCatalogPart ID="ImportCatalogPart1" 
            Title="My ImportCatalogPart" 
            BrowseHelpText="Type a path or browse to find a control's 
              description file." 
            UploadButtonText="Upload Description File" 
            UploadHelpText="Click the button to upload the description 
            ImportedPartLabelText="My User Information WebPart" 
            PartImportErrorLabelText="An error occurred while trying 
              to import a description file."  />
      <hr />
      <asp:Button ID="Button1" runat="server" 
        Text="Update ImportCatalogPart" 
        OnClick="Button1_Click" />

The third part of the code example is the source code for the two WebPart controls. Notice that some properties on these controls are marked with the WebBrowsable attribute. This enables the PropertyGridEditorPart control to dynamically generate the user interface (UI) for a user to edit those properties when the controls are in edit mode. The properties are also marked with a WebDisplayName attribute, to specify the text of the label that appears next to each control in the editing UI. For the code example to run, you must compile this source code. You can compile it explicitly and put the resulting assembly in your Web site's Bin folder or the global assembly cache. Alternatively, you can put the source code in your site's App_Code folder, where it will be dynamically compiled at run time. This code example uses dynamic compilation. For a walkthrough that demonstrates both methods of compiling, see Walkthrough: Developing and Using a Custom Server Control.

The custom control called TextDisplayWebPart is referenced on the Web page with an <aspSample:TextDisplayWebPart> element. The other control, called UserInfoWebPart, is also declared on the Web page initially, though you will remove it later to demonstrate the ability to import a description file for a control.

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class UserInfoWebPart
    Inherits WebPart
    Private server As HttpServerUtility = HttpContext.Current.Server
    Private _userNickName As String = "Add a nickname."
    Private _userPetName As String = "Add a pet name."
    Private _userSpecialDate As DateTime = DateTime.Now
    Private _userIsCurrent As [Boolean] = True
    Private _userJobType As JobTypeName = JobTypeName.Unselected

    Public Enum JobTypeName
      Unselected = 0
      Support = 1
      Service = 2
      Professional = 3
      Technical = 4
      Manager = 5
      Executive = 6
    End Enum

    Private NickNameLabel As Label
    Private PetNickNameLabel As Label
    Private SpecialDateLabel As Label
    Private IsCurrentCheckBox As CheckBox
    Private JobTypeLabel As Label

    ' Add the Personalizable and WebBrowsable attributes to the  
    ' public properties, so that users can save property values  
    ' and edit them with a PropertyGridEditorPart control.

    <Personalizable(), WebBrowsable(), WebDisplayName("Nickname")> _
    Public Property NickName() As String
        Dim o As Object = ViewState("NickName")
        If Not (o Is Nothing) Then
          Return CStr(o)
          Return _userNickName
        End If
      End Get
      Set(ByVal value As String)
        _userNickName = server.HtmlEncode(value)
      End Set
    End Property

    <Personalizable(), WebBrowsable(), WebDisplayName("Pet Name")> _
    Public Property PetName() As String
        Dim o As Object = ViewState("PetName")
        If Not (o Is Nothing) Then
          Return CStr(o)
          Return _userPetName
        End If
      End Get
      Set(ByVal value As String)
        _userPetName = server.HtmlEncode(value)
      End Set
    End Property

    <Personalizable(), WebBrowsable(), WebDisplayName("Special Day")> _
    Public Property SpecialDay() As DateTime
        Dim o As Object = ViewState("SpecialDay")
        If Not (o Is Nothing) Then
          Return CType(o, DateTime)
          Return _userSpecialDate
        End If
      End Get

      Set(ByVal value As DateTime)
        _userSpecialDate = value
      End Set
    End Property

    <Personalizable(), WebBrowsable(), WebDisplayName("Job Type")> _
    Public Property UserJobType() As JobTypeName
        Dim o As Object = ViewState("UserJobType")
        If Not (o Is Nothing) Then
          Return CType(o, JobTypeName)
          Return _userJobType
        End If
      End Get
      Set(ByVal value As JobTypeName)
        _userJobType = CType(value, JobTypeName)
      End Set
    End Property

    <Personalizable(), WebBrowsable(), WebDisplayName("Is Current")> _
    Public Property IsCurrent() As [Boolean]
        Dim o As Object = ViewState("IsCurrent")
        If Not (o Is Nothing) Then
          Return CType(o, [Boolean])
          Return _userIsCurrent
        End If
      End Get
      Set(ByVal value As [Boolean])
        _userIsCurrent = value
      End Set
    End Property

    Protected Overrides Sub CreateChildControls()

      NickNameLabel = New Label()
      NickNameLabel.Text = Me.NickName

      PetNickNameLabel = New Label()
      PetNickNameLabel.Text = Me.PetName

      SpecialDateLabel = New Label()
      SpecialDateLabel.Text = Me.SpecialDay.ToShortDateString()

      IsCurrentCheckBox = New CheckBox()
      IsCurrentCheckBox.Checked = Me.IsCurrent

      JobTypeLabel = New Label()
      JobTypeLabel.Text = Me.UserJobType.ToString()

      ChildControlsCreated = True

    End Sub

    Private Sub SetControlAttributes(ByVal ctl As WebControl)
      ctl.BackColor = Color.White
      ctl.BorderWidth = 1
      ctl.Width = 200
    End Sub

    Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
      writer.Write("Pet Name:")
      writer.Write("Special Date:")
      writer.Write("Job Type:")

    End Sub

  End Class

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class TextDisplayWebPart
    Inherits WebPart
    Private _contentText As String = Nothing
    Private _fontStyle As String = Nothing
    Private input As TextBox
    Private DisplayContent As Label
    Private lineBreak As Literal

    <Personalizable(), WebBrowsable()> _
    Public Property ContentText() As String
        Return _contentText
      End Get
      Set(ByVal value As String)
        _contentText = value
      End Set
    End Property

    Protected Overrides Sub CreateChildControls()
      DisplayContent = New Label()
      DisplayContent.BackColor = Color.LightBlue
      DisplayContent.Text = Me.ContentText

      lineBreak = New Literal()
      lineBreak.Text = "<br />"

      input = New TextBox()
      Dim update As New Button()
      update.Text = "Set Label Content"
      AddHandler update.Click, AddressOf Me.submit_Click

    End Sub

    Private Sub submit_Click(ByVal sender As Object, _
                             ByVal e As EventArgs)
      ' Update the label string.
      If String.IsNullOrEmpty(input.Text) = False Then
        _contentText = Context.Server.HtmlEncode(input.Text) + "<br />"
        input.Text = String.Empty
        DisplayContent.Text = Me.ContentText
      End If

    End Sub

  End Class

End Namespace

Now run the code example. Load the Web page in a browser. The first step is to edit the UserInfoWebPart control. Use the Display Mode drop-down list control and select Edit to switch the page to edit mode. Click the verbs menu of the UserInfoWebPart control (the downward arrow in the title bar), and then click Edit. When the editing UI appears, several editing controls appear below the UserInfoWebPart control that you can use to edit its field values. Edit some fields, click OK, and then use the Display Mode drop-down to return the page to browse mode.

The second step is to export a .WebPart description file for the UserInfoWebPart control. Click the verbs menu on the custom control (represented by the downward arrow in the title bar), and click Export. Follow the instructions to save a .WebPart description file for the control. Now close the Web page, and edit the page source in an editor. Delete the <aspSample:userinfowebpart> control declaration element, then save and close the file. (You are doing this step to simulate a user who does not yet have the UserInfoWebPart control, so you can import the control to the page).

Load the Web page again in a browser. The UserInfoWebPart control should not appear, because you removed it. Use the Display Mode drop-down list control and select Catalog to switch the page to catalog mode. In the ImportCatalogPart control, click the Browse button, and browse to the .WebPart file you created, then click the Upload button. A reference to the control should appear with a check box next to it. Select the check box, then click Add to add the control to the page.

While you are in this view of the page, click the Update ImportCatalogPart button near the bottom of the page to see the effect of programmatically updating a number of property values on the ImportCatalogPart control. After clicking the button, observe how the various properties are changed in the UI.

Finally, click Close to exit catalog mode and return the page to browse mode. The UserInfoWebPart control should now appear in the page, containing the values that it had when you exported it earlier.

  • AspNetHostingPermission  for operating in a hosted environment. Demand value: LinkDemand; Permission value: Minimal.
  • AspNetHostingPermission  for operating in a hosted environment. Demand value: InheritanceDemand; Permission value: Minimal.


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0