Microsoft SharePoint Products and Technologies Resource Kit

SharePoint 2003
 

This chapter is taken from Microsoft SharePoint Products and Technologies Resource Kit published by Microsoft Press; ISBN 073561881X; copyright Microsoft Press 2005; all rights reserved. The author, Bill English, MCSE, Microsoft Certified Trainer, is a Microsoft MVP for Microsoft SharePoint Products and Technologies, a member of the Microsoft SharePoint Beta team, and the author and coauthor of eight computer books. The Microsoft SharePoint teams develop and support Microsoft Office SharePoint Portal Server 2003 and Microsoft Windows SharePoint Services.

No part of these chapters may be reproduced, stored in a retrieval system, or transmitted in any form or by any means—electronic, electrostatic, mechanical, photocopying, recording or otherwise—without the prior written permission of the publisher, except in the case of brief quotations embodied in critical articles or reviews.

Chapter 35: Building Applications Using Windows SharePoint Services Data

Contents

Using Windows SharePoint Services Components
Sharing Windows SharePoint Services Component Data with ASP.NET
Summary

Microsoft Windows SharePoint Services, released shortly after Microsoft Windows Server 2003, has taken team services to a whole new level. With the built-in ability to create websites by using document libraries, lists, and so on, Windows SharePoint Services has become nearly as easy to use as Microsoft Office Word or Microsoft Office Excel.

Windows SharePoint Services is also based on Microsoft .NET, thus extending the functionality of Windows SharePoint Services components and enabling development of Windows SharePoint Services sites by using Microsoft Visual Studio, Microsoft Office FrontPage, or even Notepad. The built-in functionality is exceptional—users can create and manage most of the common content themselves. This functionality is nearly the same as in Microsoft Office SharePoint Portal Server 2003, although security in Windows SharePoint Services provides limited control over individual Web Parts. Unlike SharePoint Portal Server 2003 sites, Windows SharePoint Services sites are intended to be team sites—that is, they are completely independent of any other site. Even though two or more sites can share the same database (and user authorization), the sites themselves are distinct—even navigation between them is a manual process.

Using Windows SharePoint Services Components

Because Windows SharePoint Services (and SharePoint Portal Server) are built on .NET, the entire object classes are made available to any Microsoft ASP.NET application by adding a reference to the assemblies. This means that you can add a Windows SharePoint Services document library to your application outside of the Windows SharePoint Services environment. This functionality cannot be underestimated: the ability to access internal components enables you to create external functionality on a grand scale. Rather than moving data from point A to point B, writing display pages, and so forth, we can use the same Windows SharePoint Services component, including its user interface in both sites, and still maintain security.

Note   Not all Windows SharePoint Services component objects can be used in an ASP.NET application. Some require parts of the framework that prevent use outside of a Windows SharePoint Services site. Although all lists and document libraries are supported, additional ones are being added.

Sharing Windows SharePoint Services Component Data

Although we can instantiate a Windows SharePoint Services component within our application, the focus of our example in this chapter is to access the data (or content) within a component within a Windows SharePoint Services site. In other words, we're going to set up a standard Windows SharePoint Services site, set up a component there, and then get (and display) the data it holds in an ASP.NET application.

Why would we do this? Simple: we can use a Windows SharePoint Services component to do all the work (add, update, delete, and so on) within a secured environment (even our intranet) but make this data available (view-only, in our example) on an ASP.NET application in a completely different environment. This is a great way to use your intranet content on your external sites and maintain security! In the next section, we will demonstrate how to share Windows SharePoint Services component data with ASP.NET.

Sharing Windows SharePoint Services Component Data with ASP.NET

To demonstrate how to share Windows SharePoint Services component data with ASP.NET, we will use a hypothetical company named Contoso, Inc. This section requires some familiarity with Windows SharePoint Services Administration and basic knowledge in objects, Visual Studio, and Visual Basic .NET.

The Business Requirements

Contoso, Inc. has a special application named How Cool that it sells and supports. Presently, its corporate site is built on ASP.NET, and with only 25 people on staff, they've decided to use Windows SharePoint Services for internal department sites, document management, and knowledge management. The Support Group has its own site called the "How Cool Support Area," where it hosts running discussions, posts follow-up alerts on support calls, and performs other such functions.

The Support Group has just released How Cool Version 2, and after receiving many repeat calls regarding some minor upgrade issues, it set up a Problem/Solutions Knowledge Base List Web Part to enable various support people to post common problems and their solutions. Since doing this, support people were able to cut their research time in half. After a review, the Support Group found that many clients had already been to the company website seeking support before they called in, so it decided that offering this same list to outside customers would be an ideal way to reduce outside calls to the Support Group. The Support Group wanted to offer the list to customers with some differences, including making the information read only, making the information searchable, and doing this in a way that required minimum effort for the Support Group to maintain.

The Technical Requirements

Your mission as a developer is to expose the content held in the Windows SharePoint Services site component using a page in an external-facing ASP.NET application.

The Sample Setup Process

The setup process we will use for this sample project consists of presetup steps and setup steps, as detailed in the following list:

  • Presetup Steps
    • Set up a user account, and grant it the permissions necessary to create the sites.
    • Add the new user account to Microsoft SQL Server.
    • Create new Microsoft Internet Information Services (IIS) virtual directories to hold the sites.
    • Create a new Windows SharePoint Services site as the Support Site.
    • Choose the Windows SharePoint Services template.
    • Create a new ASP.NET application to simulate the External Site.
    • Create an ASP.NET Home Page in the External Site.
  • Setup Steps
    • Verify the Windows SharePoint Services content database for the site.
    • Use Windows SharePoint Services Site Administration to add a Web Part.
    • Add some data to the Web Part.
    • Locate the Web Part GUID.
    • Use Visual Studio to create a new ASP.NET page.
    • Code the DataList.
    • Test the new page.
    • Try it out: verifying the new entries.

Presetup Steps

First we need to set up a user account and grant it the permissions necessary to create the sites. For the setup we will use in our example, Windows SharePoint Services must already be installed. Verify this by clicking Start, choosing All Programs, pointing to Administrative Tools, and selecting SharePoint Central Administration. (If necessary, consult the Windows SharePoint Services Administrator's Guide for installation instructions and requirements.) You must also have permissions to create a Windows account if one is not available and an account that has privileges to administer Microsoft Internet Information Services (IIS). A Windows SharePoint Services SharePoint Administrators group member account is not automatically permitted access to IIS Administration, only Windows SharePoint Services and SharePoint Portal Server.

Creating a New Windows SharePoint Services Administrator Account

Windows SharePoint Services security requires that an account be used to administer Windows SharePoint Services sites and that it belong to the SharePoint Administrator's group. A base account is usually set up when Windows SharePoint Services is installed, and in many environments—including development environments—only one account is used. However, it is best practice to designate a specific account to manage particular sites to better control the hierarchy of security. (IIS and access control lists [ACL] are used to prevent Administrators from accessing sites they do not own.) For this example, any SharePoint Administrator account can be used, but we will follow best practices and create a new account named WSSASPTester.

To create a new Windows user account

  1. If you are using NTLM (basic Windows Accounts), click Start, point to All Programs, point to Administrative Tools, and select Computer Management.
  2. Click the plus sign (+) next to Local Users And Groups to expand it, and then click the Users folder. The list of users should appear on the right side of the screen.
  3. Right-click the Users folder, and from the menu, select New User. This opens the New User screen.
  4. Enter the user information for the new account, WSSASPTester, as follows:
    • User name: WSSASPTester
    • Full Name: WSSASPTester Tester
    • Description: WSSASPTester Tester Account
    • Password/Confirm Password: <enter desired password>
  5. Change the check-box options. First deselect the User must change password at next logon option, and then select the User Cannot Change Password and Password Never Expires options. The Account Is Disabled box should be clear.
  6. Click Create to create the account.
  7. In the right pane of the window, right-click the new WSSASPTester account, and from the menu, select Properties.
  8. On the Properties window, click the Member Of tab. By default, you should see the Users group.
  9. At the bottom of the window, click the Add button to open the Select Groups window. From the Select Groups window, click Advanced.
  10. In the lower left corner, open the Select Groups Advanced window and then click the Find Now button. This should display a list of groups and users for the server.
  11. Scroll the bottom window until you locate the group with the name STS_WPG. (The instance number is the IIS instance number specific to your systems installation.) Click the group name in the lower box to select it.
  12. Without deselecting the OWS group, scroll down until you find the VS Developers Group. Hold down the control key and click to select the VS Developers Group as well. With both selected, click OK to close the advanced window, and click OK again on the Select Groups window. This returns you to the Account Properties page.
  13. Click Apply to save the account settings, and then click OK to close.

To create a new Active Directory directory service user account

  1. If you are using Active Directory, click Start, point to All Programs, point to Administrative Tools, and select Active Directory Users and Computers.
  2. Click the plus sign (+) next to the <server>.local name to expand it (if it isn't already), and click the Users folder. The list of users should appear on the right side of the screen.
  3. Right-click the Users folder, and from the menu, choose New, and select User. This opens the New Object - User screen.
  4. Enter the user information for the new account, WSSASPTester, as follows:
    • First name: WSSASPTester
    • Initials: (leave blank)
    • Last name: Tester
    • User logon: WSSASPTester
    • (Leave the @domain setting as is.)
  5. When finished, click Next.
  6. Enter the password for the account that meets the Active Directory directory service security requirements. Depending on the system settings, the default requires you to use a password of at least 8 characters, containing numbers and both uppercase and lowercase letters.
  7. Next, change the check-box options. First deselect the User must change password at next logon option, and then deselect the User Cannot Change Password and Password Never Expires options. The Account Is Disabled box should be clear.
  8. Click Next, and then click Next again to create the account.
  9. In the right pane of the window, right-click the new WSSASPTester account, and from the menu, select Properties.
  10. On the Properties window, click the Member Of tab. By default, you should see the Domain Users group for the Active Directory instance.
  11. At the bottom of the window, click the Add button to display the Select Groups window.
  12. From the Select Groups window, click Advanced in the lower left corner to open the Select Groups Advanced window.
  13. Under Common Queries, find the Name: line. Leave the drop-down menu selection as Starts With, and in the box next to it, enter OWS and then click the Find Now button.
    Note   Active Directory can contain a large number of users and groups; it is highly recommended that you use the keyword search function.

    This should display a group with the name STS_WPG. (The instance number is the IIS instance number specific to your systems installation.) This group has the following description: Microsoft SharePoint role 'admin' for web 'http://<your web>'. (Double-check that the site shown is the server you are working with.)

  14. Click the group name in the lower box to select it, click OK to close the Advanced window, and click OK again in the Select Groups window.

    This account will also need rights to work as a Visual Studio developer.

  15. Click the Add button again to open Select Groups, and click Advanced to open the Select Groups Advanced window.
  16. Just like in the earlier steps, in the Name:, Starts With query, enter VS and click Find Now. This should display the VS Developers Group.
  17. Click the group name in the lower box to select it, click OK to close the Advanced window, and click OK again in the Select Groups window. The Account Groups screen is displayed.
  18. In the Account Properties window, click Apply and then click OK to close the window.

To add the new account to SQL Server

This section assumes you are using SQL 2000 Standard or Enterprise. If you are using the MSDE Database installed by SharePoint Portal Server out of the box, this does not apply—to add a user to MSDE, you must use the MSDE ISQL Tool and the sp_adduser stored procedure. In either case, the user privileges described here are the same.

An account to be used to access data in the Contoso, Inc. Support Group must also be able to create a database in SQL Server to hold content for the site. To enable this, the user must have SQL Server Administration privileges either through the Administrator account or the internal 'sa' account.

  1. Log in as an SQL Administrator.
  2. Click Start, point to All Programs, point to Microsoft SQL Server, and select Enterprise Manager to open the SQL Server Enterprise Manager console.
  3. Under Microsoft SQL Servers, locate the Windows SharePoint Services database instance. If the instance is not shown—that is, only (local) is shown—you need to register the server as follows:
    1. Right-click SQL Server Group, and select New SQL Server Registration.
    2. Click Next on the opening page of the wizard.
    3. In the box just below Available Servers, enter the instance name for Windows SharePoint Services as <server>\SHAREPOINT. (If your server name is S2003E, this would be S2003E\SHAREPOINT.)
    4. Click the Add button. The name you entered should appear under Added Servers.
    5. Click the name to select (highlight) it, and click the Next button.
    6. On the Authentication Mode screen, select Windows Authentication and click Next. When you are successfully connected, click Close.
    7. Click the plus sign (+) to expand the SQL Server group, and then click the <server>\SHAREPOINT database instance.
    8. Click the plus sign (+) next to the Security folder to expand it.
    9. Click the Logins icon to display the users in the right window pane.

To add WSSASPTester as a login name for SQL Server

  1. Right-click the Login icon, and from the menu, select New Login.
  2. On the SQL Server Login Properties page, find the ellipsis (. . .) button beside Name to open the user list.
    Note   Make sure the domain name listed under List Names From is correct. If this is a local system account, do not assign a domain-level account.
  3. Scroll the list until you find WSSASPTester. Double-click the name, and it should appear in the Add Name box. When it does, click OK.
  4. Back on the SQL Sever Login Properties page, click the Server Roles tab. Scroll down the list until you locate Database Creators, and click the check box to select it.
  5. Click the Database Access tab, and be sure that the master, model, tempdb, and msdb check boxes are selected.
  6. Click OK to finish adding the account.

Creating Virtual Sites and New IIS Virtual Directories to Hold Them

For this example, we'll need two sites to work with: a Windows SharePoint Services site and an empty ASP.NET site. You can start with either a subsite or a top-level site. For this example, we're going to assume we're starting from scratch, including the virtual site. Follow these steps:

  1. Create file system directories to hold the virtual sites. These can be located anywhere, but for our example, we are putting them at the top of the E drive.
  2. Create a new directory named e:\OurNewSharePointSite. (This will hold the Windows SharePoint Services site.)
  3. Create another new directory named e:\OurNewASPNetSite.
  4. Open the IIS administration console.
  5. Click the plus sign (+) next to the server name to expand the tree.
  6. Click the plus sign (+) next to the Web Sites folder to expand the tree.
  7. Right-click the Web Sites folder, and select New and then Web Site. (This opens the Web Site Creation Wizard.)
  8. In the opening window of the wizard, click Next.
  9. Enter the description of the website as OurNewSharePointSite.
  10. Leave the IP default setting, and enter the TCP Port Number as any number other than port 80 or 8080 (or any administration site port). For our example, OurNewSharePointSite will be on port 382. When you have entered the port number, click Next.
  11. On the Web Site Home Directory window, click Browse and navigate to the directory for the SharePoint site (e:\OurNewSharePointSite).
  12. Click e:\OurNewSharePointSite to select it, and then click OK. The path shown should be the directory you selected. Click Next to continue.
  13. On the Web Site Access Permissions page, leave the default settings (which are Read and Run) selected and click Next to complete the wizard.
  14. Click Finish to close. The new site should appear in the list of websites.
  15. Repeat steps 5 and 6 for OurNewASPNetSite using a different port number (not 80 or 8080). In our example, we will use port 383.

As a best practice, we need to set the Application Pool settings for the Windows SharePoint Services site, OurNewSharePointSite, so that it uses the common application pool for all SharePoint sites. If SharePoint Portal Server is installed, always use the application pool created by SharePoint Portal Server 2003, named MSSharePointPortalAppPool, as the setting for any SharePoint Portal Server 2003 or Windows SharePoint Services sites. If SharePoint Portal Server 2003 is not installed, use MSSharePoint-AppPool. To set the application pool used by the site, follow these steps:

  1. In the IIS Management console under the Web Sites folder, right-click the OurNewSharePointSite site, and then from the menu, select Properties.
  2. On the Site Properties page, select the Home Directory tab.
  3. On the bottom of the tab, find the Application Pool drop-down list.
  4. Select either MSSharePointPortalAppPool or MSSharePointAppPool (depending on your installation), and click OK.

You might have noticed that we used OurNewSharePointSite as the name of our Windows SharePoint Services site in IIS. This name has no connection to the SharePoint site name; it is simply the virtual directory that will hold the site.

Tip   Leave the default privileges on the site. By default, a newly created virtual server in Windows SharePoint Services inherits the settings from defaults set on the Central Administration pages. You can change these default settings once the virtual server is created.

When you have completed this, you should see both sites in the IIS Management console.

Creating the Windows SharePoint Services Site as the Support Site

Creating a Windows SharePoint Services site is done through the Windows SharePoint Administration console known as SharePoint Central Administration. To open the console, click Start, point to All Programs, point to Administration Tools, and click SharePoint Central Administration. This opens the Windows SharePoint Services Central Administration page.

Note that if SharePoint Portal Server is also installed on your system, there are actually two consoles: one for Windows SharePoint Services and one for SharePoint Portal Server. The title of the page indicates which one you are on, showing either "Windows SharePoint Services/Central Administration" or "SharePoint Portal Server Central Administration." (The colors are also slightly different.) Make sure you are using the correct one, as they are very similar. You alternate between the two consoles by using the links on the left side of the page under Links To Related Administration Home Pages.

Like the FrontPage extensions they replace, new websites created in IIS are not extended with Windows SharePoint Services. For us to use the site we just created (OurNewSharePointSite), the virtual directory needs to be extended to include the Windows SharePoint Services extensions.

On the Windows SharePoint Services Administration page, find the Virtual Server Configuration section and click Extend Or Upgrade Virtual Server. This opens the Virtual Server List page, which displays the list of sites found that do not have Windows SharePoint Services extensions installed. The site you've just created should appear with the following information:

NameURLVersion 
OurNewSharePointSitehttp://<server>:<port>/Not InstalledExtend

The <server> is the name of your server or Localhost, depending on your installation. The port number is the one you selected when creating the site in the IIS Management console.

Note   You can show all sites via the Go To Complete List link at the top of the page.

Notice that both sites created are listed. However, we want to extend only OurNewSharePointSite. In the list, the name of the site is a link that will extend the site and add the Windows SharePoint Services extensions. Click the name to launch the Windows SharePoint Services Extend Virtual Server page. This page shows the current virtual server to be extended. Under the Provisioning Options section, you will see the following two options:

  • Extend and create a content database.   This option allows you to create a new database for this site that can be used to host new sites.
  • Extend and map to another virtual server.   This option allows you to extend a virtual server and connect to the same database as another virtual server. This option is primarily for clustering or large installations and is beyond the scope of our example.

To extend this site, click Extend and create a content database that opens the Extend And Create Content Database page.

There are seven subsections, with options under each on this page: Current Virtual Server, Application Pool, Site Owner, Database Information, Custom URL, Quota Template, and Site Language. Most of these settings are important in a real site installation. However, for this example we will use the default settings for all sections except as follows:

  • For the Application Pool section, click the Use An Existing Application Pool option button. If SharePoint Portal Server is installed, select StsAppPool1. If only Windows SharePoint Services is installed, select StsAppPool.
    Note   When creating a new site, ALWAYS select Using An Existing Application Pool. If SharePoint Portal Server is installed, always use the Application Pool created by SharePoint Portal Server 2003 called MSSharePointPortalAppPool as the setting for any SharePoint Portal Server 2003 or Windows SharePoint Services sites. If SharePoint Portal Server 2003 is not installed, use MSSharePointAppPool.
  • For the Site Owner section, the account specified will default to the account you are currently using. It appears in the form of <domain - server>\<user account>. Leaving the domain or server name as is, change the account to the one we created named WSSASPTester (in our example, S2003E\WSSASPTester). Enter an e-mail address for the site owner as WSSASPTester@<domain>.
    Note   Do not worry if the e-mail address is not real. Windows SharePoint Services does not check this.
  • For the Database Information section, leaving the Use Default Content Database Server option selected is sufficient in most default installations. However, it is best, particularly in test scenarios, to set up your own database. To do this, simply deselect the Use Default option and enter a name that relates to the Windows SharePoint Services site. For our example, we'll use the name Contoso1.
    Note   If you do use the default content database server, a new database will be created as STS_<server>_<IIS Instance number>. Although you can find it easily enough by locating the site settings in the IIS MetaBase.xml file, it is much easier to specify a name to match the site.

Click OK to start the extension process. In most cases, you will have no difficulties in this process. However, a common error message you'll encounter is "Unable to create the database—extensions may not be complete" or something similar. If you are using a development system and have difficulties that appear to be related to accounts or privileges, you can default to using the Administrator account. However, you should do this only as a last resort and never on a QA, staging, or production system.

When the Windows SharePoint Services extension process has been completed, you will receive the Virtual Server Successfully Extended page. You'll notice that there is a link shown next to New Top-Level Web Site URL, as well as an OK button at the bottom of the page. This OK button is a little odd with regard to navigation, as it will return you to the Extend Virtual Servers page—apparently under the assumption that you would extend multiple virtual servers and then set them up later.

In our case, we want to quickly create the Contoso, Inc. Support Group site, so our interest is in the link. The link should look something like this: http://<server>:<port>. The server in our example is S2003E using port 382, so this appears as: http://s2003e:382.

Note   This will also be the URL needed to navigate to the site from your browser.

Click this link to launch the Windows SharePoint Services site Template Selection page.

Troubleshooting Hint

Depending on how your installation was configured and whether both SharePoint Portal Server and Windows SharePoint Services are installed, you might get the following error when you click the link that simply says: Unable to connect to database. Check database connection information and make sure the database server is running.

This error can be caused by one or more issues. The most common issue, which is explained in Microsoft Knowledge Base Article 833183, is that the MSSQL$SHAREPOINT SQL Service instance is not running. (The correction is to set the service, start it through the services in the Administrative Tools, and manually start it.)

Another common problem is that Windows SharePoint Services is installed before SharePoint Portal Server, the configuration database, or both are installed on the SQL Server Default instance. This problem can usually be corrected by removing the extensions from the site and running the extension process again. However, when selecting the Database options, select the SQL Default Instance (just the server name) instead of the <server>\SHAREPOINT instance.

Choosing the Windows SharePoint Services Template

When a Windows SharePoint Services site has been created but a base site has not yet been established, it immediately launches the Site Template Selection page.

As you can see, a wide range of prebuilt templates are available, from the standard Team Site template to the Great Plains Site template. Note that this is just a simple example of the flexibility in Windows SharePoint Services. As the number of available application-related packages increases, from CRM to ERP, more prebuilt site templates will be available. You can also create your own, but explaining how to do that is beyond the scope of this example.

We'll use the Decision Meeting Workspace Site template for the site in our example, as it is an appropriate selection to meet the needs of a typical support group. Preconfigured items include Document Management document library and Tasks, Decisions, and Agenda lists. After some minor customization, the Decision Meeting Workspace Site template could easily provide the resources needed by a substantial support organization.

To set the Template Style, click Decision Meeting Workspace and then click OK. After creating the Windows SharePoint Services site, you will be brought to the Home Page of the site.

Notice the title is automatically set to Team Web Site; don't confuse this with the Team Site template. All Windows SharePoint Services template sites have the same title. You can change this at any time via the Site Settings.

Create an ASP.NET Application

To create the non–Windows SharePoint Services site for this example (by definition, a site that does not have WSS extensions installed), we need to create a new ASP.NET application to use as our external site. When we created the virtual sites earlier in the chapter, the site OurNewASPNETSite was created at port 383. To create a new application, we need to open it by using Visual Studio and then create a home page.

Note   For the purposes of our examples, we will be using Visual Basic .NET. C users should have no difficulty translating this example into a C project.

First open Visual Studio, and then from the top menu, select File and New Project. From the left side of the New Project selection page, scroll down and click the Visual Basic Projects folder to open the VB Templates on the right site of the page. On the right side, locate the ASP.NET Web Application Template and click to select it.

In the Location section, enter the path of the virtual site we created, http://localhost:383 (where localhost is the local system or the name of the system you are working on), and click OK. Once the project has opened, Visual Studio might have automatically opened a page named WebForm1.aspx. If it has, close it because we will not be using it. (You can delete this file if you want.)

Right-click the References folder in the Solution Explorer, and select Add Reference. This opens the Add Reference window with three tabs: .NET, COM, and Projects. If you are not already on the .NET tab, click it to open it. Click the Component Name title bar in the window to sort the components by name in reverse order. Locate the Windows SharePoint Services component, and click it to select it.

Congratulations! You've just added Windows SharePoint Services functionality to your site. Well, sort of—this reference enables you to access the objects from within the code of your aspx pages. To actually use the Windows SharePoint Services objects, you'll need to include a reference to the library using the <% Register page directive of the HTML file, as shown here:

<%@ Register Tagprefix="WebPartPages" 
   Namespace="Microsoft.SharePoint.WebPartPages"
   Assembly="Microsoft.SharePoint, Version=11.0.0.0, Culture=neutral, 
   PublicKeyToken=71e9bce111e949c" %>

Once you've registered, you can create Windows SharePoint Services objects on the page, as in the following example:

<form runat="server" ID="form1">
   <WebPartPages:ListViewWebPart runat="server" ID="Listviewwebpart1"
   Description="Test List part!" Dir="default" IsIncluded="true"    
   FrameState="Normal" FrameType="Standard">
   </WebPartPages:ListViewWebPart>
</form>

To complete this, let's quickly build a home page that displays a simple image for testing.

Note   Visual Studio does not default to showing all files, which can make it hard to find parts of the project. To save some time, at the very top of the Solution Explorer window, click the Show All Files icon (which is the third icon from the left).

To build a home page for testing

  1. From the top menu, click Project and select Add New Item.
  2. In the right pane, click Web Form to select it.
  3. In the Name box on the bottom of the window, clear whatever is there, enter Default.aspx and then click Open.
  4. We need an image to put on the home page, so right-click LocalHost (Or Server) in the Solution Explorer window, select Add, and then click Add Existing Item.
  5. At the bottom of the page, in the Files of type drop-down list, select Image Files.
  6. Next, from the top of the page, use the Look In drop-down list to navigate to the c:\Windows (or c:\Winnt) folder. From there, click any bitmap (BMP) or JPG file.
  7. Click the Open button to add it to the project. You should have the Default.aspx file open in the editor.
  8. If you are in HTML mode, click Design mode. (The layout grid should be showing.)
  9. In the Solution Explorer pane, click the new image you added, drag it to the Default.aspx page, and drop it near the top left corner of the page.
  10. In the Solution Explorer pane, right-click Default.aspx and from the menu, select Set As Start Page. (This sets the Default.aspx page as the page to open if we are running the debugger.)
  11. Now save your project by selecting File and then Save All from the top menu. (You can also press Ctrl+Shift+S to save everything.)
  12. Then from the top menu again, select Build and then Build Solution. (You can also press Ctrl+Shift+B.) An Output window should appear and indicate that the build was successful.

Now we need to test the application to make sure it works. Open your browser, and navigate to the new site—in our example, the URL is http://localhost:383 (or http://<servername>:383). You should see the new page with the image as we created it.

Setup Steps

At this point, you have two sites, OurNewSharePointSite and OurNewASPNETSite, up and running. For the first part of this example, we're going to do the following:

  • Verify the content database for the site.
  • Use Windows SharePoint Services Site Administration to add a Web Part.
  • Add some data to the Web Part.
  • Locate the Web Part GUID.
  • Use Visual Studio to create a new ASP.NET page.
  • Code the DataList.
  • Test the new page.
  • Try it out: verifying the new entries.

Verify the Content Database for the Site

When using Web Parts outside of the Windows SharePoint Services environment, it is helpful to be able to locate information about it (the GUID and so on) that is stored in the content database for the site. For our example, we will use this database to check out information about the Web Part, so we need to locate the one created for OurNewSharePointSite.

Note   Knowing how to locate the correct content database for a site is also useful for working with sites that others have created—not everyone follows a convention.

As mentioned previously in the creation of the OurNewSharePointSite site, the content database you selected should have a distinctive name. In our example, we named it Contoso1. If you opted instead to use the default content database (that is, you left the Use The Default Content Database option selected when you created the site), a new database would have been created using a default name of STS_<servername>_<IIS Instance number>.

Once you have located the IIS instance number, open the SQL Server Enterprise Manager. (You do this by clicking Start, pointing to All Programs, selecting Microsoft SQL Server, and clicking Enterprise Manager.) In SQL Server Enterprise Manager, click the plus sign (+) next to the SQL Servers Group and then click the plus sign (+) next to the Server Instance for Windows SharePoint Services, <server>\SHAREPOINT, to expand it. Click the Databases folder and find your database.

To verify the site, click the plus sign (+) next to the database name, and then click Tables. The database tables will appear in the window pane on the right. Right-click the table named Sites, and from the menu select Open Table and then click Return All Rows. This will display all the records from the table in a grid.

Notice that there is only one entry. This entry should match the site we created (http://s2003e/382). Also note the ID column—this is the GUID assigned to the site when it was created by Windows SharePoint Services. This GUID is internal to Windows SharePoint Services and SharePoint Portal Server 2003. (It does not correspond to a Registry Entry.)

Note   Almost all objects "created" by Windows SharePoint Services (or SharePoint Products and Technologies) use GUIDs to keep them unique. This allows complete reuse because objects are instances instead of copies.

Adding a Web Part to OurNewSharePointSite

To complete the setup for our Windows SharePoint Services site, we are going to simply change the name and add a new Web Part to act as our Problem/Solutions Knowledge Base. To do this, we need to log in under the WSSASPTester account to author the site.

Tip   You can use Administrator to do this, but it's better to be sure your security settings are correct for the site by using the Site Owner account.

In your browser, navigate to the new OurNewSharePointSite using the URL http://<servername>:382 (or by using the port you used when you created it).

The next step is to add a Web Part to this page. On the top right of the page, find the Modify This Workspace link and click it to open the drop-down list menu. Select Add Pages to open the Add dialog box. Under Page Name, enter the new page name, SupportKBPage, and then click Add.

This opens the new page in the browser for editing.

In the menu on the right, you should see the Add Web Parts With Create Lists option. Locate the General Discussion Web Part at the bottom of the list. Click and drag it to the left column of the new Workspace page. The new Web Part should appear with the title General Discussion.

Note that we could have defined a completely new Web Part list and defined our own fields to be included, because much more data would generally be required for a support-related issue (such as the date of the call, who called in, and so on). A prebuilt Web Part and one you create both work the same.

We need to change some properties of the General Discussion Web Part so that it is easy to identify. In the title bar of General Discussion, click the drop-down arrow to show the menu and select Modify Shared Web Part. This should open the General Discussions properties window on the right side of the page. To show this as a true discussion, we'll make the following changes:

  1. Change the Selected View to Threaded. (You will receive a message "Switching to a different view removes changes you made to this view, and may disable Web Part connections that depend on columns in this view." Click OK to close this message.)
  2. Change the Toolbar Type to Full Toolbar.
  3. Scroll down to find the Appearance submenu, and click the plus sign (+) next to it to open it. Change the title from General Discussion to Problem/Solutions Knowledge Base.
  4. Scroll down a bit further and change Frame Style to Title Bar and Border.
  5. Scroll down to the Advanced submenu, and click the plus sign (+) to expand it. Deselect the Allow Minimize, Allow Close, and Allow Zone Change options. (This forces the Web Part to appear on the page and specifies that it cannot be moved or closed by the user.)
  6. Scroll to the bottom of the window, and click the Apply button.
  7. Click OK to close the Web Part properties.

Add Data to the Web Part

The first thing we need to do is add some data to the Web Part so that we can see something from the ASP.NET application. On the Problem/Solutions Knowledge Base Web Part, click New Discussion. This opens the New Item page. For the subject, enter How Cool Problem/Solutions, and for the text, you can enter anything you want. The text you enter could be a description of the discussion, a list of team members, and so on. Right now we're just entering text to get the discussion started.

Click Save and then click Close from the menu to save this discussion thread. We need to add another item just for good measure. Click New Discussion in the title bar of the Problem/Solutions Knowledge Base Web Part to open the New Item page. Type some text. (What you enter is not important.) For the example, we've typed in text describing a problem with the solution, and as you'll notice, we've taken advantage of the built-in text formatting.

Click Save and then click Close from the menu at the top, which returns you to the new page. You should now see the two new discussion threads in your Web Part.

Using Text Formatting in the messages is particularly important. When the user clicks the plus sign (+) next to the discussion to expand it, she gets to see the nicely formatted information.

The formatting also supports the use of HTML links. (You can see this function simply by entering http://<link info>.) We must warn you, however, if you expose links to external users, you must consider security. If you do use links, they should be accessible to anonymous users.

Locate the Windows SharePoint Services Web Part GUID

As you probably know, Windows SharePoint Services and SharePoint Portal Server use system GUIDs to manage Web Parts and objects within the environment. In true object-oriented fashion, this arrangement allows one object to be reused by all users.

In our example, we selected a discussion list that is actually a List View Object. When we created it, Windows SharePoint Services created a GUID to identify the settings and data we gave it. When the Web Part is rendered on a page, the GUID is used to get the object and then add the settings and data to it when it is displayed. This process is how Windows SharePoint Services keeps track of almost every item created—from a list to a document library.

As in Windows SharePoint Services and SharePoint Portal Server, if we want to access a Web Part, Web Part data, or both, we also need the GUID because it is the only way to locate the item we want to access. Using the GUID, we can pursue the following options:

  • Instantiate the same object on a different page.
  • Use the GUID to instantiate the same object in a different Windows SharePoint Services site.
  • Use Microsoft Office to move data between Windows SharePoint Services Web Parts and Access, Word, and Excel.
  • Access the data directly in the content database (as in our example).

There are three ways to get the GUID for a specific Web Part: by using Notepad, by using FrontPage, or by querying the content database.

To use Notepad to locate a Web Part GUID

  1. Open your Web browser, navigate to the site (in our example, http://s2003e:382).
  2. Navigate to the new page we created to display the discussion Web Part.
  3. Right-click the page, and select View Source. This opens the page's HTML code in Notepad.
  4. In the Edit menu, click Find (or press Ctrl+F) to open the Find dialog box.
  5. Search for the title of the Web Part by typing in its name, Problem/Solutions Knowledge Base.

    The first occurrence in the file will be the title assigned to the TD tag; the next occurrence should be the actual title between <span> tags.

  6. Scroll down (and be careful because there is no formatting), and locate the ctx.listName setting. This is the actual GUID of the list, and it is enclosed in braces { }.
Note   You will see the WebPartID, which also has a GUID. This is not the GUID for the Web Part; it is the Web Part Page GUID for the page, not for the part.

In the following code snippet, you can see the TD Title and <span> titles highlighted. Lower in the text, you can see the highlighted GUID on the ctx.listName line:

<tr class="ms-WPHeader">
<td accesskey="W" tabindex="0" title="Problem/Solutions Knowledge Base 
- Use General Discussion to hold newsgroup-style discussions on topics 
relevant to your team." id="WebPartTitleWPQ5" style="width:100%;"><div 
id ="MSOFixedWidthTitle" fixedWidth="400px" 
style="overflow:hidden;text-overflow:ellipsis;" class="ms-WPTitle">
<a href="http://s2003e:382/Lists/General%20Discussion/AllItems.aspx"><nobr>
<span>Problem/Solutions Knowledge Base</span><span id="WebPartCaptionWPQ5">
</span></nobr></a></div></td><td align="right" 
onkeydown ="MSOMenu_KeyboardClick(WebPartWPQ5_MenuLink, 13, 40)" 
style="width:10px;padding-right:2px"> <a
onclick="MSOWebPartPage_OpenMenu(MSOMenu_WebPartMenu, this, 
WebPartWPQ5,'False');" id="WebPartWPQ5_MenuLink" style="cursor:hand;">
<img src="/_layouts/images/Menu1.gif" tabindex="0" class=
"ms-HoverCellInActive" onmouseout="this.className=
'ms-HoverCellInActive'" onmouseover="this.className=
'ms-HoverCellActiveDark'" border="0" align="absmiddle" title="Web Part Menu"
alt="Web Part Menu" /></a></td>
</tr></table></td></tr><tr><td class=
"ms-WPBorder" valign="top"><div WebPartID="3e75d5c4-15e2-4c5d-8286-
50cfbbe80124" HasPers="false" id="WebPartWPQ5" allowMinimize="false"
allowRemove="false" allowDelete="false" allowExport="false" 
... ...
... ...
border=0><SCRIPT>
ctx = new ContextInfo();
ctx.listBaseType = 3;
ctx.listTemplate = 108;
ctx.listName = "{CD68E7BA-2DEA-4E40-AB44-46CE32A5E468}";
ctx.listUrlDir = "Lists/General Discussion";

Again note that the WebPartID is not the GUID for the Web Part.

To use FrontPage to locate a Web Part GUID

Using FrontPage is almost as easy as using Notepad to locate a Web Part GUID, although you do have to open the site to do it this way, as the following steps demonstrate:

  1. Open Microsoft Office FrontPage 2003 and from the top menu, select File and then click Open Site.
  2. Type in http://s2003e:382, which is the URL for OurNewSharePointSite.
  3. When the site opens, the Site Folders list should appear on the left side of the screen. If it does not, you need to open it by going to the top menu and selecting View, and clicking Folder List (or by pressing Alt+F1).
  4. Scroll through the folders until you find the Pages folder, and click the plus sign (+) next to the folder to expand it (that is, to open it).
  5. Find the page named SupportKBPage.aspx (which is the page we created when we set up the Windows SharePoint Services site). Double-click this page to open it in the editor.

    Depending on your settings, the page will open in either Design, Split, or Code mode. We want to use Design mode to quickly locate our Web Part.

  6. Select Design mode. In Design mode, notice that the page items appear as components. You can click any item and, as a block, it is selected.
  7. Click the title bar of our Web Part, Problem/Solutions Knowledge Base, to select it. (Notice that the List View Options drop-down menu appears as a little page when you select it.) The Web Part selection should look something like this:

    <FPSELECTWEBPARTIMG>

  8. With the Web Part selected, change from Design to Code mode. You'll notice that the code for the Web Part is already selected:

    <FPWEBPARTCODEIMG>

  9. Scroll down through the selected code until you locate the following line:

    <ListName xmlns=http://schemas.microsoft.com

The GUID appears between the <ListName. . .> and </ListName> tags and includes the curly braces ({ }).

To use SQL Server

In content databases, several key tables are used to create, manage, and store Web Part data. The most notable tables used are as follows:

  • Docs.   Stores a reference to every document library
  • Lists.   Stores a reference to every list
  • Links.   Stores a reference to every link
  • Sites.   Stores references for every site in this site tree

In addition, there is a table named UserData in which user-entered data is stored. In our example, we are using a List table (because discussions are a list type), which means the reference information is stored in the Lists table.

By default, Windows SharePoint Services databases use Windows Authentication for security reasons. Therefore, you should log in to the system as WSSASPTester to open the SQL Server database, although you can do this from any account that has access to the Windows SharePoint Services database we created (for example, Administrator, sa, and so on).

  1. Open the SQL Server Query Analyzer by clicking Start, pointing to All Programs, selecting Microsoft SQL Server, and clicking Query Analyzer.
  2. In the Connect To SQL Server dialog box, enter your server instance name. (By default, for Windows SharePoint Services this is <server>\SHAREPOINT.) In our example, our server is S2003E, so the server name would be entered as: s2003e\SHAREPOINT.
  3. If you are using WSSASPTester or Administrator, select Windows Authentication. If you are using a SQL Server account, such as sa, you need to click SQL Server authentication and enter the Login name and password.
  4. Click OK to log in to the database, and open Query Analyzer.
  5. On the very top menu bar, there is a drop-down list that indicates the database you are currently accessing. If you logged in as WSSASPTester, this should already be pointing to Contoso1. If anything else is shown, such as "master," use the drop-down list to locate and select Contoso1. In the Query window, enter the following select statement:
    SELECT tp_ID FROM Lists WHERE tp_Title LIKE '%Problem/Solutions%'
    

Entering this information should return a single row in the Query Results window. The GUID for the list is the column named tp_ID. (Note that the GUID does not have curly braces in the database.)

Note   If you do not find the row using the query just shown, the list might have used the Default Title, General Discussions. If this is the case, substitute General Discussions for Problem/Solutions in the select statement and try again.

Use Visual Studio to Create a New ASP.NET Page

In our example, our goal is to display the same data from the Web Part in the Windows SharePoint Services site, OurNewSharePointSite, in the ASP.NET application site, OurNewASPNETSite, with as little difficulty and required maintenance as possible. Basically, we're going for a "set it and forget it" arrangement because we don't want to have to change code or make changes if the data changes.

To do this, we have several options that include using a custom object you create to instantiate a cloned Web Part within the ASP.NET site. However, these methods are complicated because of several factors, including security, access to style sheets, image objects, and so on. In addition, to use a Web Part within the confines of an ASP.NET site requires Windows SharePoint Services extensions to be installed on that site.

As is usually the case, and as it is with our example, our Windows SharePoint Services site and ASP.NET sites are completely isolated from one another. The general assumption is that to provide security, the ASP.NET site users should have zero access to the Windows SharePoint Services site or its objects. Although we have both sites on the same machine, using TCP/IP, these two sites could be in London and New York City.

To accomplish our goal of displaying the data from an internal Windows SharePoint Services site to an external ASP.NET site, we will use a direct connection to the Windows SharePoint Services database and use a DataList control in ASP.NET to display the data directly from the database table.

Getting to the data is the first requirement, and the key to this is accessing the GUID for the list, as we did in the previous section. This key enables us to pull the data from SQL Server to use it as we need to in the ASP.NET page.

Updating the Home Page   In our example, we left our ASP.NET site with a single page named Default.aspx and referred to it as the home page. We added a single image to it to test the site and make sure it was operational.

For the next steps and to keep the example simple, we are going to add our functionality to a new page named ProbSolutionKB.aspx. We'll add a link to it from the home page (Default.aspx) so that we can access it for testing. Open Visual Studio and open the project created for the ASP.NET site (in our example, port 383).

In the original setup, we set the Default.aspx page to be the start page of the project when we run the application. If you have not done this, you should do it now. In Visual Studio Solution Explorer, right-click Default.aspx and select Set As Start Page from the menu.

To start off, we want to make this example more realistic by making the home page look a little better. (This is not required.) We're going to modify the Default.aspx page (which is the home page for the site) by adding a heading to it using a table and adding a new image. We'll also add a link to the new page to be created.

In Visual Studio, first add the image for the How Cool Version 2 product, HowCoolV2sm.jpg (or any other image). (You can even keep the CoffeeBean.bmp we used in the setup if you prefer.) Regardless of how you choose to use Visual Studio—that is, whether you use the Design mode or code by hand—we want to accomplish the following tasks:

  • Add a background color to the page.
  • Create a main table that will surround the page objects.
  • Create a table within the main table to handle our page layout.
  • Add the image to the page as a heading logo.
  • Add a link to the page to be created.

First we need to upload the HowCoolV2sm.jpg image to the project. Right-click the project name, select Add, and then click Add Existing Item, which brings up the Add Existing Item dialog window. Browse to the file location where the image is located, click to select it, and then click Open.

Note   If you navigate to the folder and do not see the file, check to see whether the Files Of Type drop-down list is set to Image Files or All Files. (There are several selections, and the default is usually set to be VB Code Files or C Code Files.)

To open the file for editing, in the Solutions Explorer, double-click Default.aspx (unless it is already open). If the editor opens in the Design view, switch to the HTML view. Cut and paste (or type in) the new Default.aspx HTML code as shown in the following code sample. (Omit the <%@ Page directive from our example, and leave the line as it is in your project. It should be the same but it might not be!)

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Default.aspx.vb" 
Inherits="localhost._Default"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>Contoso - How Cool v2 Home Page</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" 
   content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0"
   title="Contoso ©2004">
<form id="Form1" method="post" runat="server">
<table width="100%" align="center" cellpadding="0" cellspacing="0"
   bgcolor="#660000">
   <tr>
           <td height="5"></td>
   </tr>
   <tr>
       <td>
          <table width="90%" align="center" cellpadding="0" 
          cellspacing="0"
              bgcolor="#660000" border="0">
                <tr bgcolor="#ffffff">
                    <td valign="middle" align="left" bgcolor="#ffffff">
<font style="FONT-WEIGHT: bold; COLOR: black; FONT-FAMILY: 
verdana,arial; FONT-VARIANT:small-caps"> Contoso, Inc.<br>
Welcome to the How Cool Home Page</font></td> 
                    <td valign="middle" align="right" bgcolor="#ffffff">
<IMG SRC="http://localhost:383/How CoolV2sm.jpg"></td>
                </tr>
                <tr bgcolor="#ffffff">
                   <td Colspan=2 align=center><hr color=#660000></td>
                </tr>
                <tr bgcolor="#ffffff">
                   <td Colspan=2 align=center><br><font 
                   style="FONT-SIZE: 9pt; FONT-WEIGHT: bold; 
                   COLOR: black; FONT-FAMILY: verdana,arial;">
<a href="ProbSolutionKB.aspx">How Cool v2 Support Problem/Solutions Knowledge Base
</a></font><br><br></td>
               </tr>
          </table>
      </td>
   </tr>
   <tr>
      <td height="5"></td>
   </tr>
</table>
</form>
</body>
</HTML>

Regardless of what you add for code here, be sure that you add the new link shown for ProbSolutionKB.aspx. (In the preceding example, this new link, <a href="ProbSolutionKB.aspx">How Cool v2 Support Problem/Solutions Knowledge Base</a>, appears in boldface type.) Save your work either by pressing Ctrl+S or by selecting File from the top menu and then clicking Save Default.aspx. To build the project to ensure there are no errors, from the top menu, select Build and then click Build Project.

Assuming you have no build errors, next you need to test the new home page in your browser (not within Visual Studio). Do this by either opening Internet Explorer and navigating to the URL of the site (in our example, http://s2003e:383) or, in Visual Studio in the Solution Explorer pane, right-clicking the name (Default.aspx) and selecting Browse With from the menu. In the Browse With dialog box, select Microsoft Internet Explorer from the Browser List and then click Browse.

Note   You could also simply build and start the project by pressing the F5 key or, from the top menu, selecting Debug and then clicking Start. Because Default.aspx is already set as the start page, it will automatically open (if there are no build errors). If you do use this method, verify that the page works and then stop debugging so that we can add the new page in the next section.

If you click the link for the Knowledge Base page, you should get a message that says "The page cannot be found," but the link should be correct (http://s2003e:383/ProbSolutionKB.aspx). Once you have tested the page, close the browser.

Build the New Page   Now that we've redone the home page, we can use the code to get started on our new page to give our new site a consistent look and feel. First, we need to open a new page. To do this, in Visual Studio, in the Solution Explorer pane, right-click the project name, select Add, and then click Add New Item. Then select WebForm under Templates, and in the lower part of the window under Name enter ProbSolutionKB.aspx. Click Open. If it is in Design mode, switch to HTML mode.

Because we've already redone the home page, we can use most of the HTML code to get our new page started. If the Default.aspx page is not open (keeping in mind that you can switch pages via the tabs at the top of the page), double-click the name in the Solution Explorer to open it. If it is in Design mode, switch to HTML mode.

In the HTML editor, select and copy the following code:

<body topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" 
title="Contoso ©2004">
<form id="Form1" method="post" runat="server">
<table width="100%" align="center" cellpadding="0" cellspacing="0" 
bgcolor="#660000">
   <tr>
      <td height="5"></td>
   </tr>
   <tr>
      <td>
         <table width="90%" align="center" cellpadding="0" 
            cellspacing="0" bgcolor="#660000" border="0">
            <tr bgcolor="#ffffff">
               <td valign="middle" align="left" 
bgcolor="#ffffff"><font style="FONT-WEIGHT: bold; COLOR: black; 
   FONT-FAMILY: verdana,arial; FONT-VARIANT: small-caps">Contoso, Inc.
   <br>Welcome to the How Cool Home Page</font></td>
               <td valign="middle" align="right" 
bgcolor="#ffffff"> <IMG SRC="http://localhost:383/HowCoolV2sm.jpg"></td>
            </tr>
            <tr bgcolor="#ffffff">
               <td Colspan=2 align=center><hr color=#660000></td>
            </tr>
            <tr bgcolor="#ffffff">
               <td Colspan=2 align=center><br><font style="FONT-
SIZE: 9pt; FONT-WEIGHT: bold; COLOR: black; FONT-FAMILY: verdana,arial;">
<a href="ProbSolutionKB.aspx">How Cool v2 Support Problem/Solutions Knowledge Base
</a></font><br><br></td>
            </tr>
         </table>
      </td>
   </tr>
   <tr>
      <td height="5"></td>
   </tr>
</table>
</form>
</body>
</HTML>

Switch to the new page, ProbSolution.aspx, and in the HTML editor, select from the <BODY> start tag to the end of the code and delete it. Then copy the code from the preceding code sample and paste it in. We now need to change the heading and title so that we know which page we are using in the browser. First, change the <TITLE>ProbSolutionKB.aspx</TITLE> line to be <TITLE>Problem/Solutions Knowledge Base</TITLE>. Next we want to change the heading on the page itself from "Contoso, Inc." to "Contoso Support" and "Welcome to the How Cool Home Page" to the Support Group telephone number. Change the highlighted code in the page from this code

<tr bgcolor="#ffffff">
   <td valign="middle" align="left" bgcolor="#ffffff">
<font style="FONT-WEIGHT: bold; COLOR: black; FONT-FAMILY: verdana,arial; 
   FONT-VARIANT: small-caps">Contoso, Inc.<br>
Welcome to the How Cool Home Page</font>
</td>
   <td valign="middle" align="right" bgcolor="#ffffff">
<IMG SRC="http://localhost:383/HowCoolV2sm.jpg"></td>
</tr>

to the following code

<tr bgcolor="#ffffff">
   <td valign="middle" align="left" bgcolor="#ffffff">
<font style="FONT-WEIGHT: bold; COLOR: black; FONT-FAMILY: verdana,arial; 
   FONT-VARIANT: small-caps">OurSoftware Support</font><br>
<font style="FONT-WEIGHT: bold; FONT-SIZE: 8pt; COLOR: black; FONT-
   FAMILY: verdana,arial">Support main line: 898-392-3383</font>
      </td>
      <td valign="middle" align="right" bgcolor="#ffffff">
<IMG SRC="HowCoolV2sm.jpg"></td>
</tr>

Next, we need to change the link to allow us to get back to the home page and add a link to refresh this page by making it call itself (which is explained later). The code you've cut and pasted so far should now look like the following:

<tr bgcolor="#ffffff">
   <td Colspan=2 align=center><br>
<font style="FONT-SIZE: 9pt; FONT-WEIGHT: bold; COLOR: black; 
   FONT-FAMILY: verdana,arial;">
<a href="ProbSolutionKB.aspx">How Cool v2 Support Problem/Solutions Knowledge Base
</a></font><br><br>
   </td>
</tr>

Change the code in boldface type in the preceding code sample to the code shown in boldface type in the following code sample:

<tr bgcolor="#ffffff">
   <td Colspan=2 align=center><br>
<font style="FONT-SIZE: 9pt; FONT-WEIGHT: bold; COLOR: black; 
   FONT-FAMILY: verdana,arial;">
<a href="ProbSolutionKB.aspx">Return To 
   Home</a></font>&nbsp;&nbsp;&nbsp;&nbsp;
   <a href="ProbSolutionKB.aspx">Refresh Page</a></font><br><br>
   </td>
</tr>

Save your work by pressing Ctrl+S or selecting File and then clicking Save ProbSolutionKB.aspx. Then test the page by right-clicking the name in the Solution Explorer window pane, selecting Browse With, and then selecting Internet Explorer. Again, do not use the Visual Studio internal browser to test this page, as it will mask problems that the other browsers do not.

Add a DataList to the Page   In this next part of this example, we have to add a component (a DataList object) to the page and write some procedural code that will load data from the Windows SharePoint Services Web Part into our ASP.NET Page.

Adding a DataList to the ASP.NET page is done in the HTML editor in either Design mode by means of a drag-and-drop operation, or it's done by simply coding the object in by hand. (Most folks prefer to use both. They use a drag-and-drop operation to place the object on the page and then switch to the HTML editor to change the attributes.) For this example, we did both, as you will likely do on real projects.

If it is not open already, open the ProbSolutionKB.aspx page in the HTML editor and make sure it is in HTML mode. Then in the table we created in HTML, add a new Table Row and put a marker there as shown in the following code:

<tr bgcolor="#ffffff">
   <td Colspan=2 align=center valign=middle><font style="FONT-SIZE: 7pt;
COLOR: black; FONT-FAMILY: verdana,arial"><a href="Default.aspx">Return to Home
   </a></font>&nbsp;&nbsp;&nbsp;&nbsp;<font style=
   "FONT-SIZE: 7pt; 
COLOR: black; FONT-FAMILY: verdana,arial"><a href="ProbSolutionKB.aspx">
   Refresh Page</a></font></td>
</tr>
<tr>
   <td colspan="2" width="100%">PUTCONTROLHERE</td>
</tr>

Switch to Design mode and you'll see the marker "PUTCONTROLHERE" on the page. Click the Toolbox, and under the Web Forms click DataList and drag it until you see the cursor ( | ) appear in or next to the marker text. (If you do not see the toolbox, from the top menu, select View and then click Toolbox or press Ctrl+Alt+X.)

On the page, delete the text marker (PUTCONTROLHERE) so that only the control remains in the table row. Right-click the DataList, and then from the menu select Properties. This should open the Properties window for the DataList, which allows you to work with the majority of settings for determining how the DataList will appear.

For the example, right-click on the list and select Properties. From the Properties page, select AutoFormat and choose a style. (Doing this is not required, but for this example, the Colorful 1 style was selected.)

While we would ordinarily use a cascading style sheet (CSS) to assign CSS classes to each of the areas (such as Heading, Item, Selected, and so on), for this example, we have simply changed the font in each section to be Verdana, Arial (which are typical fonts for screen displays) instead of accepting the default font on the page (which is usually a Courier or Times font). As in the step just mentioned, doing this is not required, but it is usually done because the default settings are not exactly pretty.

Because the DataList has no bindings assigned, you can actually test the page at this point, although you will not see the DataList. (It must be populated with data to show.) The next step is to add the code required to populate the DataList when the page opens. If it is not already, make sure your browser is closed (and not debugging), and open the ProbSolutionKB.aspx page (in Design or HTML mode). Right-click the page in the Editor, and from the menu, select View Code to open the Visual Basic (or C) Editor.

The first thing we need to be sure of is that our new DataList is listed as an object in our code. If you created the list by means of a drag-and-drop operation in Design mode, this entry is already made for you. If you did not create it that way, you must add it before you can use it in the code. In the Code editor, find the Region named Web Form Designer Generated Code and click the plus sign (+) next to it to expand it. Below the END SUB line for the InitializeComponent Sub, you should see a line that starts with "Protected WithEvents".

If you do not see this line (which is typical if you added the DataList by hand), you need to add it.

Verifying the Data   Before continuing with the code, we need to switch to SQL to understand the data we need to get in order to load the DataList on our page. To do this, we need the GUID of the Web Part we're going to use and query the database created for the Windows SharePoint Services site.

Open the SQL Server Query Analyzer (by clicking Start, pointing to All Programs, clicking Microsoft SQL Server, and clicking SQL Query Analyzer). If you are prompted for a login, enter WSSASPTester and select Windows Authentication. You can use any other login that has privilege, but you must make sure that you are pointing to the Windows SharePoint Services database (in our example, Contoso1).

There are a few queries you can run to see the data from the Query Analyzer. For our example, our Web Part was created with the GUID of

{CD68E7BA-2DEA-4E40-AB44-46CE32A5E468}

We will use this as our key to get information in the Windows SharePoint Services database. Note, however, that not all information found in these tables is needed. For example, in the Lists table, there is a considerable amount of information about the List, but we are interested only in the Title and Description.

In the UserData table—which is generic for all types of lists, documents, and so on—there are many fields used to accommodate the kinds of data that can be stored in Web Parts. For example, there are 64 "generic" nvarchar fields used to store data. If your Web Part uses two such fields, they will be assigned to [nvarchar1] and [nvarchar2]. However, where your data is located will depend on your list, and you will have to query the UserData table to determine where the data actually is.

The quickest way to determine this is to create a specific entry in your list (or Web Part) that uses every field added with a title such as "FIRSTTEST." You can then use this entry to query the UserData table, find the FIRSTTEST row, and check which fields are being used.

So while we can get lots of information about a particular list (or Web Part), we need to determine the exact data we want. In our example, we searched the UserData table for our first entry and found that the fields "nvarchar1" and "ntext2" represent the title and the description, respectively. This allows us to set up the specific query we'll need in the ASP page, as you will see in the following example:

/* In these examples, the List GUID created is {CD68E7BA-2DEA-4E40-
AB44-46CE32A5E468} */
/* This selects the entire row from Lists: */
SELECT * FROM [Contoso1].[dbo].[Lists]
WHERE [tp_ID] = '{CD68E7BA-2DEA-4E40-AB44-
46CE32A5E468}'

/* To simply get the basic info, use this: */
SELECT [tp_Title], [tp_Description], [tp_ItemCount]
FROM [Contoso1].[dbo].[Lists]
WHERE [tp_ID] = '{CD68E7BA-2DEA-4E40-AB44-46CE32A5E468}'
/* This returns all the columns for ALL items for the given list: */
SELECT * FROM [Contoso1].[dbo].[UserData]
WHERE [tp_ListId] = '{CD68E7BA-2DEA-4E40-
AB44-46CE32A5E468}'

/* After looking at the data, only two fields are required (we get the*/
/* ItemOrder and Unique ID just to show which fields can be used to*/
/* create special sorting options programmatically: */
SELECT [tp_ItemOrder], [uniqueidentifier1], [nvarchar1], [ntext2]
FROM [Contoso1].[dbo].[UserData]
WHERE [tp_ListId] = '{CD68E7BA-2DEA-4E40-
AB44-46CE32A5E468}'
Order by tp_Ordering, uniqueidentifier1

Once you have the query as you need it (as we did for both the Lists and UserData tables), save this to Notepad for the next step.

Coding the DataList

At this point, we have all we need to code the DataList. After adding the Web Part in Windows SharePoint Services, getting the GUID by using Notepad, and then figuring out the queries we need to get our data, all that remains is creating the code to execute the SQL code and populate the DataList on our page.

In Visual Studio, if it is not already open, you need to open the ProbSolutionKB.aspx file. In the Editor, right-click and from the menu, select View Code to open the Code Editor. If the Region "Web Form Generated Code" is expanded (visible), click the plus sign (+) next to it to minimize it and get it out of your way while you edit.

The next bit of code is all added:

  • We add a local reference to the System.Data.SqlClient namespace so that we can access the database.
  • We add a subroutine to handle populating the database.
  • We add a call to the subroutine in the Page_Load subroutine to execute it when the page loads.

Using the following sample code, type in the code shown in boldface type. We've commented each section so that you can follow it:

GUIDGUIDGUIDGUID' ADDED for access to the SQL Database
Imports System.Data.SqlClient
Public Class ProbSolutionKB
Inherits System.Web.UI.Page
     #Region " Web Form Designer Generated Code "

     Private Sub Page_Load(ByVal sender As System.Object, ByVal e 
       As System.EventArgs) Handles MyBase.Load
       'Put user code to initialize the page here
       '
       ' If this was only to load once, then you can uncomment
       ' the IF statement; without this, the page will reload
       ' each time (this means added items will be found on refresh):
       '
       Dim AGUIDInStringFormat As String = "{CD68E7BA-2DEA-4E40-AB44-
              46CE32A5E468}"
       '
       If IsPostBack Then  ' Use this to run ONLY ONCE when loaded
         '    LoadTheDataGrid(AGUIDInStringFormat)
        Else '    Use this to reload  every time
          LoadTheDataGrid(AGUIDInStringFormat)
End If
'
End Sub
Private Sub LoadTheDataGrid(ByVal OurStringGUID As String)
       '
       Dim SQLConn As New SqlConnection
       Dim SQLDataAdapter As New SqlDataAdapter
       Dim SQLSelectString As String
       Dim SQLSelectListHeaderString As String
       Dim SQLSelectListDetailString As String
       Dim DiscussionData As DataSet
       Dim TotalItems As Integer
       '
       ' Open the database using a SQL Login:
       '
       SQLConn.ConnectionString = "Integrated Security=SSPI;Persist 
              Security
          Info=False;Initial Catalog=Contoso1;Data Source=s2003e;"
       SQLConn.Open()
       '
       ' We know the GUID assigned to the SPECIFIC Windows SharePoint 
       ' Services Object in three ways:
       ' Display the page and do a View Source (fastest)
       ' Open the page in FrontPage and change to the Source view
       ' Search the lists table in SQL for the Name of the list
       '
       ' Once we have the GUID, we can use direct SQL to get the 
       ' information we want from the List directly from 
       ' SharePoint database:
       '
       ' Setup the SQL Statement - this returns the Title and 
       ' Description of the list:
       '
       SQLSelectListHeaderString = "SELECT [tp_Title],[tp_Description]
          FROM LISTS WHERE [tp_ID] = '" & OurStringGUID & "' "
       '
       ' Setup the Detail SQL Statement - this returns all of the
       ' List Items from the UserData table.
       ' NOTE: YOU MUST ORDER the Query by the tp_Ordering column.
       ' In Discussion lists, this column is used to keep track of 
       ' the threads. For the Main Topic, it assigns a unique 14 digit
       ' to the message; the first reply appends another 14 digits
       ' and the next appends again and so on:
       ' Main Topic 1: 12345678901234
       ' First Reply:  1234567890123412345678901234
       ' Second Reply: 123456789012341234567890123412345678901234
       '
       ' Main Topic 2: 23948798746242
       ' First Reply:  2394879874624298712349872347
       ' Second Reply: 239487987462429871234987234712345678901234
       '
       ' Order By this column ensures that discussion threads will be
       ' kept with the correct messages.
       '
       SQLSelectListDetailString = "SELECT 
           [tp_ItemOrder],[uniqueidentifier1],
           [nvarchar1], [ntext2] FROM [Contoso1].[dbo].[UserData] 
           WHERE [tp_ListId] = '" & OurStringGUID & "' 
           AND tp_ModerationStatus = 0 AND tp_IsCurrent = 1
          Order by tp_Ordering, uniqueidentifier1 "
       '
       ' Create a new data set to hold both Select Results:
       '
       DiscussionData = New DataSet
       '
       ' LISTS (Information about the object from the LISTS table):
       ' Set the SQL Select command:
       SQLDataAdapter.SelectCommand = & _
              New SqlCommand(SQLSelectListHeaderString, SQLConn)
       ' Add the table to the Data Set:
       DiscussionData.Tables.Add("Lists")
       ' Get the Data:
       SQLDataAdapter.Fill(DiscussionData.Tables("Lists"))
       ' Clear the Adapter:
       SQLDataAdapter.Dispose()
       '
       ' USERDATA
       ' (Detail Items contained in the List from the USERDATA table):
       SQLDataAdapter.SelectCommand = & _
              New SqlCommand(SQLSelectListDetailString, SQLConn)
       DiscussionData.Tables.Add("UserData")
       SQLDataAdapter.Fill(DiscussionData.Tables("UserData"))
       SQLDataAdapter.Dispose()
       '
       ' Capture the total number of entries we found (NOTE: This
       ' number is also in the Lists Table as column tp_ItemCount,
       ' but better to use what is returned):
       '
       TotalItems = DiscussionData.Tables("UserData").Rows.Count
       '
       ' We're done with the data connection so close it:
       '
       SQLConn.Close()
       '
       ' Now we'll dynamically bind the data to the DataList...
       '
       ' Create a new DataTable and create Columns for us to fill:
       '
       Dim OurDT As New DataTable
       Dim OurDRs As Integer
       Dim BuildDataRow As DataRow
       Dim GetIndex As Integer
       '
       ' Add two columns, Subject title and Message
       '
       OurDT.Columns.Add("Title", GetType(String))
       OurDT.Columns.Add("DescText", GetType(String))
       '
       ' Loop through the table and build the DataTable:
       '
       For GetIndex = 0 To (TotalItems - 1)
              BuildDataRow = OurDT.NewRow()
              BuildDataRow("Title") = & _
DiscussionData.Tables("UserData").Rows(GetIndex).Item("nvarchar1")
              BuildDataRow("DescText") = & _ 
DiscussionData.Tables("UserData").Rows(GetIndex).Item("ntext2")
              OurDT.Rows.Add(BuildDataRow)
       Next
      '
      ' Now establish a new DataView from the table just created:
      '
       Dim OurDataView As DataView = New DataView(OurDT)
      '
      ' Bind it to the DataList control and we're done!
      '
       DataList1.DataSource = OurDataView
       DataList1.DataBind()
       End Sub
End Class

When you are done editing, save your work by pressing Ctrl+S or by selecting File from the top menu and clicking Save ProbSolutionKB.aspx.

Now, before we finish, we have to add the Binding to our DataList on the HTML code side. This basically sets the fields we expect to use (in this case, Title and DescText from the code) and sets how they will be formatted when they are displayed.

From the top tabs, select ProbSolutionKB.aspx or double-click the name in the Solution Explorer to open it in the editor. If you are in Design mode, switch to HTML mode. Look at the following code to see what changes need to be made to the base code:

<tr>
   <td colspan="2" width="100%">
   <asp:datalist id="DataList1" runat="server" BorderColor="#CC9966" 
      BorderStyle="None" BackColor="White" CellPadding="4" 
      GridLines="Both" 
   BorderWidth="1px" CellSpacing="2" width=100%>
   <SelectedItemStyle Font-Size="X-Small" Font-Names="verdana,arial" 
      Font-Bold="True" ForeColor="663399" BackColor="#FFCC66">
   </SelectedItemStyle>
   <HeaderStyle Font-Size="Smaller" Font-Names="verdana,arial" Font-Bold="True"
      ForeColor="#FFFFCC" BackColor="#990000"></HeaderStyle>
   <HeaderTemplate>
      How Cool 2: Problem/Solutions Knowledge Base
   </HeaderTemplate>
   <EditItemStyle Font-Size="X-Small" Font-Names="Verdana,Arial">
   </EditItemStyle>
   <AlternatingItemStyle Font-Size="X-Small" Font-Names="verdana,arial">
   </AlternatingItemStyle>
   <ItemStyle Font-Size="X-Small" Font-Names="verdana,arial" 
      ForeColor="#330099" BackColor="White"></ItemStyle>
   <ItemTemplate>
      <font style="FONT-WEIGHT: bold; FONT-SIZE: 8pt; COLOR: #000066;
         FONT-FAMILY: verdana,arial">Reported Issue:</font><br>
      <font style="FONT-WEIGHT: bold; FONT-SIZE: 10pt; COLOR: black;
         FONT-FAMILY: verdana,arial">
<% #DataBinder.Eval(Container.DataItem,"Title")%>
      </font>
      <hr color="#990000">
      <font style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: 
         Verdana,arial">
<#% DataBinder.Eval(Container.DataItem,"DescText")%>
      </font>
      <br>
   </ItemTemplate>
   <FooterStyle Font-Size="XX-Small" Font-Names="verdana,arial" 
      HorizontalAlign="Right" ForeColor="#660099" 
      BackColor="#FFFFCC"></FooterStyle>
   <FooterTemplate>OurSoftware How Cool 2 Support email: <a href=
   "mailto:HC2@OurSoftware.com">HC2@OurSoftware.com</a></FooterTemplate>
   </asp:datalist>
   </td>
</tr>

Notice the changes made to the DataList, including the following:

  • Added "How Cool 2: Problem/Solutions Knowledge Base" as the heading
  • Added the Item Template section
  • Added two DataBinder statements for the two fields we will populate the list with
  • Added a footer for the support group

Again, when you are done editing, save your work by pressing Ctrl+S or by selecting File from the top menu and clicking Save ProbSolutionKB.aspx.

Now check to make sure everything is OK by building the project. From the top menu, select Build and then click Build Solution. If you discover any errors, check them against the code listed previously. (Problems are usually limited to only typos.)

Testing the New Page

Because we've already added the link to the home page and have set Default.aspx to be the Project Startup page, we're ready to test the page. For a comparison, open your browser and navigate to the Windows SharePoint Services site (OurNewSharePointSite), http://s2003e:382. Click the Page tab to open the SupportKBPage, and you should see the Problem/Solution Knowledge Base Discussion Web Part with the two entries we made when it was created.

Note   You should have seen these entries when testing in SQL Server Query Analyzer.

Now from Visual Studio, press the F5 key (or from the top menu, select Debug and click Start). Doing this will build the project and then start the Start Page—in our case, Default.aspx. It also will help you if any problems occur because Debug mode will enable you to open the project and view the source code that might be causing a problem.

If all goes well, your default browser should open to the home page.

Click the link (as shown, "How Cool v2 Support Problem/Solutions Knowledge Base") and this should open the ProbSolutionKB.aspx page. If it opens successfully, you should see our final result.

Note   A common problem here occurs if you do not have the correct account access to SQL Server. Make sure you have an account that has access to the Windows SharePoint Services database specifically.
Note   We mentioned how important it was to format text when you entered it in the Windows SharePoint Services site Web Part. As you can see, the formatting you applied in there is carried over into the DataList.

Try It Out: Verifying New Entries

Now that we know we can display the contents of the Web Part, it's time to check out the dynamic nature of it. As you recall, one of our objectives is to cut down or eliminate maintenance. With what we've just built, we have satisfied that and then some. When entries are added to the Web Part, they are automatically available to our ASP.NET application through the database. This means that Add, Edit, Update, and Delete are not our concern—the Web Part handles all that. We look only for current data.

You might have noticed that in the example, we included a link on the ProbSolutionsKB.aspx page that links the page back to itself. We called this link Refresh Page, and it is there for a reason.

If it is not already open, open your browser and navigate to the ProbSolutions-KB.aspx page (via the Home Page link or by typing in the URL http://s2003e:383/ProbSolutionsKB.aspx). Click the Refresh Page link and the page should be reloaded. (You can also use the Reload button on your browser or press the F5 key.)

In another browser window, navigate to the OurNewSharePointSite site with the URL http://s2003e:382. From the home page, click the SolutionKBPage tab to display it and the Problem/Solutions Knowledge Base Web Part.

On the Web Part, click New Discussion and enter a new discussion. In this one, we will simply enter a new one for testing. However, in the Text area, we will enter a LINK as well. We don't have to explicitly indicate a link—Windows SharePoint Services already does this when you enter http://<server>.

Click Save and then click Close to save this item. You should now see it in the Problem/Solutions Knowledge Base discussion list. Switch back to the browser showing the ASP.NET page, ProbSolutionKB.aspx, and click Refresh Page (or press the F5 key). Your new entry should appear in the list. If you'd like, try the link as well; it should bring you to the Team Site home page.

Summary

This example is just one simple way in which to provide an external face to your SharePoint Portal Server or Windows SharePoint Services site. This example is intentionally simple because it offers a quick way to provide secured data to a public or nonsecured display, likely something most developers can grasp quickly. However, in a full production environment, there are many ways in which to access Windows SharePoint Services and SharePoint Portal Server data via the database, depending on your needs. I would encourage you to look into the SharePoint Products and Technologies Web Services layer, which provides extended access to all the services available.

Show: