Section 9.6. Adding Properties


9.6. Adding Properties

The default web part template comes with a Text property. That property appears at the bottom of the property task pane in the Miscellaneous category if you display the web part page in a personal view and then select Modify My Web Part, as shown in Figure 9-11.

animal 9-11. Displaying the custom Text property that comes with the web part template

The provided Text property is really only intended as a basic starting point for your own properties. Starting from Text , the most common next steps are:

  1. Change the property storage from personal to Shared . Shared properties are available to everyone who views the page.

  2. Serialize the property so that changes in the task pane are reflected in the web part.

  3. Link the property setting to the value of a child control on the web part. That allows members to change the property and see the effects of the change.

  4. Save the property to the content database; otherwise , changes are lost when the member navigates away from the page.

The following code illustrates these changes by extending the template code to create a simple web part with a textbox and a Save button. The textbox is linked to the Text property, so if the member clicks Save, the property is preserved the next time the page is viewed :

 Private Const _defaultText As String = ""      Dim _text As String = _defaultText      ' 1) Change storage to WebPartStorage(Storage.Shared).      '   and      ' 2) Serialize: XmlElement(GetType(String), ElementName:="Text").      <Browsable(True), Category("Custom"), DefaultValue(_defaultText), _        WebPartStorage(  Storage.Shared  ), _        FriendlyName("TextBox"), _          Description("TextBox Text Property"), _  XmlElement(GetType(String), ElementName:="Text")  > _  .        Property [Text]() As String          Get              Return _text          End Get          Set(ByVal Value As String)             _text = Value             ' 3) Link the property setting to a child control.             _txt.Text = _text          End Set      End Property      ' 2) Continued. Flag that the Text property should be      ' stored in the content database using the property's      ' XmlElement attribute settings.  Public Function ShouldSerializeText() As Boolean          Return True      End Function  ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''      ' Web part UI definition.      ' Web controls to include in web part.      Dim WithEvents _btnSave As New Button      Dim WithEvents _txt As New TextBox      Protected Overrides Sub CreateChildControls()          ' Set control properties          _txt.ID = "_txt1"          _btnSave.Text = "Save Settings"          ' Add to controls collection          Controls.Add(_txt)          Controls.Add(_btnSave)      End Sub      'Render this Web Part to the output parameter specified.      Protected Overrides Sub RenderWebPart _       (ByVal output As System.Web.UI.HtmlTextWriter)         ' Render view state controls.         RenderChildren(output)      End Sub      ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''      ' Child control event procedures      ' 3) Continued. Update the Text property if the text box changed.  Private Sub _txt_TextChanged(ByVal sender As Object, _        ByVal e As System.EventArgs) Handles _txt.TextChanged          Me.Text = _txt.Text      End Sub  ' 4) Save all the property settings to the content database.  Private Sub _btnSave_Click(ByVal sender As Object, _        ByVal e As System.EventArgs) Handles _btnSave.Click          Me.SaveProperties = True      End Sub  

The following sections explain these steps in greater detail.

9.6.1. Setting Property Attributes

The attributes for the property indicate whether or not the property appears in the task pane, what heading it is listed under, how it is stored, and other descriptive information. Table 9-3 explains the attribute settings.

Table 9-3. Web part property attribute settings

Attribute

Setting

Browsable

true displays the custom property in the property task pane. False hides the property.

Category

The task-pane section to include the property in. This defaults to Miscellaneous if omitted or if you specify one of the built-in categories, like Appearance .

DefaultValue

The default value of the property.

Description

The tool tip to display for the property in the task pane.

FriendlyNameAttribute

The caption to display for the property in the task pane.

ReadOnly

true prevents changes in the task pane. False allows changes. Only affects settings from the task pane.

WebPartStorage

Storage.Shared displays the custom property in the shared view of the page. Storage.Personal displays the property in the personal view. Storage.None to omit the setting and not store it.

ControlledExport

TRue allows users to export the property from the personal view of a web part. False prevents export.

HtmlDesignerAttribute

A custom property builder specified by a URL.

XmlElement

The XML element and data type to store the property as. This attribute is explained more in "Serializing Properties."


Specifying a default value reduces the web part's storage requirements because the property's value is only stored if it is different from the default. Because of this, it's important to ensure the DefaultValue attribute matches the setting used in code. The template property does that by initializing the _text variable with the _defaultText constant as shown here:

 Private Const _defaultText As String = ""      Dim _text As String = _defaultText      <Browsable(True), Category("Custom"), DefaultValue(_defaultText), ... 

It's a good idea to follow this practice in your own properties.

9.6.2. Serializing Properties

In order to save a property setting, SharePoint must have an XML namespace, element name , and data type to use when storing the value. The class XmlRoot attribute and the property XmlElement attribute define those things for the custom property. For example, the following attributes store the Text property as a string in <Text xmlns="Ch09Samples"></Text> :

 <DefaultProperty("Text"), ToolboxData("<{0}:Properties runat=server></{0}:Properties>       "),  XmlRoot(Namespace:="Ch09Samples")  > _       Public Class Properties           ...         <Browsable(True), Category("Custom"), DefaultValue(_defaultText), _             WebPartStorage(Storage.Shared), _             FriendlyName("TextBox"), _               Description("TextBox Text Property"), _  XmlElement(GetType(String), ElementName:="Text")  > _  .             Property [Text]() As String            ... 

You can store any type that can be serialized. Just use GetType to specify the type in the property's XmlElement attribute. For complex types, you need to provide attributes to indicate how the types should be serialized. For example, the following Enum provides serialization information so that SharePoint can store the Color property correctly:

 Enum enumColor          <XmlEnum("Default")> [Default] = Drawing.KnownColor.ActiveCaption          <XmlEnum("Black")> Black = Drawing.KnownColor.Black          <XmlEnum("Blue")> Blue = Drawing.KnownColor.Blue          <XmlEnum("Gray")> Gray = Drawing.KnownColor.GrayText          <XmlEnum("Green")> Green = Drawing.KnownColor.Green          <XmlEnum("Red")> Red = Drawing.KnownColor.Red          <XmlEnum("White")> White = Drawing.KnownColor.White       End Enum       Private Const _defaultColor As enumColor = enumColor.Default       Dim _color As enumColor = _defaultColor       <Browsable(True), Category("Custom"), DefaultValue(_defaultColor), _          WebPartStorage(Storage.Shared), _          FriendlyName("Color"), _          Description("TextBox Color Property"), _          XmlElement(Type:=GetType(enumColor), _          ElementName:="Color")> _          Property Color() As enumColor            Get               Return _color            End Get            Set(ByVal Value As enumColor)                _color = Value                _txt.ForeColor = Drawing.Color.FromKnownColor(_color)            End Set          End Property          Public Function ShouldSerializeColor() As Boolean              Return True          End Function 

In this case, the XmlEnum attribute associates a string with each Enum value. SharePoint uses those strings when it serializes the property. For example:

 <Color xmlns="Ch09Samples">Default</Color>. 

The other part of serialization is the ShouldSerialize PropName method. This is a special type of method that allows you to turn serialization on or off for a property. To allow serialization, create the method and return true as shown here:

 Public Function ShouldSerializeText() As Boolean          Return True      End Function 

Note that the ShouldSerialize PropName doesn't override an inherited method; it's just a Public method with a special name. The WebPart class includes these other ShouldSerialize methods that can be overridden to control built-in properties:

See the SharePoint SDK for information on overriding these WebPart methods.

9.6.3. Linking Properties to Controls

So far, I've only dealt with storing the settings from the task pane to the custom property. To see these changes displayed in a child control, you need to set one of the control's properties from the property Set clause. For example, the following code updates the textbox when the custom Text property changes:

 Dim _text As String = _defaultText      Dim WithEvents _txt As New TextBox      Property [Text]() As String          Get              Return _text          End Get          Set(ByVal Value As String)              _text = Value              ' 3) Link the property setting to a child control.  _txt.Text = _text  End Set      End Property 

On the other side, changes to the textbox should update the custom Text property, as shown here:

 Private Sub _txt_TextChanged(ByVal sender As Object, _        ByVal e As System.EventArgs) Handles _txt.TextChanged          Me.Text = _txt.Text     End Sub 

Now changes to the property are displayed in the control, and vice versa.

9.6.4. Saving Property Settings

Use the SaveProperties property to save properties to the content database. Without this step, only design-time changes made through the task pane are saved. You can think of task pane settings as a sort of second-level default: the first-level defaults are those settings built in to the web part; the second-level are those stored when you modify the web part.

The following code saves the web part's properties to the content database when the user clicks Save:

 Dim WithEvents _btnSave As New Button      '  Save  the property settings      Private Sub _btnSave_Click(ByVal sender As Object, _        ByVal e As System.EventArgs) Handles _btnSave.Click          Try              ' Reequires write privileges.              Me.SaveProperties = True          Catch               _msg &= "You must be signed in as a contributor to save changes. "          End Try      End Sub 

Setting SaveProperties to true tells SharePoint to serialize property settings and save them to the content database after the page is rendered. You only need to set the property once, but the _btnSave command button causes a postback event when clicked, which re- renders the control and thus saves the settings.

In some cases, you may not want to save a runtime property. For example, if a web part performs a query on a database, it makes little sense to save the results since that data changes over time. For those properties, return False from the ShouldSerial PropName method.

Though not strictly required, it's a good idea to provide a ShouldSerial PropName method even if the property isn't serialized, since it allows you to override that behavior in a derived web part.


9.6.5. Controlling/Debugging Serialization

You can use any type of property that can be serialized. That includes numeric types, enumerations, arrays, and objects. SharePoint knows how to serialize the numeric types, but in other cases you need to include attributes to specify how those types are serialized. To see how your web part serializes its properties:

  1. Display the web part on a test page.

  2. Save the properties.

  3. Click the down arrow on the web part's title bar and choose Export. SharePoint displays a download dialog that lets you save a . dwp file containing the current property settings.

The Enum sample in the section "Serializing Properties" earlier in the chapter shows how to include serialization information needed to store an enumeration. Arrays of simple types are serialized using subelements of the correct type, such as this array property:

 Dim _items As String() = {"this", "that", "other"}      ' No default value, always store value.     <Browsable(True), Category("Custom"), _        WebPartStorage(Storage.Shared), _        FriendlyName("Array"), _        Description("String array property."), _        XmlElement(GetType(String()), ElementName:="Items")> _        Property Items() As String()          Get              Return _items          End Get          Set(ByVal Value As String())               _items = Value          End Set      End Property      Public Function ShouldSerializeItems() As Boolean           Return True      End Function 

is serialized as:

 <Items xmlns="Ch09Samples">          <string>this</string>          <string>that</string>          <string>other</string>      </Items> 

Using XmlArray and XmlArrayItem attributes instead of XmlElement lets you specify how each item of the array is serialized. For example the following attributes serialize the array items as Item elements rather than string elements:

 <Browsable(True), Category("Custom"), _            WebPartStorage(Storage.Shared), _            FriendlyName("Array"), _            Description("String array property."), _  XmlArray(ElementName:="Items"), _   XmlArrayItem(GetType(String), ElementName:="Item")> _  Property Items() As String() 

Saving property settings to the content database can cause subtle errors as you develop your part. Changing the type or name of a property changes how it is serialized, which often results in orphaned entries in your content database. SharePoint provides an UnknownXmlElements collection as a way to cull these items from the database. The following code checks for orphaned items and removes them during development:

 ' Use this code to clean up database during development.      Public Overrides Sub AfterDeserialize()      #If DEBUG Then          For Each itm As System.Xml.XmlElement In UnknownXmlElements              Debug.WriteLine(itm.Name, itm.Value) ' < Set a breakpoint here.              ' Delete the item.              UnknownXmlElements.Remove(itm)           Next      #End If      End Sub 

You face a similar problem when you upgrade a web part in the field. Obsolete properties must be mapped to new properties. See the topic on the AfterDeSerialize method in the SharePoint SDK for an example of how to handle these upgrade issues.

9.6.6. Setting Properties in DWP

You can use the XPath created by the XmlNamespace and XmlElementName attributes to override the web part's default property settings in the web part description (. dwp ). For example, the following . dwp file sets initial value for Text property:

 <?xml version="1.0" encoding="utf-8"?>      <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2" >          <Title>Properties</Title>          <Description>Demonstrates web part properties.</Description>          <Assembly>Ch09Samples</Assembly>          <TypeName>Ch09Samples.Properties</TypeName>          <!-- Specify initial values for any custom properties here. -->  <Text xmlns="Ch09Samples">Setting from DWP</Text>  </WebPart> 

When a member imports this . dwp file to a page, Setting from DWP is displayed in the textbox. The Excel Office Web Part Add-In covered in Chapter 8 uses this technique to create customized web parts from the base Spreadsheet web part. In that case, the SolutionFileLocation property is set to a solution file containing the customizations made to the web part:

 <?xml version="1.0"?>      <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2"         xmlns:ODP="http://schemas.microsoft.com/WebPart/v2/Spreadsheet">           <Title>Loan Amortization1</Title>           <Description>Enter description here.</Description>           <Assembly>Microsoft.Office.Dataparts, Version=11.0.0.0, Culture=neutral,            PublicKeyToken=71e9bce111e9429c</Assembly>           <TypeName>Microsoft.Office.Dataparts.SpreadsheetCtl</TypeName>  <ODP:SolutionFileLocation>/Samples1/LoanSolutionSpec.xml           </ODP:SolutionFileLocation>  </WebPart> 

The solution file in turn identifies the Excel XML spreadsheet file to display in the part:

 <?xml version="1.0"?>       <SolutionSpecification xmlns="http://schemas.microsoft.com/WebPart/v2/Spreadsheet/        Solutionspecification">            <WebPartSettings>  <XMLSSFileLocation>/Samples1/LoanXMLSS.xml</XMLSSFileLocation>  </WebPartSettings>        </SolutionSpecification> 



Essential SharePoint
Essential SharePoint 2007: A Practical Guide for Users, Administrators and Developers
ISBN: 0596514077
EAN: 2147483647
Year: 2005
Pages: 153
Authors: Jeff Webb

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net