Exercise 5-2: Adding Child Controls to Web Parts


Exercise 5-2: Adding Child Controls to Web Parts

One of the challenges associated with creating web parts is using existing ASP.NET controls in your user interface. This is because the controls are not dragged onto a design surface from the toolbox. Instead, you must create them programmatically. This exercise introduces you to the basic techniques required to utilize existing controls in your web part.

Creating the New Project

Before beginning, make sure that you have the web part template installed. This template will be the foundation of your project. For this exercise, you will be creating a web part that accesses the pubs database using VB.NET.

  1. Open Visual Studio .NET 2003.

  2. Select File New Project from the menu.

  3. In the New Project dialog, select the Visual Basic Projects folder.

  4. From the project items, select Web Part Library.

  5. Name the new project SPSPubsAuthors .

  6. Click OK.

  7. In the Solution Explorer, locate the file WebPart1.vb .

  8. Rename this file PubsAuthors.vb .

  9. In the Solution Explorer, locate the file WebPart1.dwp .

  10. Rename this file PubsAuthors.dwp .

  11. Open the file Manifest.xml for editing.

  12. In the DwpFiles section, change the web part description file name to PubsAuthors.dwp .

Modifying the Web Part Description File

The web part template that you are using creates a default web part description file with a .dwp extension. This file contains information that is used by SPS to upload the web part and make it available. However, the information needs to be changed to reflect the names you will use in this project.

  1. Open the file PubsAuthors.dwp in Visual Studio .NET.

  2. Change the <Title> tag to contain the name PubsAuthors .

  3. Change the <Description> tag to contain the text " A web part to access the pubs database ."

  4. Change the <Assembly> tag to contain SPSPubsAuthors . You may come back later and create a complete entry including Version , Culture , and PublicKeyToken , but this entry alone should work for the exercise.

  5. Change the <TypeName> tag to contain SPSPubsAuthors.View .

  6. Save the file and close it.

Listing 5-11 shows the final contents of the web part description file.

Listing 5-11: The Web Part Description File
start example
 <?xml version="1.0" encoding="utf-8"?> <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2" >     <Title>PubsAuthors</Title>     <Description>A web part to access the pubs database</Description>     <Assembly>SPSPubsAuthors</Assembly>     <TypeName>SPSPubsAuthors.View</TypeName>     <! Specify initial values for any additional base class or custom properties here. > </WebPart> 
end example
 

Coding the Web Part

Writing the code for the web part requires some extra steps to utilize the ASP.NET controls. In addition to creating properties and rendering the output, you must instantiate and configure the additional controls.

  1. Open PubsAuthors.vb in Visual Studio .NET.

  2. In the code, rename the class from WebPart1 to View . Be sure to make the changes both in the name of the class and the attributes that decorate the class.

  3. Change the DefaultProperty decoration of the class from "Text" to "".

  4. Remove the code from the RenderWebPart function.

  5. Go through the class and strip out all of the comments and the one pre-defined property.

Listing 5-12 shows the how the code should appear in the file.

Listing 5-12: Starting the Web Part in PubsAuthors.vb
start example
 Imports System Imports System.ComponentModel Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Xml.Serialization Imports Microsoft.SharePoint Imports Microsoft.SharePoint.Utilities Imports Microsoft.SharePoint.WebPartPages <DefaultProperty(""), ToolboxData("<{0}:View runat=server></{0}:View>"), _ XmlRoot(Namespace:="SPSPubsAuthors")> _  Public Class View     Inherits Microsoft.SharePoint.WebPartPages.WebPart     Protected Overrides Sub RenderWebPart _     (ByVal output As System.Web.UI.HtmlTextWriter)     End Sub End Class 
end example
 

Defining the Properties

The design of your web part is going to use a DataGrid control to display the authors table from the pubs database. In this web part, you will set up properties for the server, user name, and password. You will enter these properties directly into the web part to make the database connection. Listing 5-13 shows the properties to define for the web part.

Listing 5-13: Defining the Properties
start example
 Private strSQLserver As String = "" Private strDatabase As String = "" Private strUserName As String = "" Private strPassword As String = "" 'SQL Server Name <Browsable(True), Category("Miscellaneous"), DefaultValue(""), _ WebPartStorage(Storage.Shared), FriendlyName("SQLServer"), _ Description("The server where eRelationship is installed.")> _ Property SQLServer() As String     Get          Return strSQLserver     End Get     Set(ByVal Value As String)         strSQLserver = Value     End Set End Property 'Database Name <Browsable(True), Category("Miscellaneous"), DefaultValue(""), _ WebPartStorage(Storage.Shared), FriendlyName("Database"), _ Description("The database where the Enterprise Data is located.")> _ Property Database() As String     Get         Return strDatabase     End Get     Set(ByVal Value As String)         strDatabase = Value     End Set End Property 'User Name <Browsable(True), Category("Miscellaneous"), DefaultValue(""), _ WebPartStorage(Storage.Shared), FriendlyName("UserName"), _ Description("The account to use to access the database.")> _ Property UserName() As String     Get         Return strUserName     End Get     Set(ByVal Value As String)         strUserName = Value     End Set End Property 'Password <Browsable(True), Category("Miscellaneous"), DefaultValue(""), _ WebPartStorage(Storage.Shared), FriendlyName("Password"), _ Description("The password to access the database.")> _ Property Password() As String     Get         Return strPassword     End Get     Set(ByVal Value As String)         strPassword = Value     End Set End Property 
end example
 
Caution

You should never design a web part to accept user names and passwords as properties. We are doing it in this exercise to simplify the development of the web part. Later in the book, you will learn to incorporate the Microsoft Single Sign-On (SSO) service into the web part. SSO is the correct mechanism for handling all user names and passwords for web parts.

Defining the Child Controls

In order to use existing ASP.NET controls in your new web part, you must over-ride the CreateChildControls method. In this method, you programmatically create a new instance of each child control, adjust its properties, and add it to the Controls set for the web part. Listing 5-14 shows how to create the child controls for the web part.

Listing 5-14: Creating Child Controls
start example
 Protected WithEvents grdNames As DataGrid Protected WithEvents lblMessage As Label Protected Overrides Sub CreateChildControls()     'Grid to display results     grdNames = New DataGrid     With grdNames         .Width = Unit.Percentage(100)         .HeaderStyle.Font.Name = "arial"         .HeaderStyle.Font.Size = New FontUnit(FontSize.AsUnit).Point(10)         .HeaderStyle.Font.Bold = True         .HeaderStyle.ForeColor = System.Drawing.Color.Wheat         .HeaderStyle.BackColor = System.Drawing.Color.DarkBlue         .AlternatingItemStyle.BackColor = System.Drawing.Color.LightCyan     End With     Controls.Add(grdNames)     'Label for error messages     lblMessage = New Label     With lblMessage         .Width = Unit.Percentage(100)         .Font.Name = "arial"         .Font.Size = New FontUnit(FontSize.AsUnit).Point(10)         .Text = ""     End With     Controls.Add(lblMessage) End Sub 
end example
 

Rendering the Web Part

Because your web part is displaying just the rows from the authors table, you will not need to accept user input for search criteria. Therefore, you can simply query the database and generate the display directly in the RenderWebPart method. However, if you were accepting user input, you would have to be concerned with the web part life cycle and when the input becomes available as discussed in the beginning of this chapter. Listing 5-15 shows how to render the web part output.

Listing 5-15: Rendering the Web Part
start example
 Protected Overrides Sub RenderWebPart _ (ByVal output As System.Web.UI.HtmlTextWriter)     Dim objDataSet As System.Data.DataSet     'Set up connection string from custom properties     Dim strConnection As String     strConnection += "Password=" & Password     strConnection += ";Persist Security Info=True;User ID="     strConnection += UserName + ";Initial Catalog=" + Database     strConnection += ";Data Source=" + SQLServer     'Query pubs database     Dim strSQL As String = "select * from authors"     'Try to run the query     Try         With New System.Data.SqlClient.SqlDataAdapter             objDataSet = New DataSet("root")             .SelectCommand = _             New System.Data.SqlClient.SqlCommand(strSQL, _             New System.Data.SqlClient.SqlConnection(strConnection))             .Fill(objDataSet, "authors")         End With     Catch ex As Exception         lblMessage.Text = ex.Message         Exit Sub     End Try     'Bind to grid     Try         With grdNames             .DataSource = objDataSet             .DataMember = "authors"             .DataBind()         End With     Catch ex As Exception         lblMessage.Text = ex.Message         Exit Sub     End Try     'Draw the controls in an HTML table     With output         .Write("<TABLE BORDER=0 WIDTH=100%>")         .Write("<TR>")         .Write("<TD>")         grdNames.RenderControl(output)         .Write("</TD>")         .Write("</TR>")         .Write("<TR>")         .Write("<TD>")         lblMessage.RenderControl(output)         .Write("</TD>")         .Write("</TR>")         .Write("</TABLE>")     End With End Sub 
end example
 

Deploying the Web Part

Once the web part is coded, you must prepare the project to be compiled. In order to run in SPS, the web part assembly must have a strong name and be deployed in the \bin directory underneath the root of the web site. Additionally, the web part must be marked as safe in the web.config file. If you have already completed Exercise 5-1, you will find these steps nearly identical.

Creating a Strong Name

Web parts need a strong name in order to run in SPS. In order to give the web part a strong name, you have to create a key pair file using the Strong Name tool, sn.exe . Once the strong name is created, you must create a reference to it in the assembly file. If you have already completed Exercise 5-1, you can use the same key file for this web part. Although it's true that you can use the same key file pair for every web part, the recommended practice is to use a new one for each web part.

  1. Open a command window by selecting Start All Programs Accessories Command Prompt.

  2. In the command window, navigate to \Program Files\Microsoft VisualStudio .NET 2003\SDK\v1.1\Bin .

  3. In the command-line window, create a key file by executing the following line:

     sn.exe -k c:\keypair.snk 
  4. In Visual Studio .NET, open the AssemblyInfo.vb file.

  5. In the AssemblyInfo.vb , add a new line as follows :

     <Assembly: AssemblyKeyFile("c:\keypair.snk")> 
  6. Save and close AssemblyInfo.vb .

Compiling the Web Part

Once the strong name is defined and referenced in the key file, you are ready to compile the code. Because web parts must run in the \bin directory underneath the root of the web site, it is easier if you simply compile your assembly into the required directory. This will make it easier to get the web part working.

  1. Right-click the SPSPubsAuthors project in Visual Studio .NET and select Properties from the pop-up menu.

  2. In the Property Pages dialog, select Configuration Properties Build.

  3. Set the Output Path property to \inetpub\ wwwroot \bin .

  4. Click OK.

  5. Compile the web part by selecting Build Build SPSPubsAuthors.

  6. When the web part compiles successfully, close Visual Studio .NET.

Modifying the web.config File

Even though the web part has compiled successfully, it cannot run in SPS until it is marked as safe. Marking the web part as safe requires that you make an entry in the web.config file under the <SafeControls> section. You will also have to change the trust level for the site because web parts cannot access databases under the default trust level of WSS_Minimal.

  1. Open a command window by selecting Start All Programs Accessories Command Prompt.

  2. In the command window, navigate to \Program Files\Microsoft VisualStudio .NET 2003\SDK\v1.1\Bin .

  3. In the command-line window, display the PublicKeyToken by running the following line:

     sn.exe -T c:\inetpub\wwwroot\bin\SPSPubsAuthors.dll 
  4. Record the value of the PublicKeyToken for use in the web.config file.

  5. Using a text editor, open the web.config file, which is located under the \inetpub\wwwroot directory.

  6. Locate the <SafeControls> section of the file. In this section, you must add a new <SafeControl> entry for your web part. The following example shows the form, but you must substitute your particular PublicKeyToken .

     <SafeControl Assembly="SPSPubsAuthors, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ba635e9bfab94eac" Namespace="SPSPubsAuthors" TypeName="*" /> 
  7. Locate the <system.web> section of the file. In this section, change the <trust> element so that the security policy is set to WSS_Medium as shown here:

     <trust level="WSS_Medium" originUrl="" /> 
  8. Save the file and close it.

  9. Select Start Administrative Tools Internet Information Server (IIS) Manager to open the IIS Manager.

  10. In the IIS Manager, right-click SPSPORTAL and select All Tasks Restart IIS.

  11. In the Stop/Start/Restart dialog, click OK to restart IIS, and apply the new security policy.

Using the Web Part

Once the web part is properly compiled, placed in the \bin directory, and marked as safe, it can be used in a portal page. To use the web part, you will import it into a gallery. Once it's imported, you can drag it onto a page and set its properties.

  1. Log in to SPS as a member of the Administrator Site Group.

  2. Navigate to any site that you have previously created.

  3. On the site home page, select Modify Shared Page Add Web Parts Import.

  4. In the Import pane, click Browse.

  5. Locate the file PubsAuthors.dwp and click Open.

  6. In the Import pane, click Upload.

  7. Drag the PubsAuthors web part from the pane to any zone on the page.

  8. When the web part appears, select Modify Shared Web Part from its drop-down menu.

  9. In the Miscellaneous section, enter a value for the SQLServer , UserName , and Password properties.

  10. Enter the value pubs for the Database property.

  11. Click OK. The records should now appear in the grid.




Microsoft SharePoint[c] Building Office 2003 Solutions
Microsoft SharePoint[c] Building Office 2003 Solutions
ISBN: 1590593383
EAN: N/A
Year: 2006
Pages: 92

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