The SharePoint Portal Server Object Model

Archived content. No warranty is made as to technical accuracy. Content may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

Published: June 9, 2004

This is a sample chapter from the Microsoft SharePoint Products and Technologies Resource Kit. You can obtain the complete resource kit (ISBN 0-7356-1881-X), which includes a companion CD-ROM, from Microsoft Press.

On This Page

Introduction
The Microsoft.SharePoint.Portal Namespace
Microsoft.SharePoint.Portal.Topology
Microsoft.SharePoint.Portal.UserProfiles
Microsoft.SharePoint.Portal.WebControls
Other Namespaces
Summary

Introduction

The Microsoft Office SharePoint Portal Server object model encompasses a number of namespaces—about 50 in total—that provide a way to manipulate SharePoint Portal Server configuration and information. Because the object model is so large, it cannot possibly be fully covered here; however, this chapter will discuss the most important and frequently used namespaces, classes, and methods. It will provide an overview of these components and provide samples useful for administrators.

Out of the approximately 50 namespaces provided in the SharePoint Portal Server object model, only 16 of them are supported. The remaining namespaces are reserved for Microsoft’s internal use. If you were to go through some of the .aspx pages provided with SharePoint Portal Server, you might notice that the reserved namespaces are frequently used.

This chapter will focus on the SharePoint Portal Server object model from the administrative perspective. It will cover the basics of the object model and provide some code samples that would be of use to administrators. Other general background information would be useful for administrators to know about, should they run into a problem with a Web Part or add-on, but the chapter does not provide in-depth developer information. Developers will get a general understanding of the object model from reading this chapter but should refer to the SharePoint Products and Technologies SDK for an in-depth reference.

The Microsoft.SharePoint.Portal Namespace

All code and references in the SharePoint Portal Server object model stem from the Microsoft.SharePoint.Portal namespace. The definition for this namespace is found in Microsoft.SharePoint.Portal.dll. When creating projects, you will need to reference this file. If you are developing on a computer running SharePoint Portal Server, the file will be registered for you during installation; it can be found in Program Files\Common Files\Microsoft Shared\web server extensions\60\ISAPI. Otherwise, you will need to copy the file to your development machine and explicitly add a reference to it from your project. The Microsoft.SharePoint.Portal.dll file contains the code for most namespaces under Microsoft.SharePoint.Portal. The following namespaces are not included in this assembly:

  • Microsoft.SharePoint.Portal.Admin.Search

  • Microsoft.SharePoint.Portal.SingleSignOn

  • Microsoft.SharePoint.Portal.SingleSignOn.Security

Included in the Microsoft.SharePoint.Portal namespace are two very important classes—PortalApplication and PortalContext. These two classes are the basis for any code written against the SharePoint Portal Server object model. The PortalContext object is extremely important because it is the entry point for using almost every other object in the SharePoint Portal Server object model. The PortalApplication class provides functions that can get a PortalContext object. The following code shows how to get a PortalContext object from an HTTP Context object:

C#
PortalContext context = PortalApplication.GetContext(Context);
VB.NET
Dim Context As PortalContext = PortalApplication.GetContext(Context)

This example shows how the PortalContext will be derived in almost every Web Part that uses the SPS object model. To get a PortalContext object from a console application or Windows Forms application, the Microsoft.SharePoint.Portal.Topology namespace must be used.

Microsoft.SharePoint.Portal.Topology

The Microsoft.SharePoint.Portal.Topology namespace provides functions for interacting with a SharePoint Portal server farm. Using this namespace, you can add servers to a farm, change the configuration database, get a listing of servers in the farm, and in fact build a farm completely through the functions in this namespace. You can also use objects in this namespace to get Microsoft Windows SharePoint Services objects in the Microsoft.SharePoint.Administration namespace. For example, you can get a collection of VirtualServer objects that the farm uses and then perform Windows SharePoint Services operations on those VirtualServer objects to add a Web Part to all virtual servers in the farm.

Another crucial function that the Microsoft.SharePoint.Portal.Topology namespace provides is allowing you to get a PortalContext object from a Console application or a Windows Forms application. For this, you would use the TopologyManager object to get a specific PortalSite object for the portal site you want to connect to. The following code snippet demonstrates how to get a PortalContext object from a console or Windows Forms application:

C#
TopologyManager topology = new TopologyManager();
PortalSite portal = topology.PortalSites[new Uri("https://test-server")];
PortalContext context = PortalApplication.GetContext(portal);
VB.NET
TopologyManager()
Private Portal As PortalSite = topology.PortalSites("https://test-server")
Private context As PortalContext = PortalApplication.GetContext(portal)

It is important to remember that the URI you pass as an indexer in the preceding sample must be the default portal site URL. For example, if you have a portal site available at https://test-server and the URL https://192.168.0.1 also points to that site, you can only use https://test-server in the code example. Otherwise, the code will throw an exception since the object model gets the reference of the site from the database, and only the default URL is stored.

Microsoft.SharePoint.Portal.UserProfiles

The Microsoft.SharePoint.Portal.UserProfiles namespace is one of the most useful namespaces for Windows Forms and Console applications. It is often used to perform administrative functions. For example, if you do not have Active Directory to import user profiles from, you could use the namespace to import user profiles from any other directory service. You could also pre-create My Sites, otherwise known as Personal Sites, for all users with this namespace so that the server does not have a load spike in production when a user clicks to create a My Site. Creating My Sites are expensive in terms of processor time because they are the same as creating a new Site collection, so it can be beneficial to expend the processor time to create these before the servers go into production.

With this namespace, you can also work with a user’s profile and My Site. You can add properties to the profile, add links to all users’ My Sites, or create reports to see how many users are using their My Site. This namespace provides excellent functionality for administrative functions. Because this namespace provides administrative functions, several code samples will be provided in this section for administrators, whereas other sections might provide just a description of the namespaces.

The following code snippet demonstrates how to import user profiles from a text file. It assumes that each property is delimited by a colon (:) character. Although this is a simple example, it can easily be modified to provide user profile imports for any other type of directory service, be it a database, a Lightweight Directory Access Protocol (LDAP) service, or a corporate directory.

C#
public static void Import (string filename)
{
TopologyManager topology = new TopologyManager();
   PortalSite portal = topology.PortalSites[new Uri("https://test-server")];
   PortalContext context = PortalApplication.GetContext(portal);
   //initialize user profile config manager object
   UserProfileManager profileManager = new UserProfileManager(context);
   //Open Text File containing user information
   System.IO.FileInfo file = new FileInfo(filename);
   System.IO.StreamReader fs = file.OpenText();
   string read;
   while ((read = fs.ReadLine()) != null)
   {
          //parse line
          string[] userInfo = read.Split(":".ToCharArray());
          //create user profile if it doesn't exist
         string userAccount = userInfo[0];
         if (!profileManager.UserExists(userAccount))
               profileManager.CreateUserProfile(userAccount);
         //Get the userprofile so it can be changed
         UserProfile userProfile = profileManager.GetUserProfile(userAccount);
         // Set users Preferred name to their first + last name.
         userProfile["PreferredName"] = userInfo[2] + " " + userInfo[1];
         userProfile["WorkEmail"] = userInfo[0] + "@domain.com";
         userProfile.Commit();
   }
fs.Close();
}
VB.NET
Public Shared Sub Import(filename As String)
         Dim topology As New TopologyManager()
         Dim portal As PortalSite = topology.PortalSites(New Uri("https://test-server"))
         Dim context As PortalContext = PortalApplication.GetContext(portal)
         
         'initialize user profile config manager object
         Dim profileManager As New UserProfileManager(context)
         
         'Open Text File containing user information
         Dim file = New FileInfo(filename)
         Dim fs As System.IO.StreamReader = file.OpenText()
         Dim read As String
         read = fs.ReadLine()
         While Not (read Is Nothing)
            'parse line
            Dim userInfo As String() = read.Split(":".ToCharArray())
            'create user profile if it doesn't exist
            Dim userAccount As String = userInfo(0)
            If Not profileManager.UserExists(userAccount) Then
               profileManager.CreateUserProfile(userAccount)
            End If 'Get the userprofile so it can be changed
            Dim userProfile As UserProfile = profileManager.GetUserProfile(userAccount)
            ' Set users Preferred name to their first + last name.
            userProfile("PreferredName") = userInfo(2) + " " + userInfo(1)
            userProfile("WorkEmail") = userInfo(0) + "@domain.com"
            userProfile.Commit()
            read = fs.ReadLine()
         End While
         fs.Close()
      End Sub

The next example demonstrates how to add the corporate Web site URL to every user’s Links Web Part. This Web Part is shown on the users’ My Site. You can use this code to add any links that you deem necessary for all users. The sample code is a function that adds the passed URL and title to the “Corporate” category. With modifications, you could also use the code to add certain links to specific sets of users.

C#
public static void Add(string url, string title, bool IsPublic)
{
   TopologyManager topology = new TopologyManager();
   PortalSite portal = topology.PortalSites[new Uri("https://test-server")];
   PortalContext context = PortalApplication.GetContext(portal);
   //initialize user profile config manager object
   UserProfileManager profileManager = new UserProfileManager(context);
   foreach (UserProfile profile in profileManager)
   {
         profile.QuickLinks.Add(title, url, "Corporate", IsPublic);
   }
}
VB.NET
Public Shared Sub Add(url As String, title As String, IsPublic As Boolean)
         Dim topology As New TopologyManager()
         Dim portal As PortalSite = topology.PortalSites(New Uri("https://test-server"))
         Dim context As PortalContext = PortalApplication.GetContext(portal)
         
         'initialize user profile config manager object
         Dim profileManager As New UserProfileManager(context)
         
         Dim profile As UserProfile
         For Each profile In  profileManager
            profile.QuickLinks.Add(title, url, "Corporate", IsPublic)
         Next profile
      End Sub

The next example shows how to create My Sites for all users in the profile database in one shot. It is often useful to create sites for all users before the SharePoint farm goes live to save the performance hit of creating the site during peak times.

C#
public static void Create()
{
   //Connect to the portal and get the portal context.
   TopologyManager topology = new TopologyManager();
   PortalSite portal = topology.PortalSites[new Uri("https://test-server")];
   PortalContext context = PortalApplication.GetContext(portal);
   //initialize user profile config manager object
   UserProfileManager profileManager = new UserProfileManager(context);
   foreach (UserProfile profile in profileManager)
   {
Console.Write("Creating a Personal Site for " + profile["PreferredName"] + "..." );
         try
         {
                profile.CreatePersonalSite();
                Console.Write("Success!\n");
         }
         catch (PersonalSiteExistsException)
         {
                Console.Write("Site already exists!\n");
         }
         catch
         {
                // Write code to Log or Display Error
         }
}
VB.NET
Public Class CreateProfiles
        Public Shared Sub Create()
            'Connect to the portal and get the portal context.
            Dim topology As New TopologyManager
            Dim portal As PortalSite = topology.PortalSites(New Uri("https://test-server"))
            Dim context As PortalContext = PortalApplication.GetContext(portal)
            'initialize user profile config manager object
            Dim profileManager As New UserProfileManager(context)
            Dim profile As UserProfile
            For Each profile In profileManager
                Console.Write(("Creating a Personal Site for _
" + profile("PreferredName") + "..."))
                Try
                    profile.CreatePersonalSite()
                    Console.Write("Success!" + ControlChars.Lf)
                Catch
                    Console.Write("Site Already Exists!" + ControlChars.Lf)
                End Try
            Next profile
        End Sub

This final example will create a report which displays all users in the profile database and the URL of their My Site. It will display “None” for the URL if the user does not have a My Site. It will also display the total number of users who have already created a My Site. This report could easily be modified to calculate the size of each user’s My Site and the total size of all My Sites, among other useful information.

C#
public static void Report()
{
   int usersWithProfiles = 0, usersWithoutProfiles = 0;
   //Connect to the portal and get the portal context.
   TopologyManager topology = new TopologyManager();
   PortalSite portal = topology.PortalSites[new Uri("https://test-server")];
   PortalContext context = PortalApplication.GetContext(portal);
   //initialize user profile config manager object
   UserProfileManager profileManager = new UserProfileManager(context);
   foreach (UserProfile profile in profileManager)
   {
         Microsoft.SharePoint.SPSite personalSite = profile.PersonalSite;
         if (personalSite == null)
         {
                Console.WriteLine(profile["PreferredName"] + " : " + "NONE");
                usersWithoutProfiles++;
         }
         else
         {
Console.WriteLine(profile["PreferredName"] + " : " + personalSite.Url);
                usersWithProfiles++;
         }
    }
    Console.WriteLine("Users with Personal Site: " + usersWithProfiles.ToString());
Console.WriteLine("Users without Personal Sites: " + usersWithoutProfiles.ToString());
}
VB.NET
Public Shared Sub Report()
   Dim usersWithProfiles As Integer = 0
   Dim usersWithoutProfiles As Integer = 0
   'Connect to the portal and get the portal context.
   Dim topology As New TopologyManager()
   Dim portal As PortalSite = topology.PortalSites(New Uri("https://test-server"))
   Dim context As PortalContext = PortalApplication.GetContext(portal)
   'initialize user profile config manager object
   Dim profileManager As New UserProfileManager(context)
   Dim profile As UserProfile
   For Each profile In  profileManager
      Dim personalSite As Microsoft.SharePoint.SPSite = profile.PersonalSite
      If personalSite Is Nothing Then
         Console.WriteLine((profile("PreferredName") + " : " + "NONE"))
         usersWithoutProfiles += 1
      Else
         Console.WriteLine((profile("PreferredName") + " : " + personalSite.Url))
         usersWithProfiles += 1
      End If
   Next profile
   Console.WriteLine(("Users with Personal Site: " + usersWithProfiles.ToString()))
   Console.WriteLine(("Users without Personal Sites: " + usersWithoutProfiles.ToString()))
End Sub

Microsoft.SharePoint.Portal.WebControls

The Microsoft.SharePoint.Portal.WebControls namespace provides several base classes for Web Parts and for interacting exclusively with a portal site. You would not use this namespace from a Console or Windows Forms application because it can only be used from Microsoft ASP.NET. The classes in this namespace are incredibly useful because they take a significant amount of work out of developing repeatedly used functions such as a cacheable Web Part. Table 34-1 provides a description of each of the classes in this namespace.

Table 34-1. Description of Classes in the Microsoft.SharePoint.Portal.WebControls Namespace

Class Name

Description

AudiencePicker

This class provides the same graphical audience picker that is used when targeting content to particular audiences.

BaseAreaWebPart

This class is an inheritable base class that acts like an area. It creates a Web Part that is cacheable, increasing its performance. The Web Parts in the default areas inherit from this Web Part.

BreadCrumbTrail

This class provides a hierarchical view of where the user is in relation to other areas. It will show the parent area and subareas.

CategoryNavigationWebPart

This Web Part implements the top horizontal navigation bar for the portal site and the side navigation bar.

CacheableWebPart

This class provides a base class for a Web Part that implements output caching. Output caching is important to achieve high performance for Web Parts that do not change frequently.

CategoryPicker

This class provides a graphical category hierarchy. It is very similar to the Portal Site Map, provided with SharePoint Portal Server, allowing you to see a list of areas.

HtmlMenu

This class implements an HTML menu much like the drop-down menu SharePoint sites use in many lists.

HtmlMenuButton

This class implements the drop-down button that will display an HtmlMenu class when clicked on.

HtmlMenuItem

This class represents a particular item on an HtmlMenu class.

SearchBox

This class implements a text box and the search functionality behind that box. If you want to develop a more advanced search, this class would be the starting point.

SearchResults

This class implements the SharePoint Portal Server Search Results Web Part. If you want to develop a more advanced search results part, this class would be the starting point.

TextEditor

This class implements the rich text editor control used throughout SharePoint sites.

Other Namespaces

The SharePoint Portal Server object model provides several other namespaces. These namespaces are much less frequently used than the previously discussed namespaces. A short discussion of these namespaces will be provided in this section. For more information on these Namespaces, please refer to the “Reference” section of the SharePoint Products and Technologies SDK.

Microsoft.SharePoint.Portal.Admin.Search.

  • This namespace provides functions for interacting with the search catalogs. You can manage the catalogs by adding or removing content sources, forcing propagation of the catalogs, and forcing a type of crawl (Full, Incremental, and so on) on a specific search catalog. This namespace, however, does not let you work with individual content sources, only full search catalogs, so you cannot crawl a particular content source directly using the functions, only a particular catalog, such as Portal_Content.

Microsoft.SharePoint.Portal.Search.

  • The Microsoft.SharePoint.Portal.Search namespace provides only one single class—QueryProvider. With this class, you can call the search service. Although this class does provide the search ability, it is better to use the Search Web service. The Search Web service is more robust and easier to use, plus the code that calls the QueryProvider class can only be run on the local server running SharePoint Portal Server.

Microsoft.SharePoint.Portal.Search.ObjectModel.

  • This namespace provides classes and functions for manipulating search scopes. With the namespace, you can add, remove, move, update, and list the search scopes on a particular portal site.

Microsoft.SharePoint.Portal.Search.WebQueryService.

  • This namespace implements the Search Web service, the SPSQueryService class. Using the Search Web service explicitly instead of going through this class is generally easier and allows your code to be run from remote machines.

Microsoft.SharePoint.Portal.SingleSignOn.

  • This namespace contains classes and functions required for accessing the Single Sign-On service provided with SharePoint Portal Server. You can add different applications, set up the credentials systems, and request credentials from this namespace.

Microsoft.SharePoint.Portal.SingleSignOn.Security.

  • This namespace contains classes for managing access to the Single Sign-On credentials.

Microsoft.SharePoint.Portal.Security.

  • This namespace contains functions for working with security in the portal sites. It contains the classes for users, roles, and permissions. If you want to use code to create roles or add users to roles, you would use this namespace.

Microsoft.SharePoint.Portal.Audiences.

  • This namespace contains functions for working with SharePoint Portal Server audiences. You can get users in particular audiences, create audiences, and rebuild audiences with this namespace. You can use the functions in this namespace to build a Web Part that tailors its information based on audience membership, giving you more flexibility than just targeting a Web Part.

Microsoft.SharePoint.Portal.Alerts.

  • The Microsoft.SharePoint.Portal.Alerts namespace and its subnamespaces, Microsoft.SharePoint.Portal.Alerts.Types and Microsoft.SharePoint.Portal.Alerts.NotificationTypes, allow you to work with alerts. You can change alerts, remove alerts, add alerts, and enable/disable alerts programmatically.

Microsoft.SharePoint.Portal.SiteData.

  • The Microsoft.SharePoint.Portal .SiteData namespace provides functions for working with areas. It contains the code for creating areas, removing areas, applying certain area templates, and associating keywords with areas. With this namespace, you can also associate audiences with areas and work with area listings. If you want to manipulate areas through code, you would work with this namespace. For most administrators, it is faster and easier to perform the functions exposed here through the SharePoint Portal Server user interface or Microsoft Office FrontPage 2003.

Summary

This chapter provided a general overview of the SharePoint Portal Server object model. It also provided sample code snippets that would be useful to administrators for performing administrative functions. If you want to do more development work, it is strongly recommended that you download the SharePoint Products and Technologies SDK from the Microsoft Developer Network (MSDN) website. The SDK provides much more in-depth information into SharePoint Portal Server development.