SharePoint 2003 WebPart Development Notes
Chapter 1 Develop a Web Part Project
The first quarter creates a Web Part Library Project project
1. Fill a reference to Microsoft.SharePoint.dll in the project
a) If you are developing on Microsoft.SharePoint Server, you can find it directly in the reference.
b) If not, you have to use the microsoft.sharepoint.dll file COPY to your directory.
2. Fill in the reference of System.xml.
The second quarter is preparing for the development of the development
1. Specify Build Output Path.
a) Specify the directory where Assembly is located. Such as: c: / inetpub / wwwroot / bin.
b) I want to post into the GAC (C: / Windows / askEMBLY), can only register with the copy and .net command Gacutil.exe.
c) Publish into other directories (for example, / inetpub / wwwroot / mydir or mydir2 / bin), which you need to modify the web.config file, add the following node in
askBLYBINDING>
runtime>
2. Set the version number
a) Open file assemblyinfo.cs, modify
[assmbly: assemblyversion "
1.0.0
.0 ")]
3. Set a strong name for assembly accessories
WebPART is developed on the Internet or intranet. In order to create a security reason when you create WebPart, you must use a homogeneous webpart so that users can accurately hit the WebPart you provide.
a) Generate a strong name file. Sn.exe -k c: /keypair.snk
b) Fill in the name of the name
[Assembly: AssemblyKeyFile ("c: //keypair.snk")]]]]
Section 3 Code Development
Assume that you are developed using WebPart Library.
(1) Defining Toolbox Data
Set the attribute value of the class. Add the property settings for this class before the class declaration.
[ToolBoxData ("<{0}: WebPart1 Runat = Server> {0}: WebPart1>")] // Note that the definition of Target is the same as the class name
Public Class WebPart1: Microsoft.SharePoint.WebPartPages.WebPart {
...
}
(2) Defining XML Namespace
If you want to successfully import user-defined WebPart, you must set the XML NameSpace property for each WebPart. This action is done when the Web Part Class is defined.
[XMLROOT (Namespace = "MyWebParts")]
(3) logic implementation
/ / -------------------------------------------------------------------------------------------- --------------------
// 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
{
///
/// 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
// 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 ("
TEXT Property:" Spencode.htmlencode (Text));
}
}
}
Note: By default, the confirmation level is set to WSS_MINIMAL, which cannot access SharePoint Object Model. In order to set the SaveProperties property, you must perform the following three actions.
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.
Section IV Configuring your Web Part
(1) Register your web part as a SafeControl
As a security approach, Windows SharePoint Services requires you to register Web Part's assembly and Namespace as a SafeControl file in the web.config file.
Next, a WebPart assembly is registered as a SafeControl, editing the c: /inetpub/wwroot/web.config file, and fill the following nodes into the SafeControl Attributes: Assembly = "[assembly" - The .NET Assembly In Which The Control IS Conta Contain Version, Culture, _U97? Nd Public Key Token Information. Namespace = "[namespace]" - The .NET Namespace in Which the control is defined. Typename = "[typeename]" - The .NET Class Name of the control. You can type an asseterisk (*) 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 AskEMBLY = "SimpleWebPart, Version = 1.0.0 .0, culture = neutral, publickeytoken = DEF 148956C 61A 16B " Namespace = "MyWebParts" Typename = "*" Safe = "true" /> Note: Replace your Web Part's assembly. Replace the value of publickeyToken, to get this value correctly, use the sn.exe command. Sn.exe -t c: /inetpub/wwwroot/bin/simplewebpart.dll In addition to this approach, there is another kind of to copy your assembly to the GAC, view its properties, or get it. Section 5 Create a Web Part Definition file (.dwp) A very simple DWP file completes the property settings for a separate WebPart. With DWP import, you can realize the web part in SharePoint. In a web part definition file, Assembly and TypeName are must be set. The content is as follows XML Version = "1.0"?> WebPart> Section 6 Import your web part to Web Part Page 1. Open a Web Part Page on your server. . 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 The Click SET Web Part Title To Test The Part. Chapter II Create a custom user attribute of a web part WebPart itself has built a part of the basic properties, such as the height, title, etc. of WebPart. But when you need more complex settings for WebPart, your own properties can no longer meet your requirements, then you must use custom properties. The first section creates a custom user attribute (1) Modify XML Settings In addition to some special requirements, you can define custom controls like the Web UserControl of ASP.NET. Since the properties of the Web Part are defined by the user, save in the SharePoint Storage System in XML, you have to make the following to save the custom properties. 1. Add a reference to System.xml.dll. 2. Define the XML NameSpace property while you define the properties. 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")]]]] (2) Creating a property in accordance with the property In each web part custom property, you need to set up the method, and a typical property setting is as follows. [AttributeDeclaration1, AttributeDeclaration2, ...] Public propertyType PropertyVariable Private propertyType PrivatePropertyvariable PRIVATYVARIABLE { get { Return PrivatePropertyVariable; } set { PrivatePropertyVariable = value; } These you define the properties will be able to determine that it is stored and personalized when the user uses your WebPart. (3) Setting the properties of custom properties These properties you set will display the value you set and store in the WebPart property box in the WebPart process. Most of the properties are classes provided in System.comPonentModel Namespace, which you can reference and define them during development. Some properties, such as the WebPartStorage property, which is used to set the properties of WebPart. The property and definition are listed below: Attribute Purpose Browsable Set to false if you do not want to display the custom property in the property pane. Also, if you set the WebPartStorage attribute to Storage.None, your property will not 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 do not 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 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 T E Property Pane. FriendlyNameAttribute The Caption Displayed for The Custom Property In The Property Pane. if you do ' 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 do not want the setting to persist for the custom property. the custom property will not be displayed in the property pane. HtmlDesignerAttribute Used to associate a property builder. (iv) a simple Web Part custom properties with the property that contains examples of user The following example will demonstrate how to define the following custom properties: 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 type: 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 value 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 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; // conncture 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")]]] "" 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")]]]] "" "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")]] "" "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")]]] "" Type a datetime value. ")]]]] [Browsable (TRUE)] [Xmlelement (typeof (system.datetime)]]] Public system.datetime mydatetime { get { Return_mydatetime; } set { _mydatetime = value; } } Public Bool ShouldSerializationMyDateTime () { 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 ShouldSerializationMycolor () { Return True; } /// /// Render this Web Part to the Output Parameter Specifie. /// summary> /// /// The HTML Writer to Write Out To /// param> Protected Override Void RenderWebPart (HTMLTextWriter Output) { // Write Stored Property Values to the Web Part. Output.write (" Stored Property VALUES B>"); Output.write (" this.mystring; Output.write (" THIS.myBool.toString ()); Output.write (" this.myint.toString ()); Output.write (" this.myfloat.tostring ()); Output.write (" this.mydatetime.tostring ()); Output.write (" THIS.MYENUM.TOSTRING ()); Output.write (" this.mycolor.tostring ()); } } } (5) Post your procedure slightly (6) The effect of the defined attribute is displayed in WebPart Property Type Displayed in Property Pane as Bool Check Box DateTime Text Box Enum Dropdown Int Text Box String Text Box Chapter III Create a WebPart with TOOL PART The first quarter adds a GetToolParts method in your WebPart class 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) are not 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" PR ogramming 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 . . ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, /// /// 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> /// // 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 Wepele 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 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"; 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; } } /// /// 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> /// /// 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; } /// /// Render this Web Part to the Output Parameter Specifie. /// summary> /// /// The HTML Writer to Write Out To /// param> Protected Override Void RenderWebPart (HTMLTextWriter Output) { Output.write (Spencode.htmlencode ("Your Custom Text IS: THISTEXT " b> } } } Section 2 Create Custom Toolpart's Class (1) Join a new class definition in your project First, you need to create a category in the same project to define your TOOL Part. 1. Use Web Part Templates to add a class to your Tool Part. Use the ToolPart template to create a code. 2. Add a class to your Tool Part Use Web Custom Control. Add a reference to WebPartPages Using Microsoft.SharePoint.WebPartPages; Inherit ToolPart class Public Class Toolpart1: Toolpart (3) Overloading ApplyChanges Method code show as below / / -------------------------------------------------------------------------------------------- --------- // 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 { /// /// description of the toolpart. Override the gettoolparts method /// in Your Web Part Class to Invoke this Toolpart. To Establish /// a reason to the Web Part the user Has Selected, Uses USE THE /// ParentToolPane.selectedWebPart Property. /// summary> Public Class Toolpart1: Microsoft.SharePoint.WebPartPages.toolpart { // Declaring a Sample Varialble Private string infutname; // An Event Handler for the init event Private void Toolpart1_init (Object Sender, System.Eventargs E) { InputName = this.uniqueID "Message"; } /// /// Constructor for the class. A Great Place To Set Set /// default values for Additional Base Class Properties /// here. /// Public ToolPart1 () { // SET Default Properties this.title = "Custom Text"; THISINIT = New EventHandler (ToolPart1_init); } /// /// Called by the Tool Pane to Apply Property Changes To /// The successd Web Part. /// summary> Public override void applychanges () { SimpleWebPart WP1 = (SimpleWebPart) This.ParentToolpane.selectedWebpart; // dend the customer text to the Web Part. WP1.TEXT = Page.Request.form [InputName]; } /// /// 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 printy Changes Here } /// /// Called by The Tool Pane If The User Discards Changes /// TO The SELECTED Web Part. /// summary> Public override void cancelchanges () { } /// /// render this Tool Part to the Output Parameter /// specified. /// summary> /// /// 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 (" } } }
String: b>"
Boolean: b>"
INT: B>"
float: b>"
DateTime: b>"
ENUM: B>"
Color Enum: b>"
"));
");