Section 9.2. Creating Web Part Appearance


9.2. Creating Web Part Appearance

The core of the web part template code is the RenderWebPart method. This method is called just before the control is disposed and it determines the appearance of the part on the page.

To create this appearance, you write HTML to the output object. For example, the following code displays a simple table containing information about the current user 's identity:

 ' Requires this line at class level      ' Imports System.Security.Principal      Protected Overrides Sub RenderWebPart _        (ByVal output As System.Web.UI.HtmlTextWriter)          ' Get the User identity.          Dim user As IPrincipal = Me.Context.User          ' Write table to output          With output               .Write("<TABLE id='tblUser'>")               .Write("<TR><TD>Authenticated</TD><TD>")               .Write(user.Identity.IsAuthenticated())               .Write("</TD></TR><TR><TD>User name</TD><TD>")               .Write(user.Identity.Name())               .Write("</TD></TR><TR><TD>Authentication type</TD><TD>")               .Write(user.Identity.AuthenticationType())               .Write("</TD></TR><TR><TD>Code is impersonating</TD><TD>")               .Write(WindowsIdentity.GetCurrent().Name)              .Write("</TD></TR><TR><TD>Request language: </TD><TD>")               .Write(context.Request.UserLanguages(0))               .Write("</TD></TR><TR><TD>Request host: </TD><TD>")               .Write(context.Request.UserHostName)               .Write("</TD></TR><TR><TD>Request IP: </TD><TD>")               .Write(context.Request.UserHostAddress)               .Write("</TD></TR></TABLE>")          End With      End Sub 

At runtime, the preceding web part displays user information in a two-column table, as shown in Figure 9-5.

animal 9-5. Rendering UserInfo web part at runtime (unauthenticated)

HTML tables are a useful way to control the layout of web parts , but embedding all those table, row, and item tags in code results in code that is hard to debug, update, and localize. The only way to see the result of your HTML is to run the project, and it's easy to make errors in those string literals.

Fortunately, there's a better way. Instead of embedding HTML literals in code, create your tables as HTM files stored as resources, then load those and modify those files at runtime. This approach uses .NET's powerful string functions to substitute values from code into the table. To see how this works:

  1. Create a new . HTM file in your web part project.

  2. Set the file's Build Action property to Embedded Resource.

  3. Edit the HTM page with Visual Studio's design tools to create the table, add headings, scripts, or controls as needed. Use literal placeholders (for example,: {0} ) for items you will replace from code.

  4. Create a procedure to load the resource by file name.

  5. Create a procedure to fill in the table variables using the String object's Format or Write methods .

  6. Write the result to the output object in the RenderWebPart event.

Figure 9-6 shows a user information table created in Visual Studio design mode that has seven placeholders for values to be filled in from code.

The following utility procedure loads the resource from the assembly and returns its HTML as a string. Resource names are case-sensitive, so be sure to correctly capitalize the file name when calling this procedure:

 ' Requires this line at class level:      ' Imports System.Reflection      Friend Function GetHtml(ByVal fName As String) As String 

animal 9-6. Creating a web part table in Visual Studio design mode

 ' Get the web part assembly.      Dim asm As [Assembly] = [Assembly].GetExecutingAssembly      ' Build the full name of the resource (case-sensitive).      Dim resName As String = asm.GetName.Name & "." & fName      ' Declare a stream for the resource.      Dim stream As IO.Stream      Try         stream = asm.GetManifestResourceStream(resName)         ' Create a reader for the stream.         Dim reader As New IO.StreamReader(stream)         ' Read the stream and return it as a string.         Return reader.ReadToEnd     Catch ex As Exception         Trace.Write(ex.ToString())         Return ""     End Try End Function 

Next, the BuildTable procedure creates an array of values to plug in to the table's literal placeholders, gets the table from the assembly, and performs the substitution. I put this task in a dedicated procedure, rather than in RenderWebPart , to make it easier to extend RenderWebPart laterit's a good idea to keep that event uncluttered:

 ' Builds the UserInfo Table      Private Function BuildTable() As String         ' Create an array for table variables         Dim arr(6) As String         ' Populate the array with info from the current context.         With Me.Context             arr(0) = .User.Identity.IsAuthenticated             arr(1) = .User.Identity.AuthenticationType             arr(2) = .User.Identity.Name             arr(3) = .Request.UserLanguages(0)             arr(4) = .Request.Browser.Browser             arr(5) = .Request.Browser.Platform             arr(6) = .Request.UserHostAddress         End With         ' Read the table resource.         Dim sTable As String = GetHtml("userInfoTable.htm")         ' Substitute the user info values into the table and return.         Return String.Format(sTable, arr)     End Function     ' Draw the web part.    Protected Overrides Sub RenderWebPart _      (ByVal output As System.Web.UI.HtmlTextWriter)        ' Write the table to output        output.Write(BuildTable)     End Sub 

At run-time, the web part loads the table from the assembly, fills in the placeholders, and displays the result as shown in Figure 9-7.

animal 9-7. Displaying a table from an embedded resource

This approach isn't limited to tables. You can add client-side scripts, controls, styles, formatting, or any other type of valid HTML. Since the output is stored in an HTM file, you can preview the output in the browser, test the scripts, and edit/localize versions much more easily than if the output was embedded in code.



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