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.
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.
Open Visual Studio .NET 2003.
Select File New Project from the menu.
In the New Project dialog, select the Visual Basic Projects folder.
From the project items, select Web Part Library.
Name the new project SPSPubsAuthors .
Click OK.
In the Solution Explorer, locate the file WebPart1.vb .
Rename this file PubsAuthors.vb .
In the Solution Explorer, locate the file WebPart1.dwp .
Rename this file PubsAuthors.dwp .
Open the file Manifest.xml for editing.
In the DwpFiles section, change the web part description file name to PubsAuthors.dwp .
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.
Open the file PubsAuthors.dwp in Visual Studio .NET.
Change the <Title> tag to contain the name PubsAuthors .
Change the <Description> tag to contain the text " A web part to access the pubs database ."
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.
Change the <TypeName> tag to contain SPSPubsAuthors.View .
Save the file and close it.
Listing 5-11 shows the final contents of the web part description file.
<?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>
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.
Open PubsAuthors.vb in Visual Studio .NET.
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.
Change the DefaultProperty decoration of the class from "Text" to "".
Remove the code from the RenderWebPart function.
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.
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
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.
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
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. |
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.
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
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.
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
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.
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.
Open a command window by selecting Start All Programs Accessories Command Prompt.
In the command window, navigate to \Program Files\Microsoft VisualStudio .NET 2003\SDK\v1.1\Bin .
In the command-line window, create a key file by executing the following line:
sn.exe -k c:\keypair.snk
In Visual Studio .NET, open the AssemblyInfo.vb file.
In the AssemblyInfo.vb , add a new line as follows :
<Assembly: AssemblyKeyFile("c:\keypair.snk")>
Save and close AssemblyInfo.vb .
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.
Right-click the SPSPubsAuthors project in Visual Studio .NET and select Properties from the pop-up menu.
In the Property Pages dialog, select Configuration Properties Build.
Set the Output Path property to \inetpub\ wwwroot \bin .
Click OK.
Compile the web part by selecting Build Build SPSPubsAuthors.
When the web part compiles successfully, close Visual Studio .NET.
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.
Open a command window by selecting Start All Programs Accessories Command Prompt.
In the command window, navigate to \Program Files\Microsoft VisualStudio .NET 2003\SDK\v1.1\Bin .
In the command-line window, display the PublicKeyToken by running the following line:
sn.exe -T c:\inetpub\wwwroot\bin\SPSPubsAuthors.dll
Record the value of the PublicKeyToken for use in the web.config file.
Using a text editor, open the web.config file, which is located under the \inetpub\wwwroot directory.
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="*" />
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="" />
Save the file and close it.
Select Start Administrative Tools Internet Information Server (IIS) Manager to open the IIS Manager.
In the IIS Manager, right-click SPSPORTAL and select All Tasks Restart IIS.
In the Stop/Start/Restart dialog, click OK to restart IIS, and apply the new security policy.
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.
Log in to SPS as a member of the Administrator Site Group.
Navigate to any site that you have previously created.
On the site home page, select Modify Shared Page Add Web Parts Import.
In the Import pane, click Browse.
Locate the file PubsAuthors.dwp and click Open.
In the Import pane, click Upload.
Drag the PubsAuthors web part from the pane to any zone on the page.
When the web part appears, select Modify Shared Web Part from its drop-down menu.
In the Miscellaneous section, enter a value for the SQLServer , UserName , and Password properties.
Enter the value pubs for the Database property.
Click OK. The records should now appear in the grid.