In-Depth

Build and Debug Web Parts with SharePoint Extensions

Visual Studio 2008 Extensions for SharePoint makes developing and testing Web Parts almost easy, provided you install it correctly.

One of the primary ways to extend SharePoint is to create Web Parts -- the same Web Parts that are used in ASP.NET. But because SharePoint is an application platform built on top of .NET, creating a Web Part project and then debugging your Web Part inside SharePoint has always been different … and awkward. In addition to making life difficult for SharePoint developers, the troublesome process has discouraged ASP.NET developers from bringing their skills to SharePoint.

Microsoft released the Visual Studio 2008 Extensions for Windows SharePoint Services 1.3 (VSeWSS) as a community technology preview (CTP) in January 2009. The extensions simplify creating and debugging many kinds of SharePoint components. The CTP version is feature-complete, though presumably there are still some bugs left to remove (the final version is scheduled for release in the spring). On the Visual Studio side, the CTP supports VS 2008 but not VS 2005. On the SharePoint side, the CTP supports both Windows SharePoint Services and Office SharePoint Server. The Extensions package supports installing your Web Part, debugging it on the same computer as VS -- remote debugging is not supported.

We'll walk you through the process of installing the Extensions and using them to create and debug a Web Part Project. Along the way, you'll see how to create a configurable search tool for a SharePoint site.

Installing the Extensions
The Extensions download package can be retrieved here by following the link in the body of the page (don't click on the Downloads link -- it takes you to a patch you probably won't need). You can download up to three components: two .MSI files (one each for 32-bit and 64-bit Windows) and the release document. You must have IIS, SharePoint and VS 2008 installed on your computer to run the installation package.

The installation package installs a Web service (called VSeWSS) on your computer that VS will use to communicate with SharePoint. One of the first challenges that you'll face after starting the installation wizard is to configure the Web service (Figure 1). Your first step is to pick an application pool to use for the Web service. If you don't want to use an existing pool, you'll need to create the new pool in IIS Manager before starting the installation. There are two conditions that the identity assigned to the pool must meet:

  • It must have the same permissions as those granted to the identity used by the SharePoint Central Administration site
  • The identity must be part of the Administrators group
    I picked the simplest solution to meet the first condition: I used the SharePoint Central Administration site's pool as the pool for the Web service. This also saved me from having to set up a new pool.

To meet the second condition, you must determine the Identity used by the pool you've picked. You do this in IIS Manager, under Application Pools, by finding the pool you picked in the dialog. Once you've found the pool, right-click on it and select Properties. You'll find the identity name on the Identity tab (on my machine, the identity was Network Service). The next step is to add the Identity to the Administrators group: From your computer's Start menu, select Administrative Tools | Computer Management and drill down through Local Users and Groups | Group to select Administrators. Right-click on the group, select Add to Group and enter the name from the Identity tab.

After you make these changes, you can leave the Wizard to run unattended. After the installation is complete, you can use VS to determine if your installation was correct.

Creating Your Web Part Project
With the Extensions installed, you're ready to start using their first feature: A set of SharePoint templates that support creating most SharePoint components. To create a Web Part, for instance, you select Web Part project template in the SharePoint category of the New Project dialog (see Figure 2). The resulting project has a folder called Web Part1 -- delete it (renaming Web Parts is not 100% reliable, at least in the CTP) and use the standard Add New Item dialog to add your Web Part with the correct name. For this article, I added a Web Part called VideoSearchPart.

The result is a new folder with the three files required for a SharePoint Web Part: The code file for the Web Part, an XML file containing the information needed to install the Web Part and a .WEBPART file with the XML used to configure the Web Part. While it doesn't appear in Solution Explorer, the Web Part template also includes a feature.xml and a setup.bat file, which you'll use when installing your Web Part on your production SharePoint site.

Because you can only debug your WebPart on your development computer, you'll need to either copy your target site to your local computer or create a test site on your computer. In this particular case, I created a test SharePoint site by starting SharePoint Central Administration from my Start menu and, from the Application Management tab, picking Create or Extend Web Site to bring up the dialog that lets me add a new site. After clicking the OK button to create my site, I used the next page in the process to add a Site Collection using SharePoint's Wiki template.

If your development SharePoint site isn't installed on port 80 at http://Localhost then you'll have one more configuration step to make: You must set the start URL for debugging to point to the URL for your site. To do this, open your project properties, navigate to the Debug tab and set the "Start browser with URL" text box to the URL for the local SharePoint site where you want to test your Web Part .

With your project created and configured, you can now check to see if your installation went correctly: Right-click on the project and select Quick Deploy | Recycle Application Pool. If there were any errors in your installation, you will get a message in your Error List. If you changed the "Start browser with URL" option and you get a message that refers to the original LocalHost URL, select Recycle the Application Pool option again (the Extensions seem to use the original setting once, before using your updated setting).

Configuring the Project and the Site
You're not quite ready to start creating your Web Part. While the Extensions make debugging easy, they don't configure your SharePoint site to support debugging or report error information. To make these changes, return to IIS Manager, drill down through Web sites to your SharePoint site, right-click and select Properties. On the Home Directory tab, you'll find the path to the folder holding your site's files in the "Local path" text box. In Windows Explorer, navigate to that folder and open the web.config file in the folder. In this file, change the debug attribute on the compilation element to "true" in order to turn on debugging:

<compilation batch="false" debug="true">

You should also configure your SharePoint site to display any error messages that are generated by setting the customErrors tag's mode attribute to Off (the default setting suppresses all error messages):

<customErrors mode="Off" />

To get the full list of called modules listed on the error screen, you'll also need to set the SafeMode's CallStack attribute to "true":

<SafeMode CallStack="true" />

Before adding code to the .VB or .CS file that represents your Web Part, you should update the .XML and .WEBPART files in the project (it doesn't appear to be possible to change these values after debugging your Web Part for the first time, at least in the CTP). Inside the properties element in the .WEBPART file, rewrite the default property elements in the file with the title and description you want to have displayed in SharePoint's Add a Web Part dialog. This example shows the settings for my sample search part:

<properties>
        <property name="Title" type="string">Video Title 
        Search</property>
        <property name="Description" type="string">Fuzzy 
        search on video titles</property>
      </properties>

By default, your Web Part will appear in the Add Web Parts dialog in the Miscellaneous section. To have your Web Part appear in a different category, open your Web Part's XML file and add two Property tags inside the File element: One with its Name attribute set to Group and the other with its Name attribute set to QuickAddGroups. With the two properties defined, set the Value attribute on both tags to whatever value you want for your group name. This example will cause the part to appear in a section called "PHV Tools":

<File Path="VideoSearchPart.webpart"
Url="VideoSearchPart.webpart" 
        Type="GhostableInLibrary" >
      <Property Name="Group" Value="PHV Tools"/>
      <Property Name=vvQuickAddGroups" Value="PHV Tools" />
</File>

Programming the Web Part
You're finally ready to start creating your Web Part. Within the Web Part's code file you must -- in the CreateChildControls method -- create the controls that will appear on your Web Part. The simplest approach is to create a table, add it to the Web Part object's Controls collection, add rows and cells to the table, then add your controls to the Controls collection of the cells in the table. This code adds a Label control to the first cell in the first row of the table:

Dim tbl As New Table
Me.Controls.Add(tbl)

Dim trTitle As New TableRow
tbl.Rows.Add(trTitle)

Dim tcTitle As New TableCell
trTitle.Cells.Add(tcTitle)

Dim TitleLabel As New Label()
TitleLabel.Text = "Look for movies with title:"
tcText.Controls.Add(SearchTitle)

For my example, I created a table with four rows: the first row contains a Label and TextBox for the user to enter the title of a movie to search for, the second row contains a Label and a TextBox for the user to enter a category (such as Action or Drama), the third row contains the button to trigger the search, and the final row holds a GridView to display the result. In the CreateControls method, you should also wire up any events that your Part needs. This code adds a button to the table and wires an event routine to it:

Dim trButton As New TableRow
tbl.Rows.Add(trButton)

Dim tcButton As New TableCell
trButton.Cells.Add(tcButton)

Dim SearchButton As New Button()
SearchButton.Text = "Search"
AddHandler SearchButton.Click, AddressOf Me.StartSearch
tcButton.Controls.Add(SearchButton)

The event routine pulls data from the two TextBoxes in the table (in the first and second rows) and fills a DataSet that is bound to a GridView (in the fourth row):

Private Sub StartSearch(ByVal sender As Object, _
   ByVal e As System.EventArgs)
Dim conn As New SqlConnection("…")
Dim cm As SqlCommand = conn.CreateCommand
Dim da As New SqlDataAdapter(cm)
Dim ds As New System.Data.DataSet
Dim searchString As String

Dim tbl As Table
tbl = CType(Me.Controls(0), Table)

searchString = CType( _
   tbl.Rows(0).Cells(0).Controls(1), TextBox).Text
cm.CommandText = "Select * From …"
da.Fill(ds, "Results")

Dim gv As GridView
gv = CType(tbl.Rows(2).Cells(0).Controls(1), GridView)
gv.DataSource = ds
gv.DataMember = "Results"
gv.DataBind()

End Sub

It wouldn't be a real SharePoint application if it didn't support some level of customization. For my example, the category TextBox is supported by a customizable category property that manages an internal field called _category:

Private _category As String

<Personalizable(PersonalizationScope.User)> _
   <WebBrowsable(True)> _
   <WebDisplayName("Movie category")> _
   <System.ComponentModel.Category( _
   "Movie Search Settings")> _    
   <WebDescription( _
   "A valid movie category to search within")> 
Public Property Category() As String
  Get
     Return _category
  End Get
  Set(ByVal value As String)
     _category = value
  End Set
End Property

When the SeachCategory TextBox is added to the Table that makes up the control, I initialize the TextBox with the _category field that is set through the personalizable property:

Dim SearchCategory As New TextBox()
SearchCategory.Text = _category
tcCategory.Controls.Add(SearchCategory)

SharePoint will now allow the user to set a value for the Category property by selecting the "Personalize this Page" choice on the "Welcome User" menu at the top of the page to put the page in "personalization mode." Once the user enters a value, SharePoint will ensure that the property is automatically set to that value whenever the user returns to the page.

SharePoint vs. SQL
Is MOSS putting the squeeze on database development?

By Jeffrey Schwartz

It has been well-chronicled how pervasive Microsoft Office SharePoint Server (MOSS) is becoming in the enterprise.

But for some database developers and administrators -- and in certain cases even higher-ups in the IT food chain -- SharePoint's rampant growth is a concern, particularly in organizations where data that belongs in SQL Server is finding its way into MOSS. "You don't have to be a developer to go in there," says Ed Smith, a systems analyst at Tetra Pak International, a global supplier of packaging machines. "You can get two secretaries together, they can figure out what they want to do and they can start putting stuff in there."

This is a common occurrence that can quickly become problematic, particularly in cases where data that requires referential integrity is put into a SharePoint list, says independent consultant and Microsoft MVP Don Demsak, who's observed this trend and a growing demand for SharePoint developers. "SharePoint is very successful because you're removing levels of impedance, and a lot of DBAs hate SharePoint for those same reasons," explains Demsak. "Basically you're storing everything in a BLOB, and you can't relate to object-relational mapping, and you can't do good entity relationships. You can't do relational models because there's all sorts of problems when people try to extend that SharePoint model past where it's supposed to go."

Strengths and Weaknesses
SharePoint is popular for storing and sharing documents and other unstructured content, but when an individual has data based on rows and columns and is trying to join one list to another, "that's not what those tools were made for," Demsak says. "When you need a relational database, you use a relational database -- the way it was supposed to be."

Paul Andrew, Microsoft technical product manager for the SharePoint developer platform says many are already building custom applications on SharePoint that use a mix of SQL Server schema and tables within MOSS. "Of course, each has its own strengths, and each is better suited in different parts of an application," Andrew says.

"Complex data with a deep relational structure doesn't fit well in SharePoint lists," according to John Beasley, a director with U.K.-based Microsoft Gold Certified Partner InfoStrata Solutions Ltd. To get around this, he uses Quest Web Parts for SharePoint, which allows simple relational structures to be simulated in SharePoint lists, as well as allowing developers to keep data in SQL Server while accessing it via SharePoint. InfoStrata is a Quest partner, but there are other third-party tools developers -- such as Bamboo Solutions and CorasWorks Corp. -- that make use of ASP.NET Web Parts Controls to enable the building of customizable pages.

SharePoint, Beasley notes, removes the tedium of re-developing routine facilities, such as security, document management and workspaces. "This massively reduces our time to market," he says in an e-mail. Using these tools "means you get to do all the correct data analysis you're used to, but can still use SharePoint to provide all the front-end facilities it's so good at providing."

Adding Controls
Still, others argue that companies need to understand when to build applications for SQL Server versus SharePoint. "Looking at SharePoint Lists and relational databases, there isn't a comparison," says Graham Sutcliffe, director of technology at RD2 Inc., a Dallas-based design firm.

"They both have their uses. You can't stifle an organizations progression, but you have to put people in charge of its data. Not trusting the data is the same as not trusting the CEO's decisions, because essentially that's what decisions are made upon,' he says, before adding a caution: "One thing you don't want to do is swing the pendulum too far and turn the people responsible for data into a religious organization."

Others are avoiding the problem altogether by putting controls over who's permitted to commit data to MOSS servers. That's the case for the city of Prince George, British Columbia, Canada. "We've locked it down pretty much, so that all they can do is put in content directly," says programmer and analyst Rob Woods. "Nobody else really has the option of doing any of this kind of stuff except for the IT staff."

Jeffrey Schwartz is the news editor for Visual Studio Magazine.

Simple Debugging
At this point, you get the real payoff for the work you've done in setting up SharePoint Extensions and configuring your project: to test and debug your project you just set breakpoints in your code and press F5. When your site displays, you'll need to add your Web Part to a page by selecting, from the Site Actions menu, the Edit Page choice. When the page redisplays in Edit Mode, click on any of the Add Web Parts bars to display the Add a Web Part dialog with your Web Part. After adding the Web Part to your page you'll find that you can debug it as you would any other .NET project type.

The SharePoint Extensions are a real boon for developers creating SharePoint apps. In addition to simplifying the process for creating new Web Part projects, the debugging process is much simpler. Not only does this make life easier for SharePoint developers, it lowers the barrier to entry for ASP.NET developers interested in migrating their skills to the SharePoint arena.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus
Most   Popular
Upcoming Events

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.