SharePoint 2003 WebPart 开发笔记
第一章 开发一个Web Part Project
第一节 新建一个Web Part Library project 项目
1.在项目中填加对Microsoft.SharePoint.dll的引用
a)如果你在Microsoft.SharePoint server上开发,可以在引用中直接找到。
b)如果没有,那就要将Microsoft.SharePoint.dll文件copy到你的目录中,加以引用。
2.填加System.Xml的引用。
第二节 在开发以前的准备工作
1.指定Build output path。
a) 指定到Assembly所在目录。如:C:/inetpub/wwwroot/bin。
b) 想发布到GAC中(C:/windows/assembly),只能用copy 和 .net 命令gacUtil.exe注册。
c) 发布到其它目录中(for example, /inetpub/wwwroot/mydir or mydir2/bin),这样,你需要修改web.config文件,在<configuration>中加入下面的节点
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="mydir;mydir2/bin"/> </assemblyBinding> </runtime> |
2.设置版本号
a) 打开文件AssemblyInfo.cs,修改成
[assembly: AssemblyVersion(" 1.0.0 .0")] |
3.为装配件设置强名
WebPart是在Internet or Intranet上开发设计的,为了在创建WebPart时的安全原因,你必须用强名来指定你的WebPart,这样用户才能准确的打到你提供的WebPart。
a) 生成一个强名文件。Sn.exe –k c:/keypair.snk
b) 填加强名引用
[assembly: AssemblyKeyFile("c://keypair.snk")] |
第三节 代码开发
假定你是使用WebPart Library进行开发的。
(一)定义Toolbox data
设置类的属性值。在类声明前加上对该类的属性设置。
[ToolboxData("<{0}:WebPart1 runat=server></{0}:WebPart1>")] // 注意其中Target的定义与类名相同 public class WebPart1 : Microsoft.SharePoint.WebPartPages.WebPart{ … } |
(二)定义XML namespace
如果想成功导入用户自定义WebPart,你必须为每一个WebPart设置XML namespace属性。这个动作是在Web Part Class 定义的时候完成的。
[XmlRoot(Namespace="MyWebParts")] |
(三)逻辑实现
//-------------------------------------------------------------------- // File: SimpleWebPart.cs // // Purpose: A sample Web Part that demonstrates how to create a basic // Web Part. //--------------------------------------------------------------------
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Serialization; using Microsoft.SharePoint; using Microsoft.SharePoint.WebPartPages; using Microsoft.SharePoint.Utilities; using System.Web.UI.HtmlControls;
namespace MyWebParts { /// <summary> /// This Web Part changes it's own title and implements a custom property. /// </summary> [XmlRoot(Namespace="MyWebParts")] public class SimpleWebPart : WebPart { private const string defaultText = "hello"; private string text=defaultText;
// Declare variables for HtmlControls user interface elements. HtmlButton _mybutton; HtmlInputText _mytextbox;
// Event handler for _mybutton control that sets the // Title property to the value in _mytextbox control. public void _mybutton_click (object sender, EventArgs e) { this.Title = _mytextbox.Value; try { this.SaveProperties=true; } catch { Caption = "Error... Could not save property."; } }
// Override the ASP.NET Web.UI.Controls.CreateChildControls // method to create the objects for the Web Part's controls. protected override void CreateChildControls () { // Create _mytextbox control. _mytextbox = new HtmlInputText(); _mytextbox.Value=""; Controls.Add(_mytextbox);
// Create _mybutton control and wire its event handler. _mybutton = new HtmlButton(); _mybutton.InnerText = "Set Web Part Title"; _mybutton.ServerClick += new EventHandler (_mybutton_click); Controls.Add (_mybutton); }
[Browsable(true),Category("Miscellaneous"), DefaultValue(defaultText), WebPartStorage(Storage.Personal), FriendlyName("Text"),Description("Text Property")] public string Text { get { return text; }
set { text = value; } }
protected override void RenderWebPart(HtmlTextWriter output) { RenderChildren(output); // Securely write out HTML output.Write("<BR>Text Property: " + SPEncode.HtmlEncode(Text)); } } }
|
注意:默认情况下,信认级别设置成WSS_Minimal,它不能访问SharePoint object model。为了能设置 SaveProperties 属性,你必须执行下面三个动作。
a) Create a custom policy file for your assembly.
b) Install your assembly in the global assembly cache.
c) Increase the trust level for the entire virtual server.
第四节 配置您的Web part
(一)注册你的Web Part 作为一个SafeControl
作为一个安全办法,Windows SharePoint Services 要求你在Web.Config文件中注册Web Part’s assembly和namespace作为一个Safecontrol。
下面将一个WebPart Assembly注册成一个SafeControl,编辑c:/inetpub/wwwroot/web.config文件,将下面的节点填加到<SafeControls>块中。
格式说明:
<!--
SafeControl Attributes:
Assembly="[Assembly]" - The .NET assembly in which the control is contained. This attribute can also contain version, culture,_u97 ?nd public key token information.
Namespace="[Namespace]" - The .NET namespace in which the control is defined.
TypeName="[Typename]" - The .NET class name of the control. You can type an asterisk (*) wildcard character to indicate all TypeNames in a Namespace.
Safe="[True|False]" - Specifies whether a Web Part or Web Form Control is safe and can be displayed on a Web Parts Page. This attribute is True by default.
-->
<SafeControl Assembly="SimpleWebPart, Version= 1.0.0 .0, Culture=neutral, PublicKeyToken=def 148956c 61a 16b" Namespace="MyWebParts" TypeName="*" Safe="True" /> |
注意:将你的Web Part’s assembly.替换为PublicKeyToken的值,要正确获得这个值,请使用sn.exe命令。
sn.exe -T c:/inetpub/wwwroot/bin/SimpleWebPart.dll |
除了这种办法,还有一种就是将你的Assembly拷备到GAC下,查看它的属性,也能获得。
第五节 创建Web Part Definition 文件(.dwp)
一个非常简单的DWP文件为一个单独的WebPart完成了属性设置。通过dwp的导入,可以实现将web part在sharepoint中灵活托放。
在一个Web part definition文件中,Assembly和TypeName是必须被设置的。
内容如下
<?xml version="1.0"?> <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2"> <Assembly>AssemblyName(with no .dll extension), Version=VersionNumber, Culture=Culture, PublicKeyToken=PublicKeyToken</Assembly> <TypeName>WebPartNamespace.WebPartClassName</TypeName> <Title>DefaultWebPartTitle</Title> <Description>WebPartDescription</Description> </WebPart> |
第六节 向Web Part Page中导入你的Web Part
1. Open a Web Part Page on your server.
2. Click Modify My Page or Modify Shared Page (depending on whether you're in Personal View or Shared View) in the upper right corner of the page and click Add Web Parts from the menu.
Click Import.
3. Browse to the location of the SimpleWebPart.dwp file and click the Upload button. After uploading, the page will refresh and "My Simple Web Part" should be displayed under Imported Web Part.
4. Drag the icon next to "My Simple Web Part" to a zone on the Web Part Page.
5. Type some text in the text box, and then click Set Web Part Title to test the part.
第二章 创建一个Web Part的自定义用户属性
WebPart本身就已经内置了一部分基本的属性,如WebPart的高度,标题等。但当你需要对WebPart进行更复杂的设置时,本身自带的属性已经不能满足你的要求,这时,你就必须使用自定义属性了。
第一节 创建自定义用户属性
(一)修改XML Settings
除了一些特殊的要求外,你完全可以象在ASP.net的Web UserControl那样定义自定义控件。由于Web Part 的属性被用户定义,并且以XML形式保存在SharePoint storage System中,所以你必须作下面这些,才能将自定义的属性保存起来。
1. 添加System.Xml.dll的引用。
2. 在你定义的属性的同时,定义XML namespace属性。If you add the XML namespace at the root level, you are not required to assign XML namespaces at the property level. An XML namespace assigned at the property level will override the XML namespace assigned at the root level. The XmlRoot attribute has the following form:
[XmlRoot(Namespace="name of namespace")] |
(二)创建属性的符加信息
在每一个Web Part自定义属性都需要你设置符加的方法,一个典型的属性设置如下
[AttributeDeclaration1, AttributeDeclaration2,...] public PropertyType PropertyVariable private PropertyType PrivatePropertyVariable { get { return PrivatePropertyVariable; } set { PrivatePropertyVariable = value; } |
这些你定义的属性将可以确定当用户使用你的WebPart时,它的存储方式以及个性化特性。
(三)设置自定义属性的属性
你设置的这些属性将在添加WebPart过程中的WebPart属性框中显示出你设置并存储的值。大部分的属性是System.ComponentModel namespace中提供的类,你可以在开发过程中引用和定义它们。有些属性,如WebPartStorage属性,它就是用来设置WebPart的属性用的。下面列举了属性及定义:
Attribute | Purpose |
Browsable | Set to false if you don’t want to display the custom property in the property pane. Also, if you set the WebPartStorage attribute to Storage.None, your property won't display in the property pane. |
Category | The title of the section of the property pane that you want created to display the custom property. If you don't specify the Category attribute or if you specify the Category attribute as "Default", your custom property is displayed in the Miscellaneous section of the property pane. Note If you specify one of the default categories, such as Appearance, your Category attribute setting is ignored, and your property is displayed in the Miscellaneous section. |
DefaultValue | The default value of the custom property. Specifying the default value minimizes the Web Part's storage requirements by storing the property's value only if it is different from the default. |
Description | The contents of the tool tip that appears when you pause the mouse pointer over the custom property in the property pane. |
FriendlyNameAttribute | The caption displayed for the custom property in the property pane. If you don't specify this attribute, the actual property name will be displayed in the property pane. |
ReadOnly | Set to true if you want the custom property to be read-only in the property pane. |
WebPartStorage | Set to Storage.Shared to display the custom property in the property pane when the user is in shared view of the page. Set to Storage.Personal to display the custom property in the property pane when the user is in Shared or Personal view of the page. Set to Storage.None if you don’t want the setting to persist for the custom property. The custom property won’t be displayed in the property pane. |
HtmlDesignerAttribute | Used to associate a property builder with the property. |
(四)一个简单的Web Part中包含用户自定义属性的例子
下面的这个例子将演示如何定义下面的自定义属性: string, bool, int, float, enum, System.DateTime, and System.Drawing.KnownColor.
//-------------------------------------------------------------------- // File : WebPartCustomProperties.cs // // Purpose : A sample Web Part that implements custom properties // of the following types: string, bool, int, float, enum, // System.DateTime, and System.Drawing.KnownColor // // After building and installing this Web Part, display // the property pane to see how the user interface // for setting their values is rendered. //---------------------------------------------------------------------
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Serialization; using Microsoft.SharePoint; using Microsoft.SharePoint.WebPartPages;
namespace WebPartLibrary2 { /// <summary> /// Summary description for CustomPropertyWebPart. /// </summary> [DefaultProperty("Text"), ToolboxData("<{0}:CustomPropertyWebPart runat=server></{0}:CustomPropertyWebPart>"), XmlRoot(Namespace="WebPartLibrary2")] public class CustomPropertyWebPart : Microsoft.SharePoint.WebPartPages.WebPart { const string c_MyStringDefault = "Sample String"; const bool c_MyBoolDefault = false; const int c_MyIntDefault = 20; const float c_MyFloatDefault = 33.33f ; public enum myFarmEnum { barn=0, tractor, hay, pitchfork }; protected myFarmEnum _myEnum;
// Private variables private string _myString; private bool _myBool; private int _myInt; private float _myFloat; private System.DateTime _myDateTime; private System.Drawing.KnownColor _myColor = System.Drawing.KnownColor.Red;
// Constructor public CustomPropertyWebPart() { // Initialize private variables. _myString = c_MyStringDefault; _myBool = c_MyBoolDefault; _myInt = c_MyIntDefault; _myFloat = c_MyFloatDefault; _myEnum = myFarmEnum.hay; _myDateTime = System.DateTime.Now; }
// Creates a custom property that is a string. // This property will be displayed as a text box in the // property pane.
// Create a custom category in the property sheet. [Category("Custom Properties")] // Assign the default value. [DefaultValue(c_MyStringDefault)] // Property is available in both Personalization // and Customization mode. [WebPartStorage(Storage.Personal)] // The caption that appears in the property sheet. [FriendlyNameAttribute("Custom String")] // The tool tip that appears when pausing the mouse pointer over // the friendly name in the property pane. [Description("Type a string value.")] // Display the property in the property pane. [Browsable(true)] [XmlElement(ElementName="MyString")] // The accessor for this property. public string MyString { get { return _myString; } set { _myString = value; } }
// Creates a custom property that is a Boolean value. // This property will display as a check box in the // property pane.
[Category("Custom Properties")] [DefaultValue(c_MyBoolDefault)] [WebPartStorage(Storage.Personal)] [FriendlyNameAttribute("Custom Boolean")] [Description("Select to set value to True.")] [Browsable(true)] [XmlElement(ElementName="MyBoolean")] // The accessor for this property. public bool MyBool { get { return _myBool; } set { _myBool = value; } }
// Creates a custom property that is an integer. // This property will display as a text box in the // property pane. [Category("Custom Properties")] [DefaultValue(c_MyIntDefault)] [WebPartStorage(Storage.Personal)] [FriendlyNameAttribute("Custom Integer")] [Description("Type an integer value.") ] [Browsable(true)] [XmlElement(ElementName="MyInt")] public int MyInt { get { return _myInt; } set { _myInt = value; } }
// Creates a custom property that is a float. // This property will display as a text box in the // property pane. [Category("Custom Properties")] [DefaultValue(c_MyFloatDefault)] [WebPartStorage(Storage.Personal)] [FriendlyNameAttribute("Custom Float")] [Description("Type a floating point value.") ] [Browsable(true)] [XmlElement(ElementName="MyFloat")] public float MyFloat { get { return _myFloat; } set { _myFloat = value; } }
// Creates a custom property that is a System.DateTime. // This property will display as a text box in the // property pane. [Category("Custom Properties")] [WebPartStorage(Storage.Personal)] [FriendlyNameAttribute("Custom Date Time")] [Description("Type a DateTime value.")] [Browsable(true)] [XmlElement(typeof(System.DateTime))] public System.DateTime MyDateTime { get { return _myDateTime; } set { _myDateTime = value; } }
public bool ShouldSerializeMyDateTime() { return true; }
// Creates a custom property that is an enum. // This property will be displayed as a drop-down list in the // property pane. [Category("Custom Properties")] [DefaultValue(myFarmEnum.hay)] [WebPartStorage(Storage.Personal)] [FriendlyName("Custom Enum")] [Description("Select a value from the dropdown list.")] [Browsable(true)] public myFarmEnum MyEnum { get { return _myEnum; } set { _myEnum = value; } }
// Creates a property that is a known system color. // This property will be displayed as a drop-down list in the // property pane. [Category("Custom Properties")] [WebPartStorage(Storage.Personal)] [FriendlyNameAttribute("Custom Color")] [Description("Select a color from the dropdown list.")] [Browsable(true)] [XmlElement(typeof(System.Drawing.KnownColor))] public System.Drawing.KnownColor MyColor { get { return _myColor; } set { _myColor = value; } }
public bool ShouldSerializeMyColor() { return true; } /// <summary> /// Render this Web Part to the output parameter specified. /// </summary> /// <param name="output"> /// The HTML writer to write out to /// </param> protected override void RenderWebPart(HtmlTextWriter output) { // Write stored property values to the Web Part. output.Write("<b>Stored Property Values</b>"); output.Write("<br><b>String: </b>" + this.MyString); output.Write("<br><b>Boolean: </b>" + this.MyBool.ToString()); output.Write("<br><b>Int: </b>" + this.MyInt.ToString()); output.Write("<br><b>Float: </b>" + this.MyFloat.ToString()); output.Write("<br><b>DateTime: </b>" + this.MyDateTime.ToString()); output.Write("<br><b>Enum: </b>" + this.MyEnum.ToString()); output.Write("<br><b>Color Enum: </b>" + this.MyColor.ToString());
} } } |
(五)发布你的程序
略
(六)定义的属性在WebPart中显示的效果
Property Type | Displayed in property pane as |
bool | Check box |
DateTime | Text box |
enum | Dropdown |
int | Text box |
string | Text box |
第三章 创建一个拥有Tool Part的WebPart
第一节 在你的WebPart类中添加GetToolParts方法
To determine which tool parts to include in the property pane for your Web Part, you must override the GetToolParts method of the WebPart base class in your Web Part's class. The GetToolPart method returns an array of references to the new ToolPart objects that will be displayed in the property pane for your Web Part. The ToolPart objects are rendered by the tool pane in the order listed in the array. This provides you with the ability to show multiple ToolParts if your Web Part requires them. Note that when you override the WebPart class’s GetToolParts method, the default ToolPart objects (WebPartToolPart and CustomPropertyToolPart) aren’t displayed automatically. You must include code to display them.
By default, the GetToolParts method will return the CustomPropertyToolPart and WebPartToolPart objects. The CustomPropertyToolPart object will display the built-in tool part that is shown by default for custom properties as described in the "Creating a Web Part with Custom Properties" programming task. If you want to display some of the custom properties for your Web Part using the built-in custom properties tool part, you must include a reference to the CustomPropertyToolPart object in the array of references returned by your GetToolParts method. The WebPartToolPart object will display all the base class properties of the Web Part. After the Web Part developer overrides this method, he has to specifically opt to show these default tool parts.
The following code is the example you will find in the Web Part template that illustrates how the GetToolParts method is implemented by default.
/// <summary> /// Gets the custom tool parts for this Web Part by overriding the /// GetToolParts method of the WebPart base class. You must implement /// custom tool parts in a separate class that derives from /// Microsoft.SharePoint.WebPartPages.ToolPart. /// </summary> ///<returns>An array of references to ToolPart objects.</returns>
// public override ToolPart[] GetToolParts() //{ // ToolPart[] toolparts = new ToolPart[2]; // WebPartToolPart wptp = new WebPartToolPart(); // CustomPropertyToolPart custom = new CustomPropertyToolPart(); // toolparts[0] = custom; // toolparts[1] = wptp; // return toolparts; //} |
The following code sample shows a complete Web Part class that implements a single custom property that will be displayed in a custom tool part.
//--------------------------------------------------------- // File : SimpleWebPart.cs // // Purpose : A simple Web Part that implements one custom // property. //---------------------------------------------------------
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Serialization; using Microsoft.SharePoint; using Microsoft.SharePoint.WebPartPages;
namespace WebPartLibrary2 { /// <summary> /// Summary description for SimpleWebPart. /// </summary> [DefaultProperty("Text"), ToolboxData("<{0}:SimpleWebPart runat=server></{0}:SimpleWebPart>"), XmlRoot(Namespace="WebPartLibrary2")]
public class SimpleWebPart : Microsoft.SharePoint.WebPartPages.WebPart { private const string defaultText = "Your text here"; private string text = defaultText;
[Browsable(false),Category("Miscellaneous"), DefaultValue(defaultText), WebPartStorage(Storage.Personal), FriendlyName("Text"),Description("Text Property")] public string Text { get { return text; }
set { text = value; } }
/// <summary> /// Gets the custom tool parts for this Web Part by /// overriding the GetToolParts method of the WebPart /// base class. You must implement custom tool parts in /// a separate class that derives from /// Microsoft.SharePoint.WebPartPages.ToolPart. /// </summary> ///<returns> /// An array of references to ToolPart objects. ///</returns> public override ToolPart[] GetToolParts() { ToolPart[] toolparts = new ToolPart[3]; WebPartToolPart wptp = new WebPartToolPart(); CustomPropertyToolPart custom = new CustomPropertyToolPart(); toolparts[0] = custom; toolparts[1] = wptp;
// This is the custom ToolPart. toolparts[2] = new WebPartLibrary2.ToolPart1();
return toolparts; }
/// <summary> /// Render this Web Part to the output parameter specified. /// </summary> /// <param name="output"> /// The HTML writer to write out to /// </param> protected override void RenderWebPart(HtmlTextWriter output) { output.Write(SPEncode.HtmlEncode("Your custom text is: <b>" + this.Text + "</b><hr>"));
} } } |
第二节 创建自定义ToolPart’s Class
(一)在你的工程中加入一个新的类定义
首先,你需要在相同的project中创建别一个类来定义你的Tool Part。
1. 用Web Part templates 开为你的Tool part添加一个类。
使用ToolPart模板来创建一代码。
2. 为你的Tool part添加一个类
使用Web Custom Control。
添加对WebPartPages的引用
using Microsoft.SharePoint.WebPartPages; |
继承ToolPart类
public class ToolPart1 : ToolPart |
(三)对ApplyChanges方法进行重载
代码如下
//--------------------------------------------------------- // File : ToolPart1.cs // // Purpose : A sample tool part that sets the CustomText // property of WebPart1. //---------------------------------------------------------
using System; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.SharePoint; using Microsoft.SharePoint.WebPartPages;
namespace WebPartLibrary2 { /// <summary> /// Description of the toolpart. Override the GetToolParts method /// in your Web Part class to invoke this toolpart. To establish /// a reference to the Web Part the user has selected, use the /// ParentToolPane.SelectedWebPart property. /// </summary> public class ToolPart1: Microsoft.SharePoint.WebPartPages.ToolPart { // declaring a sample varialble private string inputname;
// an event handler for the Init event private void ToolPart1_Init(object sender, System.EventArgs e ) { inputname = this.UniqueID + "message"; }
/// <summary> /// Constructor for the class. A great place to set Set /// default values for additional base class properties /// here. /// <summary>
public ToolPart1() { // Set default properties this.Title="Custom Text"; this.Init += new EventHandler(ToolPart1_Init); } /// <summary> /// Called by the tool pane to apply property changes to /// the selected Web Part. /// </summary> public override void ApplyChanges() { SimpleWebPart wp1 = (SimpleWebPart) this.ParentToolPane.SelectedWebPart;
// Send the custom text to the Web Part. wp1.Text = Page.Request.Form[inputname]; }
/// <summary> /// If the ApplyChanges method succeeds, this method is /// called by the tool pane to refresh the specified /// property values in the toolpart user interface. /// </summary> public override void SyncChanges() { // sync with the new property changes here }
/// <summary> /// Called by the tool pane if the user discards changes /// to the selected Web Part. /// </summary> public override void CancelChanges() { } /// <summary> /// Render this Tool part to the output parameter /// specified. /// </summary> /// <param name="output"> /// The HTML writer to write out to /// </param> protected override void RenderToolPart(HtmlTextWriter output) { // Establish a reference to the Web Part. SimpleWebPart wp1 = (SimpleWebPart) this.ParentToolPane.SelectedWebPart; output.Write("Enter your custom text: "); output.Write("<i n p u t name= '" + inputname ); output.Write("' type='text' value='" + SPEncode.HtmlEncode(wp1.Text) + "'> <br>"); } } }
|