WEBPARTS Office SharePoint Server Gurus by mikeholy

VIEWS: 448 PAGES: 183

									Web Parts Overview

Web Parts are server-side controls that run inside the context of special pages (that is, Web
Part Pages) within an ASP.NET application or a Windows SharePoint Services site. They are
the "building blocks" of pages in Windows SharePoint Services. Windows SharePoint
Services includes built-in Web Parts that you can use as soon as you have installed the
product. In addition, you can build your own Web Parts and deploy them to the server.
Because of the popularity of Web Parts in Windows SharePoint Services 2.0, support for a
new Web Part infrastructure for ASP.NET 2.0 was added to Windows SharePoint Services
3.0. The new Web Part infrastructure is similar yet distinct from the Web Part infrastructure
in Windows SharePoint Services 2.0.

Types of Web Parts in Windows SharePoint Services 3.0
There are now two different Web Part styles in Windows SharePoint Services 3.0. Both are
supported, but the ASP.NET 2.0 Web Part is the recommended style for your new projects.
      SharePoint-based Web Parts — The older style Web Parts have a dependency on
       Microsoft.SharePoint.dll and must inherit from the WebPart base class in
       the Microsoft.SharePoint.WebPartPages namespace. These Web Parts can only be
       used in SharePoint Web sites. Yet in Windows SharePoint Services 3.0, the
       Microsoft.SharePoint.dll was changed so that Web Parts written in the older style
       would be compatible with the Windows SharePoint Services 3.0 runtime.

          Note:

        For more information about when to derive from the Windows SharePoint Services
        WebPart Class, see the section "When to Derive from the Windows SharePoint
        Services WebPart Class" in the Web Part Infrastructure in Windows SharePoint
        Services topic.
      ASP.NET 2.0 Web Parts — These Web Parts are built on top of the ASP.NET Web
       Part infrastructure. The newer ASP.NET-style Web Parts have a dependency
       on System.Web.dll and must inherit from a different base class named WebPart in
       the System.Web.UI.WebControls.WebParts namespace. These Web Parts can be
       used in Windows SharePoint Services applications whether Windows SharePoint
       Services is involved or not, making them highly reusable.

          Note:

        If you are creating your Web Part specifically for a SharePoint site, and it will
        consume the Windows SharePoint Services object model, you can derive from the
        ASP.NET System.Web.UI.WebControls.WebParts.WebPart base class and add
        a reference to the SharePoint object model in your project.


More about ASP.NET 2.0 Web Parts
The Windows SharePoint Services 3.0 Web Part infrastructure is built on top of a control
named SPWebPartManager that is derived from the ASP.NET
2.0WebPartManager control. The SPWebPartManager control overrides the standard
behavior of the WebPartManager control to persist Web Part data inside the Windows
SharePoint Services content database instead of in the ASP.NET services database. In most
cases, you do not have to worry about dealing directly with
the SPWebPartManager control because the one and only required instance is already
defined in default.master. When you create a content page that links todefault.master,
the SPWebPartManager control is already there.

  Note:

Web Part zones for a Web Part Page in Windows SharePoint Services 3.0 should be created
by using the WebPartZone control defined inside
theMicrosoft.SharePoint.WebPartPages namespace, not by using the
standard WebPartZone control from ASP.NET 2.0.
When you create a Web Part Page for a standard ASP.NET 2.0 application, you need to add
logic that interacts with the WebPartManager control to manage the Web Part display
mode, and generally you also need to explicitly add editor parts and catalog parts to the
page along with the HTML layout to accommodate them. Fortunately, you do not have to
perform these changes when creating content pages for a Windows SharePoint Services 3.0
site. Instead, you inherit from theWebPartPage class that is defined inside
the Microsoft.SharePoint.WebPartPages namespace and it does all the work behind the
scenes for you.
For more information about creating ASP.NET Web Parts, see ASP.NET AJAX in Windows
SharePoint Services and Web Parts Control Set Overview in the ASP.NET documentation.

Custom Web Parts
Custom Web Parts provide developers with a method to create user interface elements that
support both customization and personalization. A site owner or a site member with the
appropriate permissions can customize Web Part Pages by using a browser or by using
Microsoft Office SharePoint Designer 2007 to add, reconfigure, or remove a Web Part.
In Windows SharePoint Services 2.0, developers could extend SharePoint sites by creating
custom Web Parts, to add the extra dimensions of user customization and personalization.
The term customization implies that changes are seen by all site members. Individual users
can further personalize Web Part Pages by adding, reconfiguring, and removing Web Parts.
The term personalization implies that these changes will be seen only by the user that made
them. Developing custom Web Parts provides an easy and powerful way to extend Windows
SharePoint Services sites.
Because the Windows SharePoint Services Web Part infrastructure is now built on top of the
ASP.NET 2.0 Web Parts control set, you can reuse your knowledge of ASP.NET programming
to create quick and robust custom Web Parts.
Following are some ways in which you can benefit from and use custom Web Parts:
      Creating custom properties you can display and modify in the user interface.
      Improving performance and scalability. A compiled custom Web Part runs faster than
       a script.
      Implementing proprietary code without disclosing the source code.
      Securing and controlling access to content within the Web Part. Built-in Web Parts
       allow any users with appropriate permissions to change content and alter Web Part
       functionality. With a custom Web Part, you can determine the content or properties
       to display to users, regardless of their permissions.
      Making your Web Part connectable, allowing Web Parts to provide or access data
       from other connectable Web Parts.
      Interacting with the object models that are exposed in Windows SharePoint Services.
       For example, you can create a custom Web Part to save documents to a Windows
       SharePoint Services document library.
      Controlling the cache for the Web Part by using built-in cache tools. For example,
       you can use these tools to specify when to read, write, or invalidate the Web Part
       cache.
      Benefiting from a rich development environment with debugging features that are
       provided by tools such as Microsoft Visual Studio 2005.
      Creating a base class for other Web Parts to extend. For example, to create a
       collection of Web Parts with similar features and functionality, create a custom base
       class from which multiple Web Parts can inherit. This reduces the overall cost of
       developing and testing subsequent Web Parts.
      Controlling the implementation of the Web Part. For example, you can write a
       custom server-side Web Part that connects to a back-end database, or you can
       create a Web Part that is compatible with a broader range of Web browsers.
Web Part Infrastructure in Windows SharePoint Services

Web Parts in Windows SharePoint Services 3.0 are based on the Microsoft ASP.NET 2.0 Web
Part infrastructure. To create Web Parts for applications targeting Windows SharePoint
Services, you should build custom Web Parts on top of the ASP.NET Web Part infrastructure.
However, in a very few cases, you may have to create Web Parts that support Windows
SharePoint Services features that are not available in the ASP.NET Web Part infrastructure.
For more information, see "When to Derive from the Windows SharePoint Services Class" in
this topic.

Web Part Inheritance Model in Windows SharePoint Services
The Windows SharePoint Services 3.0 WebPart class has been rebased to inherit from the
Microsoft ASP.NET 2.0 WebPart class, providing a compatibility layer to ensure that Web
Parts written for Windows SharePoint Services 2.0 work in Windows SharePoint Services 3.0
without modification. It exists primarily for the purpose of backward compatibility, and
secondarily, to provide a small set of features that are not available in the
ASP.NET WebPart class.

  Note:

The Windows SharePoint Services WebPart class is part of the Web Part infrastructure
that was designed specifically for Windows SharePoint Services 2.0 sites.
The following diagram demonstrates the inheritance hierarchy for the Windows SharePoint
Services WebPart class.
Core Controls for Web Part Pages
The following section describes core controls for Web Part Pages for both SharePoint-based
Web Parts and ASP.NET 2.0 Web Parts.
SharePoint-based Web Parts
The Windows SharePoint Services 3.0 Web Part infrastructure uses many of the controls in
the ASP.NET 2.0 Web Part control set, as well as introduces several of its own controls that
inherit from base classes supplied by the ASP.NET 2.0 Web Parts control set.
For example, Web Part Pages for a Windows SharePoint Services site do not use the
standard ASP.NET WebPartManager. Instead, they use the Windows SharePoint Services-
specific SPWebPartManager that inherits from the ASP.NET WebPartManager. The
following figure shows the WebPartManager class inheritance.




Similarly, Web Part Pages for a Windows SharePoint Services site also use Windows
SharePoint Services-specific WebPartZone that inherits from the ASP.NETWebPartZone.
ASP.NET Web Parts
The ASP.NET Web Part infrastructure is based on a WebPartManager class that manages
the lifetime of Web Part instances at run time.
Each ASP.NET page that uses Web Part controls must contain:
      Exactly one WebPartManager object that tracks which Web Parts have been added
       to each particular zone, and stores and retrieves data about how each Web Part has
       been customized and personalized.
      One or more WebPartZone objects, into which Web Parts are placed.
To run Web Parts in an ASP.NET 2.0 application, you must create an .aspx page that
contains exactly one instance of the WebPartManager control and one or
more WebPartZone controls. The WebPartManager is responsible for serializing Web
Part-related data as well as storing and retrieving it from the services database.
The .aspx page serving as a Web Part Page can contain editor parts that allow users to
customize and personalize persistent Web Part properties. Web Part Pages can also contain
catalog parts that let users add new Web Parts into zones. Windows SharePoint Services 3.0
does the work to add the catalog and editor parts for you, so that you do not need to
explicitly do this in a Web page designer. The following figure shows
the WebPartZone class inheritance.




The SPWebPartManager and WebPartZone controls manage the serialization of data
associated with Web Parts into the appropriate Windows SharePoint Services content
database. To be able to persist data, your ASP.NET Web Parts must be placed on a page
with these two controls.
Because these Windows SharePoint Services-specific controls are required on pages that
contain Web Parts, you cannot simply copy your ASP.NET page into a Windows SharePoint
Services site. To move ASP .NET Web Parts from an ASP.NET application to a Windows
SharePoint Services application, you should export them from ASP .NET and import them
into a Windows SharePoint Services site.

  Note:

The default master page that is provided with the Windows SharePoint Services technology
includes an instance of SPWebPartManager, so this control is automatically included with
all of your Windows SharePoint Services content pages.


Differences in Web Part Behavior between Windows SharePoint Services 2.0 and
Windows SharePoint Services 3.0
The Windows SharePoint Services team has gone to great lengths to ensure that your
Windows SharePoint Services 2.0 Web Parts work seamlessly in Windows SharePoint
Services 3.0. There are a small number of cases, however, in which your Windows
SharePoint Services 2.0 Web Parts may behave differently. These include:
      In Windows SharePoint Services 2.0, Web Parts were managed by zones; however,
       in Windows SharePoint Services 3.0, Web Parts are managed by
       theSPWebPartManager. If you use a Web Part's Parent property, you get a
       reference to SPWebPartManager rather than a reference to the
       containingWebPartZone.
       In Windows SharePoint Services 2.0, both provider and consumer Web Parts can
        have multiple connections. In Windows SharePoint Services 3.0, the provider part
        can have multiple connections but the consumer part can have only one connection
        (same as that of ASP.NET 2.0 Web Part controls). You can replicate Windows
        SharePoint Services 2.0 behavior, however, by specifying UnlimitedConnections on
        the consumer Web Part.

When to Derive from the Windows SharePoint Services WebPart Class
In a very few cases, you may have to create Web Parts that support Windows SharePoint
Services features that are not available in the ASP.NET Web Part infrastructure. In these
cases, you can create a class that inherits from the Windows SharePoint
Services WebPart base class. Web Parts such as these are known as SharePoint-based Web
Parts and can only be used in SharePoint sites.
Following is the list of features provided exclusively by the Windows SharePoint
Services WebPart class:
       Cross page connections
       Connections between Web Parts that are outside of a Web Part zone
       Client-side connections (Web Part Page Services Component)
       A data caching infrastructure that allows caching to the content database
Another reason you may consider deriving from the WebPart class is related to creating
new versions of your Web Parts. If your original Web Part derived from theWebPart class,
and you want to upgrade instances of that Web Part to a new version, then the new version
of the Web Part should also derive from the SharePointWebPart class.



Developing Web Parts in Windows SharePoint Services
This section of the Windows SharePoint Services Software Development Kit (SDK) provides configuration
information, security guidance, and programming examples that introduce you to programming Web Parts
for Windows SharePoint Services 3.0.

In This Section
Securing Web Parts in Windows SharePoint Services

Deploying Web Parts in Windows SharePoint Services

Walkthrough: Creating a Basic Web Part

Walkthrough: Creating a Basic SharePoint Web Part

Walkthrough: Creating Connectable Web Parts in Windows SharePoint Services




Securing Web Parts in Windows SharePoint Services
Web Parts in Windows SharePoint Services provide a powerful way for users to interact with other systems.
Windows SharePoint Services has built-in security settings to restrict the access that a Web Part has to
underlying systems. A developer can create custom security policy files to give a Web Part greater access to
the underlying system. This topic introduces the built-in settings, an overview of a Code Access Security
(CAS) policy, and how to include a custom Code Access Security policy in a Windows SharePoint Services
solution.

Code Access Security
Code Access Security is a resource-constraints model that limits the access that an assembly has to
protected system resources and operations. Windows SharePoint Services has built-in security policies built
on top of the built-in security policies of ASP.NET. By default, Windows SharePoint Services uses a minimal
set of permissions in order to protect the server and underlying infrastructure from malicious code.

If your Web Part needs greater access than what is provided in the minimal settings, there are a number of
ways to increase the permissions of your Web Part, but only one is recommended. The recommended
practice is to create a custom Code Access Security policy for your Web Part. The second method is to
increase the overall trust level of the server farm in the web.config file. This is a security risk and is not
recommended. For more information about deployment, see Deploying Web Parts in Windows SharePoint
Services.

Built-In Security Settings
Windows SharePoint Services is a partial trust application by default. Windows SharePoint Services can use
the ASP.NET built-in trust levels but defines two trust levels of its own:

       WSS_Minimal

       WSS_Medium

The trust levels extend the Minimal and Medium trust levels of ASP.NET for use withWindows SharePoint
Services. Trust levels are defined in policy files found on the file system of each web server.

Important By default, the built-in Windows SharePoint Services policy files,
named wss_minimaltrust.config and wss_mediumtrust.config, are found
in %SYSTEMDRIVE%\Program Files\Common Files\Microsoft Shared\web server
extensions\12\config.
By default, Windows SharePoint Services applies the WSS_Minimal trust level for the virtual server. This
trust level grants all of the permissions in the ASP.NETMinimal trust as well as Web Part connections.
The WSS_Minimal policy restricts the Web Part from accessing many resources for advanced operations,
including the object model and file operations.

The WSS_Medium trust level grants greater access to the environment. Also, WSS_Medium allows access
to the Windows SharePoint Services object model and file operations including read, write, append, and path
discovery. This trust level also allows access to environment variables.

The following table outlines the specific permissions granted with
the WSS_Minimal and WSS_Medium policy files in the ASP.NET 2.0 environment.


                                                                                          WSS_Minimal
Permission                           WSS_Medium Trust Level                               Trust Level

 AspNetHostingPermission             Medium                                               Minimal

 DirectoryServicesPermission         None                                                 None

 DnsPermission                       Unrestricted                                         None

 EnvironmentPermission               Read: TEMP, TMP, OS, USERNAME,                       None
                                     COMPUTERNAME

 EventLogPermission                  None                                                 None

 FileIOPermission                    Read, Write, Append, PathDiscovery:Application       None
                                     Directory

 IsolatedStoragePermission           AssemblyIsolationByUser, Unrestricted                None
                                     UserQuota

 MessageQueuePermission              None                                                None

 OleDBPermission                     None                                                None

 Performance Counters                None                                                None

 PrintingPermission                  Default printing                                    None

 ReflectionPermission                None                                                None

 RegistryPermission                  None                                                None

 SecurityPermission                  Execution, Assertion, ControlPrincipal,             Execution
                                     ControlThread, RemotingConfiguration

 ServiceControllerPermission         None                                                None

 SharePointPermission                ObjectModel = true                                  None
 (Microsoft.SharePoint.Security)

 SocketPermission                    None                                                None

 SqlClientPermission                 AllowBlankPassword=false                            None

 WebPermission                       Connect to origin host (if configured)              None

   Note:

 For more information about Code Access Security, see Using Code Access Security with
 ASP.NET and also Security Guidelines for .NET Framework 2.0.


Creating a Code Access Security Policy
Windows SharePoint Services 3.0 added the ability to deploy a CAS policy file with a solution. This feature
makes it easier for you to create custom permissions for your Web Parts and allows Windows SharePoint
Services to handle the deployment.

The following code example shows the basic structure of a CAS policy file in a Windows SharePoint Services
solution package.

Xml
<CodeAccessSecurity>
      <PolicyItem>
        <PermissionSet class="NamedPermissionSet" version="1"
         Description="Permission set for custom test WebParts">
           <IPermission class="AspNetHostingPermission" version="1"
           Level="Minimal" />
           <IPermission class="SecurityPermission" version="1"
           Flags="Execution" />
           <IPermission
           class="Microsoft.SharePoint.Security.SharePointPermission,
           Microsoft.SharePoint.Security, version=11.0.0.0,
           Culture=neutral, PublicKeyToken=71e9bce111e9429c" version="1"
           ObjectModel="True" />
           <IPermission class="System.Net.WebPermission, System,
           version=1.0.5000.0, Culture=neutral,
           PublicKeyToken=b77a5c561934e089" version="1">
              <ConnectAccess>
                <URI uri="https?://.*" />
              </ConnectAccess>
           </IPermission>
           <IPermission
           class="System.Security.Permissions.SecurityPermission,
           mscorlib, version=1.0.5000.0, Culture=neutral,
           PublicKeyToken=b77a5c561934e089" version="1"
           Flags="ControlThread, UnmanagedCode" />
           <IPermission
           class="System.Security.Permissions.EnvironmentPermission,
           mscorlib, version=1.0.5000.0, Culture=neutral,
           PublicKeyToken=b77a5c561934e089" version="1" Read="UserName" />
        </PermissionSet>
        <Assemblies>
          <Assembly PublicKeyBlob=PublicKeyBlob />
        </Assemblies>
    </PolicyItem>
</CodeAccessSecurity>
The list below includes some general guidelines that apply when you use a <CodeAccessSecurity> section in
your solution manifest.

        There can only be one <CodeAccessSecurity> per solution manifest.

        There can be multiple <PolicyItem> nodes.

        Every <PolicyItem> node can only contain one <PermissionSet> node.

        Every <PolicyItem> node can only contain one <Assemblies> node.

        Each <PermissionSet> node can contain multiple <IPermission> nodes.

        There can be multiple <Assembly> nodes under the <Assemblies> node.

For more information about the schema of the <CodeAccessSecurity> area, see CodeAccessSecurity
Element.
When you deploy your assembly using a custom CAS policy, you must use the -allowCasPolicies option
with the stsadm.exe utility. The command is as follows:stsadm -o deploySolution -name <insert
name> -allowCasPolicies

Deploying Web Parts in Windows SharePoint Services
Windows SharePoint Services requires that a Web Part be deployed in the Web Part gallery before it can be
added to the page. This section describes differences between the bin folder and the Global Assembly Cache
(GAC), security permissions considerations, how to strong name an assembly for deployment, how to create
a SafeControl entry, and finally, how to create a Web Part definition file to deploy the Web Part.

Deployment Considerations
There are two primary locations within a SharePoint site where you can deploy a Web Part assembly.

       bin directory — The bin directory is a folder stored in your Web application root directory. The
        location of this folder is determined when the Web site is created in Internet Information Services
        (IIS). In Windows SharePoint Services, this can happen either through the SharePoint 3.0 Central
        Administration site, or by manually creating a new Web site in IIS manager.


            Important:

         If a bin directory does not exist you must add one manually. Do not store Web Parts in the
         local _app_bin directory, which is reserved for use by Microsoft.
         For more information, see How to: Find the Web Application Root.
       global assembly cache — A global location where signed assemblies can be deployed. The global
        assembly cache enables you to share assemblies across numerous applications. The global assembly
        cache is automatically installed with the .NET runtime. Components are typically stored
        in C:\WINNT\Assembly.

Each location has advantages and disadvantages, as described in the following table.


Deployment
Location         Advantages                                            Disadvantages

 bin directory   Assemblies run with partial trust, by default.        In order for the Web Part to run in
                 Code that runs from this directory has a low level    multiple Web applications, you must
                 of code access security (CAS) permissions.            deploy it to the global assembly cache.
                 Because administrators must explicitly raise
                 permissions that have been granted to a Web
                 Part so it can function properly, they often prefer
                 that assemblies run in the bin directory with a
                 known set of required CAS permissions.
                 A bin directory is specific to a Web application.
                 This makes it possible to isolate code to a
                 particular Web application.

 global          Assemblies run with full trust by default. They       Generally no CAS restrictions on code
 assembly        are globally installed, so they will work in any      installed to the global assembly cache;
 cache           Web application. The global assembly cache can        therefore, you lose the defense-in-
                 contain multiple versions of the same assembly.       depth security benefit.
                                                                       Also, an assembly deployed to the GAC
                                                                       is cached, so if the assembly is rebuilt,
                                                                       it is not automatically updated on the
                                                                       SharePoint site. You must force
                                                                       Windows SharePoint Services to reload
                                                                       the assembly by resetting Internet
                                                                       Information Services (IIS).
Security Permissions Considerations
By default, code access security permissions for the bin directory are low; only pure execution is allowed. In
most cases you need to elevate these permissions to make your assembly run correctly, for example, if your
Web Part requires access to the SharePoint object model.

There are two ways to elevate permissions:

         Recommended method — Create a new trust policy file and point your web.config file at the
          new file. This option is more complicated but it gives you a precise attribution of permissions for
          your Web Parts.

          For more information about trust policy files, see Securing Web Parts in Windows SharePoint
          Services.

         Optional method — Raise the net trust level of the bin directory. In the web.config file in the
          Web application root, there is a tag called <trust> with a default attribute
          of level="WSS_Minimal". You can change this level to WSS_Medium. While this option is
          simpler, it grants arbitrary new permissions that you might not need and is less secure than
          creating a new trust policy file.

Strong Naming a Web Part Assembly
Strong naming uses a private key to digitally sign an assembly. Strong naming also stamps the assembly
with a public key to validate the signature. This technique guards against unauthorized versions of a Web
Part. If the public key fails to validate the digital signature, Windows SharePoint Services will refuse to run
the module.

When deploying a Web Part to the bin, the recommend practice is to strong name the assembly. When
deploying a Web Part to the Global Assembly Cache, the assembly must have a strong name. An assembly
without a strong name is not recommended in Windows SharePoint Services.
To sign an assembly, you use the sn.exe tool that is included with the .NET Framework Software
Development Kit (SDK). For more information about the .NET Framework SDK, see SDKs, Redistributables &
Service Packs. The sn.exe tool is also used to extract the public key that is needed to register your control
as safe in the SafeControls list. For more information about using the sn.exe tool, see Strong Name Tool
(Sn.exe).

Creating a SafeControl Entry
A fundamental assumption of the Windows SharePoint Services technology is that untrusted users can
upload and create ASPX pages within the system that is running Windows SharePoint Services. To prevent
untrusted users from arbitrarily adding server-side code within ASPX pages, Windows SharePoint Services
provides a SafeControls list.

The SafeControls list is a list of approved controls and Web Parts specific to your SharePoint site that you
have designated as safe for invocation on any ASPX page within your site. This list is contained in
the web.config file in your Web application root.

A SafeControl entry is an XML-based declaration of a Web Part that has the following form.

Xml
<SafeControl Assembly="AssemblyNameWithoutDLLExtension,
Version=AssemblyVersionNumber, Culture=neutral,
PublicKeyToken=PublicKeyToken" Namespace="NamespaceOfYourProject"
TypeName="*" Safe="True" />
The SafeControl entry uses the assembly name, namespace, versioning information, and, if it is signed, it
also requires a public key token to verify that the control is safe. If a Web Part assembly is signed, you can
use the Strong Name Tool to retrieve the public key token for use in the SafeControl entry. The following
command will retrieve the public key token for an assembly.
Creating a .Webpart File
A Web Part definition (.webpart) file is a simple XML file that contains property settings for a single Web
Part. To import your Web Part into a Web Part Page, simply upload the .webpart file or add the Web Part
to the Web Part gallery. After uploading the Web Part, you can display the Web Part by dragging it into one
of the zones of the Web Part Page. To display a default name and description for the Web Part after it is
imported, you should include the Title and Description properties. If you want to set other Web Part
properties during import, you can also define them in a .webpart file. A .webpart file takes the following
form.

Xml
<?xml version="1.0" encoding="utf-8" ?>
  <webParts>
        <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
          <metaData>
            <type name="TypeName, Version=VersionNumber, Culture=neutral,
            PublicKeyToken=PublicKeyToken" />
            <importErrorMessage>Cannot import this Web
            Part.</importErrorMessage>
          </metaData>
          <data>
            <properties>
               <property name="Title" type="string">
                    WebPartTitle</property>
               <property name="Description" type="string">
                    WebPartDescription
               </property>
            </properties>
          </data>
        </webPart>
      </webParts>



Walkthrough: Creating a Basic Web Part
This walkthrough provides the steps for creating a basic custom Web Part that can be added to your Web
Part Pages. It is a simple Web Part that allows the user to define a custom message to be displayed inside
the Web Part. This Web Part will derive from the ASP.NET 2.0 Web Part class, which is the recommended
practice for Windows SharePoint Services. Note that this walkthrough describes how to create a Web Part
without the Visual Studio Extensions for Windows SharePoint Services.

For more information about ASP.NET Web Parts, see the following ASP.NET documentation: ASP.NET
QuickStart Tutorials and ASP.NET Web Parts Controls.
   Note:

 You can also develop your Web Parts by using the Visual Studio Extensions for Windows SharePoint
 Services. By using these extensions, you can greatly reduce the work involved in creating and deploying
 your Web Parts. The extensions require development in a server environment, and offer the following
 benefits:
        Automatic generation of your solution package
        Automatic generation of the WebPart XML file
        Ability to deploy Web Parts directly from inside Visual Studio to your Web site
 For guidance on using the extensions or to download extensions for Visual Studio 2005 or Visual Studio
 2008, see
        Windows SharePoint Services 3.0 Tools: Visual Studio 2005 Extensions User Guide, Version 1.1
        Windows SharePoint Services 3.0 Tools: Visual Studio Extensions, Version 1.1
        Windows SharePoint Services 3.0 Tools: Visual Studio Extensions, Version 1.2
 Prerequisites

Windows SharePoint Services 3.0

Visual Studio 2005

 Step 1: Create an ASP.NET Web Part assembly

To create a Web Part, you start by creating a class library project that derives from the WebPart base class.

To create an ASP.NET Web Part Assembly
    1.   Start Visual Studio 2005

    2.   On the File menu, point to New, and then click Project.

    3.   In Project Types, under Visual Basic or C#, select Windows.

    4.   In the Templates pane, select Class Library.

    5.   Type Sample.DisplayMessage as the project name.

 Step 2: Rename the base class and add required namespaces

After you create the project, a blank class file is displayed. You can change the default class name
of Class1 to easily identify your new Web Part. In a class library, only a few namespaces are included. You
must add two required namespaces and references to their assemblies. You must also derive the base class
from WebPart.

To add namespace references and rebase your Web Part
    1.   Rename the default class by selecting Class1 in Solution Explorer, right-click, click Rename, and
         type DisplayMessageWebPart as the file name.

    2.   On the Project menu, click Add Reference.

    3.   In the Add Reference dialog on the .NET tab, select System.Web and click OK.

    4.   In the references area of the class file, add a reference
         to System.Web.UI.WebControls.WebParts and rebase your class to inherit from WebPart, as shown
         in the following code sample.

         C#

         using System;
         using System.Collections.Generic;
         using System.Text;
         using System.Web;
         using System.Web.UI.WebControls.WebParts;


         namespace Sample.DisplayMessage
         {
              public class DisplayMessageWebPart : WebPart
              {
              }
         }

         Visual Basic

         Imports System
         Imports System.Collections.Generic
         Imports System.Text
         Imports System.Web
         Imports System.Web.UI.WebControls.WebParts


         Public Class DisplayMessage
              Inherits WebPart


         End Class
    5.   You have now created a basic structure for the Web Part.

 Step 3: Add a user-customizable Web Part property

After configuring the new class to act as a Web Part, add a customizable property for the Web Part.

The Web Part property determines the text that is rendered inside the Web Part. This is customized on the
basis of the individual user.


   Note:

 For more information about customization and personalization, see Web Parts Personalization.
For Web Parts based on the ASP.NET Web Parts Pages base class, the tags that are used for the
customizable properties are named differently than Web Parts that are based on the WebPart base class.
The following list describes each of those properties:

        The WebBrowsableAttribute class attribute ensures that your custom property renders in the editing
         tool pane in Windows SharePoint Services.

        The WebDescriptionAttribute class attribute displays a tooltip to help guide users when editing your
         custom property.
       The WebDisplayNameAttribute class attribute shows a display name for your custom property.

       The PersonalizableAttribute class attribute determines if changes to your custom property affects all
        users or on a per-user basis.

To create the Web Part property
    1. In the DisplayMessageWebPart file, copy and paste the following code to create a basic
       customizable property.

        C#

        private string customMessage = “Hello, world!”;


        public string DisplayMessage
        {
             get { return customMessage; }
             set { customMessage = value; }
        }

        Visual Basic

        Private customMessage As String = “Hello, world!”


        Public Property DisplayMessage() as String
             Get
                   Return customMessage
             End Get
             Set(ByVal value as String)
                   customMessage = value
             End Set
        End Property
   2.   Then, add the following tags above the public declaration to allow changes on a per-user basis:

        C#

        [WebBrowsable(true),
        WebDescription("Displays a custom message"),
        WebDisplayName("Display Message"),
        Personalizable(PersonalizationScope.User)]

        Visual Basic

        <WebBrowsable(True), _
         WebDescription("Displays a custom message"), _
         WebDisplayName("Display Message"), _
         Personalizable(PersonalizationScope.User)> _

    3.   Now you have created a customizable Web Part property.

 Step 4: Override the Render method and build your Web Part

Now you must add functionality to your Web Part. By overriding the Control.Render Method, you can tell the
Web Part what operations to perform when the page is visited. In this example, the Web Part will render the
user-defined text.

To override the Render method and compile the assembly
    1. In the DisplayMessageWebPart file, copy and paste the following code to override
       the Render method.

         C#

         protected override void Render(System.Web.UI.HtmlTextWriter writer)
         {
              writer.Write(DisplayMessage);
         }

         Visual Basic

         Protected Overrides Sub Render(ByVal writer As
         System.Web.UI.HtmlTextWriter)
              writer.Write(DisplayMessage)
         End Sub

    2.   Compile the solution. Now you have an assembly that contains
         your DisplayMessageWebPart Web Part.

 Step 5: Place your assembly in the bin directory or global assembly cache

Within a SharePoint site, you can deploy a Web Part assembly to one of two locations listed below. Note that
the recommended practice is to deploy assemblies to the bin directory.

        bin directory — The bin directory is a folder stored in your Web application root directory. For
         most installations, this is located in
         the%SYSTEMDRIVE%\inetpub\wwwroot\wss\VirtualDirectories\<port
         number>\bin directory, but if you need more information, see How to: Find the Web Application
         Root.

        Global Assembly Cache (GAC) — The GAC enables you to share assemblies across numerous
         applications. The GAC is automatically installed with the .NET framework runtime. Components are
         typically installed in the %SYSTEMDRIVE%\WINDOWS\Assembly directory.

For more information about choosing the correct deployment location, see Deploying Web Parts in Windows
SharePoint Services.

For the following example, place the assembly in the bin directory.
         Step 6: Add your Web Part to the SafeControls list

         Windows SharePoint Services provides a SafeControls list to prevent users from arbitrarily adding
         server-side code within ASPX pages. The SafeControls list is a list of approved controls and Web
         Parts that are specific to the SharePoint site that you have designated as safe for invocation on any
         ASPX page within your site. This list is contained in the web.config file in your Web application
         root. The local path contains the physical location of the web.config file.


   Note:

 The web.config file is located in the folder where the virtual directory for the Web site is located. This is
 normally c:\inetpub\wwwroot\wss\VirtualDirectories\<port number>\, but your
 administrator may have set up your directory differently and this may not be the location of the file.
 You can find the location of your web.config file with the Internet Information Services (IIS) snap-in.
 The IIS snap-in is an administration tool for IIS that has been integrated with other administrative
 functions. To launch the IIS snap-in and locate the web.config file:
     1. Click Start, point to Programs, point to Administrative Tools, and click Internet Information
         Services (IIS) Manager.
     2. Expand the node that is the name of your computer, and expand the Web Sites item in the tree
     3. Locate the Web site that is running your Windows SharePoint Services installation (often it
         is Default Web Site).
     4. Right-click and select Properties.
     5. Select the Home Directory tab.
To add your Web Part to the SafeControls list
    1. Open the web.config file in the application root.

    2.   In the SafeControls section of your web.config file, add a SafeControls entry for your custom
         assembly in the web.config file as follows.


         Xml

         <SafeControl Assembly="Sample.DisplayMessage, Version=1.0.0.0,
         Culture=neutral, PublicKeyToken=null" Namespace="Sample.DisplayMessage"
         TypeName="DisplayMessageWebPart" Safe="True" />

 Step 7: Add your Web Part to the Web Part gallery

In order to add your Web Part to a Web Part page, you must add it to the gallery.

To add your Web Part to the Web Part Gallery
    1.   Navigate to the page on your SharePoint site where you want the Web Part to be accessible.

    2.   In the Web Part page, click Site Actions, and select Site Settings.

    3.   On the Site Settings page, click Web Parts under the Galleries heading.

    4.   On the toolbar in the Web Part gallery, click New.

    5.   In the New Web Parts list, check the box next
         to Sample.DisplayMessage.DisplayMessageWebPart and click Populate Gallery.

    6.   Your Web Part can now be added to any Web Part page.

 Step 8: Add your Web Part to a Web Part Page

In this step, you import the Web Part to a page in any SharePoint site and test the custom property you
added to the Web Part. The following procedure explains the steps for adding the Web Part to a page and
changing the Display Message custom property.
To add and test your Web Part
    1.   Navigate to the Web Part page on your SharePoint site where you want to add the Web Part.

    2.   In the Web Part page, click Site Actions, and select Edit Page.

    3.   In the Web Part zone where you want to add the DisplayMessageWebPart, click Add a Web
         Part.

    4.   On the Add Web Parts dialog, find the Miscellaneous category under All Web Parts and check
         the box next to DisplayMessageWebPart. Click Add.

    5.   To modify the text displayed on the Web Part, choose Modify Shared Web Part from the chrome
         drop-down list.

    6.   In the DisplayMessageWebPart properties pane, expand the Miscellaneous category and
         change the Display Message value. Click Apply.

    7.   Now the Web Part is displaying the user-defined value inside the Web Part.




Walkthrough: Creating a Basic SharePoint Web Part
This programming task includes the steps for creating a basic custom Windows SharePoint Services Web
Part. It is a simple Web Part that allows you to change the Web Part‘s Title property, which is a Windows
SharePoint Services WebPart base class property that sets the text in the title bar of the Web Part.


   Important:

 Beginning with Windows SharePoint Services 3.0, the Windows SharePoint Services Web Part infrastructure
 is built on top of the Microsoft ASP.NET 2.0 Web Part infrastructure and Web Parts that derive from the
 ASP.NET WebPart class are completely supported in Windows SharePoint Services. You should create
 ASP.NET Web Parts whenever possible.
 For more information about choosing the best Web Part base class from which to derive, see Developing
 Web Parts in Windows SharePoint Services in the Windows SharePoint Services Software Development Kit
 (SDK). For more information about ASP.NET Web Parts, see the Web Parts Control Set Overview in the
 ASP.NET documentation.
 Prerequisites

Microsoft Visual Studio 2005

Windows SharePoint Services 3.0

 Step 1: Create a Web Control Library project

Web Parts are based on ASP.NET Web Form Controls. You create Web Parts in Microsoft Visual C# or
Microsoft Visual Basic by using the ASP.NET Web Control Library template.

To create a new Web Control Library project
    1.   Start Visual Studio 2005.

    2.   On the File menu, point to New, and then click Project.

    3.   In the New Project dialog box, click Visual C# Projects or Visual Basic Projects, and then
         select the Web Control Library template.

    4.   Type SimpleWebPart as the name and specify the location for the project files, and then click OK.

 Step 2: Add a Reference to Microsoft.SharePoint.dll
To create a Web Part, you need to add a reference to the Microsoft.SharePoint assembly
(Microsoft.SharePoint.dll) in your Web Control Library project.

To add a reference to Microsoft.SharePoint.dll
    1.   On the Project menu, click Add Reference.

    2.   On the .NET tab, double-click Windows SharePoint Services.

    3.   Click OK.

 Step 3: Set the Version Number and set up partially trusted callers

By default, the AssemblyVersion property of your project is set to increment each time you recompile your
Web Part. A Web Part page identifies a Web Part with the version number that is specified in
the web.config file. With the AssemblyVersion property set to increment, if you recompile your Web
Part after importing it into a Web Part page, the Web Part framework will look for the version number you
specified in the web.config file. If the version number does not match, an error will occur. To prevent the
version number of your Web Part from incrementing each time you recompile, you need to set the version
number in the AssemblyInfo file.

Since you are creating signed code, you must also tell your assembly to allow partially trusted code calls. By
default, any strong-named assembly that does not explicitly opt in to its use by partially trusted code will be
callable only by other assemblies that are granted full trust by security policy.

To set the version number and allow partially trusted callers
    1.   In Solution Explorer, double-click the AssemblyInfo file

    2.   Edit the line:

         C#

         [assembly: AssemblyVersion(“1.0.*”)]

         Visual Basic

         <Assembly: AssemblyVersion(“1.0.*”)>

         so that it reads:

         C#

         [assembly: AssemblyVersion(“1.0.0.0”)]

         Visual Basic

         <Assembly: AssemblyVersion(“1.0.0.0”>
    3.   Add the following line to the top of the file:

         C#

         using System.Security;

         Visual Basic

         Imports System.Security;
    4.   Add the following line to the bottom of the file:

         C#

         [assembly: AllowPartiallyTrustedCallers]

         Visual Basic

         <Assembly: AllowPartiallyTrustedCallers()>

 Step 4: Rename the Class and Namespace

If you are creating multiple Web Parts, you should generally use the same namespace across all of your Web
Parts. By default, the Web Control Library assigns the namespace the same name as your project. For this
example, we are using the arbitrary namespace of MyWebParts for the WebPart class. After you create
the project, a blank class file is displayed. You can change the default class name of WebCustomControl to
easily identify your new Web Part.

To rename the class and namespace
    1.   Rename the default class by selecting WebCustomControl1 in Solution Explorer, right-click,
         click Rename, and type SimpleWebPart as the file name.

    2.   For C#, change the Web Part namespace by editing the line:

         C#

         namespace SimpleWebPart
         so that it reads:

         C#

         namespace MyWebParts
    3.   For Visual Basic, right-click on the the SimpleWebPart project in the Solution Explorer and
         click Properties. Replace the text in the Assembly nameand Root namespace text boxes
         to MyWebParts.SimpleWebPart

 Step 5: Add a Namespace Directive

To make it easier to write a basic WebPart class, you should use the using directive in C# or
the Imports directive in Visual Basic to reference the following namespace in your code:

        The Microsoft.SharePoint.WebPartPages namespace provides the types for Web Part pages, such as
         theMicrosoft.SharePoint.WebPartPages.WebPart class.

To add a namespace directive
        Add the following using or Imports directive near the top of your code:

         C#

         using Microsoft.SharePoint.WebPartPages;

         Visual Basic

         Imports Microsoft.SharePoint.WebPartPages
 Step 6: Inherit from the Web Part Class

By default, the Web Control Library template creates a custom control that inherits from
the System.Web.UI.Control class (a parent class of both the ASP.NET and SharePoint WebPart classes).
To create a SharePoint Web Part, you should inherit from
the Microsoft.SharePoint.WebPartPages.WebPart base class.

To inherit from the Web Part base class.
       Replace this line of code:

        C#

        public class SimpleWebPart : WebControl

        Visual Basic

        Public Class SimpleWebPart
             Inherits WebControl

        with this line:

        C#

        public class SimpleWebPart : WebPart

        Visual Basic

        Public Class SimpleWebPart
             Inherits WebPart

 Step 7: Use the RenderWebPart Method

The WebPart base class seals the Render method of System.Web.UI.Control because the Web Part
infrastructure needs to control rendering the contents of a Web Part. For this reason, custom Web Parts
must override the RenderWebPart method of the WebPart base class.

To use the RenderWebPart method.
       Replace this line of code:

        C#

        protected override void Render(HtmlTextWriter output)

        Visual Basic

        Protected Overrides Sub RenderContents(ByVal output as HtmlTextWriter)
        with this line:

        C#

        protected override void RenderWebPart(HtmlTextWriter output)
         Visual Basic

         Protected Overrides Sub RenderWebPart(ByVal output as HtmlTextWriter)

 Step 8: Define the Logic and Rendering of your Web Part

After you complete the previous steps, you can define the logic and rendering for your Web Part. For this
part, we will write some basic ASP.NET code to create two controls: a text box and a button that will set
the Title property of the Web Part.

To define the logic and rendering of your Web Part
    1.   Create two user interface objects by adding the following code near the top of
         the SimpleWebPart file.


         C#

         Button saveTitle;
         TextBox newTitle;

         Visual Basic

         Public saveTitle as Button
         Public newTitle as TextBox
    2.   Create the button handling event by adding the following code inside the class.

         C#

         public void saveTitle_click(object sender, EventArgs e)
         {
                this.Title = newTitle.Text;
                try
                {
                        this.SaveProperties = true;
                }
                catch (Exception ex)
                {
                        this.Title = "Error: " + ex.Message;
                }
         }

         Visual Basic

         Public Sub saveTitle_Click(ByVal sender As Object, ByVal e As
         EventArgs)
              Me.Title = newTitle.Text
          Try
                Me.SaveProperties = True
          Catch ex As Exception
                Me.Title = "Error: " & ex.Message
          End Try
     End Sub
3.   Override the CreateChildControls() method by adding the following code inside the class.

     C#

     protected override void CreateChildControls()
     {
            //Create text box
            newTitle = new TextBox();
            newTitle.Text = "";
            Controls.Add(newTitle);


            //Create button
            saveTitle = new Button();
            saveTitle.Text = "Set Web Part Title";
            saveTitle.Click += new EventHandler(saveTitle_click);
            Controls.Add(saveTitle);
     }

     Visual Basic

     Protected Overrides Sub CreateChildControls()
          'Create text box
          newTitle = New TextBox()
          newTitle.Text = ""
          Controls.Add(newTitle)


          'Create button
          saveTitle = New Button()
          saveTitle.Text = "Set Web Part Title"
          AddHandler saveTitle.Click, AddressOf saveTitle_Click
          Controls.Add(saveTitle)
         End Sub
    4.   Replace the RenderWebPart() method with the following line of code.

    5.       protected override void          RenderWebPart(HtmlTextWriter output)
    6.       {
    7.             RenderChildren(output);

         }

         Visual Basic

         Protected Overrides Sub RenderWebPart(ByVal output as HtmlTextWriter)
                 RenderChildren(output)
         End Sub

 Step 9: Create a Valid Strong Name for the Assembly

Web Parts are designed to be distributed over the Internet or an intranet. For security reasons, when you
create a custom Web Part, you should give it a strong name to ensure that the Web Part can be trusted by
your users. For more information about strong naming, see Deploying Web Parts in Windows SharePoint
Services and also Assembly Signing Frequently Asked Questions.

To assign a strong name to an assembly
    1.   In Solution Explorer, right-click on the SimpleWebPart project and click Properties.

    2.   In the SimpleWebPart properties, click the Signing tab on the left side.

    3.   On the Signing tab, check the Sign the assembly checkbox.

    4.   Select New in the Choose a strong name key file drop-down menu.

    5.   In the Create Strong Name Key dialog, type SimpleWebPartKey and uncheck Protect my key
         file with a password.

    6.   Now, the assembly will be signed when it is built.

 Step 10: Build Your Web Part

After you add all of the preceding code, you can build your sample Web Part.

To build your Web Part
        On the Build menu, click Build Solution.

 Step 11: Copy Your DLL to the Bin Directory

After the Web Part is built, you must copy the resulting DLL to the bin directory.

To copy your DLL to the bin directory
    1. On the file system, locate the SimpleWebPart.dll file. The default location for Visual Studio
       2005 is C:\Documents and Settings\UserName\My Documents\Visual Studio
       2005\Projects\SimpleWebPart\SimpleWebPart\bin\Debug.
    2.   Copy the SimpleWebPart.dll file from the output directory to the Web application root bin
         directory. The default location of the Web application root for
         isC:\Inetpub\wwwroot\wss\VirtualDirectories\PortNumber\bin.

         For more information, see How to: Find the Web Application Root.
 Step 12: Increase the Default Trust Level and Add a SafeControl Entry for your
Web Part

provides a SafeControls list to prevent users from arbitrarily adding server-side code within ASPX pages. The
SafeControls list is a list of approved controls and Web Parts specific to your SharePoint site that you have
designated as safe for invocation on any ASPX page within your site. This list is contained in
the web.configfile in your Web application root. The local path contains the physical location of
the web.config file.

By default, the trust level for this server is WSS_Minimal, which does not allow access to the Windows
SharePoint Services object model. For this Web Part to set the SaveProperties property, you must perform
one of the following three actions:

        Create a custom policy file for your assembly, or

        Install your assembly in the global assembly cache, or

        Increase the trust level for the entire virtual server.

In this example, you will increase the default trust from WSS_Minimal to WSS_Medium in
the web.config file.


   Note:

 The web.config file is located in the folder where the virtual directory for the Web site runs. It is usually
 located in the following directory:c:\inetpub\wwwroot\wss\VirtualDirectories\PortNumber,
 but your administrator may have set up your directory differently and this may not be the location of the
 file.
 You can find the location of your web.config file by using the Internet Information Services (IIS) snap-
 in. The IIS snap-in is an administration tool for IIS that has been integrated with other administrative
 functions. To launch the IIS snap-in and locate the web.config file:
       1. Click Start, point to Programs, point to Administrative Tools, and click Internet Information
          Services (IIS) Manager.
       2. Expand the node that is the name of your computer, and expand the Web Sites item in the tree.
       3. Locate the web site that is running your Windows SharePoint Services installation (often it
          is Default Web Site).
       4. Right-click and select Properties.
       5. Select the Home Directory tab.
To increase the default trust level and add a SafeControl entry for your Web Part
    1. Open the web.config file in the Web application root.

    2.   In the level attribute of the trust section, change WSS_Minimal to WSS_Medium.

    3.   In the SafeControls section of your web.config file, add a SafeControl entry for your custom
         assembly as follows.

         Xml

         <SafeControl Assembly="SimpleWebPart, Version=1.0.0.0, Culture=neutral,
         PublicKeyToken=PublicKeyToken" Namespace="MyWebParts"
         TypeName="SimpleWebPart" Safe="True"/>
    4.   Replace the PublicKeyToken with the actual value for your Web Part's assembly. To determine the
         correct PublicKeyToken for your Web Part, use the sn.exe command-line utility.

         sn.exe -T
         C:\inetpub\wwwroot\wss\VirtualDirectories\PortNumber\bin\SimpleWebPart.
         dll
 Step 13: Create a DWP File to Deploy your Web Part

A Web Part definition file (.dwp) is a simple XML file that contains property settings for a single Web Part. To
import your Web Part into a Web Part page, simply upload the .dwp file. After uploading the Web Part, you
can display the Web Part by dragging it into one of the zones of the Web Part page.

Two properties are required in the .dwp file: Assembly and TypeName. However, to display a default
name and description for the Web Part after it is imported, you should also include
the Title and Description properties. If you want to set other Web Part properties during import, you can
also define them in a .dwp file. A .dwp file takes the following form.

Xml


<?xml version="1.0"?>
<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
      <Assembly>AssemblyName(with no .dll extension),
           Version=VersionNumber, Culture=Culture,
           PublicKeyToken=PublicKeyToken</Assembly>
      <TypeName>WebPartNameSpace.WebPartClassName</TypeName>
      <Title>DefaultWebPartTitle</Title>
      <Description>WebPartDescription</Description>
</WebPart>
To create a DWP file
      1.   Copy and paste the following XML into a new text file.

           Xml

           <?xml version="1.0"?>
           <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
              <Assembly>SimpleWebPart, Version=1.0.0.0, Culture=Neutral,
           PublicKeyToken=PublicKeyToken</Assembly>
                 <TypeName>MyWebParts.SimpleWebPart</TypeName>
                 <Title>My Simple Web Part</Title>
                 <Description>A simple Web Part</Description>
           </WebPart>

              Important:

            You must replace PublicKeyToken in the XML above with the public key token of your assembly.
      2.   Save this file as SimpleWebPart.dwp in the bin directory of the Web application root.

 Step 14: Import your Web Part into a Web Part Page

To use and test your Web Part, import it into a Web Part page on a server that is running Windows
SharePoint Services or Microsoft Office SharePoint Server 2007.
To import your Web Part
    1.   Navigate to the page on your SharePoint site where you want the Web Part to be accessible.

    2.   In the Web Part page, click Site Actions, and select Site Settings.

    3.   On the Site Settings page, click Web Parts under the Galleries heading.

    4.   On the toolbar in the Web Part gallery, click Upload.

    5.   On the Upload Web Part page, click Browse and select the .dwp file that you created.


            Note:

          This should be in C:\inetpub\wwwroot\wss\VirtualDirectories\PortNumber\bin\.
    6.   Click OK.

    7.   Navigate back to the Web Part page. In the Web Part page, click Site Actions, and select Edit
         Page.

    8.   In your preferred zone, click Add a Web Part and check the box next to My Simple Web Part in
         the dialog box. Click Add.

    9.   After the Web Part is added to the zone, type some text in the text box and click Set Web Part
         Title to test the Web Par




Walkthrough: Creating Connectable Web Parts in Windows
SharePoint Services
This programming task describes how to create two connectable SharePoint Web Parts: a Web Part that can
consume a single cell value and another Web Part that can provide a single cell value.


   Important:

 Beginning with Windows SharePoint Services 3.0, the SharePoint Web Part infrastructure is built on top of
 the Microsoft ASP.NET 2.0 Web Part infrastructure and Web Parts that derive from the
 ASP.NET WebPart class are completely supported in SharePoint, including the ASP.NET connection model.
 Whenever possible, you should create ASP.NET Web Parts, and use the ASP.NET connection model to
 connect your Web Parts.
 For more information about choosing the best WebPart base class from which to derive, see Developing
 Web Parts in Windows SharePoint Services. For more information about ASP.NET Web Parts and its
 connection model, see Web Parts Connections Overview in the ASP.NET documentation.
 About Connectable Web Parts

The SharePoint Web Part infrastructure provides a standardized set of interfaces called connection interfaces
that allow Web Parts to exchange information with each other at run time. For example, the List Web Part
that is built into Microsoft Windows SharePoint Services can provide (send) a row of data to any other Web
Part that can consume (receive) that row, such as a Web Part that implements a form to display the row.

Because the Web Part infrastructure provides a standard set of connection interfaces, connectable Web Parts
can be developed by entirely different developers or companies to communicate with one another. A Web
Part that supports connection interfaces can be connected by an end user with either Microsoft Office
SharePoint Designer 2007 or a Web browser. This allows end users to build sophisticated combinations of
Web Parts through a simple menu-driven user interface.
The Windows SharePoint Services connection classes and interfaces are implemented in
the Microsoft.SharePoint.WebPartPages.Communication namespace.

Connection Interfaces
Connection interfaces are paired events relevant to a specific item, such as a row in a list. The paired
interfaces form a communication bus between Web Parts that implement them. A connectable Web Part
raises an interface event to one or more connected parts to make them perform an action. Interfaces are
paired as a provider to a consumer. Events from the provider get handled in the consumer and vice versa.
The following table briefly describes each pair of connection interfaces.


Connection interface pair                             Description

 ICellProvider,ICellConsumer                          Connection interfaces for providing or consuming a
                                                      single value item, such as a cell or field.

 IRowProvider,IRowConsumer                            Connection interfaces for providing or consuming a
                                                      single row (or multiple rows) of values.

 IListProvider,IListConsumer                          Connection interfaces for providing or consuming an
                                                      entire list.

 IFilterProvider,IFilterConsumer                      Connection interfaces for providing or consuming a
                                                      filter value. For example, the SharePoint List Web Part
                                                      supportsIListProvider, IRowProvider,
                                                      and IFilterConsumer. Because IRowProvider can
                                                      connect to IFilterConsumer, two different SharePoint
                                                      Lists can be connected to one another. This allows one
                                                      list to filter the other connected list.

 IParametersInProvider,IParametersInConsumer          The IParameterIn interfaces allow passing and
                                                      receiving of any set of arbitrary parameters between
                                                      Web Parts. These interfaces cover a situation where
                                                      the consumer Web Part owns the parameter list and
                                                      needs to communicate this to other Web Parts.

 IParametersOutProvider,IParametersOutConsumer        The IParameterOut interfaces allow passing and
                                                      receiving of any set of arbitrary parameters between
                                                      Web Parts. These interfaces cover a situation where
                                                      the provider Web Part owns the parameter list and
                                                      needs to communicate this to other Web Parts.
Compatibility Rules
Web Parts can only be connected if they are compatible. Following are several compatibility rules which are
assessed by the Web Part infrastructure when determining whether two Web Parts can be connected. If the
Web Parts are found to be incompatible, the Connection menu item in the browser is dimmed and a tooltip
explains the reason for incompatibility.

Opposite Pairs
A connection interface can only connect with other compatible interfaces. The most basic compatibility rule
is that interfaces must be connected as opposite pairs or connected through a transformer. Connecting as
opposite pairs means that a Web Part that implements the IRowProvider interface can connect with
another part that implements the IRowConsumer interface.

Transformers
In the case where one Web Part needs to connect to another part that doesn‘t have the exact same
interface, the Web Part infrastructure provides interface transformers, which help users connect two distinct
interfaces in a natural and transparent manner.

For example, a user may want to connect a contact list to a picture viewer. However, the contact list only
has the IRowProvider interface and the picture viewer only has the ICellConsumer interface. To solve
this problem, an interface transformer is provided that allows these two interfaces to connect to each other.

The following table shows the interface pairs that can be connected to one another through a transformer
and whether the connections require Microsoft SharePoint Designer 2007.
                                                             Connect in          Connect in SharePoint
Transformer                                                  browser             Designer

 IRowProvider to ICellConsumer                               Yes                 Yes

 IRowProvider to IFilterConsumer                             Yes                 Yes

 IParametersOutProvider to IParametersInConsumer             No                  Yes

 IRowProvider to IParametersInConsumer                       No                  Yes
Cross-Page Connections
Some interfaces are allowed to connect to Web Parts on a different page. The behavior is similar to a
hyperlink.

You should understand the following about cross-page connections:

       A Web page editor that is compatible with Microsoft Windows SharePoint Services, such as
        SharePoint Designer required to author cross-page connections. However, once a cross-page
        connection has been formed, it can be used by any supported Web browser at run time.

       Only connectable Web Parts that have implementations designed to run on the server
        (the CanRunAt method has a ConnectionRunAt value of Server orServerAndClient) can establish
        cross-page connections. Connections that are formed on the client side are not allowed to cross
        Web Pages.

The following table shows the interfaces that can be connected across pages.


Source page interface         Target page interface

 IRowProvider                 IFilterConsumer

 IRowProvider                 IParametersInConsumer

 IFilterProvider              IFilterConsumer

 IParametersOutProvider       IParametersInConsumer

 IParametersInProvider        IParametersInConsumer
When working with cross-page Web Part connections, you must do the following:

       Pass ConnectionRunAt.Server or ConnectionRunAt.ServerAndClient to
        the runAtOptions parameter of the RegisterInterface method.
       Pass true to the allowCrossPageConnection parameter of the RegisterInterface method.
       Implement the GetInitEventArgs method to provide specific information about data that is passed
        through the connection interface.

Client and Server Connections
At any given time, Web Parts are allowed to run on the client or the server. Some Web Parts, if designed
accordingly, can detect the conditions under which they are running and dynamically switch to run on the
client or the server. Web Parts can only be connected to other Web Parts running in the same location. For
example, server-side parts can only be connected to other server-side parts. Server-side parts cannot be
connected to client-side parts. The connection chain must be homogenous. If a part can dynamically switch
between client or server connections, the Web Part infrastructure will automatically pin the Web Part to be a
client-side or server-side part depending upon the Web Part chain to which it is being connected.

Maximum Number of Connections
When registering an interface, the maximum number of connections to other Web Parts can be specified in
the maxConnections parameter of theRegisterInterface method. If the connection limit is exceeded on a
Web Part, it cannot be connected to other parts.
The options are 1 or unlimited.
        Microsoft.SharePoint.WebPartPages.WebPart.UnlimitedConnections specifies that a connectable Web
         Part can accept an unlimited number of connections to another Web Part.

        Microsoft.SharePoint.WebPartPages.WebPart.LimitOneConnection specifies that a connectable Web
         Part can accept only one connection.

No Circular Connections
A Web Part cannot be connected to itself, either directly or through a chain of connections.

Shared and Private Web Part Connections
A shared Web Part can be connected to a private Web Part, if the private Web Part is a consumer and the
shared Web Part supports an unlimited number of connections.

Program Flow
Connected Web Parts pass information to each other by firing specific interface events. When a Web Part
implements an interface such as ICellProvider, it must override a number of methods. The firing of the
interface events is performed by the Web Part infrastructure calling into the overridden methods at
designated times. The following steps for creating connectable Web Parts define which methods need to be
overridden and the typical code that a Web Part author should use to do so.

 Creating a Web Part that Implements the ICellProvider Interface

This programming task defines the process of creating a class that implements all of the necessary methods
and events for a connection interface using theICellProvider interface. For a complete code example, refer
to the ICellProvider and ICellConsumer source code samples at the end of these steps.

To start this programming task, perform the steps described in Walkthrough: Creating a Basic SharePoint
Web Part up to the steps for "Defining the Rendering and Logic of Your Web Part."

Following are 11 high-level steps that you must complete to implement a connection interface for your Web
Part:

    1.   Create the interface class.

    2.   Declare events.

    3.   Override the EnsureInterfaces method, and then call the RegisterInterfacemethod.

    4.   Override the CanRunAt method.

    5.   Override the PartCommunicationConnectmethod.

    6.   Override the PartCommunicationInitmethod.

    7.   Override the PartCommunicationMainmethod.

    8.   Override the GetInitEventArgs method.

    9.   Implement the interface event handlers.

    10. Override the RenderWebPartmethod.

    11. Implement supporting methods.

 Step 1: Create the interface class

Create a class that implements one of the predefined connection interfaces. In this example, we'll implement
the ICellProvider interface. For the remaining steps (2-11), all of the code goes in this class.

Example
C#


public class CellProvider : WebPart, ICellProvider
{
          // Much code goes here. See steps 2 – 11.
}

    Step 2: Declare events

Declare all of the relevant events for the connection interface. In this location, other variables used by the
Web Part are also declared. Because we're working with the ICellProvider interface, the following example
declares variables for its CellProviderInit and CellReady events.

Example
C#


// CellProviderInit Event


public event CellProviderInitEventHandler CellProviderInit;


// CellReady Event


public event CellReadyEventHandler CellReady;

 Step 3: Override the EnsureInterfaces method, and then call the
RegisterInterface method

Override the EnsureInterfaces method. This method is called by the Web Part infrastructure before the
Web Part renders, and is the time when the Web Part should register all of its interfaces by calling one of the
two RegisterInterface methods.

Example
C#


public override void EnsureInterfaces()
{
     // Register Interfaces                 (See following section)


}
Within the overridden EnsureInterfaces method, you notify the Web Part infrastructure about the
interfaces that will be used by calling theRegisterInterfacemethod. As noted in Step 3,
the RegisterInterface method occurs within the EnsureInterfaces method.
The RegisterInterface method takes several parameters, which are defined below.

Method Definition
C#


protected InterfaceProperties RegisterInterface(string interfaceName,
                             string interfaceType,
                             int maxConnections,
                               ConnectionRunAt runAtOptions,
                               object interfaceObject,
                               string interfaceClientReference,
                               string menuLabel,
                               string description)

  Note:

A second RegisterInterface method is available that provides an
additional allowCrossPageConnection parameter for specifying explicitly whether an interface supports cross-
page connections. The RegisterInterface method that does not include this parameter hard-codes the
setting of theallowCrossPageConnection parameter to true for all connection interfaces that are supported by
the connection compatibility rules defined by the Web Part infrastructure (see "Cross Page Connections,"
earlier in this topic). All other connection interfaces are hard coded to false.
Method Parameters

Parameter        Description

interfaceNam     A string property that is the friendly name of the interface. The friendly name should be
e                unique within a part. This property cannot contain the following special characters: <, >, &,
                 double quotation mark, single quotation mark, comma, or semicolon.

interfaceType    A property that represents the type of the interface (IRowProvider, ICellConsumer, and
                 so on).

maxConnectio     A property that the Web Part infrastructure can query to determine how many connections
ns               can be formed on a given interface.maxConnections is an int. It can have a value
                 of Microsoft.SharePoint.WebPartPages.WebPart.LimitOneConnection orMicrosoft.Sh
                 arePoint.WebPartPages.WebPart.UnlimitedConnections.

runAtOptions     Defines where the interface can run (Client, Server, ClientAndServer, None).

interfaceObjec   A reference to the actual object that implements this interface.
t

interfaceClien   For client-side connections, interfaceClientReference is a string that is used as the identifier for
tReference       the client-side object that implements that interface. This identifier should contain a _WPQ_
                 to guarantee uniqueness of the name, and it can contain special characters like (). An empty
                 string can be used if the part does not support client-side communication. The Web Part
                 infrastructure encodes double quotation marks as single quotation marks.
                    Note:

                 WPQ_ is a token that is replaced with a unique identifier by the Web Part infrastructure when
                 a part is rendered.


menuLabel        A general label or explanation of the interface. This will appear in the connection menu user
                 interface. It is recommended that you start your menu label using a verb such as "Provide"
                 or "Consume" so that the user creating a connection understands the direction of the flow of
                 data.

description      An extended description of the interface.
Example
C#


InterfaceProperties myCellProviderInterface = RegisterInterface(
     "MyCellProviderInterface_WPQ_",               //InterfaceName
     "ICellProvider",                  //InterfaceType
     WebPart.UnlimitedConnections,              //MaxConnections
     ConnectionRunAt.ServerAndClient,                //RunAtOptions
     this,                      //InterfaceObject
     "CellProviderInterface_WPQ_",              //InterfaceClientReference
     "Provide Value From Text Box",                       //MenuLabel
     "Provides the value entered into the text box.");                      //Description

     Note:

 To catch code access security permission exceptions, enclose the RegisterInterface call in
 a try/catch block. For an example of how to do this, see the RegisterInterface method topic.
    Step 4: Override the CanRunAt method

All connectable Web Parts must override the CanRunAt method. This method is called by the Web Part
infrastructure to determine whether a Web Part can be run on the server, the client, or both. The Web Part
needs to determine where it can run based on the current configuration of the user's client and the other
Web Parts to which it is connected. The values that it can return are the
following ConnectionRunAt enumeration values: Client, Server, ClientAndServer, andNone. For
example, a Web Part may have two different renderings: rich and downlevel. The Web Part may need an
ActiveX component installed for its rich rendering. In this case, the CanRunAt method would
return Client if the ActiveX component is installed or Server if it isn't installed.

Example
C#


public override ConnectionRunAt CanRunAt()
{
     // This Web Part can run on both the client and the server
     return ConnectionRunAt.ServerAndClient;
}

    Step 5: Override the PartCommunicationConnect method

All connectable Web Parts must override the PartCommunicationConnect method. This method is called
by the Web Part infrastructure to notify the Web Part that it has been connected, and to pass along relevant
information such as which part it was connected to. This occurs as soon as the Web Part infrastructure links
up the appropriate events for the connection. In this method, the Web Part author should keep track of
where the interface can be run, create whatever UI controls are needed, and verify that the connection was
formed correctly. This method has several parameters which are defined below.

Method Definition
C#


public override void PartCommunicationConnect (string interfaceName,
                         WebPart connectedPart,
                         string connectedInterfaceName,
                         ConnectionRunAt runAt)
Method Parameters

Parameter                Description

interfaceName            Friendly name of the interface that is being connected.

connectedPart            Reference to the other Web Part that is being connected to.
                         Both connectedPart and connectedInterfaceName parameters provide a means for the
                         connecting part to identify the type of part that it is being connected to. This allows
                         the Web Part to establish a more informed interaction with the other part. For
                         example, if the source part has detailed knowledge of the target part, the source
                         part can tap into the target part‘s public object model. However, both of these parts
                         need to be designed with this intent for this to work correctly. For example, a chart
                         part and pivot part could be designed to share the same layout of a common data
                         source when they were connected.

connectedInterfaceName   Friendly name of the interface on the other Web Part through which they are
                         connected.

runAt                    Where the interface can be executed. This will be either the client or the server and
                         is determined by the Web Part infrastructure based on several factors.
Example
C#


public override void PartCommunicationConnect(string interfaceName,
    WebPart connectedPart,
    string connectedInterfaceName,
    ConnectionRunAt runAt)
{
    // Check to see if this is a client-side part
    if (runAt == ConnectionRunAt.Client)
    {
        // This is a client-side part
        _runAtClient = true;
        return;
    }


    // Must be a server-side part - create the Web Part's controls
    EnsureChildControls();


    // Check if this is my particular cell interface
    if (interfaceName == "MyCellProviderInterface_WPQ_")
    {
         // Keep a count of the connections
     _cellConnectedCount++;
     }
}

    Step 6: Override the PartCommunicationInit method

A connectable Web Part can optionally override the PartCommunicationInit method. This method is called
by the Web Part infrastructure to allow the Web Part to fire any initialization events. The Web Part should
fire any events that end with "Init" (for example, CellProviderInit).

Init parameters are useful when a Web Part needs to broadcast some information about itself to other parts.
For example, when a List part connects to a Form part, the List part could broadcast its field names. The
Form part could then render its user interface based on the field names from the List part.

Example

     Note:

 For client-side Web Parts, this event and its event handler must be implemented on the client.
C#


public override void PartCommunicationInit()
{
     //If the connection wasn't formed then don't send Init event
     if(_cellConnectedCount > 0)
     {
         //If there is a listener, send Init event
         if (CellProviderInit != null)
         {
             //Need to create the args for the CellProviderInit event
             CellProviderInitEventArgs cellProviderInitEventArgs = new
             CellProviderInitEventArgs();


             //Set the FieldName
             cellProviderInitEventArgs.FieldName = _cellName;
             cellProviderInitEventArgs.FieldDisplayName = _cellDisplayName;


             //Fire the CellProviderInit event
             CellProviderInit(this, cellProviderInitEventArgs);
         }
     }
}

    Step 7: Override the PartCommunicationMain method

A connectable Web Part can optionally override the PartCommunicationMain method. This is called by the
Web Part infrastructure to allow the Web Part to fire any of the other events from the interface (for
example, CellReady). During the execution of the PartCommunicationMain method, the actual
communication of data values (as opposed to schema) takes place between Web Parts.

Example

     Note:

For client-side Web Parts, this event and its event handler must be implemented on the client.
C#


public override void PartCommunicationMain()


{
   // NOTE: THIS CODE IS SPECIFIC TO EACH AND EVERY WEB PART’S
IMPLEMENTATION.
     // If the connection wasn't formed then don't send Ready event
     if(_cellConnectedCount > 0)
     {
         // If there is a listener, send CellReady event
         if (CellReady != null)
         {
             // Need to create the args for the CellProviderInit event
             CellReadyEventArgs cellReadyEventArgs = new CellReadyEventArgs();


             // If user clicked button then send the value
             if (_cellClicked)
             {
                 // Set the Cell to the value of the TextBox text
                 // This is the value that will be sent to the Consumer
                 cellReadyEventArgs.Cell = _cellInput.Text;
             }


             else
             {
                 // The user didn't actually click the button
                  // so just send an empty string to the Consumer
                  cellReadyEventArgs.Cell = "";
             }


             // Fire the CellReady event
             // The Consumer will then receive the Cell value
             CellReady(this, cellReadyEventArgs);
         }
     }
}

    Step 8: Override the GetInitEventArgs method

A connectable Web Part should override the GetInitEventArgs method if needed.
The GetInitEventArgs method is only required for the interfaces that use transformers. For
example, IRowProvider, ICellConsumer, IFilterConsumer, IParametersOutProvider,
and IParametersInConsumer can support transformers. The GetInitEventArgs method is called by the
Connection Authoring tools for all the initial data required to create the transformer user interface. The
method returns the InitEventArgs object and takes in the interface name.

For example, when connecting two Web Parts that support
the IRowProvider and ICellConsumer interfaces, the user needs to specify which field in
theIRowProvider Web Part should map to the input value in the ICellConsumer Web Part. This is
achieved by the Web Part infrastructure calling theGetInitEventArgs method on each of the interfaces. The
connection authoring tools such as Microsoft Office SharePoint Designer 2007 or the browser use
theInit parameters passed to build the user interface for the transformer, which allows the user to pick the
field mapping.

Method Definition
C#


public override InitEventArgs GetInitEventArgs(string interfaceName)
Method Parameters

Parameter                      Description

 interfaceName                 A string property that is the friendly name of the interface.
Example

     Note:

 This method can be implemented on the server or client.

     Important:

 A code example for a Web Part that implements the ICellProvider interface has been used as the example
 throughout these steps. However, theICellProvider interface shouldn‘t override
 the GetInitEventArgs method because it can't use a transformer. However, for completeness, following is
 an example from the CellConsumer.cs code sample at the end of this programming task, which does
 override the GetInitEventArgs method.
C#
public override InitEventArgs GetInitEventArgs(string interfaceName)
{
     //Check if this is my particular cell interface
     if (interfaceName == "MyCellConsumerInterface_WPQ_")
     {
         EnsureChildControls();


         //Need to create the args for the CellConsumerInit event
         CellConsumerInitEventArgs cellConsumerInitArgs =
            new CellConsumerInitEventArgs();


         //Set the FieldName and FieldDisplayName
         cellConsumerInitArgs.FieldName = _cellName;
         cellConsumerInitArgs.FieldDisplayName = _cellDisplayName;


         //return the InitArgs
         return(cellConsumerInitArgs);
     }
     else
     {
         return(null);
     }
}

    Step 9: Implement the interface event handlers

Implement the appropriate event handlers based on the type of interface being used. In this example,
the ICellProvider interface must implement the CellConsumerInitEventHandler event handler. This event
handler must be implemented whether the data passed by the ICellConsumer interface is used or not. The
consumer part will fire this event when its PartCommunicationInitmethod runs.

Method Defintion
C#


public void CellConsumerInit(object sender, CellConsumerInitEventArgs
cellConsumerInitEventArgs)
Method Parameters

Parameter               Description

sender                  The object calling this method.
 cellConsumerInitEventArgs   Parameters passed by the consumer Web Part during
                             the PartCommunicationInit phase.
Example
C#


public void CellConsumerInitEventHandler(object sender,
CellConsumerInitEventArgs cellConsumerInitEventArgs)
{
     // This is where the Provider part could see what type of "Cell"
     //       the Consumer was expecting/requesting.
     // For this simple code example, this information is not used
     // anywhere.


}

    Step 10: Override the RenderWebPart method

All Web Parts must override the RenderWebPart method. The details of this are specific to each and every
Web Part. The Web Part infrastructure calls this method to render the Web Part. For a full example, see the
CellProvider.cs source code located at end of this programming task topic. For brevity, the following provides
a skeleton sample.

Example
C#


protected override void RenderWebPart(HtmlTextWriter output)
{
     // Need to ensure that all of the Web Part's controls are created
     EnsureChildControls();


     // Render client connection code if the connection is client-side
     if (_runAtClient)
     {
          // Script for client-side rendering
     }
     else
     {
          // If connected then display all cell child controls
          if (_cellConnectedCount > 0)
          {
               // Code for server-side rendering
         }


         else
         {
             // There wasn't a cell connection formed,
         }
     }
}

    Step 11: Implement supporting methods

At this location in the ICellProvider source code, all supporting methods should be defined. A skeleton is
shown below. For a full example, see the CellProvider.cs source code located at end of this programming
task topic.

Example
C#


// Create all controls for this Web Part
protected override void CreateChildControls()
{
     //Code for Child Controls
}


// The Button OnClick event handler
private void CellButtonClicked(object sender, EventArgs e)
{
     _cellClicked = true; //user clicked button, set to true
}

 A Pair of Sample Web Parts that Implement the ICellProvider and ICellConsumer
Interfaces

The following two code samples illustrate how to create two connectable Web Parts that implement
the ICellProvider and ICellConsumer interfaces.

To complete this programming task, cut and paste the following code samples into two C# files of your Web
Part project, and then build your project.

C#


//--------------------------------------------------------------------
// File : CellProvider.cs
//
// Purpose : A sample connectable Web Part that implements the
//               ICellProvider interface.
//
//---------------------------------------------------------------------


using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.WebPartPages.Communication;
using System.Runtime.InteropServices;


namespace ICellDemo
{
     /// <summary>
     /// The CellProvider Web Part class implementes the ICellProvider
     /// interface. Its UI is very basic - it displays a simple text
     /// box and button.     The CellConsumer Web Part class implements
     /// the ICellConsumer interface.       When the CellProvider is
     /// connected to the CellConsumer on a Web Part Page, the CellProvider
     /// can pass the value in its text box to the CellConsumer which displays
     /// the value inline.
     /// </summary>
     ///


     //Step #1: Implement the Connection Interface (ICellProvider)
     public class CellProvider : WebPart, ICellProvider
     {
           //Step #2: Declare Connection Events
           public event CellProviderInitEventHandler CellProviderInit;
           public event CellReadyEventHandler CellReady;
      //Used to keep track of whether or not the connection will be running
client-side
     private bool _runAtClient = false;


     //Keep a count of ICell connections
     private int _cellConnectedCount = 0;


     //Web Part UI
     private Button _cellButton;
     private TextBox _cellInput;


     //Cell information
     private string _cellName;
     private string _cellDisplayName;


      //Used to keep track of whether or not the Button in the Web Part was
clicked
     private bool _cellClicked = false;




     //Step #3: EnsureInterfaces
     //Notification to the Web Part that is should ensure that all
     //its interfaces are registered using RegisterInterface.
     public override void EnsureInterfaces()
     {
         //Registers an interface for the Web Part
         RegisterInterface("MyCellProviderInterface_WPQ_",     //InterfaceName
            InterfaceTypes.ICellProvider,                  //InterfaceType
            WebPart.UnlimitedConnections,                  //MaxConnections
            ConnectionRunAt.ServerAndClient,               //RunAtOptions
            this,                                    //InterfaceObject
            "CellProviderInterface_WPQ_",
//InterfaceClientReference
            "Provide String from Textbox",                  //MenuLabel
            "Provides a Textbox string");                  //Description
       }




       //Step #4: CanRunAt - called by framework to determine where a part can
run.
       public override ConnectionRunAt CanRunAt()
       {
           //This Web Part can run on both the client and the server
           return ConnectionRunAt.ServerAndClient;
       }


      //Step #5: PartCommunicationConnect - Notification to the Web Part that
it has been connected.
       public override void PartCommunicationConnect(string interfaceName,
           WebPart connectedPart,
           string connectedInterfaceName,
           ConnectionRunAt runAt)
       {
           //Check to see if this is a client-side part
           if (runAt == ConnectionRunAt.Client)
           {
               //This is a client-side part
               _runAtClient = true;
               return;
           }


           //Must be a server-side part so need to create the Web Part's
controls
           EnsureChildControls();


           //Check if this is my particular cell interface
           if (interfaceName == "MyCellProviderInterface_WPQ_")
           {
               //Keep a count of the connections
               _cellConnectedCount++;
         }
     }


      //Step #6: PartCommunicationInit - Notification to the Web Part that it
has been connected.
     public override void PartCommunicationInit()
     {
         //If the connection wasn't actually formed then don't want to send
Init event
         if(_cellConnectedCount > 0)
         {
             //If there is a listener, send Init event
             if (CellProviderInit != null)
             {
                 //Need to create the args for the CellProviderInit event
               CellProviderInitEventArgs cellProviderInitArgs = new
CellProviderInitEventArgs();


                 //Set the FieldName
                 cellProviderInitArgs.FieldName = _cellName;
                 cellProviderInitArgs.FieldDisplayName = _cellDisplayName;


                 //Fire the CellProviderInit event.
                 CellProviderInit(this, cellProviderInitArgs);
             }
         }
     }


      //Step #7: PartCommunicationMain - Called by the framework to allow
part to fire any remaining events
     public override void PartCommunicationMain()
     {
         //If the connection wasn't actually formed then don't want to send
Ready event
         if(_cellConnectedCount > 0)
         {
             //If there is a listener, send CellReady event
             if (CellReady != null)
             {
                 //Need to create the args for the CellProviderInit event
                 CellReadyEventArgs cellReadyArgs = new CellReadyEventArgs();


                 //If user clicked button then send the value
                 if (_cellClicked)
                 {
                     //Set the Cell to the value of the TextBox text
                     //This is the value that will be sent to the Consumer
                     cellReadyArgs.Cell = _cellInput.Text;
                 }
                 else
                 {
                     //The user didn't actually click the button
                     //so just send an empty string to the Consumer
                     cellReadyArgs.Cell = "";
                 }




                 //Fire the CellReady event.
                 //The Consumer will then receive the Cell value
                 CellReady(this, cellReadyArgs);
             }
         }
     }


      //Step #8: GetInitArgs is not needed in this case. GetInitEventArgs
only needs to be
      //implemented for interfaces that can participate in a transformer
which are
      //the following: ICellConsumer, IRowProvider, IFilterConsumer,
IParametersOutProvider,
     //IParametersInConsumer
      //Step #9: Implement CellConsumerInit event handler.
      public void CellConsumerInit(object sender, CellConsumerInitEventArgs
cellConsumerInitArgs)
      {
            //This is where the Provider part could see what type of "Cell" the
Consumer
            //was expecting/requesting.
            //For this simple code example, this information is not used
anywhere.
      }


      //Step #10: RenderWebPart - defines Web Part UI and behavior
      protected override void RenderWebPart(HtmlTextWriter output)
      {
            //Need to ensure that all of the Web Part's controls are created
            EnsureChildControls();


            //Render client connection code if the connection is client-side
            if (_runAtClient)
            {
                //Connected client-side
            output.Write(ReplaceTokens("<br><h5>Connected Client-
Side</h5><br>\n"
                  + "<input type=\"text\" id=\"CellInput_WPQ_\"/>\n"
               + "<button id=\"CellButton_WPQ_\"
onclick=\"CellButtonOnClick_WPQ_()\">Fire CellReady</button>\n"
                  + "<SCRIPT LANGUAGE=\"JavaScript\">\n"
                  + "<!-- \n"
               + "    var CellProviderInterface_WPQ_ = new
myCellProviderInterface_WPQ_();\n"


                  + "    function myCellProviderInterface_WPQ_()\n"
                  + "    {\n"
                  + "           this.PartCommunicationInit = myInit;\n"
                  + "           this.PartCommunicationMain = myMain;\n"
               + "          this.CellConsumerInit = myCellConsumerInit;\n"


               + "          function myInit()\n"
               + "          {\n"
               + "              var cellProviderInitArgs = new Object();\n"
               + "              cellProviderInitArgs.FieldName =
\"CellName\";\n"


               + "
WPSC.RaiseConnectionEvent(\"MyCellProviderInterface_WPQ_\",
\"CellProviderInit\", cellProviderInitArgs);\n"
               + "          }\n"


               + "          function myMain()\n"
               + "          {\n"
               + "              var cellReadyArgs = new Object();\n"
                      + "            cellReadyArgs.Cell = \"\";\n"


               + "
WPSC.RaiseConnectionEvent(\"MyCellProviderInterface_WPQ_\", \"CellReady\",
cellReadyArgs);\n"
               + "          }\n"


               + "          function myCellConsumerInit(sender,
cellConsumerInitArgs)\n"
               + "          {\n"
                + "           }\n"
               + "     }\n"


               + "     function CellButtonOnClick_WPQ_()\n"
               + "     {\n"
               + "          var cellReadyArgs = new Object();\n"
               + "        cellReadyArgs.Cell =
document.all(\"CellInput_WPQ_\").value;\n"


               + "
WPSC.RaiseConnectionEvent(\"MyCellProviderInterface_WPQ_\", \"CellReady\",
cellReadyArgs);\n"
            + "    }\n"
            + "//-->\n"
            + "</SCRIPT>"));
    }
    else //Connected server-side
    {
        //If connected then display all cell child controls
        if (_cellConnectedCount > 0)
        {
            //Just render some informational text
            output.RenderBeginTag(HtmlTextWriterTag.Br);
            output.RenderEndTag();
            output.RenderBeginTag(HtmlTextWriterTag.H5);
            output.Write("Connected Server-Side");
            output.RenderEndTag();
            output.RenderBeginTag(HtmlTextWriterTag.Br);
            output.RenderEndTag();


            //Render the TextBox control
            _cellInput.RenderControl(output);


            //Render the Button
            _cellButton.RenderControl(output);
        }
        else
        {
            //There wasn't a cell connection formed,
            //so just output a message
            output.Write("NO CELL INTERFACE CONNECTION");
        }
    }
}


//Step #11.1 (Supporting Methods): CreateChildControls
          protected override void CreateChildControls()
          {
              //Create the Button
              _cellButton = new Button();
              _cellButton.ID = "CellButton";
              _cellButton.Text = "Fire CellReady";
              Controls.Add(_cellButton);


              //Create the TextBox
              _cellInput = new TextBox();
              _cellInput.ID = "CellInput";
              Controls.Add(_cellInput);


              //Set the Cell information.
              //This information will be passed to the Consumer by
              //firing the CellProviderInit event.
              _cellName = "CellInput";
              _cellDisplayName = "CellDisplayInput";


              _cellClicked = false; // Initialize to false -- user hasn't clicked
yet
         _cellButton.Click += new EventHandler(CellButtonClicked); // listen
for Button's click event
          }


          //Step #11.2 (Supporting Methods): CellButtonClicked
          // <param name="sender">The Button object</param>
          // <param name="e">The Event Arguments</param>
          private void CellButtonClicked(object sender, EventArgs e)
          {
              _cellClicked = true; //user clicked button, set to true
          }
      }
}
//--------------------------------------------------------------------
// File : CellConsumer.cs
//
// Purpose : A sample connectable Web Part that implements the
//             ICellConsumer interface.
//
//---------------------------------------------------------------------
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.WebPartPages.Communication;
using System.Runtime.InteropServices;


namespace ICellDemo
{


     //Step #1: Implement the Connection Interface (ICellConsumer)
     public class CellConsumer : WebPart, ICellConsumer
     {


         //Step #2: Declare Connection events
         public event CellConsumerInitEventHandler CellConsumerInit;


      //Used to keep track of whether or not the connection will be running
client-side
         private bool _runAtClient = false;


         //Keep a count of ICell connections
         private int _cellConnectedCount = 0;


         //Web Part UI
         private Label _cellLabel;
       //Cell information
       private string _cellName;
       private string _cellDisplayName;


       //Step #3: EnsureInterfaces
       //Notification to the Web Part that is should ensure that all
       //its interfaces are registered using RegisterInterface.
       public override void EnsureInterfaces()
       {
           //Registers an interface for the Web Part.
           RegisterInterface("MyCellConsumerInterface_WPQ_",      //InterfaceName
              InterfaceTypes.ICellConsumer,                //InterfaceType
              WebPart.UnlimitedConnections,                //MaxConnections
              ConnectionRunAt.ServerAndClient,             //RunAtOptions
              this,                                  //InterfaceObject
            "CellConsumerInterface_WPQ_",
//InterfaceClientReference
              "Get String Value",                         //MenuLabel
              "Just a simple ICellConsumer");                  //Description
       }


       //Step #4: CanRunAt - called by framework to determine where a part can
run.
       public override ConnectionRunAt CanRunAt()
       {
           //This Web Part can run on both the client and the server
           return ConnectionRunAt.ServerAndClient;
       }


      //Step #5: PartCommunicationConnect - Notification to the Web Part that
it has been connected.
       public override void PartCommunicationConnect(string interfaceName,
           WebPart connectedPart,
           string connectedInterfaceName,
           ConnectionRunAt runAt)
      {
           //Check to see if this is a client-side part
           if (runAt == ConnectionRunAt.Client)
           {
               //This is a client-side part
               _runAtClient = true;
               return;
           }


           //Must be a server-side part so need to create the Web Part's
controls
           EnsureChildControls();


           //Check if this is my particular cell interface
           if (interfaceName == "MyCellConsumerInterface_WPQ_")
           {
               //Keep a count of the connections
               _cellConnectedCount++;
           }
      }


      //Step #6: PartCommunicationInit - Notification to the Web Part that it
has been connected.
      public override void PartCommunicationInit()
      {
         //If the connection wasn't actually formed then don't want to send
Init event
           if(_cellConnectedCount > 0)
           {
               //If there is a listener, send init event
               if (CellConsumerInit != null)
               {
                   //Need to create the args for the CellConsumerInit event
               CellConsumerInitEventArgs cellConsumerInitArgs = new
CellConsumerInitEventArgs();
                 //Set the FieldNames
                 cellConsumerInitArgs.FieldName = _cellName;


                 //Fire the CellConsumerInit event.
                 //This basically tells the Provider Web Part what type of
                 //cell the Consuemr is expecting in the CellReady event.
                 CellConsumerInit(this, cellConsumerInitArgs);
             }
         }
     }


      //Step #7: PartCommunicationMain - this method doesn't need to be
implemented for the Consumer
      //because the Consumer doesn't have any events that need to be fired
during this phase.




      //Step #8: GetInitArgs - called by the connection authoring tool, e.g.,
browser or SharePoint Designer
     //to get the data required to build the transformer UI.
     public override InitEventArgs GetInitEventArgs(string interfaceName)
     {
         //Check if this is my particular cell interface
         if (interfaceName == "MyCellConsumerInterface_WPQ_")
         {
             EnsureChildControls();


             //Need to create the args for the CellConsumerInit event
            CellConsumerInitEventArgs cellConsumerInitArgs = new
CellConsumerInitEventArgs();


             //Set the FieldName
             cellConsumerInitArgs.FieldName = _cellName;
             cellConsumerInitArgs.FieldDisplayName = _cellDisplayName;


             //return the InitArgs
                return(cellConsumerInitArgs);
            }
            else
            {
                return(null);
            }
      }
    //Step #9.1: Implement CellProviderInit Event Handler.
      public void CellProviderInit(object sender, CellProviderInitEventArgs
cellProviderInitArgs)
      {
            //This is where the Consumer part could see what type of "Cell" the
Provider
            //will be sending.
            //For this simple code example, this information is not used
anywhere.
      }


      //Step #9.2: Implement CellReady Event Handler.
      //Set label text based on value from the CellProvider Web Part
      public void CellReady(object sender, CellReadyEventArgs cellReadyArgs)
      {
         //Set the label text to the value of the "Cell" that was passed by
the Provider
            if(cellReadyArgs.Cell != null)
            {
                _cellLabel.Text = cellReadyArgs.Cell.ToString();
            }
      }


      //Step #10: RenderWebPart - defines Web Part UI and behavior
      protected override void RenderWebPart(HtmlTextWriter output)
      {
            //Need to ensure that all of the Web Part's controls are created
            EnsureChildControls();
         //Render client connection code if needed
         if (_runAtClient)
         {
              //Connected client-side
            string strClientCode = "<br><h5>Connected Client-
Side</h5><br>\n";
              strClientCode += "<div id=\"ConsumerDiv_WPQ_\"/>\n";
              strClientCode += "<SCRIPT LANGUAGE=\"JavaScript\">\n";
              strClientCode += "<!-- \n";
            strClientCode += "    var CellConsumerInterface_WPQ_ = new
myCellConsumerInterface_WPQ_();\n";


              strClientCode += "   function myCellConsumerInterface_WPQ_()\n";
              strClientCode += "   {\n";
              strClientCode += "        this.PartCommunicationInit =
myInit;\n";
            strClientCode += "          this.CellProviderInit =
myCellProviderInit;\n";
              strClientCode += "        this.CellReady = myCellReady;\n";


              strClientCode += "        function myInit()\n";
              strClientCode += "        {\n";
            strClientCode += "              var cellConsumerInitArgs = new
Object();\n";
            strClientCode += "              cellConsumerInitArgs.FieldName =
\"CellName\";\n";


            strClientCode += "
WPSC.RaiseConnectionEvent(\"MyCellConsumerInterface_WPQ_\",
\"CellConsumerInit\", cellConsumerInitArgs);\n";
              strClientCode += "        }\n";


            strClientCode += "          function myCellProviderInit(sender,
cellProviderInitArgs)\n";
              strClientCode += "        {\n";
              strClientCode += "        }\n";
            strClientCode += "            function myCellReady(sender,
cellReadyArgs)\n";
             strClientCode += "           {\n";
            strClientCode += "
document.all('ConsumerDiv_WPQ_').innerHTML = cellReadyArgs.Cell;\n";
             strClientCode += "           }\n";


             strClientCode += "     }\n";
             strClientCode += "//-->\n";
             strClientCode += "</SCRIPT>";


             output.Write(ReplaceTokens(strClientCode));
         }
         else //Connected server-side
         {
             //If we are connected then display all child controls
             if (_cellConnectedCount > 0)
             {
                 //Just render some informational text
                 output.RenderBeginTag(HtmlTextWriterTag.Br);
                 output.RenderEndTag();
                 output.RenderBeginTag(HtmlTextWriterTag.H5);
                 output.Write("Connected Server-Side");
                 output.RenderEndTag();
                 output.RenderBeginTag(HtmlTextWriterTag.Br);
                 output.RenderEndTag();


                 //Render the Label control
                 _cellLabel.RenderControl(output);
             }
             else
             {
                 //else display no connection message
                 output.Write("NO CELL INTERFACE CONNECTION");
             }
             }
         }


         //Step #11.1 (Supporting Methods): CreateChildControls
         protected override void CreateChildControls()
         {
             //Create the Label
             _cellLabel = new Label();
             _cellLabel.ID = "CellLabel";
             Controls.Add(_cellLabel);


             //Set the Cell information.
             //This information will be passed to the Provider by
             //firing the CellConsumerInit event.
             _cellName = "CellInputabc";
             _cellDisplayName = "My CellInput";
         }
    }
}
To deploy and test these sample Web Parts
    1.   Perform the steps described in the "Deploying Your Web" section of the Walkthrough: Creating a
         Basic SharePoint Web Part programming task, making sure to create a SafeControl block and Web
         Part Definition file (.dwp) that reflects the appropriate values for your Web Part assembly.

    2.   After importing the sample Web Parts into a Web Part Page, connect the Web Parts:

             a.   Click Modify Shared Page (or Modify My Page), and then click Design This Page.

             b.   Click the Web Part Menu on the Cell Consumer Web Part, point to Connections, point
                  to Consume Cell from, and then click Cell Provider Web Part.

             c.   In the Cell Provider Web Part, enter a value into the text box, and then click the Fire
                  CellReady button.
Development Tools and Techniques for Working with Code in
Windows SharePoint Services 3.0 (Part 1 of 2)
Summary: Learn the skills you need to develop for Windows SharePoint Services 3.0, about the differences
from traditional ASP.NET development, about the required development environment, and the steps to build
a Windows SharePoint Services solution with Visual Studio 2005 Extensions for Windows SharePoint Services
3.0. This article is part 1 of 2. (33 printed pages)

Patrick Tisseghem, U2U

June 2007

Applies to: Windows SharePoint Services 3.0, Visual Studio 2005 Extensions for Windows SharePoint
Services 3.0

Contents


       Introduction to Developing with Windows SharePoint Services Technology

       Required Development Skills

       ASP.NET Applications vs. SharePoint Sites

       What You Develop for Windows SharePoint Services

       The Development Environment

       Visual Studio 2005 Extensions for Windows SharePoint Services 3.0

       A Closer Look at Windows SharePoint Services Solutions

       About the Author

       Additional Resources

Introduction to Developing with Windows SharePoint Services Technology
Many developers are eager to leverage Windows SharePoint Services 3.0 as a development platform for
increasing collaboration and building document management solutions for information workers. This article
provides insight into the skills you need to develop for Windows SharePoint Services, the differences from
traditional ASP.NET development, the development environment that is required, and the steps you must
take to build a Windows SharePoint Services solution with Visual Studio 2005 Extensions for Windows
SharePoint Services 3.0. The second part of the article explores the concept of Windows SharePoint Services
solutions, addressing the architecture of a solution, and the techniques for creating, deploying, maintaining,
and upgrading Windows SharePoint Services solutions. This article also includes walkthroughs that show the
different approaches developers and administrators can take.

We start by understanding what SharePoint development actually entails before discussing the different
techniques for building, packaging, deploying, and maintaining Windows SharePoint Services solutions.

Required Development Skills
People often ask what it takes to be a skilled SharePoint developer, and are surprised to discover that the
developer must master many skills.

Following is the list of areas in which to gain expertise that we have identified as being helpful when starting
with SharePoint development.
ASP.NET 2.0
The latest version of Windows SharePoint Services and Microsoft Office SharePoint Server (MOSS) 2007 rely
completely on Microsoft ASP.NET 2.0 as the foundation. Therefore, being skilled in ASP.NET 2.0 concepts,
terminologies, and development is the top priority for a Windows SharePoint Services developer. In addition
to understanding the flow of an ASP.NET request, its different stages, and its internal architecture and
extensibility options, a developer must be experienced in developing and using master pages, content
pages, ASP.NET server and user controls, templates in ASP.NET, ASP.NET Web Parts and their
infrastructure, and the ASP.NET provider model. (Many resources are available to you if you need to come
up to speed in any of these areas, however, these are beyond the scope of this article.)

Windows Workflow Foundation
When working on Windows SharePoint Services solutions for information workers, you often must build
custom workflows. The built-in workflows that are delivered with MOSS 2007 answer—to a certain extent—
the demands of the business, but developers are often asked to build custom workflows using the
extensions for both Windows Workflow Foundation (WF) and the project templates for building SharePoint-
specific workflows. To succeed, the developer needs a good understanding of WF, including the process of
building the workflow, building custom activities, interacting with the SharePoint environment within the
workflow, and more.

XML Technologies
Windows SharePoint Services technologies rely heavily on XML technologies. These are the foundation for
the many schema definitions that drive the provisioning engine. There are schema definitions for sites, lists,
document libraries, fields, content types, and more. The Collaborative Application Markup Language (CAML)
is used in most of these schema definitions. In addition, developers must also know about the related XML
technologies such as XSLT and XPath because in their development on Windows SharePoint Services, they
will encounter those technologies as well.

Windows SharePoint Services 3.0 and MOSS 2007 APIs
A Windows SharePoint Services developer must understand the APIs that are exposed by both Windows
SharePoint Services 3.0 and MOSS 2007. Building solutions with Windows SharePoint Services requires a
deep understanding of many of the classes that are exposed within the object models. In addition, if the
applications target smart clients working remotely with SharePoint technologies, knowledge of the XML Web
services delivered with Windows SharePoint Services and MOSS is also necessary.

Finally, all of the solutions must be deployed and made available within the SharePoint server farm scoped
to a certain level (for example, a site collection). You must understand how to package the different
components that make up a solution, and how to install and activate the features that make the solutions
available on new and existing sites. This article provides more information and guidelines on how to do this.

ASP.NET Applications vs. SharePoint Sites
Windows SharePoint Services development and traditional ASP.NET development differ in many ways. To
help you understand the differences, we can compare ASP.NET applications with Windows SharePoint
Services applications.

Figure 1 displays the different components and the interaction flow of a mainstream ASP.NET application.




Figure 1. Components and flow of a mainstream ASP.NET application
Users send requests to the server running Internet Information Services (IIS) for specific resources. These
requests are accepted by IIS and delegated to an ISAPI extension DLL for further processing. Typically,
resources are retrieved from the file system, such as .config files, .aspx pages, cascading style sheets,
custom-built .NET assemblies, and user controls. All of these can act on the final response that is delivered
to the user in his or her browser. In many applications, an interaction with a data store is also needed to
store and retrieve data that is used to process the request and generate the response.

So, what is different when we compare Figure 1 with Figure 2, which represents the components and flow
for a site based on Windows SharePoint Services?




Figure 2. Components and flow of a Windows SharePoint Services site
As you can see in Figure 2, Windows SharePoint Services abstracts developers from many of the details of
hosting highly scalable, template-driven sites. In many cases, SharePoint administrators and experienced
users do not even touch that low-level infrastructure. However, an understanding of it is helpful.

Windows SharePoint Services is a site-provisioning engine that relies heavily on schema definitions for
templates of many types of artifacts that are important to its environment. There are definitions for site
templates; for infrastructure pages such as the default.aspx, which make up the home page of a team site;
for lists and libraries; and for helper pages that enable the interaction among the content that is stored in
these different containers.

When starting a request for a Windows SharePoint Services page, there is interaction with the configuration
database and the content database that retrieves the details of the request. This includes accessing the
many XML files that contain the schema definitions, and accessing building blocks (Web Parts) that each
have to execute their code that is encapsulated in a .NET assembly made available via either the global
assembly cache or the local bin folder. The Windows SharePoint Services provisioning engine joins all these
processes.

When we look at the traditional ASP.NET application again, what happens there if you need more than one
application, maybe two, five, or even dozens? Figure 1 starts to look complex because there the same
infrastructure is repeated for each additional application. Developers following the best practices and
patterns can produce many re-usable building blocks, but much of the infrastructure must still be re-created
each time.

By comparison, many Windows SharePoint Services sites—dozens, hundreds, even thousands of
collaboration sites—can be delivered with one common provisioning engine. This is the power of using
Windows SharePoint Services compared to using ASP.NET applications.
What You Develop for Windows SharePoint Services
Windows SharePoint Services is a solutions platform, which means that it is extensible and ready to run
custom solutions. The following sections discuss the solution types that Windows SharePoint Services
developers can build.

Assembly-Based Solutions

We can refer to these solutions as code-based solutions. Assembly-based solutions are developed with
managed code (a .NET Framework language such as Microsoft Visual C# or Microsoft Visual Basic 2005) and
compiled as a .NET assembly (a DLL). You can build different types of these solutions as well. The following
table describes only some of the possible assembly-based solutions.

Table 1. Types of assembly-based solutions

Solution Type        Description

 Web Parts            Building blocks for a SharePoint Web Part Page that deliver specific functionality to the
                      visitor of the site. Web Parts can deliver data from stores that are not based on
                      Windows SharePoint Services (such as Microsoft SQL Server and Oracle stores);
                      capture data to drive business processes; aggregate or roll up information that is
                      available in the SharePoint sites, or perform many other functions. Many Web Parts are
                      available by default with both Windows SharePoint Services 3.0 and MOSS 2007.

 Event handlers       A .NET assembly containing one or more classes that encapsulate code that is executed
                      when certain events (such as adding an item to a list, creating a column for a document
                      library, deleting a site, and so on) occur in SharePoint sites.

 Information          A rich policy framework in MOSS that developers can use to build custom policies that
 management           enforce certain behavior for content stored and managed in SharePoint sites.
 policies

 Workflow             A workflow is a collection of activities Windows SharePoint Services or the information
 Activities and       workers involved in the workflow must take. Numerous activities are available;
 templates            however, you can create custom activities compiled in a .NET assembly and deploy
                      them so that experienced users creating workflows in Microsoft Office SharePoint
                      Designer 2007 can use them. Developers can also create workflow templates by using
                      the workflow extensions for Visual Studio 2005 and deploy these as .NET assemblies to
                      the SharePoint servers.

 Timer Jobs           Assemblies containing code that can be scheduled and executed by the SharePoint
                      Timer Service. An example is a job scheduled to create a report every evening for the
                      administrator about documents that have been checked out for more than a week.
ASP.NET Resources

Figure 2 showed the infrastructure that Windows SharePoint Services uses to deliver the sites. This
infrastructure contains many ASP.NET resources that are directly available and help deliver the simplified
development experience you have with Windows SharePoint Services. As a developer, you can create and
integrate your own resources. Table 2 describes the possible types of resources you can create.




Table 2. Types of ASP.NET resources

Resource          Description

 Site page        An ASP.NET page that is stored in a document library in the site collection itself (and is thus
                  stored in the content database). Can be used to deliver custom functionality (such as
                  reporting or dashboard pages) to the user. Site pages can be dynamically created and offer
                  much flexibility. However, because they are stored in the content database, Windows
                  SharePoint Services applies a strict security policy to these pages, and no inline code is
                 allowed. Additionally, these pages are run in no-compile mode.

 Application     A physical ASP.NET page stored in the \12\Template\Layouts folder. This folder is
 page            commonly shared by all Windows SharePoint Services sites that are hosted on the Web
                 server. Application pages are ideal for creating additional administration features for
                 SharePoint sites. Because they are not part of the database, inline code is allowed.

 Style sheets    Together, these define the look and feel of a site, as well as the common functionality that
 and master      is used by all the pages of a site.
 pages

 Navigation      ASP.NET-based navigation controls that deliver an experience based on the ASP.NET
 control         provider model. Windows SharePoint Services provides many default ASP.NET-based
                 navigation controls. Custom navigation controls are typically required when delivering
                 public (Internet) facing sites with Windows SharePoint Services.

 User control    ASP.NET user control (.ascx file) that can deliver common functionality to the pages in
                 SharePoint sites. Windows SharePoint Services provides several controls in
                 the \12\Template\ControlTemplates folder. Create additional custom user controls,
                 and for example, visualize them within the master pages. User controls can deliver a
                 particular editing experience to the user, such as custom information management policies
                 or custom fields.
Schemas

Schemas are XML-based solutions that use the Collaborative Application Markup Language (CAML). Table 3
describes the features whose delivery you can drive by using schemas.

Table 3. Types of features delivered with schemas

Feature          Description

 Site            A custom template for sites that are deployed in
 definition      the \12\Template\SiteTemplate folder. The core file for a custom site definition is
                 Onet.xml, which contains the global definitions for the site along with the possible
                 configurations.

 Features        Introduced in Windows SharePoint Services 3.0, a modular approach for delivering custom
                 schemas and functionality to SharePoint sites. Features can activate what you build and
                 deploy. Many of the previously mentioned types of solutions are made available by using
                 Feature definitions. You can find the list of deployed Feature definitions in
                 the \12\Template\Features folder

 Custom Lists    The schemas for custom lists and document libraries are also defined via CAML-based files,
                 many times as part of a Feature definition. However, they can also be part of a custom site
                 definition.

 Site Columns    Schema for re-usable packaged definitions of content that can be stored and managed in
 and Content     SharePoint containers (lists and document libraries). Site columns and content types are
 Types           delivered through Feature definitions most of the time.

 Custom Field    These CAML-based files, together with a .NET assembly that contains the code-behind,
 Definitions     deliver additional field types that users can select from when creating custom metadata in
                 a document library, for example.
Data Manipulation

All of the content that is stored and managed in SharePoint sites, together with all the configuration data, is
kept in SQL Server databases that you do not need to interact with directly. Windows SharePoint Services
and MOSS have very rich object models that are delivered by a number of .NET assemblies, of which the
Microsoft.SharePoint.dll and the Microsoft.Office.Server.dll are the most important.
The server object model is accessible only when the application is deployed to one of the computers that is
part of the server farm. If the application accessing Windows SharePoint Services is remotely deployed, use
the Web Services APIs instead.

Solutions that directly interact with the SharePoint classes must have access to the SharePoint context of
the sites (either the collaboration sites or the administration sites, depending on the type of the solution).
Examples are Windows–based applications that are deployed to a server running Windows SharePoint
Services, Web Parts that run in the context of Windows SharePoint Services, custom Web services that
expose data in a customized way, Windows services that run on the SharePoint server, and more.

Numerous Web services are available in Windows SharePoint Services that expose most of the necessary
data manipulation operations. However, when in need of custom functionality, you can always create custom
Web services and have Windows SharePoint Services host and integrate them with the built-in Web services.

There is also an HTTP-based protocol, the FrontPage Server Extensions Remote Procedure Call (RPC)
protocol, which is used by remote clients to manipulate documents that are stored in document libraries in
Windows SharePoint Services. Microsoft Office system clients are examples of smart clients that use this
protocol.

The Development Environment
Developers can use two environments to build SharePoint solutions. Your choice depends on varying factors,
including network infrastructure, licensing, size of the team, and the type of solution you want to build. In
this article, we suggest one that we consider a best practice.

Working Remotely
In the setup we describe, developers are working locally on a non-server operating system with Microsoft
Visual Studio 2005 installed. They build the solutions, and then go through the steps of deploying these
solutions to a central server running Windows SharePoint Services 3.0 and possibly MOSS. Figure 3 displays
the setup.




Figure 3. Setup for working remotely
Depending on the type of solution, specific .NET assemblies (for example, the Microsoft.SharePoint.dll) must
be copied to the local development environment.

There are many advantages to working this way. The first important advantage is that developers do not
have to install server software on their local development computers. This impacts licensing, and also eases
the installation burden for developers who are already doing a lot of development on their local computers.
The second advantage is that you can set up a centrally managed source-code control system, and the
backup can also be centrally managed by the administrators.

However, there are many difficulties that developers experience when working this way. First, debugging the
code remotely is challenging. For example, when building a Web Part in which the developer needs to debug
the code, you need to consider many environment variables such as the following:


       The developer requires powerful privileges on the server while debugging the solution for a site.

       The developer also blocks all of the other developers who are working on solutions for the same
        site.

       Every time testing must be done, developers must package the code and go through the
        deployment steps to the server before being able to see their code in action. This can be good,
        because from the start, developers have to take care of the proper packaging, but it is often going
        to be counter-productive when working this way.


           Note:

         Many assembly-based solutions require an IISRESET on the server running Windows SharePoint
         Services to activate the updated version.
Working Locally
Alternatively, you can configure the development environment so that all of the SharePoint development
work can be done locally. Figure 4 shows this setup.




Figure 4. Setup for working locally




We recommend this configuration for a number of reasons:
        In the long run, the developer‘s productivity benefits from being able to build, test, and debug the
         solution locally. This typically is the case when building assembly-based solutions.

        Testing the solution does not impede the work of colleagues. However, working locally requires
         more discipline from the developers. Setting up an efficient back-up and source-control system, for
         example, is more challenging in this situation.

        The local development environment can either be a native installation of Windows Server 2003 with
         Windows SharePoint Services 3.0 and possibly MOSS installed. However, as mentioned previously,
         this can be quite a burden for the developer who has other development work to do on the same
         computer. A configured Microsoft Virtual PC development environment is a good choice if you do not
         want to do a native installation, although it does require more memory and hard-disk space to use
         this approach.

Visual Studio 2005 Extensions for Windows SharePoint Services 3.0
Visual Studio 2005 Extensions for Windows SharePoint Services 3.0 can improve your productivity in a
number of development tasks. It provides the following:


        Project templates for building Web Parts, team sites, blank site definitions, and list definitions.

        Individual item templates for adding Web Part classes, custom field controls, and modules to an
         existing project, as well as list definitions, and content types (both with an optional event receiver).

        An external Windows application called the SharePoint Solution Generator that can pick up a
         provisioned team site, reverse-engineer it, and provide you with all of the individual pieces
         assembled together in a Visual Studio 2005 project.

It is important to remember that Visual Studio 2005 Extensions are meant to support the developer in the
development process, and through the testing and debugging phases. As you use the walkthroughs in this
article, the extensions can enable you to focus on the code, start writing it without the requirement of first
setting the project infrastructure, have the code compiled and packaged in a Windows SharePoint Services
solution, and deployed without hassle to one of your site collections—ready to be tested and debugged.

However, you can use a few configuration options to deviate from the default way the solution is packaged
and deployed. The different scenarios where you will have to take control of, package, and deploy the
solutions in a manual way are described later in this article.

Following are a few walkthroughs that show some of the development tasks you can undertake with the
Visual Studio Extensions for Windows SharePoint Services 3.0.

Walkthrough: Building a Web Part Project
If you are familiar with the Visual Studio Extensions for Windows SharePoint Services 3.0 and with using it
to build Web Parts, you might want to proceed to the next section. For the readers who are not familiar with
the extensions, this short walkthrough describes the different steps for creating a project with one Web Part
showing the world famous Hello World string. (Don‘t worry! It is going to get more exciting.)

To create a project with one Web Part that shows the Hello World string
    1.   Open Visual Studio 2005, and then create a new Web Part project as shown in Figure 5.
2.   Figure 5. Creating a Web Part project




     In Solution Explorer, notice that you have a reference to the Microsoft.SharePoint.dll and the
     System.Web.dll. The last reference is important because there is a WebPart1.cs file that contains a
     class that is inherited from the ASP.NET 2.0 WebPart class. This is the new "flavor" of Web Part
     classes that you build in Windows SharePoint Services 3.0.

3.   Write only the minimal code shown here to output a small string as the body of the Web Part. The
     final code looks like the following.

     C#
     using System;
     using System.Runtime.InteropServices;
     using System.Web.UI;
     using System.Web.UI.WebControls.WebParts;
     using System.Xml.Serialization;


     using Microsoft.SharePoint;
     using Microsoft.SharePoint.WebControls;
     using Microsoft.SharePoint.WebPartPages;


     namespace MSDN
     {
          [Guid("28c3eefe-2c03-4791-9f69-4405c80e1d92")]
         public class HelloWorldWebPart :
     System.Web.UI.WebControls.WebParts.WebPart
          {
                protected override void Render(HtmlTextWriter writer)
                {
                      writer.Write("Hello Readers!");
                }
          }
     }

4.   Before testing the Web Part, perform the following configuration tasks. As displayed in Figure 6,
     open the properties of the project in Solution Explorer, and then click the SharePoint Solution tab.

     We explain the concepts of Features and solutions later in this article, but in brief, certain elements
     of the XML files involved are exposed here, as follows:

         1.   A solution node with the name and ID of the solution.

         2.   A node for the feature.xml file where the name of the folder to be created in
              the \12\Template\Features path can be changed. In addition, this node shows the
              title, the description, and the scope (by default, set to the level of the site collection).

         3.   A node for the manifest file (elements.xml) where you can set the title and the description
              of the Web Part itself.


                Note:

                 The dimmed attributes cannot be changed. For a Web Part project, for example, there is
               no way to change the feature.xml file and register an event handler. Later, I describe a
               workaround to this problem.
In Visual Studio 2005, press F5 to install the SharePoint solution and deploy it to one of your extended IIS
Web applications. Use the Debug tab to specify to Visual Studio where you want to list the Web Part as an
activated feature.

Later in the article, I explain what goes on behind the scenes in more detail. In short, the code is packaged
into a SharePoint solution, added to the solution store at the level of the server farm, and deployed to the
site collection. At this moment, you should be able to add the Web Part to a page on the targeted site, as
shown in Figure 7.




Figure 7. Web Part built and deployed by using F5
Walkthrough: Creating a Custom Field Type
The Visual Studio 2005 Extensions for Windows SharePoint Services 3.0 also supports you in developing
other types of SharePoint solutions. For example, you can create an empty project and then add individual
item templates. Following are the steps to create a simple field type, and to deploy and activate it quickly
and easily within your Windows SharePoint Services development environment.

To create, deploy, and activate a simple field type
    1.   Open Visual Studio 2005, and then create a new SharePoint project.

         This time, there is basically nothing created for you. Of course! You picked an empty project! But
         what you can do now is add a new item based on the Field Control template, as shown in Figure 8.
         The one I create is a simple field that captures, stores, and makes a project reference number
         available. (There is a small amount of validation logic encapsulated in this process that forces you to
         create a three-digit number.)

         Figure 8. Adding a Field Control item template
1.   When you proceed, two classes are added: one for the custom field and one that can be used to
     render a control for capturing the value of the field in a customized way. The only piece of code to
     add is in the ProjectReferenceNumberField class. Within this class, add the following methods.

     C#
                public override string GetValidatedString(object value)
                {
                      if (value.ToString().Length != 3)
                      {
                             throw new SPFieldValidationException
                                        ("Only 3 characters allowed!");
                      }
                      else
                      {
                             return value.ToString();
                      }
                }
2.   Before pressing F5, use the properties of the project to configure the way the custom field type is
     made available. This time, there are no feature.xml files but there is another XML file created with
     the prefix fldtypes that is placed in the \12\TEMPLATE\XML folder. You can set values for
     the TypeDisplayName and the TypeShortDescription. Again, use the Debug tab to specify what
     site the browser should navigate to when pressing F5 (Figure 9).
1.   Press F5. Figure 10 shows how the new field becomes part of the list of possible field types. Figure
     11 shows the validation code that checks the length of the field value and returns an error message
     to the user.




     Figure 10. Creating a column using the new field type
                                            Figure 11. Custom validation of the length of the field value




Walkthrough: Reverse Engineering a Team Site




The next example demonstrates how to use the SharePoint Solution Generator to reverse-engineer an
existing (and possibly customized) SharePoint team site with the Visual Studio 2005 Extensions for Windows
SharePoint Services 3.0. The walkthrough shows you how to reverse-engineer one of the 40 templates that
are available for download from the MSDN site. Many of these are delivered as .stp files (the result of the
Save As Template command in the browser).
         Note:

You can download the templates from Application Templates for Windows SharePoint Services 3.0.




In this walkthrough, we give the Sports League template to the SharePoint Solution Generator, and
generate a .NET project that contains the individual components of a site definition and the Features that
are involved.
To use the SharePoint Solution Generator to reverse-engineer a SharePoint team site




                    1.                   Download the Sports League template, install it and upload it in a Site Template gallery of one of
                                         your site collections.
                    2.                   Create a site that is based on this newly available template. Figure 12 shows the result of these
                                         actions.




                    3.Before you start with the SharePoint Solution Generator, remove the Web Part with the Windows
                    SharePoint Services image from the page.

Open the SharePoint Solution Generator (Figure 13), click Site Definition, and proceed to the next step.
1.
     Type the URL to the site you want to reverse-engineer, or navigate to it by using the tree view.
     Specify where to create the Visual Studio 2005 project.

2.   Click the Start button to start the Solution Generator.

3.   When the Solution Generator is finished, you can open the Visual Studio 2005 project. Figure 14
     shows the outcome.
    1.   Many pieces make up the project, and discussing all of them is beyond the scope of this article.
         However, you can see the schema definitions of the lists and libraries and the site definition itself.

    2.   Press F5 again to make everything available on your development computer. You can configure
         many of the details of the different features that represent each of the individual pieces of the site,
         as well as the site definition itself by using the SharePoint Solution tab.

A Closer Look at Windows SharePoint Services Solutions
One of the benefits of using the Visual Studio 2005 Extensions for Windows SharePoint Services 3.0 is that
the outcome of your development work is packaged in a SharePoint solution. This is great for a developer
who quickly wants to test out the code on his or her development computer, however, remember that there
is a lack of flexibility in changing the configuration parameters that are used for the packaging and
deployment of the solution.

Solution is the official term we use now to refer to the distribution package that delivers your custom
Windows SharePoint Services development work to the front-end Web servers, and possibly to the
application servers in your server farm. Figure 15 shows an overview of the various components that can be
packaged in a SharePoint solution. These components include:


        .NET assemblies that wrap up the code that drive the solution.

        Deployment files such as resource files, images, or other helper files.

        Many solutions involve the delivery of new templates and definitions for sites, lists, libraries, fields,
         content types, and more. These definitions are in the form of CAML-based XML files.

        And finally, configurations that have to be performed at the level of the front-end Web server (for
         example in the web.config files for the registration of Web Parts) can be included.




Figure 15. Anatomy of a SharePoint solution
In addition to all of this, you must include a very important file—the manifest file—to assist Windows
SharePoint Services in the deployment process of the solution. The manifest file is an XML file, which I
describe in more detail later. But in short, the manifest file contains the listing of all assets involved in a
solution, along with target locations for these assets and the various configurations in which they must
occur.

Anatomy of a Manifest File
What can be included in the manifest file? A lot—and what follows is a brief explanation of each type of item.
Before starting, it is interesting to mention that the schema definition for the manifest file is included in the
Wss.xsd file that is available in the WSS system folder.


  Note:

 You can find the WSS system folder in the path C:\Program Files\Common Files\Microsoft Shared\Web Serv

So you might want to add this to your Visual Studio 2005 environment to get IntelliSense support. Figure 16
shows the main XML elements for a manifest file.




Figure 16. Main XML elements in a solution manifest file
Solution Element

The Solution element is the root element of the manifest file. The SolutionId attribute is an important
element of the file. SolutionId identifies the solution in the solution store (which is part of the configuration
database, discussed later in this article). You identify a solution with a GUID.

Xml


<Solution SolutionId="1de3b0fc-78e9-4fe6-ae63-51ea50109982"
xmlns="http://schemas.microsoft.com/sharepoint/" >
</Solution>
DeploymentServerType and ResetWebServer are optional attributes. DeploymentServerType can
have two possible values: ApplicationServer orWebFrontEnd. Typically, most of your solutions target the
front-end Web servers in your server farm. Examples of solutions that target application servers (for
example, index servers, servers running Excel Services, document conversion servers, and so on) are
custom configurations or additional custom converters. TheIISReset attribute can be used to start a reset
of Internet Information Services (IIS) when the solution is deployed to a specific IIS Web application.
FeatureManifest Element

Features play an important role in many Windows SharePoint Services solutions because they represent the
individual pieces of the solution (such as a field type, a Web Part, a workflow, and so on). You must
represent every Feature that is included in the solution with a FeatureManifest element. The following
code example contains the Feature that advertises a Web Part in a SharePoint site.

Xml


<Solution SolutionId="dda6427b-b880-46c0-a428-10c4bac0ce91"
xmlns="http://schemas.microsoft.com/sharepoint/" >
    <FeatureManifests>
    <FeatureManifest Location="HelloWorldWebPart_28c3eefe-2c03-4791-9f69-
4405c80e1d92\feature.xml" />
    </FeatureManifests>
    …
</Solution>
When you deploy the solution to a front-end Web server, all of the Feature-related files are copied to the
location specified here.

Assembly Element

Most of the SharePoint solutions involve one or more .NET assemblies. The Assembly element is used in
the manifest file to make the DLL available on the destination server. Following is an example.

Xml


<Solution SolutionId="dda6427b-b880-46c0-a428-10c4bac0ce91"
xmlns="http://schemas.microsoft.com/sharepoint/" >
…
    <Assemblies>
    <Assembly Location="HelloWorldWebPart.dll"
DeploymentTarget="GlobalAssemblyCache" >
          <SafeControls>
        <SafeControl Assembly="HelloWorldWebPart, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=9f4da00116c38ec5" Namespace="MSDN"
TypeName="HelloWorldWebPart" Safe="True" />
          </SafeControls>
        </Assembly>
    </Assemblies>
</Solution>
The first attribute for the Assembly element is Location, which stores the relative path of the DLL in the
solution file. Next, there is the DeploymentTargetattribute, which has two possible
values: GlobalAssemblyCache or WebApplication. GlobalAssemblyCache indicates that the assembly
should be deployed in the global assembly cache; WebApplication tells Windows SharePoint Services to
drop the assembly in the private application folder of the IIS Web application. As discussed
later, WebApplication implies that the solution that is used depends on the trust level that the
administrator sets in the web.config file that is associated with the IIS Web application. Deploying the
assembly in the global assembly cache, which is a fully trusted location, means that as a developer, you do
not have to worry about setting this trust level.

The Web Parts in the solution must be registered as safe controls in the web.config file.
The Assembly element can contain one or more SafeControl elements (grouped together in
a SafeControls element). Each SafeControl element describes the configuration that must be done in the
web.config file.

Another possible set of child elements of the Assembly element are the ClassResource elements (grouped
together in a ClassResources element). Each represents a possible resource that is needed by the
deployed assembly. Examples are resource files, XML files, or pictures.

ApplicationResourceFile Element

The manifest files can contain one or more ApplicationResourceFile elements with a relative path to a
resource file that must be deployed. At the time of deployment, the resource files are copied to the private
application resource folder of the IIS Web Application, as shown in the following code.

Xml


<Solution SolutionId="8f37f0a7-ec35-4a63-9c3d-91205d9a2ac6"
              xmlns="http://schemas.microsoft.com/sharepoint/" >
…
      <ApplicationResourceFiles>
           <ApplicationResourceFile Location="hellowp.resx"/>
             <ApplicationResourceFile Location="hellowp.en-us.resx"/>
      </ApplicationResourceFiles>
</Solution>
CodeAccessSecurity Element

The CodeAccessSecurity important element is important to include in the manifest file when you want to
grant specific permissions to your code. Later in the article, there is a more detailed discussion about this. In
short, the CodeAccessSecurity element has one or more PolicyItem child elements that each define the
specifics regarding the code access security policy to apply for the solution. There are two parts for a policy
item: the listing of the permissions that are part of it and the assemblies for which these permissions should
play a role.

The list of permissions, each represented in an IPermission element, is collected in
a PermissionSet element that is the child of the PolicyItem element. TheIPermission elements each
define a code access security permission that is required for the assembly to run correctly. This is discussed
in more detail, later in the article.

One or more Assembly elements can play a role in code access security. You must define them one by one,
identifying each by name, version, and full public key.

DwpFile Element

Web Parts must be made available in the Web Part gallery before they can be dropped on the Web Part
Pages. XML files, with either a .dwp extension or a .webpart extension, store the metadata information that
is necessary to make the Web Parts available. The solution manifest file can contain one or
more DwpFile elements that are collected together in the DwpFiles element, with each pointing to one of
these files.
Xml


      <DwpFiles>
      <DwpFile FileName="hellowebpart.webpart"
Location="hellowebpart.webpart"/>
      </DwpFiles>
Resource Element

You can drop resource files in the folder that contains your Feature, and use it from that location.
A Resource element represents such a resource in the solution manifest file. The only attribute to set is the
relative path in the package to the resource file.

SiteDefinitionManifest Element

You use this element when you are deploying a custom site definition. The SiteDefinitionManifest element
has a Location attribute that picks up all the files in the specified folder and creates the needed folder in
the \12\Template\SiteTemplates folder. The WebTempFile child element deploys the
webtemp*.xml file to make the template known to Windows SharePoint Services.

Xml


  <SiteDefinitionManifests>
       <SiteDefinitionManifest Location="LitwareSiteTemplate">
         <WebTempFile Location="1033\xml\webtempLitware.xml" />
       </SiteDefinitionManifest>
  </SiteDefinitionManifests>
RootFile Element

Solution files can be copied to a specified folder directly under the \12 folder during deployment by
inserting a RootFile element in the solution manifest file.

TemplateFile Element

The TemplateFile element can be used to define the template files that must be deployed under
the \12\Template folder. An example of the type of file you can deploy in this way is the fldtypes*.xml
file, which defines the details of a custom field type. Use the Location attribute to specify the relative path
to the file.

Windows SharePoint Services Solution Samples
Earlier in the article, three walkthroughs guided you through the steps of creating and deploying a Web Part,
a custom field type, and a custom site definition. Let‘s inspect each of the solutions and the different files
that are included with them.

Web Part Solution File

Let‘s first take a look at the SharePoint solution that was generated for the simple Web Part created earlier
in the article. In the \bin\debug folder of the project, you find the .wsp file together with a subfolder
called solution, which contains all of the solution pieces that are packaged in the .wsp file. Figure 17
summarizes all of the components in a Web Part solution.
Figure 17. Components that make up a Web Part solution




There is the folder that contains the three files in the Feature that make the Web Part available to the users:
feature.xml, elementManifest.xml, and HelloWebPart.webpart. There is the assembly with the code and the
manifest file.

The manifest file looks like the following code.

Xml
<Solution SolutionId="219eec47-aeae-4ec2-9a2d-b7774a7e92d1"
xmlns="http://schemas.microsoft.com/sharepoint/" >
  <FeatureManifests>
    <FeatureManifest Location="HelloWebPart_6ad212bb-5425-4d30-aa62-
6acc23d04146\feature.xml" />
  </FeatureManifests>
  <Assemblies>
    <Assembly Location="HelloWebPart.dll"
DeploymentTarget="GlobalAssemblyCache" >
        <SafeControls>
        <SafeControl Assembly="HelloWebPart, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=9f4da00116c38ec5" Namespace="MSDN"
TypeName="HelloWebPart" Safe="True" />
        </SafeControls>
      </Assembly>
  </Assemblies>
</Solution>
The code contains two main blocks. The first, represented by the FeatureManifests element, tells Windows
SharePoint Services to copy the Feature to the\12\Template\Features folder on the server where the
solution is deployed. The second, represented by the Assemblies element, has two roles: to deploy the
assembly in the global assembly cache, and to define the necessary modifications to the web.config file with
the SafeControl registration.

Custom Field Type Solution

The second type of solution that was created in the walkthroughs was a custom field type. Navigating to the
solution folder again, you find an assembly and a manifest file at the root, but instead of a Feature folder,
there is a folder named XML, that contains the template file that must be deployed.

The manifest file looks like the following code.

Xml
<Solution SolutionId="d5fdc38c-1892-4700-a7e0-723d02d6dfc0"
xmlns="http://schemas.microsoft.com/sharepoint/" >
  <TemplateFiles>
    <TemplateFile Location="xml\fldtypes_50896c5a-bcfe-47b9-a4da-
5aa78d3c0d3e.xml" />
  </TemplateFiles>
  <Assemblies>
    <Assembly Location="SimpleFieldTypeDemo.dll"
DeploymentTarget="GlobalAssemblyCache" >
        <SafeControls>
        <SafeControl Assembly="SimpleFieldTypeDemo, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=9f4da00116c38ec5"
Namespace="ProjectReferenceNumber" TypeName="ProjectReferenceNumberField"
Safe="True" />
        </SafeControls>
      </Assembly>
  </Assemblies>
</Solution>
Again, there are two important parts to this code: one deploys the template file to its proper location, and
the second deploys the assembly. The SafeControlentry is not strictly needed unless the field type is used
as a custom field control in publishing pages.

Custom Site Definition Solution

The last type of solution to discuss is the Windows SharePoint Services site exported with the SharePoint
Solution Generator, by using a sports league as an example. Figure 18 displays the many components that
are generated and collected in a .NET project.




Figure 18. Components of a custom site definition solution
First, you see the core schemas for the site definition including the important files, onet.xml and the
webtemp*.xml. An assembly can contain code that can be executed at the time of provisioning a site. For
the rest of the schemas, you see plenty of Feature definitions in the project—for the site, the provisioning
code, and for the lists and document libraries that must be included in the provisioned site. The manifest file
looks like the following XML.

Xml


<Solution SolutionId="c2f14355-caea-4e02-b2fb-be198b71a99f"
xmlns="http://schemas.microsoft.com/sharepoint/" >
  <FeatureManifests>
    <FeatureManifest Location="LeagueCalendar_2a46379a-0cc6-4f0f-b901-
d69c688270d5\feature.xml" />
    <FeatureManifest Location="PlayersList_63daf9b3-2d56-4b80-b235-
c064b9b14d38\feature.xml" />
    <FeatureManifest Location="SharedDocuments_3dc03f6a-7abe-4cc7-8995-
7d799bf1fa55\feature.xml" />
    <FeatureManifest Location="Teams_254d82e9-f759-4e29-86f0-
7a5870fc7a7d\feature.xml" />
    <FeatureManifest Location="MSDNLeagueSiteTemplate_af2531ff-18bf-45f9-
b47c-f9e820f570d3\feature.xml" />
    <FeatureManifest Location="MSDNLeagueSiteTemplate_d8e211da-abed-4556-
87c9-0ceb6fa1220f\feature.xml" />
  </FeatureManifests>
  <Assemblies>
    <Assembly Location="MSDNLeagueSiteTemplate.dll"
DeploymentTarget="GlobalAssemblyCache" >
         <SafeControls>
        <SafeControl Assembly="MSDNLeagueSiteTemplate, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=a203fc97bcb29c46"
Namespace="MSDNLeagueSiteTemplate" TypeName="MSDNLeagueSiteTemplate"
Safe="True" />
         </SafeControls>
     </Assembly>
  </Assemblies>
  <SiteDefinitionManifests>
    <SiteDefinitionManifest Location="MSDNLeagueSiteTemplate_072c8ac2-012e-
405d-b436-a4809fcb6c1f">
      <WebTempFile Location="1033\xml\webtempMSDNLeagueSiteTemplate_ee077f02-
b4a0-45ba-829c-8eeb1991cf90.xml" />
     </SiteDefinitionManifest>
  </SiteDefinitionManifests>
</Solution>
The section of code that differs from the previous examples is the last part with
the SiteDefinitionManifests element. The SiteDefinitionManifest element deploys the site definition in
the \12\Template\SiteTemplates folder, and the WebTempFile element does the same for the
webtemp*.xml file.

Custom List Definition

A final example is the definition of a custom list. This is shown with a short walkthrough that demonstrates
how the Visual Studio 2005 Extensions for Windows SharePoint Services 3.0 can help you in the initial
stages.

To create a custom list definition
    1.   Navigate to one of your sites and create a list based on the custom list template.

    2.   Name the list Employees, and then add the following columns: First Name, Last Name (changing
         the Title column), Department, and Telephone Number.

         You can now use the SharePoint Solution Generator to generate the bulk of the custom list
         definition.

    3.   Open the SharePoint Solution Generator, and on the first page, select List Definition.

    4.   Enter the URL of your site and select the list instance created at the beginning of this walkthrough.

    5.   Provide the location where you want to create the Visual Studio project, and then click Finish to
         start the generation process.

    6.   Let‘s now construct the Feature for this new list template. Create a folder on your file system in a
         location you choose, with a Features folder as a subfolder.
7.   Under the Features folder, create another subfolder named EmployeesList. Copy the Employees
     folder from the .NET project folder into it.

8.   At the level of the EmployeesList folder, create a feature.xml file containing the following XML.

     Xml

     <Feature Id="{489C77F1-B064-408e-9B85-029A33BDF9D7}"
           Title="Employees"
         Description="This feature provides support for creating an Employee
     List."
           Version="1.0.0.0"
           Scope="Web"
           Hidden="FALSE"
           xmlns="http://schemas.microsoft.com/sharepoint/">
           <ElementManifests>
                <ElementManifest Location="ListTemplates\Employees.xml"/>
                <ElementFile Location="Employees\allitems.aspx" />
                <ElementFile Location="Employees\dispform.aspx" />
                <ElementFile Location="Employees\editform.aspx" />
                <ElementFile Location="Employees\newform.aspx" />
                <ElementFile Location="Employees\schema.xml" />
           </ElementManifests>
     </Feature>

9.   Create a ListTemplates folder under the EmployeesList folder, and then create the Employees.xml in
     it containing the CAML for the list template.

     Xml

     <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
           <ListTemplate
                   Name="Employees"
                   Type="10100"
                   BaseType="0"
                   OnQuickLaunch="TRUE"
                   SecurityBits="11"
                   DisplayName="Employees"
                   Description="Employees List Type"
                   Image="/_layouts/images/CHNGCOL.GIF"/>
          </Elements>
    10. Open the schema.xml in the Employees folder, and make sure that the Type attribute for the root
        element matches the number you used in the Timesheets.xml for the type (in the example, 10100).
        Also open each of the .aspx pages, and then remove the first line containing the comment.

You now have the Feature ready. Next, you must package all of this into a SharePoint solution.

To package the Feature into a SharePoint solution
    1.    Create a manifest file at the root level of the folders you created earlier. It is a simple task because
          there is no code involved.

          Xml

          <Solution SolutionId="{B2BE6294-D62F-4f14-9266-7C37AD2B9DBA}"
                        xmlns="http://schemas.microsoft.com/sharepoint/" >
                <FeatureManifests>
                     <FeatureManifest Location="EmployeesList\feature.xml" />
                </FeatureManifests>
          </Solution>

    2.    Create a .ddf file at the same level as the manifest file to package everything into a solution file.


    3.      ;
    4.      ; *** .ddf file for generating SharePoint solution
    5.      ;
    6.      .OPTION EXPLICIT               ; Generate errors
    7.      .Set CabinetNameTemplate=Employees.wsp
    8.      .set DiskDirectoryTemplate=CDROM ; All cabinets go in a single
          directory
    9.      .Set CompressionType=MSZIP;** All files are compressed in cabinet
          files
    10. .Set UniqueFiles="ON"
    11. .Set Cabinet=on
    12. .Set DiskDirectory1=Package
    13.
    14. ; *** the manifest file
    15. manifest.xml manifest.xml
    16.
    17. ; *** the feature files
    18. Features\EmployeesList\feature.xml EmployeesList\feature.xml
    19. Features\EmployeesList\ListTemplates\Employees.xml
       EmployeesList\ListTemplates\Employees.xml
    20. Features\EmployeesList\Employees\AllItems.aspx
       EmployeesList\Employees\AllItems.aspx
    21. Features\EmployeesList\Employees\DispForm.aspx
       EmployeesList\Employees\DispForm.aspx
    22. Features\EmployeesList\Employees\EditForm.aspx
       EmployeesList\Employees\EditForm.aspx
    23. Features\EmployeesList\Employees\NewForm.aspx
       EmployeesList\Employees\NewForm.aspx

          Features\EmployeesList\Employees\schema.xml
          EmployeesList\Employees\schema.xml
    24. Package everything into the .wsp file, add the solution to the solution store, and then deploy it
        globally by using the following Stsadm calls (typically contained within a batch file).


    25. set MakeCabTool=c:\Program Files\Microsoft Visual Studio
       8\SmartDevices\SDK\SDKTools\makecab.exe
    26. set SPAdminTool=%CommonProgramFiles%\Microsoft Shared\web server
       extensions\12\BIN\stsadm.exe
    27.
    28. "%MakeCabTool%" /f wsp_structure.ddf
    29. "%SPAdminTool%" -o addsolution -filename package\MSDNTimesheet.wsp

          "%SPAdminTool%" -o deploysolution -name MSDNTimesheet.wsp -immediate
You can now try out your work by activating the Feature from the Site Features page in one of your sites,
and create a new list instance based on the new template. I work with this solution later in the article when
discussing retracting and upgrading solutions.




Development Tools and Techniques for Working with Code in
Windows SharePoint Services 3.0 (Part 2 of 2)
Summary: Explore Windows SharePoint Services solutions, solution architecture, and techniques for
creating, deploying, maintaining, and upgrading Windows SharePoint Services solutions. This article is part 2
of 2. (26 printed pages)

Patrick Tisseghem, U2U

June 2007

Applies to: Windows SharePoint Services 3.0, Visual Studio 2005 Extensions for Windows SharePoint
Services 3.0

Contents


         Deploying Windows SharePoint Services Solutions
        Manually Packaging a Windows SharePoint Services Solution

        Code Access Security and Web Part Solutions

        Managing Solutions

        Conclusion

        About the Author

        Additional Resources

This article is a continuation of Development Tools and Techniques for Working with Code in Windows
SharePoint Services 3.0 (Part 1 of 2).

Deploying Windows SharePoint Services Solutions
The deployment of a Windows SharePoint Services solution to a front-end Web server or an application
server is performed in two phases, as shown in Figure 19.




Figure 19. Steps for deploying a SharePoint solution




Adding a Solution to the Solution Store
A SharePoint solution must be added to the solution store that is available in the server farm. The solution
store is part of the configuration database and stores the various .wsp files. You add the solution to the
store via the Stsadm.exe command-line utility or by using a programmatic approach.

Using Stsadm.exe

You can call Stsadm.exe with the addsolution operation by specifying the relative path to the .wsp file.
Following is a sample.


stsadm –o addsolution –filename mysolution.wsp

  Note:

 If you are localizing the solution, you can also use a third parameter: lcid.

Using the Windows SharePoint Services 3.0 Object Model

In another approach, you can create a .NET Framework application that talks to the object model that is
exposed by Windows SharePoint Services. You can add a SharePoint solution to the solution store by using
one line of code as follows.

C#


SPSolution solution = SPFarm.Local.Solutions.Add(@"C:\Package\MySol.wsp");
The SPFarm class in the Microsoft.SharePoint.Administration namespace that enables you to connect
to the server farm (either one that is created locally or one you joined remotely). You can populate
an SPSolutionCollection object with new solutions by calling the Add method, as long as it is either an
instance of anSPSolution class or the path to the SharePoint solution file. An SPSolution instance is
returned. Numerous properties and methods are exposed at this level.
Deploying a Solution
Your next step is to actually deploy the solution on one or more Web servers that are Windows SharePoint
Services–enabled, either as front-end Web servers or as application servers. You can deploy the solution in
three ways:


        By using Stsadm.exe

        By using the Windows SharePoint Services 3.0 object model

        By using the SharePoint Central Administration Web Site

These deployment methods are described in the following sections.

Using Stsadm.exe

Stsadm.exe has an option, deploysolution, which you can use to deploy the solution via a command
prompt. The name of the solution in the solution store is one of the parameters and the URL of the site
collection you are targeting. The following is an example.


stsadm –o deploysolution –name mysolution.wsp
          –url http://moss.litwareinc.com
Instead of targeting one site collection, you also have the option to push your solution to every site
collection available within the server farm. You use theallcontenturls parameter for this as follows.


stsadm –o deploysolution –name mysolution.wsp –allcontenturls
By default, the solution is immediately deployed, but you can also schedule the deployment by using
the time parameter.

The allowgacdeployment and allowcaspolicies parameters are also very important and are discussed later in
more detail. In short, allowgacdeployment is true by default and enables Windows SharePoint Services to
deploy the assemblies in the global assembly cache. The allowcaspolicies parameter enables the creation
of a custom code access security (CAS) policy file and the activation of it in the Web.config file of the
targeted site collection.

Deploying a Solution via the Windows SharePoint Services 3.0 Object Model

At the level of the SPSolution instance, you can use two methods to programmatically deploy your
solution: Deploy and DeployLocal. Both can accept a collection of SPWebApplication objects populated
with the Internet Information Services (IIS) Web applications that you want to target with the deployment.
You populate the collection as follows.

C#


Collection<SPWebApplication> webapps = new Collection<SPWebApplication>();
SPWebApplication webapp =
         SPWebApplication.Lookup(new Uri("http://wss.litwareinc.com"));
webapps.Add(webapp);
Both methods also allow for the deployment of the assemblies included in the Web Part solutions to the
global assembly cache. The difference between the two methods is that you can call Deploy with
a DateTime parameter that stores the exact moment you want the solution to be deployed, as shown in
Figure 20.
Figure 20. SharePoint solution scheduled for deployment




Following is a code example that uses the Deploy method.

C#


solution.Deploy(DateTime.Now.AddMinutes(5), true, webapps, true);
Following is a sample of the call for the DeployLocal method.

C#


solution.DeployLocal(true, webapps, true);
Deploying a Solution via the SharePoint Central Administration Web Site

Administrators can also navigate to the Operations page in Central Administration and use Solution
Management to deploy the Windows SharePoint Services solution to an IIS Web application either
immediately or at a specific time in the future.

Administrators receive a warning when the manifest file that is part of the solution requires assemblies to be
deployed in the global assembly cache.

Manually Packaging a Windows SharePoint Services Solution
Developers of Windows SharePoint Services solutions will very often create SharePoint solution packages in
a manual way. This is the case when there is a need to:


        Deploy .NET assemblies in the private application folder instead of the global assembly cache.
         Add code access security permissions to the solution that must be applied during the deployment.

         Deviate from the names used by default for the Feature folders.

         Localize the Windows SharePoint Services solution.

         Associate Feature event handlers to certain types of Windows SharePoint Services solutions, such as
          Web Part solutions.

         Add resources (XML files, pictures, and so on) to the solution package.

To manually create a solution file, you perform these basic steps:

     1.   Collect all individual solution files in a folder. There are no concrete guidelines about how you should
          do this, but a best practice is to separate the different types of solution files into their own
          subfolders.

     2.   Create a .ddf file (abbreviation of Diamond Directive File) that defines the structure of the Windows
          SharePoint Services solution file. This file contains the list of individual solution files that determine
          the output .wsp file.

     3.   Execute the command-line utility MakeCab.exe with the .ddf file as input and the .wsp file as
          output.

The following short walkthrough demonstrates all of the steps.

Walkthrough: Generating and Deploying a Custom Web Part Solution Package
Windows SharePoint Services 3.0 offers developers the option to execute custom code when a Feature is
installed, activated, deactivated, or uninstalled. An example is a Web Part that is dependent on a specific
task list. When the Web Part Feature is activated, custom code can check whether this task list is part of the
lists within the site. If not, the code creates the list, and then removes the list when the Feature is
deactivated. The custom code is wrapped into a .NET assembly referred to as the Feature Receiver
Assembly.

This walkthrough assumes you have a Web Part project created, as discussed in Development Tools and
Techniques for Working with Code in Windows SharePoint Services 3.0 (Part 1 of 2). When the Web Part
Feature is installed, activated, deactivated, or uninstalled, Windows SharePoint Services fires asynchronous
events. You can handle these events in a custom .NET assembly by creating a .NET class that inherits from
the abstract Microsoft.SharePoint.SPFeatureReceiverclass. Following are the class from the sample and
the four members to implement.

C#


using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;


namespace MSDN.Samples
{
   public class MSDNTaskListEventHandler: SPFeatureReceiver
   {
        public override void FeatureActivated(SPFeatureReceiverProperties
properties)
       {
           SPSite sitecollection = (SPSite)properties.Feature.Parent;
           SPWeb web = sitecollection.RootWeb;
           try
           {
                 // -- Check if list exists.
                 SPList list = web.Lists["MSDN Tasks"];
           }
           catch
           {
                 // -- If not, create the list.
                web.Lists.Add("MSDN Tasks", "A custom list",
SPListTemplateType.Tasks);
           }
       }


        public override void FeatureDeactivating(SPFeatureReceiverProperties
properties)
       {
           SPSite sitecollection = (SPSite)properties.Feature.Parent;
           SPWeb web = sitecollection.RootWeb;
           try
           {
                 // -- Check if list is there, and if so, delete it.
                 SPList list = web.Lists["MSDN Tasks"];
                 web.Lists.Delete(list.ID);
           }
           catch (Exception ex)
           {
           }
       }
        public override void FeatureInstalled(SPFeatureReceiverProperties
properties)
            {
            }


        public override void FeatureUninstalling(SPFeatureReceiverProperties
properties)
            {
            }
      }
}
The coding work results in two assemblies. One assembly contains the code delivering the Web Part. A
second assembly contains the previous code. At the moment of writing, Visual Studio Extensions for
Windows SharePoint Services 3.0 does not allow you to connect the event handler with the Web Part Feature
definition file. In addition, Web Part assembly must be deployed in the private application folder instead of
the global assembly cache. Because of this, you must create the solution package manually.


    Note:

 In the following steps, the way you organize the different files representing the solution components can be adapted to your
 part of the Visual Studio 2005 solution.

Create a folder with two subfolders to collect all of the solution components. A first subfolder stores the
assemblies (named Assemblies in this article), and the second subfolder stores the different XML files
defining the Features (named Features in this article). Copy the Web Part assembly and the event handler
assembly into the Assemblies folder.

Create a subfolder under the Features folder for every Feature that must be included in the SharePoint
solution. There is only one Feature for this walkthrough. Assume that it is called MSDNTaskCreator; the
Features folder contains a subfolder with that name. At the root of this folder, add a feature.xml file that
contains the following XML.

Xml


<Feature        Title="MSDNTaskCreator"
                Id="55312295-a323-4333-b875-1bbe8ef7fd04"
                Description="Small Web Part creating a custom task item"
                Version="1.0.0.0" Scope="Site" Hidden="FALSE"
          ReceiverAssembly="MSDNFeatureEventhandlers, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=5e5a470a5445a8f1"
                ReceiverClass="MSDN.Samples.MSDNTaskListEventHandler"
          DefaultResourceFile="core"
xmlns="http://schemas.microsoft.com/sharepoint/">
    <ElementManifests>
          <ElementManifest Location="elementManifest.xml" />
          <ElementFile Location="MSDNTaskCreator.webpart" />
    </ElementManifests>
</Feature>
How does this XML deviate from the XML that is generated with Visual Studio Extensions for Windows
SharePoint Services 3.0? Two additional attributes are added to the feature.xml file:


           The ReceiverAssembly attribute contains the full strong name of the .NET assembly that contains
            the event handler code.

           The ReceiverClass attribute stores the full name of the class within that assembly.

You must create a manifest file in the root folder. It is different from the one that is generated by Visual
Studio Extensions for Windows SharePoint Services 3.0. Following are the contents.

Xml


<Solution SolutionId="d63d0395-96a4-449e-83ce-5f7239bbd3ad"
xmlns="http://schemas.microsoft.com/sharepoint/" >
    <FeatureManifests>
          <FeatureManifest Location="MSDNTaskCreator\feature.xml" />
    </FeatureManifests>
    <Assemblies>
    <Assembly Location="MSDNTaskCreator.dll"
DeploymentTarget="WebApplication" >
            <SafeControls>
        <SafeControl Assembly="MSDNTaskCreator, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=9f4da00116c38ec5" Namespace="MSDN.Samples"
TypeName="MSDNTaskCreator" Safe="True" />
            </SafeControls>
          </Assembly>
        <Assembly Location="MSDNFeatureEventHandlers.dll"
DeploymentTarget="GlobalAssemblyCache" />
    </Assemblies>
</Solution>
Notice that the name of the Feature no longer includes a GUID. The first assembly element has an attribute
named DeploymentTarget, with the valueWebApplication instead of GlobalAssemblyCache. A second
assembly element with the definition of the .NET assembly contains the event handler code to deploy in the
global assembly cache.

Now we can create the .ddf file named, in this case, .wsp_structure.ddf. Create it directly in the
DeploymentFiles folder. First, add the following header information.


;
; *** .ddf file for generating SharePoint solution.
;
.OPTION EXPLICIT              ; Generate errors
.Set CabinetNameTemplate=MSDNTaskCreatorWebPart.wsp
.set DiskDirectoryTemplate=CDROM ; All cabinets go in a single directory
.Set CompressionType=MSZIP;** All files are compressed in cabinet files
.Set UniqueFiles="ON"
.Set Cabinet=on
.Set DiskDirectory1=Package
The header contains two fairly dynamic parts:


        CabinetNameTemplate is set to the name of the SharePoint solution file
         (MSDNTaskCreatorWebPart.wsp).

        DiskDirectory1 is set to Package. This is the directory containing the generated .wsp file.

The second part of the .ddf file defines the structure of the package.


; *** the manifest file
manifest.xml manifest.xml


; *** the feature files
Features\MSDNTaskCreator\feature.xml MSDNTaskCreator\feature.xml
Features\MSDNTaskCreator\elementManifest.xml
MSDNTaskCreator\elementManifest.xml
Features\MSDNTaskCreator\MSDNTaskCreator.webpart
MSDNTaskCreator\MSDNTaskCreator.webpart


; *** the assemblies
Assemblies\MSDNTaskCreator.dll MSDNTaskCreator.dll
Assemblies\MSDNFeatureEventhandlers.dll MSDNFeatureEventhandlers.dll
The .ddf file is input for MakeCab.exe, a tool you can get by installing the Microsoft Cabinet SDK
(C:\Program Files\Microsoft Cabinet SDK) and it is also part of the Smart Devices SDK
(C:\Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\SDKTools).


    Note:

 You can download the Microsoft Cabinet SDK from Internet Client SDK: Microsoft Cabinet SDK.
To facilitate the packaging and deployment, create a batch file with the following content.
set MakeCabTool=c:\Program Files\Microsoft Visual Studio
8\SmartDevices\SDK\SDKTools\makecab.exe
set SPAdminTool=%CommonProgramFiles%\Microsoft Shared\web server
extensions\12\BIN\stsadm.exe


"%MakeCabTool%" /f wsp_structure.ddf
"%SPAdminTool%" -o addsolution -filename package\ MSDNTaskCreatorWebPart.wsp
"%SPAdminTool%" -o deploysolution -name MSDNTaskCreatorWebPart.wsp -immediate
-allowGACDeployment -url http://moss.litwareinc.com
The first two lines are the settings of the paths to the Makecab and Stsadm command-line tools. Next, there
is the line creating the solution package.


makecab.exe /f wsp_structure.ddf
As a result of the execution, MSDNTaskCreatorWebPart.wsp appears in the Package folder. The next line
adds the MSDNTaskCreatorWebPart.wsp to the solution store in your server farm by executing the following
command.


stsadm.exe -o addsolution -filename Package\MSDNTaskCreatorWebPart.wsp
The final line in the batch file is the deployment of the solution to one of your site collections. You can use
the Solution Management page under the Operationstab in Central Administration, or open a Command
Prompt window again and execute the following command line.


stsadm.exe -o deploysolution -name MSDNTaskCreatorWebPart.wsp -local -
allowGACDeployment -url http://moss.litwareinc.com
The Web Part Feature is installed but not activated. To activate the Feature, open the Site Collection
Features page, and then click the Activate button. Because there is code that executes when
the FeatureActivated event fires, the MSDN Task list is created. Deactivating this feature removes this
task list from the root site of the site collection.

Code Access Security and Web Part Solutions
In many locked-down environments, administrators do not allow custom code components to have Full
trust. Administrators might choose to deploy a solution to the Web application \bin folder, where
permissions must be specifically granted. Let‘s look at the steps that are involved.

We can show all of this with a small Web Part that connects to a Web service that returns weather
information for a specific city. If you build and deploy this Web Part by using Visual Studio 2005 Extensions
for Windows SharePoint Services 3.0, the .NET assembly is deployed in the global assembly cache. You
cannot intervene in this process on your development computer to configure the solution generation process
and deployment differently. Because of the deployment in the global assembly cache, your Web Part gets
full trust and does not have any security problems connecting to the Web service.

This scenario works if administrators allow your Web Part assemblies to be deployed in the global assembly
cache. However, your Web Part assembly can often end up in the private \bin folder of the IIS Web
application. As a Web Part developer, you then depend on the trust level set in the web.config file by
administrators. In the end, you can encounter security problems with Web Parts that perform functions
similar to our weather Web Part, as described in the following walkthrough.

Walkthrough: Code Access Security and Web Part Solutions
Let‘s assume you have a small Web service that returns the weather for a city, and that there is a Web Part
that consumes the information, as shown in Figure 21. (You can work out an example with any type of Web
service.)
Figure 21. Web Part consuming a weather Web service




To deploy the Web Part assembly in the private application folder of the IIS Web application instead of the
global assembly cache (which is the default when using Visual Studio 2005 Extensions for Windows
SharePoint Services 3.0), you can make a change in the manifest file that will enforce this. You can set
theDeploymentTarget attribute at the level of the Assembly element to WebApplication instead
of GlobalAssemblyCache, as shown in the following example.

Xml
<Solution SolutionId="1de3b0fc-78e9-4fe6-ae63-51ea50109982"
xmlns="http://schemas.microsoft.com/sharepoint/" >
  <FeatureManifests>
      <FeatureManifest Location="WeatherWebPart\feature.xml" />
  </FeatureManifests>
  <Assemblies>
      <Assembly Location="WeatherWebPart.dll"
       DeploymentTarget="WebApplication" >
        <SafeControls>
        <SafeControl Assembly="WeatherWebPart, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=9f4da00116c38ec5" Namespace="WeatherWebPart"
TypeName="WeatherWebPart" Safe="True" />
        </SafeControls>
      </Assembly>
  </Assemblies>
</Solution>
Next, you must create the Windows SharePoint Services solution manually. The following .ddf file shows how
to package the different components that make up the Web Part solution.


.OPTION EXPLICIT
.Set CabinetNameTemplate=WeatherWebPart.wsp
.set DiskDirectoryTemplate=CDROM ; All cabinets go in a single directory
.Set CompressionType=MSZIP ;** All files are compressed in cabinet files
.Set UniqueFiles="OFF"
.Set Cabinet=on
.Set DiskDirectory1=Package


manifest.xml manifest.xml
assemblies\WeatherWebPart.dll WeatherWebPart.dll


Features\WeatherWebPart\feature.xml                  WeatherWebPart\feature.xml
Features\WeatherWebPart\elementManifest.xml
WeatherWebPart\elementManifest.xml
Features\WeatherWebPart\WeatherWebPart.webpart
WeatherWebPart\WeatherWebPart.webpart
A simple call to Makecab.exe with the .ddf file as input generates the Windows SharePoint Services solution.


makecab.exe /f WeatherWebPart.ddf
You can add the solution to the solution store by executing the following command in a Command Prompt
window.


stsadm.exe -o addsolution -filename package\weatherwebpart.wsp
Now, navigate to Central Administration and the Solution Management page. From here you can deploy the
solution. Notice that there is no warning because the manifest file does not require the assembly to be
deployed in the global assembly cache. Proceed and deploy the solution to one of your IIS Web applications.
It‘s a good idea to verify in the physical folder that is associated with the IIS Web application (which is
located, by default, in Inetpub\wwwroot\wss\VirtualDirectories\IIS Web application name) that
the assembly is available in the \bin folder.

Assuming the trust level in the web.config file is not set to Full, you get an exception if you try to run your
weather Web Part, as shown in Figure 22.




Figure 22. Weather Web Part deployed in private application folder
The Weather Web Part deployed in the private application folder causes unexpected problems. However, the
error is not unexpected. Open the Windows Event Viewer (located in Administration Tools) and you find the
full details of the error: "Request for the permission of type 'System.Net.WebPermission, System,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."

In other words, your Web Part is not granted the permission to communicate with the Web service. How do
you solve this? One way is to raise the trust level in the web.config file to Full, but this is risky. From the
moment you raise the trust level, all of the privately deployed assemblies get the same basic permissions as
the assemblies that are deployed in the global assembly cache. A better solution is to request the
permissions that are needed to run the Web Part correctly in SharePoint pages and include that demand
inside the manifest file. Administrators who deploy the solution will receive a notification that specific
requests for permissions are pending, and they can decide whether to grant these permissions. When
proceeding, a copy is made of the policy file that is currently activated, and the requested permissions for
the Web Part are added. This new policy file becomes the one activated in the web.config file. Now we can
examine all of these steps in more detail.

One piece of information is already available. You have the full details of the required permission (discussed
previously). Another piece of information is the full public key blob of the assembly you‘re working with. To
retrieve this information, open a Command Prompt window, and execute the following command.


Secutil.exe –hex –s WeatherWebPart.dll > keyblob.txt
The result is a text file with the full public key of the assembly in question. The tool used is secutil.exe,
which is part of the .NET Framework SDK.

Next, open the manifest file, and add the following CodeAccessSecurity element (a good location is
between the FeatureManifests and the Assemblieselements).

Xml
      <CodeAccessSecurity>
        <PolicyItem>
             <PermissionSet class="NamedPermissionSet" version="1"
      Description="My webpart's permission set">
                 <IPermission class="AspNetHostingPermission" version="1"
                     Level="Minimal"/>
                <IPermission class="SecurityPermission" version="1"
                     Flags="Execution" />
                <IPermission version="1" Unrestricted="True"
   class="Microsoft.SharePoint.Security.SharePointPermission,
Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" />
            <IPermission class="System.Net.WebPermission, System,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
Unrestricted="True"
                version="1">
                     <ConnectAccess>
                         <URI uri="$OriginHost$"/>
                         <URI uri="http://moss:95/webservices/.*"/>
                         </ConnectAccess>
                </IPermission>
            </PermissionSet>
            <Assemblies>
            <Assembly Name="WeatherwebPart" Version="1.0.0.0"
PublicKeyBlob="0x002400000480000094000000060200000024000052534131000400000100
01000DAF8ED8D945CD2ABB2EE7953A6039B791A725F11B4588AC6D70B3E0648F955E9ED4C3C43
CB044B8B0E8A6FF4D4FFBE9E3B9297D45F688A7264534E12414E17539305207EC961DA94DF294
E7722CCD9BDBFC95A896E996F57156705D281EC39280BD604E87724556AF5807D146963F19F5B
43DB69E1F22695463153A553260D2" />
            </Assemblies>
        </PolicyItem>
    </CodeAccessSecurity>
In the previous code, the IPermission and Assembly element areas are important to review. First,
the IPermission element asks for permission to communicate with the Web service (we assume that this
Web service is hosted on http://moss:95 IIS Web Application). Next, the Assembly element
contains the details of the assembly in question: the name, version, and blob you must retrieve from the
keyblob.txt file that is generated via the secutil.exe utility.

When these changes are applied to the manifest file, you must regenerate the Windows SharePoint Services
solution and re-add it to the solution store. When you deploy the solution, you will notice a warning at the
bottom of the page (see Figure 23) that indicates that the solution contains a code access security policy
that will take effect if you continue to deploy the solution. If the administrators do not see a problem with
this, they can continue and the Web Part is made available.




Figure 23. Deploying a Web Part solution with a code access security policy
If you followed all of the earlier steps correctly, the weather Web Part works again as before. Behind the
scenes, you notice a new entry in the securityPolicyelement of the web.config file that looks like the
following.

Xml


<securityPolicy>
      <trustLevel name="WSS_Medium" policyFile="C:\Program Files\Common
Files\Microsoft Shared\Web Server
Extensions\12\config\wss_mediumtrust.config" />
      <trustLevel name="WSS_Minimal" policyFile="C:\Program Files\Common
Files\Microsoft Shared\Web Server
Extensions\12\config\wss_minimaltrust.config" />
      <trustLevel name="WSS_Custom" policyFile="C:\Program Files\Common
Files\Microsoft Shared\Web Server
Extensions\12\config\wss_custom_wss_minimaltrust.config" />
      </securityPolicy>
The new level—WSS_Custom—is now the active trust level in the web.config file.

Managing Solutions
Windows SharePoint Services 3.0 also offers support for managing SharePoint solutions. You can retract
solutions, remove solutions from the solution store, and upgrade solutions in several ways.

Retracting Solutions
When you retract a SharePoint solution, Windows SharePoint Services physically removes all of the solution
components from the location where they were deployed. Retracting a solution can be completed in three
ways:
       By using Stsadm.exe

       By using Central Administration

       By using the Windows SharePoint Services 3.0 object model

These methods are described in the following sections.

Using Stsadm.exe

The option named retractsolution accepts several parameters. The name of the solution is a required
parameter. Optionally, you can specify the URL for a specific IIS Web application and site collection, or
remove the solution from all places where it was deployed via the allcontenturls parameter.
The time parameter schedules the retraction for a job definition. You use the immediate parameter when
you want to perform actions directly.

Following is a typical command for retracting a solution.


stsadm.exe –o retractsolution –name hellowebpart.wsp -immediate
Using Central Administration

After the solution is available in the solution store, you access it via the solution management page in
Central Administration. From here you can start the process of retracting a solution, as shown in Figure 24.




Figure 24. Retracting a Web Part from an IIS Web application
Using the Windows SharePoint Services 3.0 Object Model

A final approach to retracting a solution is through the Windows SharePoint Services 3.0 object model.
The SPSolution class exposes the Retract andRetractLocal methods. You can use Retract to schedule
the retracting of the solution. Both methods offer the option to retract the solution from all or from only a
specific collection of SPWebApplication objects. The following code example retracts a Web Part solution
from all IIS Web applications that are available on a local computer.

C#


SPSolution solution = SPFarm.Local.Solutions["hellowebpart.wsp"];
solution.RetractLocal();
Retracting Web Part Solutions

You can retract a solution that delivers Web Parts by using one of the previously mentioned options.
However, you should notice that retracting the Web Part does not remove the .webpart entry from the Web
Part gallery. As a consequence, the Web Part remains advertised in the Add a Web Part dialog box, and
users can still see it. However, when users add the Web Part to a page, errors are shown because the Web
Part is no longer registered as a safe control, and the assembly is removed from either the local bin folder or
the global assembly cache. Also notice that retracting a Web Part solution causes existing Web Part
instances to stop working and displays an error in the SharePoint pages. To solve this, you can have a
deactivation callout that deletes the .webpart file from the Web Part Gallery.

Retracting Schema-based Solutions
You must take care when retracting schema-based solutions, such as custom list definitions. Many instances
can exist, and you probably don't want to break them. Therefore, best practice when instances of these
types of solutions are available is to make the Feature invisible to the user rather than retracting the
solutions. A small walkthrough in the section on upgrading solutions, later in the article, shows the different
steps.

Removing Windows SharePoint Services Solutions
Windows SharePoint Services solutions that are no longer deployed can be removed from the solution store.
You can do this in three ways:


       By using Stsadm.exe

       By using Central Administration

       By using the Windows SharePoint Services 3.0 object model

The following sections describe these methods.

Using Stsadm.exe

Administrators can now launch the command-line utility Stsadm.exe, and then execute
the deletesolution option. The name parameter is the name of the solution and is required. Use the
following command to remove a solution.


stsadm.exe –o deletesolution –name hellowebpart.wsp
Using Central Administration

On the solution management page, which is accessible via the Operations tab in Central Administration,
you can remove a solution that is no longer deployed. Just click the solution name and use the Remove
Solution button on the toolbar.

Using the Windows SharePoint Services 3.0 Object Model

You can also remove the solution by calling the Remove method at the level of
the SPSolutionCollection object. This collection is exposed via the SPFarmclass, either for the local farm
or from the joined farm. The following code removes a solution from the solution store.


SPFarm.Local.Solutions.Remove("hellowebpart.wsp");
Upgrading Solutions
The last option for managing SharePoint solutions is to upgrade deployed solutions to new versions. It is
important to understand that the versioning is not performed at the level of the Windows SharePoint
Services solution. The actual versioning is performed at the level of the solution components (the Feature,
the assemblies, and so on).

Figure 25 summarizes how to perform a solution upgrade.




Figure 25. Upgrading the SharePoint solution
Assume that version 1.0.0.0 of the MySolution.wsp is added to the solution store and deployed to one or
more IIS Web applications. A second version of the Windows SharePoint Services solution must have the
same SolutionID for an upgrade to succeed. The second version is upgraded by calling the Stsadm.exe
command-line utility with the option upgradesolution. In the solution store, you provide the name of the
solution to upgrade, the new version of the solution, and then specify the options to either schedule the
upgrade or have it upgrade immediately. You also specify the options to allow deployment in the global
assembly cache and allow for custom code access security policies.

Guidelines for Upgrading SharePoint Solutions

When discussing guidelines for upgrading SharePoint solutions, we must make the distinction between code-
based solutions (such as Web Parts) and schema-based solutions (such custom list definitions).


       Upgrading Web Part solutions Web Parts are typical examples of code-based solutions.
        Upgrading a code-based solution often involves replacing the assembly in the private application
        folder of the IIS Web application or the global assembly cache with an updated version of the
        assembly. Figure 26 summarizes the possible upgrade paths.




        Figure 26. Upgrading Web Parts
version number of the .NET assembly, the upgrade process proceeds smoothly. By leaving the version
number of the assembly unchanged, you ensure that the metadata stored and made available, for example,
in the form of a .webpart registration in the Web Part gallery, does not need to be changed. All the existing
instances of the Web Parts on pages upgrade easily.

The upgrade process is a bit more complex when the strong name of the assembly is changed, typically by
upgrading the version number from perhaps 1.0.0.0 to 2.0.0.0. If no Web Part instances have been created
within the sites, you will not have a problem. The entry in the Web Part gallery is updated with the new
.webpart file, and the new version of the assembly is dropped in either the bin folder or the global assembly
cache. New additions of the Web Part to the pages reflect the new functionality.

However, users can experience errors when there are existing instances of the older version of the Web Part
on the pages, and you decide to perform an upgrade. These instances are still looking for the first version of
the assembly. When using the upgradesolution option, the older version of the assembly is actually
removed, as well as the entry in the safeControls section of the web.config file.

So your approach is a combination of upgrading the Web Part solution with a new version of the assembly
combined with two additions in the web.config of the IIS Web application hosting the SharePoint site. These
two additions are, first a SafeControl element for the first version of the assembly, and second,
a bindingRedirect ordering ASP.NET to bind to the second version of the assembly, in case there is the
request for the first version.

Walkthrough: Upgrading a Web Part Project

To upgrade a Web Part project
    1. Start by building a small Web Part project that outputs a string that displays, for example, the
       version information. You can use Visual Studio 2005 Extensions for Windows SharePoint Services
       3.0 to get started, but you must perform the packaging and deployment manually. We advise a
        project structure such as the one depicted in Figure 27. All of the techniques previously discussed
        regarding the manual packaging of a SharePoint solution are used here.




        Figure 27. Project structure for a Web Part solution




Deploy the solution and activate the Feature in the site collection so that you can add the Web Part to one of
your pages (see Figure 28).
1.   Assume that there is the request to update the Web Part. Users want to see a slightly different
     string in the Web Part. Start by changing the rendering of the content in the Web Part and follow up
     with a change of the version number of the assembly from 1.0.0.0 to 2.0.0.0 using the properties of
     the Web Part project. Build the project.

2.   Open the .webpart file and update the version number for the type element.

3.   Build the project and rebuild the SharePoint solution file. Upgrade the solution by calling the
     following from either a batch file or a command prompt.


     Stsadm -o upgradesolution -name VersionDemo.wsp -filename
     VersionDemo.wsp -immediate -allowgacdeployment
4.   Refresh the page with the Web Part instance. Figure 29 shows the error displayed as well as a new
     instance nicely reflecting the change in the output.




     Figure 29. Web Part displaying error and rendering correctly




1.   Solve the error that is displayed:

         1.   Add the SafeControl element for version 1.0.0.0 in the web.config file.




              Xml

              <SafeControl Assembly="VersionDemo, Version=1.0.0.0,
              Culture=neutral, PublicKeyToken=9f4da00116c38ec5"
              Namespace="MSDN.Samples" TypeName="VersionDemo" Safe="True" />

         2.   Add the following element in the web.config file under the assemblyBinding element for
              the redirect operation.
             Xml

             <runtime>
                   <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
                        <dependentAssembly>
                         <assemblyIdentity name="VersionDemo"
             publicKeyToken="9f4da00116c38ec5" culture="neutral" />
                         <bindingRedirect oldVersion="1.0.0.0"
             newVersion="2.0.0.0" />
                        </dependentAssembly>
             …
                   </assemblyBinding>
             </runtime>
2.   Refresh the page containing the two Web Part instances. Figure 30 shows the end result. The first
     version of the Web Part now also works against the 2.0.0.0 version of the assembly.




     Figure 30. Both Web Parts working correctly




    Upgrading Schema-Based Solutions An example of a schema-based solution is a custom list
     definition. Generally, to upgrade these types of solutions when instances based on the schema
     definitions are present on SharePoint sites, you deploy a new version of the Feature and mark the
     older version as hidden for the user. This way, the instances do not break, and new instances follow
     the updated definitions.

     Walkthrough: Upgrading Schema-Based Solutions

     Let's return to the Employees list template we created and deployed as a SharePoint solution earlier
     in the article.
Assume that users have created many instances of this list. The decision has been made to make
changes or possibly to completely remove the list definition. As mentioned, you cannot simply
remove the solution files from the SharePoint computer. You need to keep them working, although
invisible, for the administrators and users. Notice that this approach is also the one to take as an
alternative to retracting the solution, as discussed earlier.

Here are the steps to accomplish upgrading a schema-based solution.

To upgrade a schema-based solution
    1. Open the folder containing the solution components of the list definition, and then open the
       feature.xml file.

    2.   Change the Hidden attribute of the Feature element to the value TRUE.

         Xml

         <Feature Id="{489C77F1-B064-408e-9B85-029A33BDF9D7}"
               Title="Employees"
             Description="This feature provides support for creating an
         Employee List."
               Version="1.0.0.0"
               Scope="Web"
               Hidden="TRUE"
               xmlns="http://schemas.microsoft.com/sharepoint/">
               <ElementManifests>
                    <ElementManifest Location="ListTemplates\Employees.xml"/>
                    <ElementFile Location="Employees\allitems.aspx" />
                    <ElementFile Location="Employees\dispform.aspx" />
                    <ElementFile Location="Employees\editform.aspx" />
                    <ElementFile Location="Employees\newform.aspx" />
                    <ElementFile Location="Employees\schema.xml" />
               </ElementManifests>
         </Feature>
         This hides the Feature from the administration pages, but you must also hide it on the
         Create page.

    3.   Open the employees.xml file and add the Hidden attribute.

         Xml

         <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
               <ListTemplate
                      Name="Employees"
                                 Type="10100"
                                 BaseType="0"
                                 OnQuickLaunch="TRUE"
                                 SecurityBits="11"
                                 DisplayName="Employees"
                                 Description="Employees List Type"
                                 Hidden="TRUE"
                                 Image="/_layouts/images/CHNGCOL.GIF"/>
                   </Elements>

           If you want to retract only the solution, the previous steps are enough.

           If, however, you want to replace the list definition with a new version, you‘ll need to add the
           following to the solution package:


                  A new version of the Feature (with all of the related files) marked with a different GUID.

                   An expanded manifest file with the installation steps for both the original (and soon hidden)
              version, and the new version of the Feature.

                   An expanded .ddf file containing the entries for packaging the new Feature and the previous
              version in the .wsp file.

           In both scenarios, you must recreate the SharePoint solution file and deploy it by using
           the upgradesolution option for Stsadm, as discussed previously.


           Stsadm.exe -o upgradesolution -filename package\Employees.wsp -name
           Employees.wsp –immediate

Conclusion
The concept of solutions in the world of Windows SharePoint Services is extremely important for developers
and administrators to understand. Developers who build applications and extend SharePoint sites in
numerous ways must package the solution components in SharePoint solution files and deliver those to
administrators. Administrators have various options for delivering the solution to the users of the SharePoint
sites. This article discusses new options that are available for pushing the solutions from a central solution
store to the front-end Web servers and application servers. The article also discusses techniques for
maintaining and upgrading the deployed solutions.
Best Practices: Common Coding Issues When Using the
SharePoint Object Model
Summary: Learn common issues encountered by developers who write custom code by using the
SharePoint object model. (15 printed pages)

Scott Harris, Microsoft Corporation

Mike Ammerlaan, Microsoft Corporation

Steve Peschka, Microsoft Corporation

Roger Lamb, Microsoft Corporation

Published: September 2007

Updated: April 2009

Applies to: Windows SharePoint Services 3.0, Windows SharePoint Services 2.0, Microsoft Office SharePoint
Server 2007

Contents


       Overview

       Using SharePoint Data and Objects Efficiently

       Working with Folders and Lists

       Writing Applications That Scale to Large Numbers of Users

       Using SPQuery Objects

       Using Web Controls

       Creating Timer Jobs

       Conclusion

       Additional Resources

Overview
Developers who write custom code with the SharePoint object model will encounter common issues related
to performance, extensibility, and scalability. This article is a resource for developers who are working to
troubleshoot and improve the performance of existing SharePoint applications or who are writing new
SharePoint applications. In both cases, it is important to understand how to make the SharePoint object
model work efficiently, and how to apply general programming techniques (such as caching and threading)
to the SharePoint platform specifically. This information can make it easier to design your applications
correctly, find and fix problem areas in your code, and avoid known pitfalls of using the SharePoint object
model.

The following areas reflect the most common general concerns encountered by SharePoint developers:


       Using SharePoint data and objects efficiently
       Performance concerns related to folders, lists, and SPQuery objects

       Writing applications that scale to large numbers of users

       Using Web controls and timer jobs

       Disposing of SharePoint objects

This article addresses all but the last of these issues. For guidance on disposing of SharePoint objects,
see Best Practices: Using Disposable Windows SharePoint Services Objects.

Additionally, we recommend that you read the following orientation topics as good starting points for using
the SharePoint object model:


       Server and Site Architecture: Object Model Overview

       Understanding the Administrative Object Model of Windows SharePoint Services 3.0

Using SharePoint Data and Objects Efficiently
Caching is one good way to improve system performance. However, you must weigh the benefits of caching
against the need for thread safety. Additionally, you should not create certain SharePoint objects within
event receivers because this will cause performance problems related to excessive database calls.

This section describes these common areas of concern so that you can learn ways to optimize your use of
SharePoint objects and data.

Caching Data and Objects
Many developers use the Microsoft .NET Framework caching objects (for
example, System.Web.Caching.Cache) to help take better advantage of memory and increase overall
system performance. But many objects are not "thread safe" and caching those objects can cause
applications to fail and unexpected or unrelated user errors.


  Note:

 The caching techniques discussed in this section are not the same as the custom caching options for Web
 content management that are discussed inCustom Caching Overview.
Caching SharePoint Objects That Are Not Thread Safe
You might try to increase performance and memory usage by caching SPListItemCollection objects that
are returned from queries. In general, this is a good practice; however, the SPListItemCollection object
contains an embedded SPWeb object that is not thread safe and should not be cached.

For example, assume the SPListItemCollection object is cached in a thread. As other threads try to read
this object, the application can fail or behave strangely because the embedded SPWeb object is not thread
safe. For more information about the SPWeb object and thread safety, see
the Microsoft.SharePoint.SPWebclass.

The guidance in the following section describes how you can prevent multiple threads from attempting to
read the same cached object.

Understanding the Potential Pitfalls of Thread Synchronization
You might not be aware that your code is running in a multithreaded environment (by default, Internet
Information Services, or IIS, is multithreaded) or how to manage that environment. The following example
shows the code some developers use to cache Microsoft.SharePoint.SPListItemCollection objects.

Bad Coding Practice
Caching an Object That Multiple Threads Might Read

C#


public void CacheData()
{
     SPListItemCollection oListItems;


     oListItems = (SPListItemCollection)Cache["ListItemCacheName"];
     if(oListItems == null)
     {
         oListItems = DoQueryToReturnItems();
         Cache.Add("ListItemCacheName", oListItems, ..);
     }
}
Although the use of the cache in this example is functionally correct, because the ASP.NET cache object is
thread safe, it introduces potential performance problems. (For more information about ASP.NET caching,
see the Cache class.) If the query in the preceding example takes 10 seconds to complete, many users could
try to access that page simultaneously during that amount of time. In this case, all of the users would run
the same query, which would attempt to update the same cache object. If that same query runs 10, 50, or
100 times, with multiple threads trying to update the same object at the same time—especially on
multiprocess, hyperthreaded computers—performance problems would become especially severe.

To prevent multiple queries from accessing the same objects simultaneously, you must change the code as
follows.

Applying a Lock

Checking for null

C#


private static object _lock =             new object();


public void CacheData()
{
     SPListItemCollection oListItems;


     lock(_lock)
     {
         oListItems = (SPListItemCollection)Cache["ListItemCacheName"];
         if(oListItems == null)
         {
                  oListItems = DoQueryToReturnItems();
                  Cache.Add("ListItemCacheName", oListItems, ..);
         }
     }
}
You can increase performance slightly by placing the lock inside the if(oListItems == null) code
block. When you do this, you do not need to suspend all threads while checking to see if the data is already
cached. Depending on the time it takes the query to return the data, it is still possible that more than one
user might be running the query at the same time. This is especially true if you are running on
multiprocessor computers. Remember that the more processors that are running and the longer the query
takes to run, the more likely putting the lock in the if() code block will cause problems. If you want to
make absolutely sure that another thread has not created oListItems before the current thread has a
chance to work on it, you could use the following pattern.

Applying a Lock

Rechecking for null

C#


private static object _lock =              new object();


public void CacheData()
{
     SPListItemCollection oListItems;
                 oListItems = (SPListItemCollection)Cache["ListItemCacheName"];
             if(oListItems == null)
             {
                  lock (_lock)
                  {
              //Ensure that the data was not loaded by a concurrent thread
while waiting for lock.
                       oListItems = (SPListItemCollection)Cache[“ListItemCacheName”];
                       if (oListItems == null)
                       {
                            oListItems = DoQueryToReturnItems();
                            Cache.Add("ListItemCacheName", oListItems, ..);
                       }
                  }
         }
}
If the cache is already populated, this last example performs as well as the initial implementation. If the
cache is not populated and the system is under a light load, acquiring the lock will cause a slight
performance penalty. This approach should significantly improve performance when the system is under a
heavy load, because the query will be executed only once instead of multiple times, and queries are usually
expensive in comparison with the cost of synchronization.

The code in these examples suspends all other threads in a critical section running in IIS, and prevents
other threads from accessing the cached object until it is completely built. This addresses the thread
synchronization issue; however, the code is still not correct because it is caching an object that is not thread
safe.

To address thread safety, you can cache a DataTable object that is created from
the SPListItemCollection object. You would modify the previous example as follows so that your code gets
the data from the DataTable object.

Good Coding Practice

Caching a DataTable Object

C#


private static object _lock =               new object();


public void CacheData()
{
     DataTable oDataTable;
     SPListItemCollection oListItems;
     lock(_lock)
     {
               oDataTable = (DataTable)Cache["ListItemCacheName"];
               if(oDataTable == null)
               {
                    oListItems = DoQueryToReturnItems();
                    oDataTable = oListItems.GetDataTable();
                    Cache.Add("ListItemCacheName", oDataTable, ..);
               }
     }
}
For more information and examples of using the DataTable object, and other good ideas for developing
SharePoint applications, see the reference topic for theDataTable class.

Using Objects in Event Receivers
Do not instantiate SPWeb, SPSite, SPList, or SPListItem objects within an event receiver. Event receivers
that instantiate SPSite, SPWeb, SPList, orSPListItem objects instead of using the instances passed via
the event properties can cause the following problems:
            They incur significant additional roundtrips to the database. (One write operation can result in up to
             five additional roundtrips in each event receiver.)

            Calling the Update method on these instances can cause subsequent Update calls in other
             registered event receivers to fail.

Bad Coding Practice

Instantiating an SPSite Object Inside an Event Receiver

C#


public override void ItemDeleting(SPItemEventProperties properties)
{
         using (SPSite site = new SPSite(properties.WebUrl))


         using (SPWeb web = site.OpenWeb())
               {
               SPList list = web.Lists[properties.ListId];
               SPListItem item = list.GetItemByUniqueId(properties.ListItemId);
               // Operate on item.
               }
         }
}
Good Coding Practice

Using SPItemEventProperties

C#


// Retrieve SPWeb and SPListItem from SPItemEventProperties instead of
// from a new instance of SPSite.
SPWeb web = properties.OpenWeb();
// Operate on SPWeb object.
SPListItem item = properties.ListItem;
// Operate on item.
If you do not apply this fix in your code, when you call Update on the new instance, you must invalidate it
with the Invalidate method in the appropriate child class of SPEventPropertiesBase (for
example, SPItemEventProperties.InvalidateListItem or SPItemEventProperties.InvalidateWeb).

Working with Folders and Lists
When folders and lists grow in size, custom code that works with them needs to be designed in ways that
optimize performance. Otherwise, your applications will run slowly and even cause timeouts to occur. The
following recommendations for addressing performance concerns while working with large folders and lists
are based on the test results reported in Steve Peschka's white paper, Working with Large Lists in Office
SharePoint Server 2007.

    1.   Do not use SPList.Items.

         SPList.Items selects all items from all subfolders, including all fields in the list. Use the following
         alternatives for each use case.



                Retrieving all items in a list

                 Use SPList.GetItems(SPQuery query) instead. Apply filters, if appropriate, and specify
                 only the fields you need to make the query more efficient. If the list contains more than
                 2,000 items, you will need to paginate the list in increments of no more than 2,000 items.
                 The following code example shows how to paginate a large list.

                 Good Coding Practice

                 Retrieving Items with SPList.GetItems




                 C#

                 SPQuery query = new SPQuery();
                 SPListItemCollection spListItems ;
                 string lastItemIdOnPage = null; // Page position.
                 int itemCount = 2000


                 while (itemCount == 2000)
                 {
                       // Include only the fields you will use.
                     query.ViewFields = "<FieldRef Name=\"ID\"/><FieldRef
                 Name=\"ContentTypeId\"/>";
                       query.RowLimit = 2000; // Only select the top 2000.
                       // Include items in subfolder (if necessary).
                       query.ViewAttributes = "Scope=\"Recursive\"";
                       StringBuilder sb = new StringBuilder();
                     // To make it order by ID and stop scanning the table,
                 specify the OrderBy override attribute.
                     sb.Append("<OrderBy Override=\"TRUE\"><FieldRef
                 Name=\"ID\"/></OrderBy>");
                       //.. Append more text as necessary ..
                       query.Query = sb.ToString();
                       // Get 2,000 more items.
    SPListItemCollectionPosition pos = new
SPListItemCollectionPosition(lastItemIdOnPage);
     query.ListItemCollectionPosition = pos; //page info
     spListItems = spList.GetItems(query);
    lastItemIdOnPage
= spListItems.ListItemCollectionPosition.PagingInfo;
     // Code to enumerate the spListItems.
     // If itemCount <2000, we finish the enumeration.
     itemCount = spListItems.Count;


}

The following example shows how to enumerate and paginate a large list.




C#

SPWeb oWebsite = SPContext.Current.Web;
SPList oList = oWebsite.Lists["Announcements"];


SPQuery oQuery = new SPQuery();
oQuery.RowLimit = 10;
int intIndex = 1;


do
{
     Response.Write("<BR>Page: " + intIndex + "<BR>");
     SPListItemCollection collListItems = oList.GetItems(oQuery);


     foreach (SPListItem oListItem in collListItems)
     {


Response.Write(SPEncode.HtmlEncode(oListItem["Title"].ToString())
+"<BR>");
     }
                 oQuery.ListItemCollectionPosition =
             collListItems.ListItemCollectionPosition;
                  intIndex++;
             } while (oQuery.ListItemCollectionPosition != null);

            Getting items by identifier

             Instead of using SPList.Items.GetItemById, use SPList.GetItemById(int id, string
             field1, params string[] fields). Specify the item identifier and the field that you want.

2.   Do not enumerate entire SPList.Items collections or SPFolder.Files collections.

     Accessing the methods and properties that are listed in the left column of the following table will
     enumerate the entire SPList.Items collection, and cause poor performance and throttling for large
     lists. Instead, use the alternatives listed in the right column.

     Table 1. Alternatives to SPList.Items

                                                                       Better Performing
     Poor Performing Methods and Properties                            Alternatives

      SPList.Items.Count                                               SPList.ItemCount

      SPList.Items.XmlDataSchema                                       Create an SPQuery object to
                                                                       retrieve only the items you want.

      SPList.Items.NumberOfFields                                      Create an SPQuery object
                                                                       (specifying the ViewFields) to
                                                                       retrieve only the items you want.

      SPList.Items[System.Guid]                                        SPList.GetItemByUniqueId(Sy
                                                                       stem.Guid)

      SPList.Items[System.Int32]                                       SPList.GetItemById(System.I
                                                                       nt32)

      SPList.Items.GetItemById(System.Int32)                           SPList.GetItemById(System.I
                                                                       nt32)

      SPList.Items.ReorderItems(System.Boolean[],System.I              Perform a paged query by
      nt32[],System.Int32)                                             using SPQuery and reorder the
                                                                       items within each page.

      SPFolder.Files.Count                                             SPFolder.ItemCount

       Note:

      The SPList.ItemCount property is the recommended way to retrieve the number of items in a
      list. As a side effect of tuning this property for performance, however, the property can
      occasionally return unexpected results. If the precise number is required, you should use the
      poorer performing GetItems(SPQuery query), as shown in the preceding code example.


3.   Use PortalSiteMapProvider (Microsoft Office SharePoint Server 2007 only).

     Steve Peschka's white paper Working with Large Lists in Office SharePoint Server 2007 describes an
     efficient approach to retrieving list data in Office SharePoint Server 2007 by using
     the PortalSiteMapProvider class. PortalSiteMapProvider provides an automatic caching
infrastructure for retrieving list data. The GetCachedListItemsByQuery method
of PortalSiteMapProvider takes an SPQuery object as a parameter, and then checks its cache to
determine whether the items already exist. If they do, the method returns the cached results. If
not, it queries the list and stores the results in a cache. This approach works especially well when
you are retrieving list data that does not change significantly over time. When data sets change
frequently, the class incurs the performance cost of continually writing to the cache in addition to
the costs of reading from the database. Consider that thePortalSiteMapProvider class uses the
site collection object cache to store data. This cache has a default size of 100 MB. You can increase
the size of this cache for each site collection on the object cache settings page for the site collection.
But this memory is taken from the shared memory available to the application pool and can
therefore affect the performance of other applications. Another significant limitation is that you
cannot use thePortalSiteMapProvider class in applications based on Windows Forms. The
following code example shows how to use this method.

Good Coding Practice

Using PortalSiteMap Provider




C#

// Get the current SPWeb object.
SPWeb curWeb = SPControl.GetContextWeb(HttpContext.Current);


// Create the query.
SPQuery curQry = new SPQuery();
curQry.Query = "<Where><Eq><FieldRef Name='Expense_x0020_Category'/>
<Value Type='Text'>Hotel</Value></Eq></Where>";


// Create an instance of PortalSiteMapProvider.
PortalSiteMapProvider ps = PortalSiteMapProvider.WebSiteMapProvider;
PortalWebSiteMapNode pNode =
ps.FindSiteMapNode(curWeb.ServerRelativeUrl) as PortalWebSiteMapNode;


// Retrieve the items.


SiteMapNodeCollection pItems = ps.GetCachedListItemsByQuery(pNode,
"myListName_NotID", curQry, curWeb);


// Enumerate through all of the matches.
foreach (PortalListItemSiteMapNode pItem in pItems)
     {
     // Do something with each match.
                }

     4.   Whenever possible, acquire a reference to a list by using the list's GUID or URL as a key.

          You can retrieve an SPList object from the SPWeb.Lists property by using the list's GUID or
          display name as an indexer. Using SPWeb.Lists[GUID] andSPWeb.GetList(strURL) is always
          preferable to using SPWeb.Lists[strDisplayName]. Using the GUID is preferable because it is
          unique, permanent, and requires only a single database lookup. The display name indexer retrieves
          the names of all the lists in the site and then does a string comparison with them. If you have a list
          URL instead of a GUID, you can use the GetList method to look up the list's GUID in the content
          database before retrieving the list.

Writing Applications That Scale to Large Numbers of Users
You might not be aware that you need to write your code to be scalable so that it can handle multiple users
simultaneously. A good example is creating custom navigation information for all sites and subsites on each
page or as part of a master page. If you have a SharePoint site on a corporate intranet and each
department has its own site with many subsites, your code might resemble the following.

C#


public void GetNavigationInfoForAllSitesAndWebs()
{
     foreach(SPSite oSPSite in SPContext.Current.Site.WebApplication.Sites)
     {
          try
          {
                SPWeb oSPWeb      = oSPSite.RootWeb;
                AddAllWebs(oSPWeb );
          }
          finally
          {
                oSPSite.Dispose();
          }
     }
}
C#


public void AddAllWebs(SPWeb oSPWeb)
{
     foreach(SPWeb oSubWeb in oSPWeb.Webs)
     {
              try
           {
                  //.. Code to add items ..
                  AddAllWebs(oSubWeb);
           }
           finally
           {
                   if (oSubWeb != null)
                   oSubWeb.Dispose();
           }
      }
}
While the previous code disposes of objects properly, it still causes problems because the code iterates
through the same lists over and over. For example, if you have 10 site collections and an average of 20 sites
or subsites per site collection, you would iterate through the same code 200 times. For a small number of
users this might not cause bad performance. But, as you add more users to the system, the problem gets
worse, as shown in Table 2.

Table 2. Iterations increase as number of users increases

Users Iterations

 10       2000

 50       10000

 100      200000

 250      500000
Although the code executes for each user that hits the system, the data remains the same for each user.
The impact of this can vary depending on what the code is doing. In some cases, repeating code might not
cause a performance problem; however, in the previous example the system must create a COM object
(SPSite orSPWeb objects are created when retrieved from their collections), retrieve data from the object,
and then dispose of the object for each item in the collection. This can have a significant impact on
performance.

How to make this code more scalable or fine-tune it for a multiple user environment can be a hard question
to answer. It depends on what the application is designed to do.

You should take the following into consideration when asking how to make code more scalable:


         Is the data static (seldom changes), somewhat static (changes occasionally), or dynamic (changes
          constantly)?

         Is the data the same for all users, or does it change? For example, does it change depending on the
          user who is logged on, the part of the site being accessed, or the time of year (seasonal
          information)?

         Is the data easily accessible or does it require a long time to return the data? For example, is it
          returning from a long-running database query or from remote databases that can have some
          network latency in the data transfers?
       Is the data public or does it require a higher level of security?

       What is the size of the data?

       Is the SharePoint site on a single server or on a server farm?

How you answer the previous questions will determine in which of several ways you can make your code
more scalable and handle multiple users. The intent of this article is not to provide answers for all of the
questions or scenarios but to provide a few ideas that you can apply to your specific needs. The following
sections offer areas for your consideration.

Caching Raw Data
You can cache your data by using the System.Web.Caching.Cache object. This object requires that you
query the data one time and store it in the cache for access by other users.

If your data is static, you can set up the cache to load the data only one time and not expire until the
application is restarted, or to load the data once per day to ensure data freshness. You can create the cache
item when the application starts, when the first user session starts, or when the first user tries to access
that data.

If your data is somewhat static, you can set up the cached items to expire within a certain number of
seconds, minutes, or hours after the data is created. This enables you to refresh your data within a
timeframe that is acceptable to your users. Even if the data is cached for only 30 seconds, under heavy
loads you will still see improved performance because you are running the code only one time every 30
seconds instead of multiple times per second for each user who hits the system.

Security trimming is another issue to consider whenever you cache data. For example, if you cache items as
you iterate through a list, you may get only a subset of the data (the data that the current user can see), or
if you use a DataTable object to cache all of the items in a list, you have no easy way of applying security
trimming to users who belong to groups that can see only a subset of the data. For more information about
storing security trimmed data in caches, see theCrossListQueryCache class.

In addition, ensure you consider the issues described earlier in Caching Data and Objects.

Building Data Before Displaying It
Think about how your cached data will be used. If this data is used to make run-time decisions, putting it
into a DataSet or DataTable object might be the best way to store it. You can then query those objects for
the data to make run-time decisions. If the data is being used to display a list, table, or formatted page to
the user, consider building a display object and storing that object in the cache. At run time, you need only
retrieve the object from the cache and call its render function to display its contents. You could also store
the rendered output; however, this can lead to security issues and the cached item could be quite large,
causing increased page swapping or memory fragmentation.

Caching For a Single Server or Server Farm
Depending on how you set up your SharePoint site, you might have to address certain caching issues
differently. If your data must be the same on all servers at all times, then you must ensure that the same
data is cached on each server.

One way to ensure this is to create the cached data and store it on a common server or in a Microsoft SQL
Server database. Again, you must consider how much time it takes to access the data and what security
issues can arise from storing the data on a common server.

You can also create business-layer objects that cache data on a common sever, and then access that data
by using various interprocess communications that are available in networking objects or APIs.

Using SPQuery Objects
SPQuery objects can cause performance problems whenever they return large result sets. The following
suggestions will help you optimize your code so that performance will not suffer greatly whenever your
searches return large numbers of items.
       Do not use an unbounded SPQuery object.

        An SPQuery object without a value for RowLimit will perform poorly and fail on large lists. Specify
        a RowLimit between 1 and 2000 and, if necessary, page through the list.

       Use indexed fields.

        If you query on a field that is not indexed, the query will be blocked whenever it would result in a
        scan of more items than the query threshold (as soon as there are more items in the list than are
        specified in the query threshold). Set SPQuery.RowLimit to a value that is less than the query
        threshold.

       If you know the URL of your list item and want to query by FileRef,
        use SPWeb.GetListItem(string strUrl, string field1, params string[]
        fields) instead.

Using Web Controls
When you inherit and override controls in the Microsoft.SharePoint.WebControls namespace, remember
that SharePoint Web controls are templated controls. Unlike Microsoft ASP.NET Web controls, they are
defined and rendered with templates instead of with the CreateChildControls method. Instead of having a
thickCreateChildControls method that uses the new operator to create child controls, perform most child
control creation and rendering by using the rendering templates that are referenced in
the Template, AlternateTemplate, DisplayTemplate, CustomTemplate,
and AlternateCustomTemplate properties of the SharePoint Web control. SharePoint Web controls do
inherit the CreateChildControls method, but that method should typically do little or nothing beyond
calling the parent control's CreateChildControls method and perhaps a bit of "final polish" rendering, such
as assigning default values to child control properties in New mode or assigning the current values in Edit
mode.

For an example, see Walkthrough: Creating a Custom Field Type. In addition, see the
Microsoft.SharePoint.WebControls namespace.

Creating Timer Jobs
Design your timer jobs so that they consist of small, manageable pieces. Because administrators and other
events, such as system restarts, can stop timer jobs, you can minimize the amount of rework after any
interruption by breaking timer jobs into small pieces of work.

Conclusion
To ensure that your SharePoint system performs at its best, you need to be able to answer the following
questions about the code you write:


       Does my code properly dispose of SharePoint objects?

       Does my code cache objects properly?

       Does my code cache the correct types of objects?

       Does my code use thread synchronization when necessary?

       Does my code work as efficiently for 1,000 users as it does for 10 users?

If you consider these issues when you write your code, your SharePoint system will run more efficiently and
your users will have a much better experience. You can also help to prevent unexpected failures and errors
in your system.
Stsadm command-line tool (Office SharePoint Server)
Updated: 2006-12-01

In this article:

        Using Stsadm

        Stsadm is not interactive

        Available operations and properties

Microsoft Office SharePoint Server 2007 includes the Stsadm tool for command-line administration of Office
SharePoint Server 2007 servers and sites. Stsadm is located at the following path on the drive where
SharePoint Products and Technologies is installed: %COMMONPROGRAMFILES%\microsoft shared\web
server extensions\12\bin. You must be an administrator on the local computer to use Stsadm.

Stsadm provides a method for performing the Office SharePoint Server 2007 administration tasks at the
command line or by using batch files or scripts. Stsadm provides access to operations not available by using
the Central Administration site, such as changing the administration port. The command-line tool has a
more streamlined interface than Central Administration, and it allows you to perform the same tasks. There
are certain operations and certain parameters that are only available by using the Stsadm command-line
tool.

Using Stsadm
The command-line tool provides access to the complete set of Office SharePoint Server 2007 operations.
You can use Stsadm from the command line or with batch files or scripts. Stsadm must be run on the server
itself.

To use Stsadm, you must be a member of the local Administrators group on the server. When you invoke
Stsadm, you supply an operation and a set of command-line parameters in the form:

-operation OperationName -parameter value


  Note:

 If a value you need to use with the command-line tool includes a space or a character that is treated as
 special by the command-line interface, such as an ampersand (&), you can enclose the string in quotation
 marks ("). For example, if the URL to a site is http://my site, you can enter the URL as "http://my site".
Most parameters for the command line also have a short form that you can use instead of the full parameter
name. For example, the following command sets the configuration database to use Server1_collab on
Server1 and specifies the database user name and password to connect with:

stsadm -o setconfigdb -connect -ds Server1 -dn Server1_collab -du User1 -dp password

The following table explains the commands and parameters from this example.


Command or
parameter                   Definition

 -o setconfigdb             Creates a connection between Office SharePoint Server 2007 and a
                            configuration database.

 -connect                   Specifies that there is an existing configuration database to use.

 -ds Server1                Specifies the server name that contains the database to use.

 -dn Server1_collab         Specifies the database name to use on that server.

 -du User1                  Specifies an administrator user name for the database.
 -dp password              Specifies the password for the user.


Stsadm is not interactive
Stsadm is not an interactive tool. With Stsadm, you type the operation and parameters all at once. You will
not be prompted to fill in missing parameters while the operation is running. If a required parameter is
missing, the operation fails, and you must type the operation and parameters again.

This behavior allows better flexibility for batching commands, because the tools do not prompt you for
information after you have submitted a command. If you want a more interactive tool, try using the
administrative object model or Central Administration pages.

Available operations and properties
For a complete list of Stsadm operations and properties, see Index for Stsadm operations and properties
(Office SharePoint Server).

The following operations are available only from the command line:

 addcontentdb (the command line is        enumsolutions                        renameserver
 required for adding databases that
 need to be upgraded)

 addsolution                              enumtemplates                        restore (site collection
                                                                               level)

 addwppack                                enumwppacks                          retractsolution

 backup (site collection level)           execadmsvcjobs                       retractwppack

 binddrservice                            export                               scanforfeatures

 canceldeployment                         forcedeletelist                      setadminport

 copyappbincontent                        getadminport                         setconfigdb

 createadminvs                            getproperty                          setproperty

 createsiteinnewdb                        getsitelock                          setworkflowconfig

 databaserepair                           import                               spsearchdiacriticsensitive

 deleteadminvs                            installfeature                       syncsolution

 deleteconfigdb                           migrateuser                          uninstallfeature

 deletesolution                           provisionservice                     unregisterwsswriter

 deletewppack                             refreshdms                           updateaccountpassword

 deploysolution                           refreshsitedms                       updatealerttemplates

 deploywppack                             registerwsswriter                    updatefarmcredentials

 displaysolution                          removedrservice                      upgradesolution

 enumdeployments                          removesolutiondeploymentlock
The following parameters are available only from the command line:

 -force           -propertyname

 -globalinstall   -propertyvalue

 -newname         -servicename
 -overwrite        -ssl



Index for Stsadm operations and properties (Office
SharePoint Server)
Updated: 2009-06-08

In this article:

        Operations

        Properties


   Note:

 For a printable poster of all of the Stsadm operations and properties grouped by functionality, see Poster:
 Stsadm Technical Reference(http://go.microsoft.com/fwlink/?LinkId=120150&clcid=0x409). This file was
 created in Microsoft Office Visio 2007. If you do not have Office Visio installed, you can download a free
 viewer (http://go.microsoft.com/fwlink/?LinkId=118761&clcid=0x409). A plotter works best for printing
 this file.
To use an interactive Silverlight application to learn about the commands available, see Stsadm Silverlight
application (http://go.microsoft.com/fwlink/?LinkId=154235).

Operations

Name                               Description                                  More information

 Activatefeature                   Activates a feature in the feature           Activatefeature: Stsadm
                                   collection.                                  operation (Office SharePoint
                                                                                Server)

 Addalternatedomain                Adds an internal URL and maps it to one      Addalternatedomain:
                                   of the five URL zones of a Web application   Stsadm operation (Office
                                   or external resource.                        SharePoint Server)

 Addcontentdb                      Creates a new content database or adds a     Addcontentdb: Stsadm
                                   database that needs to be upgraded when      operation (Office SharePoint
                                   the url and databasenameparameters           Server)
                                   are specified.

 Adddataconnectionfile             Adds a new DataConnectionFile to the         Adddataconnectionfile:
                                   DataConnectionFiles collection for           Stsadm operation (Office
                                   InfoPath Forms Services.                     SharePoint Server)

 Add-ecsfiletrustedlocation        Lets an administrator add a file to the      Add-ecsfiletrustedlocation:
                                   trusted location list.                       Stsadm operation (Office
                                                                                SharePoint Server)

 Add-ecssafedataprovider           Lets an administrator add a supported        Add-ecssafedataprovider:
                                   provider type to the safe provider list.     Stsadm operation (Office
                                                                                SharePoint Server)

 Add-                              Adds a trusted data connection to a          Add-
 ecstrusteddataconnectionlib       library.                                     ecstrusteddataconnectionlibr
 rary                                                                           ary: Stsadm operation
                                                                                (Office SharePoint Server)
Add-ecsuserdefinedfunction   Adds a user defined function.                 Add-ecsuserdefinedfunction:
                                                                           Stsadm operation (Office
                                                                           SharePoint Server)

Addexemptuseragent           Adds a user agent, which is typically in      Addexemptuseragent:
                             the form of a search bot, to receive the      Stsadm operation (Office
                             XML file that contains the data of the form   SharePoint Server)
                             for indexing instead of the HTML
                             rendering of the form.

Addpath                      Adds a managed path inclusion to a Web        Addpath: Stsadm operation
                             application.                                  (Office SharePoint Server)

Addpermissionpolicy          Adds a user to a policy role for the Web      Addpermissionpolicy:
                             application based on the specified            Stsadm operation (Office
                             permission level name and corresponding       SharePoint Server)
                             zone.

Addsolution                  Adds a solution file to the solution store.   Addsolution: Stsadm
                                                                           operation (Office SharePoint
                                                                           Server)

Addtemplate                  Adds a site template to the template          Addtemplate: Stsadm
                             gallery.                                      operation (Office SharePoint
                                                                           Server)

Adduser                      Adds a user account to the specified site     Adduser: Stsadm operation
                             collection and assigns it to the specified    (Office SharePoint Server)
                             site group.

Addwppack                    Adds a Web Part package to the server         Addwppack: Stsadm
                             Web Part gallery.                             operation (Office SharePoint
                                                                           Server)

Addzoneurl                   Configures the public URL and maps it to      Addzoneurl: Stsadm
                             one of the five URL zones of a Web            operation (Office SharePoint
                             application or external resource.             Server)

Allowuserformwebservicepr    Determines whether a user form template       Allowuserformwebservicepro
oxy                          (that is, a non-administrator deployed        xy: Stsadm operation (Office
                             form template published to a content type     SharePoint Server)
                             or a document library) can use the proxy.

Allowwebserviceproxy         Turns on or off the Web service proxy for     Allowwebserviceproxy:
                             the specified Web application.                Stsadm operation (Office
                                                                           SharePoint Server)

Authentication               Authentication provides the user identity     Authentication: Stsadm
                             input to the authorization process which      operation (Office SharePoint
                             determines what actions the current user      Server)
                             is allowed to perform on a given object.

Backup                       Describes how to back up a site                       Backup: Stsadm
                             collection, an individual database, a Web         operation (Office
                             application, or an entire farm.                   SharePoint Server)
                                                                                   Back up a farm by
                                                                               using built-in tools
                                                                               (Office SharePoint
                                                                               Server 2007)

Backuphistory                Displays a history of backup and restore      Backuphistory: Stsadm
                             operations that have been run.                operation (Office SharePoint
                                                                           Server)
Binddrservice               Registers a data retrieval service adapter.      Binddrservice: Stsadm
                                                                             operation (Office SharePoint
                                                                             Server)

Blockedfilelist             Enables an administrator to add or delete        Blockedfilelist: Stsadm
                            a file type to the blocked file types list for   operation (Office SharePoint
                            a Web application.                               Server)

Changepermissionpolicy      Updates the Web application policy level         Changepermissionpolicy:
                            for a user to enable a change to specific        Stsadm operation (Office
                            permission levels the user is assigned.          SharePoint Server)

Copyappbincontent           Copies Web application–specific files, such      Copyappbincontent: Stsadm
                            as page resource (*.resx) files from their       operation (Office SharePoint
                            respective locations in the 12\CONFIG            Server)
                            folder to the correct location in each Web
                            application on the computer.

Createadminvs               Displays the port number to the                  Createadminvs: Stsadm
                            SharePoint Central Administration Web            operation (Office SharePoint
                            site.                                            Server)

Createcmsmigrationprofile   Creates a migration profile by providing a       Createcmsmigrationprofile:
                            profile name, database server name,              Stsadm operation (Office
                            database name, and database user name.           SharePoint Server)

Creategroup                 Lets site collection administrators create       Creategroup: Stsadm
                            new groups from any site collection.             operation (Office SharePoint
                                                                             Server)

Createsite                  Creates a site collection at the specified       Createsite: Stsadm
                            Uniform Resource Locator (URL) with the          operation (Office SharePoint
                            specified user as site collection owner and      Server)
                            site collection administrator.

Createsiteinnewdb           Creates a site at the specified Uniform          Createsiteinnewdb: Stsadm
                            Resource Locator (URL) and creates a             operation (Office SharePoint
                            new content database using the user              Server)
                            name and password you specify.

Createssp                   Creates a new Shared Services Provider           Createssp: Stsadm
                            (SSP) in the farm.                               operation (Office SharePoint
                                                                             Server)

Createweb                   Creates a subsite at the specified Uniform       Createweb: Stsadm
                            Resource Locator (URL).                          operation (Office SharePoint
                                                                             Server)

Databaserepair              Detects and removes orphaned items               Databaserepair: Stsadm
                            from content databases in Windows                operation (Office SharePoint
                            SharePoint Services.                             Server)

Deactivatefeature           Deactivates a feature in the feature             Deactivatefeature: Stsadm
                            collection.                                      operation (Office SharePoint
                                                                             Server)

Deleteadminvs               Unprovisions the SharePoint Central              Deleteadminvs: Stsadm
                            Administration Web site from the local           operation (Office SharePoint
                            machine.                                         Server)

Deletealternatedomain       Deletes an internal URL from a URL zone.         Deletealternatedomain:
                                                                             Stsadm operation (Office
                                                                             SharePoint Server)
Deletecmsmigrationprofile   Deletes the named migration profile.          Deletecmsmigrationprofile:
                                                                          Stsadm operation (Office
                                                                          SharePoint Server)

Deleteconfigdb              Unprovisions the local machine from the       Deleteconfigdb: Stsadm
                            farm and deletes the configuration            operation (Office SharePoint
                            database (but does not drop the               Server)
                            configuration database).

Deletecontentdb             Detaches a content database when the          Deletecontentdb: Stsadm
                            Web application, database name, and           operation (Office SharePoint
                            database server are specified.                Server)

Deletegroup                 Deletes a group created in Microsoft          Deletegroup: Stsadm
                            Office SharePoint Server 2007.                operation (Office SharePoint
                                                                          Server)

Deletepath                  Removes an included path from the list of     Deletepath: Stsadm
                            paths managed by Windows SharePoint           operation (Office SharePoint
                            Services.                                     Server)

Deletepermissionpolicy      Deletes a permission policy for a user        Deletepermissionpolicy:
                            from the site collection by specifiying the   Stsadm operation (Office
                            URL name and user login.                      SharePoint Server)

Deletesite                  Deletes the site collection with the          Deletesite: Stsadm
                            specified URL from the Web application.       operation (Office SharePoint
                                                                          Server)

Deletesolution              Removes a Windows SharePoint Services         Deletesolution: Stsadm
                            Solution Package (*.wsp) from the             operation (Office SharePoint
                            solution store.                               Server)

Deletessp                   Deletes a Shared Services Provider (SSP)      Deletessp: Stsadm operation
                            in a Web application when                     (Office SharePoint Server)
                            the title parameter is specified.

Deletessptimerjob           Deletes all of the timer jobs in the Shared   Deletessptimerjob: Stsadm
                            Services Provider (SSP).                      operation (Office SharePoint
                                                                          Server)

Deletetemplate              Deletes a specified site template from the    Deletetemplate: Stsadm
                            site template gallery.                        operation (Office SharePoint
                                                                          Server)

Deleteuser                  Deletes a user account from the specified     Deleteuser: Stsadm
                            site collection and specified site.           operation (Office SharePoint
                                                                          Server)

Deleteweb                   Deletes a subsite using the specified         Deleteweb: Stsadm
                            Uniform Resource Locator (URL).               operation (Office SharePoint
                                                                          Server)

Deletewppack                Removes the Web Parts in a Web Part           Deletewppack: Stsadm
                            package from a virtual server.                operation (Office SharePoint
                                                                          Server)

Deletezoneurl               Deletes a public URL and the zone to          Deletezoneurl: Stsadm
                            which it is mapped.                           operation (Office SharePoint
                                                                          Server)

Deploysolution              Deploys files related to a solution from      Deploysolution: Stsadm
                            the configuration database to individual      operation (Office SharePoint
                            front-end Web servers in the farm.            Server)
Deploywppack                Deploys a Web Part package.                     Deploywppack: Stsadm
                                                                            operation (Office SharePoint
                                                                            Server)

Disablessc                  Disables Self-Service Site Creation for the     Disablessc: Stsadm
                            specified Web application.                      operation (Office SharePoint
                                                                            Server)

Displaysolution             Displays specific solution or Web Part          Displaysolution: Stsadm
                            information in a solution store.                operation (Office SharePoint
                                                                            Server)

Editcmsmigrationprofile     Edits a migration profile by providing a        Editcmsmigrationprofile:
                            profile name, database server name,             Stsadm operation (Office
                            database name, and database user name.          SharePoint Server)

Editcontentdeploymentpath   Edits and manages a content deployment          Editcontentdeploymentpath:
                            path.                                           Stsadm operation (Office
                                                                            SharePoint Server)

Editssp                      Allows the site collection administrator for   Editssp: Stsadm operation
                             the Shared Services Administration site to     (Office SharePoint Server)
                             perform the following functions:
                                    Change the databases that a
                                 Shared Services Provider (SSP)
                                 uses.
                                    Change the SQL credentials
                                 associated with the SSP databases.
                                    Modify the service account
                                 credentials.
                                    Rename an SSP.

Enablecmsurlredirect        Activates the Uniform Resource Locator          Enablecmsurlredirect:
                            (URL) redirection feature for URLs in           Stsadm operation (Office
                            Microsoft Content Management Server             SharePoint Server)
                            2002.

Enablessc                   Enables Self-Service Site Creation for the      Enablessc: Stsadm
                            specified Web application.                      operation (Office SharePoint
                                                                            Server)

Enumallwebs                 Displays the IDs and site map status for        Enumallwebs: Stsadm
                            all site collections and subsites in the        operation (Office SharePoint
                            content database.                               Server)

Enumalternatedomains        Lists the internal URLs and specifies the       Enumalternatedomains:
                            URL zones and public URLs to which they         Stsadm operation (Office
                            are mapped.                                     SharePoint Server)

Enumcontentdbs              Enumerates all content databases in the         Enumcontentdbs: Stsadm
                            Web application.                                operation (Office SharePoint
                                                                            Server)

Enumdataconnectionfiledep   Enumerates all form that are dependent          Enumdataconnectionfiledepe
endants                     on the specified data connection file.          ndants: Stsadm operation
                                                                            (Office SharePoint Server)

Enumdataconnectionfiles     Enumerates all of the DataConnectionFiles       Enumdataconnectionfiles:
                            in the collection in alphabetical order.        Stsadm operation (Office
                                                                            SharePoint Server)

Enumdeployments             Enumerates all pending and active               Enumdeployments: Stsadm
                            deployments in the farm.                        operation (Office SharePoint
                                                                       Server)

Enumexemptuseragents   Returns the rendering content of the form       Enumexemptuseragents:
                       as an XML instead HTML.                         Stsadm operation (Office
                                                                       SharePoint Server)

Enumformtemplates      Lists the administrator-deployed form           Enumformtemplates:
                       templates on the farm.                          Stsadm operation (Office
                                                                       SharePoint Server)

Enumgroups             Lists all the groups in Microsoft Office        Enumgroups: Stsadm
                       SharePoint Server 2007.                         operation (Office SharePoint
                                                                       Server)

Enumroles              Lists the site groups that are available for    Enumroles: Stsadm
                       use in a particular site or subsite.            operation (Office SharePoint
                                                                       Server)

Enumservices           Lists all the services in the Web               Enumservices: Stsadm
                       application within a farm.                      operation (Office SharePoint
                                                                       Server)

Enumsites              Displays a list of sites that are hosted in a   Enumsites: Stsadm
                       Web application. To find the sites that         operation (Office SharePoint
                       need to be upgraded, use                        Server)
                       theredirectedsites parameter.

Enumsolutions          Enumerates the list of Windows                  Enumsolutions: Stsadm
                       SharePoint Services Solution Package            operation (Office SharePoint
                       (*.wsp) and Web Part packages located in        Server)
                       the solution store of the farm.

Enumssp                Lists all the details of the Shared Services    Enumssp: Stsadm operation
                       Providers (SSPs) in the farm or of a single     (Office SharePoint Server)
                       SSP.

Enumssptimerjobs       Enumerates all of the timer jobs in the         Enumssptimerjobs: Stsadm
                       Shared Services Provider (SSP).                 operation (Office SharePoint
                                                                       Server)

Enumsubwebs            Lists the subsites that have been created       Enumsubwebs: Stsadm
                       immediately below a particular site.            operation (Office SharePoint
                                                                       Server)

Enumtemplates          Lists the site templates that have been         Enumtemplates: Stsadm
                       submitted to the global site template           operation (Office SharePoint
                       catalog.                                        Server)

Enumusers              Lists the users of a particular site            Enumusers: Stsadm
                       collection or subsite.                          operation (Office SharePoint
                                                                       Server)

Enumwppacks            Lists the Web Part packages currently in        Enumwppacks: Stsadm
                       the server Web Part gallery.                    operation (Office SharePoint
                                                                       Server)

Enumzoneurls           Lists all of the public URL and the zones       Enumzoneurls: Stsadm
                       to which they are mapped.                       operation (Office SharePoint
                                                                       Server)

Email                  Sets the e-mail configuration settings for      Email: Stsadm operation
                       your server.                                    (Office SharePoint Server)

Execadmsvcjobs         Permits a user to run any administrative        Execadmsvcjobs: Stsadm
                       service job in which the Windows                operation (Office SharePoint
                              SharePoint Services Administration           Server)
                              (SPAdmin) service has been disabled.

Export                        Exports site and subsite data from your      Export: Stsadm operation
                              Microsoft Office SharePoint Server 2007      (Office SharePoint Server)
                              installation.

Extendvs                      Extends a Windows SharePoint Services        Extendvs: Stsadm operation
                              3.0 Web application and creates a new        (Office SharePoint Server)
                              content database.

Extendvsinwebfarm             Extends a Windows SharePoint Services        Extendvsinwebfarm: Stsadm
                              3.0 Web application for use in a server      operation (Office SharePoint
                              farm                                         Server)

Forcedeletelist               Allows a user to delete a list that might    Forcedeletelist: Stsadm
                              appear to be in a corrupted state.           operation (Office SharePoint
                                                                           Server)

Formtemplatequiescestatus     Displays the status of the quiesce process   Formtemplatequiescestatus:
                              of a form template.                          Stsadm operation (Office
                                                                           SharePoint Server)

Getadminport                  Returns the administration port for          Getadminport: Stsadm
                              Windows SharePoint Services.                 operation (Office SharePoint
                                                                           Server)

Getdataconnectionfileproper   Displays the file property of each data      Getdataconnectionfilepropert
ty                            connection file in the store of InfoPath     y: Stsadm operation (Office
                              Forms Services.                              SharePoint Server)

Getformtemplateproperty       Retrieves properties on individual           Getformtemplateproperty:
                              InfoPath Form Services templates.            Stsadm operation (Office
                                                                           SharePoint Server)

Getosearchsetting             Available only in the April Cumulative       Getosearchsetting: Stsadm
                              Update, this operation displays the          operation (Office SharePoint
                              current values of the Enterprise search      Server)
                              settings.

Getsitedirectoryscanschedul   Displays the current schedule of all site    Getsitedirectoryscanschedul
e                             directory links scan jobs to be run.         e: Stsadm operation (Office
                                                                           SharePoint Server)

Getsitelock                   Retrieves the lock status of a site.         Getsitelock: Stsadm
                                                                           operation (Office SharePoint
                                                                           Server)

Import                        Imports site and subsite data from your      Import: Stsadm operation
                              Microsoft Office SharePoint Server 2007      (Office SharePoint Server)
                              installation.

Installfeature                Installs a feature.                          Installfeature: Stsadm
                                                                           operation (Office SharePoint
                                                                           Server)

Listlogginglevels             Lists the current event log and trace log    Listlogginglevels: Stsadm
                              logging levels for each diagnostic logging   operation (Office SharePoint
                              category that is registered in a farm.       Server)

Listqueryprocessoroptions     Displays the current values of the           Listqueryprocessoroptions:
                              SharePoint Search query processor            Stsadm operation (Office
                              settings.                                    SharePoint Server)

Listregisteredsecuritytrimm   Lists all registered security trimmers in    Listregisteredsecuritytrimme
ers                           the farm.                                       rs: Stsadm operation (Office
                                                                              SharePoint Server)

Localupgradestatus            Displays the farm and local server              Localupgradestatus: Stsadm
                              components that need to be upgraded.            operation (Office SharePoint
                                                                              Server)

Managepermissionpolicyleve    Enables an administrator to manage the          Managepermissionpolicylevel
l                             policy levels for a Web application.            : Stsadm operation (Office
                                                                              SharePoint Server)

Mergecontentdbs               Permits a site collection to be moved from      Mergecontentdbs: Stsadm
                              one content database to another when            operation (Office SharePoint
                              the souredatabasename anddestinationdatabas     Server)
                              ename parameters are specified.

Migrateuser                   Migrates a user account in Windows              Migrateuser: Stsadm
                              SharePoint Services 3.0 to a new user           operation (Office SharePoint
                              name and binary ID.                             Server)

Osearch                       Manages the Office SharePoint Server            Osearch: Stsadm operation
                              Search service.                                 (Office SharePoint Server)

Osearchdiacriticsensitive     Enables or disables the diacritic sensitivity   Osearchdiacriticsensitive:
                              setting.                                        Stsadm operation (Office
                                                                              SharePoint Server)

Peoplepicker-                 Retrieves the user account directory path       Getsiteuseraccountdirectory
getsiteuseraccountdirectory   setting for the site collection.                path: Stsadm operation
path                                                                          (Office SharePoint Server)

Peoplepicker-                 Sets the site user account directory path       Setsiteuseraccountdirectory
setsiteuseraccountdirectory   to a specific Organizational Unit (OU) in       path: Stsadm operation
path                          the same domain when                            (Office SharePoint Server)
                              the urland path parameters are specified.

Preparetomove                 Prepares sites and content databases            Preparetomove: Stsadm
                              before moving to a new Web application          operation (Office SharePoint
                              by setting up the profile and membership        Server)
                              synchronization service.

Preupgradecheck               Runs rules that are intended to assist          Preupgradecheck: Stsadm
                              administrators in preparing for upgrade         operation (Windows
                              from Windows SharePoint Services 3.0            SharePoint Services)
                              and related products to future version of
                              SharePoint and Technology products.

Profilechangelog              Maintains a change log that records the         Profilechangelog: Stsadm
                              changes made to the user profiles.              operation (Office SharePoint
                                                                              Server)

Profiledeletehandler          Gives an administrator a chance to run a        Profiledeletehandler: Stsadm
                              workflow when a user is about to be             operation (Office SharePoint
                              deleted.                                        Server)

Provisionservice              Starts or stops the SPService on the local      Provisionservice: Stsadm
                              computer or a custom service.                   operation (Office SharePoint
                                                                              Server)

Quiescefarm                   Temporartily suspends the farm‘s ability        Quiescefarm: Stsadm
                              to accept new sessions that are essential       operation (Office SharePoint
                              to rendering infopath forms on a server.        Server)

Quiescefarmstatus             Displays the quiesce status of the server       Quiescefarmstatus: Stsadm
                              farm.                                        operation (Office SharePoint
                                                                           Server)

Quiesceformtemplate           Temporarily takes a form template offline.   Quiesceformtemplate:
                                                                           Stsadm operation (Office
                                                                           SharePoint Server)

Reconvertallformtemplates     Upgrades the form template cached data       Reconvertallformtemplates:
                              to run on the upgraded server.               Stsadm operation (Office
                                                                           SharePoint Server)

Refreshdms                    Refreshes the Directory Management           Refreshdms: Stsadm
                              Service if a database is restored or moved   operation (Office SharePoint
                              to a location where the incoming e-mail      Server)
                              settings are not correct.

Refreshsitedms                Performs the same function as                Refreshsitedms: Stsadm
                              the Refreshdms operation but on a site       operation (Office SharePoint
                              collection level.                            Server)

Registersecuritytrimmer       Enterprise Search in Microsoft Office        Registersecuritytrimmer:
                              SharePoint Server 2007 performs security     Stsadm operation (Office
                              trimming of search results at query time.    SharePoint Server)

Registerwsswriter             Enables the Windows SharePoint Services      Registerwsswriter: Stsadm
                              VSS Writer service (known as WSS Writer      operation (Office SharePoint
                              service) on any front-end Web server.        Server)

Removedataconnectionfile      Removes all DataConnectionFiles from the     Removedataconnectionfile:
                              DataConnectionFiles collection.              Stsadm operation (Office
                                                                           SharePoint Server)

Removedrservice               Removes a data retrieval service from the    Removedrservice: Stsadm
                              list of data retrieval services.             operation (Office SharePoint
                                                                           Server)

Remove-                       Lets an administrator remove a file from     Remove-
ecsfiletrustedlocation        the trusted location list.                   ecsfiletrustedlocation:
                                                                           Stsadm operation (Office
                                                                           SharePoint Server)

Remove-                       Lets an administrator remove a supported     Remove-
ecssafedataprovider           provider type to the safe provider list.     ecssafedataprovider:
                                                                           Stsadm operation (Office
                                                                           SharePoint Server)

Remove-                       Removes a trusted data connection from       Remove-
ecstrusteddataconnectionlib   a library.                                   ecstrusteddataconnectionlibr
rary                                                                       ary: Stsadm operation
                                                                           (Office SharePoint Server)

Remove-                       Removes a user-defined function from         Remove-
ecsuserdefinedfunction        Excel Calculation Services.                  ecsuserdefinedfunction:
                                                                           Stsadm operation (Office
                                                                           SharePoint Server)

Removeexemptuseragent         Removes a user agent, which is typically     Removeexemptuseragent:
                              in the form of a search bot, from the        Stsadm operation (Office
                              ExemptUserAgent collection.                  SharePoint Server)

Removesolutiondeploymentl     Removes the solution deployment lock for     Removesolutiondeploymentl
ock                           the specified server or all servers from     ock: Stsadm operation
                              the back-end database.                       (Office SharePoint Server)
Renameserver                  Changes the name of the specified server     Renameserver: Stsadm
                              in the configuration database.               operation (Office SharePoint
                                                                           Server)

Renamesite                    Changes a URL of a host-named site           Renamesite: Stsadm
                              collection to a new URL.                     operation (Office SharePoint
                                                                           Server)

Renameweb                     Changes the URL of a subsite.                Renameweb: Stsadm
                                                                           operation (Office SharePoint
                                                                           Server)

Restore                       Explains how a restoration of a site         Restore: Stsadm operation
                              collection, an individual database, a Web    (Office SharePoint Server)
                              application, or an entire farm is
                              performed.

Restoressp                    Creates a Shared Service Provider using a    Restoressp: Stsadm
                              restored database.                           operation (Office SharePoint
                                                                           Server)

Retractsolution               Retracts the specified solution‘s            Retractsolution: Stsadm
                              deployment, and removes files from the       operation (Office SharePoint
                              front-end Web server.                        Server)

Retractwppack                 Retracts the deployment of a specified       Retractwppack: Stsadm
                              Web Part package.                            operation (Office SharePoint
                                                                           Server)

Runcmsmigrationprofile        Runs a named migration profile. The          Runcmsmigrationprofile:
                              profile name is the only required            Stsadm operation (Office
                              parameter.                                   SharePoint Server)

Runcontentdeploymentjob       Runs a named deployment job.                 Runcontentdeploymentjob:
                                                                           Stsadm operation (Office
                                                                           SharePoint Server)

Scanforfeatures               Scans for new features in the file system,   Scanforfeatures: Stsadm
                              and if new features are present, installs    operation (Office SharePoint
                              them.                                        Server)

Setadminport                  Changes the default zone Uniform             Setadminport: Stsadm
                              Resource Locator (URL) and/or application    operation (Office SharePoint
                              pool located on the SharePoint Central       Server)
                              Administration Web site.

Setbulkworkflowtaskprocess    Sets the schedule for when tasks are         Setbulkworkflowtaskprocessi
ingschedule                   processed by using the Process all           ngschedule: Stsadm
                              tasks option.                                operation (Office SharePoint
                                                                           Server)

Setconfigdb                   Creates a new configuration database in a    Setconfigdb: Stsadm
                              farm or joins the local computer to an       operation (Office SharePoint
                              existing farm's configuration database.      Server)

Setcontentdeploymentjobsc     Enables the user to create an advanced       Setcontentdeploymentjobsch
hedule                        schedule to run a deployment job.            edule: Stsadm operation
                                                                           (Office SharePoint Server)

Setdataconnectionfileproper   Sets a file property to a data connection    Setdataconnectionfilepropert
ty                            file in the store of InfoPath Forms          y: Stsadm operation (Office
                              Services.                                    SharePoint Server)

Setdefaultssp                 Sets a Shared Services Provider (SSP) as     Setdefaultssp: Stsadm
                              the default SSP in a farm.                    operation (Office SharePoint
                                                                            Server)

Set-ecsexternaldata           Lets an administrator set an external data    Set-ecsexternaldata:
                              connection to Excel Calculation Services.     Stsadm operation (Office
                                                                            SharePoint Server)

Set-ecsloadbalancing          Lets an administrator define load             Set-ecsloadbalancing:
                              balancing for Excel Calculation Services.     Stsadm operation (Office
                                                                            SharePoint Server)

Set-ecsmemoryutilization      Lets an administrator determine memory        Set-ecsmemoryutilization:
                              allocation for Excel Calculation Services.    Stsadm operation (Office
                                                                            SharePoint Server)

Set-ecssecurity               Lets an administrator set security settings   Set-ecssecurity: Stsadm
                              for Excel Calculation Services.               operation (Office SharePoint
                                                                            Server)

Set-ecssessionmanagement      Lets an administrator set session             Set-ecssessionmanagement:
                              management settings for Excel                 Stsadm operation (Office
                              Calculation Services.                         SharePoint Server)

Set-ecsworkbookcache          Lets an administrator set workbook cache      Set-ecsworkbookcache:
                              settings on disk and in memory for Excel      Stsadm operation (Office
                              Calculation Services.                         SharePoint Server)

Setformtemplateproperty       Sets the properties of an individual form     Setformtemplateproperty:
                              template.                                     Stsadm operation (Office
                                                                            SharePoint Server)

Setholdschedule               Sets the schedule to process all records      Setholdschedule: Stsadm
                              that are on hold (records whose retention     operation (Office SharePoint
                              schedules are suspended).                     Server)

Setlogginglevel               Sets the Windows event log and trace log      Setlogginglevel: Stsadm
                              logging level for one or more diagnostic      operation (Office SharePoint
                              logging categories registered in the farm.    Server)

Setosearchsetting             Available only in the April Cumulative        Setosearchsetting: Stsadm
                              Update, this operation sets the current       operation (Office SharePoint
                              values of the Enterprise search settings.     Server)

Setpolicyschedule             Sets the schedule for processing changes      Setpolicyschedule: Stsadm
                              to a policy on the items that are impacted    operation (Office SharePoint
                              by that policy.                               Server)

Setqueryprocessoroptions      Sets the current values of the SharePoint     Setqueryprocessoroptions:
                              Search query processor settings.              Stsadm operation (Office
                                                                            SharePoint Server)

Setrecordsrepositoryschedul   Sets the schedule to process all records      Setrecordsrepositoryschedul
e                             that have been submitted to Records           e: Stsadm operation (Office
                              Center sites in the farm.                     SharePoint Server)

Setsearchandprocessschedul    Sets the schedule for when the search         Setsearchandprocessschedul
e                             and process timer job runs.                   e: Stsadm operation (Office
                                                                            SharePoint Server)

Setsitedirectoryscanschedul   Sets a schedule for a job to run the site     Setsitedirectoryscanschedule
e                             directory links scan.                         : Stsadm operation (Office
                                                                            SharePoint Server)

Setsitelock                   Sets a value that specifies whether the       Setsitelock: Stsadm
                              site collection is locked and unavailable     operation (Office SharePoint
                            for read or write access.                    Server)

Setsspport                  Updates the port or ports for the shared     Setsspport: Stsadm
                            Microsoft Internet Information Services      operation (Office SharePoint
                            (IIS) Web site, "Office Server Web           Server)
                            Services", which used by Microsoft Office
                            SharePoint Server 2007 Web services.

Setworkflowconfig           Enables or disables the workflow settings.   Setworkflowconfig: Stsadm
                                                                         operation (Office SharePoint
                                                                         Server)

Siteowner                   Sets the primary or secondary                Siteowner: Stsadm
                            administrator of a site collection.          operation (Office SharePoint
                                                                         Server)

Sync                        Configures the Windows SharePoint            Sync: Stsadm operation
                            Services 3.0 synchronization job.            (Office SharePoint Server)
                            Normally, this operation is used in
                            conjunction with
                            the preparetomove operation

Syncsolution                Performs a synchronization of the            Syncsolution: Stsadm
                            Windows SharePoint Services Solution         operation (Office SharePoint
                            Package (WSP) solutions stored in the        Server)
                            configuration database with the files
                            stored on disk.

Trimauditlog                Lets an administrator delete audit entries   Trimauditlog: Stsadm
                            older than a certain date, as specified      operation (Office SharePoint
                            using the enddate parameter.                 Server)

Tzmove                      Allows an administrator to update data       Tzmove: Stsadm operation
                            that is affected by a change in the start    (Office SharePoint Server)
                            and/or end of Daylight Saving time (DST).

Unextendvs                  Removes Windows SharePoint Services          Unextendvs: Stsadm
                            3.0 from a particular Web application.       operation (Office SharePoint
                                                                         Server)

Uninstallfeature            Removes the specified feature definition     Uninstallfeature: Stsadm
                            from the collection of feature definitions   operation (Office SharePoint
                            in the farm.                                 Server)

Unquiescefarm               Resumes the farm‘s ability to accept new     Unquiescefarm: Stsadm
                            sessions that are essential to rendering     operation (Office SharePoint
                            InfoPath forms on a server.                  Server)

Unquiesceformtemplate       Restores a specific form template for use    Unquiesceformtemplate:
                            on the server.                               Stsadm operation (Office
                                                                         SharePoint Server)

Unregistersecuritytrimmer   Unregisters a custom security trimmer        Unregistersecuritytrimmer:
                            when the ssp and idparameters are            Stsadm operation (Office
                            specified.                                   SharePoint Server)

Unregisterwsswriter         Disables the Windows SharePoint Services     Unregisterwsswriter:
                            VSS Writer service (known as WSS Writer      Stsadm operation (Office
                            service) on any front-end Web server.        SharePoint Server)

Updateaccountpassword       Updates the Web application pool             Updateaccountpassword:
                            passwords.                                   Stsadm operation (Office
                                                                         SharePoint Server)
Updatealerttemplates         Lets an administrator update custom          Updatealerttemplates:
                             changes to the Alerttemplates.xml file.      Stsadm operation (Office
                                                                          SharePoint Server)

Updatefarmcredential         Updates the Web application pool for the     Updatefarmcredentials:
                             SharePoint Central Administration Web        Stsadm operation (Office
                             site and the Windows SharePoint Services     SharePoint Server)
                             Timer service (SPTimer).

Upgrade                      Upgrades the specified site collection       Upgrade: Stsadm operation
                             during a gradual upgrade.                    (Office SharePoint Server)

Upgradesolution              Upgrades an existing solution. The           Upgradesolution: Stsadm
                             solution to be upgraded could be either      operation (Office SharePoint
                             deployed or not deployed; however,           Server)
                             theimmediate or time parameters apply
                             only if the solution has been deployed.

Upgradetargetwebapplicatio   Prepares the environment for the gradual     Upgradetargetwebapplicatio
n                            upgrade of a specific version 2.0 Web        n: Stsadm operation (Office
                             application by moving the existing version   SharePoint Server)
                             2.0 Web application to a new URL and
                             making a new version 3.0 Web application
                             that is based on the existing version 2.0
                             Web application and associated settings.

Userrole                     Adds or deletes permission levels to site    Userrole: Stsadm operation
                             groups.                                      (Office SharePoint Server)

Variationsfixuptool          Lets an administrator correct variations     Variationsfixuptool: Stsadm
                             system data on publishing sites or pages.    operation (Office SharePoint
                                                                          Server)

Verifyformtemplate           Verifies that the form template can be       Verifyformtemplate: Stsadm
                             browser-enabled.                             operation (Office SharePoint
                                                                          Server)


Properties

Property name                               Description     More information

Alerts-enabled                              Turns alerts    Alerts-enabled: Stsadm property (Office
                                            on or off.      SharePoint Server)

Alerts-limited                              Specifies the   Alerts-limited: Stsadm property (Office
                                            number of       SharePoint Server)
                                            alerts to
                                            which a user
                                            can create.

Alerts-maximum                              Specifies the   Alerts-maximum: Stsadm property (Office
                                            maximum         SharePoint Server)
                                            number of
                                            alerts a user
                                            can create.

Avallowdownload                             Specifies       Avallowdownload: Stsadm property
                                            whether         (Office SharePoint Server)
                                            users can
                                            download
                                            infected
                                            documents
                                to their local
                                computers.

Avcleaningenabled               Specifies        Avcleaningenabled: Stsadm property
                                whether          (Office SharePoint Server)
                                antivirus
                                cleaning is
                                enabled or
                                disabled.

Avdownloadscanenabled           Specifies        Avdownloadscanenabled: Stsadm
                                whether          property (Office SharePoint Server)
                                documents
                                are scanned
                                when they
                                are
                                downloaded.

Avnumberofthreads               Specifies the    Avnumberofthreads: Stsadm property
                                number of        (Office SharePoint Server)
                                threads to
                                use for
                                antivirus
                                processes.

Avtimeout                       Specifies        Avtimeout: Stsadm property (Office
                                how long to      SharePoint Server)
                                wait before
                                an antivirus
                                process
                                times out.

Avuploadscanenabled             Specifies        Avuploadscanenabled: Stsadm property
                                whether          (Office SharePoint Server)
                                documents
                                are scanned
                                when they
                                are
                                uploaded.

Change-log-expiration-enabled   Specifies        Change-log-expiration-enabled: Stsadm
                                whether          property (Office SharePoint Server)
                                change logs
                                are deleted
                                after the
                                time span
                                defined in
                                the Change-
                                log-
                                retention-
                                period:
                                Stsadm
                                property
                                (Office
                                SharePoint
                                Server) prop
                                erty.

Change-log-retention-period     Specifies the    Change-log-retention-period: Stsadm
                                amount of        property (Office SharePoint Server)
                                time to
                                preserve
                                change logs
Command-line-upgrade-running              Specifies       Command-line-upgrade-running: Stsadm
                                          whether the     property (Office SharePoint Server)
                                          upgrade
                                          process has
                                          already been
                                          started.

Data-retrieval-services-enabled           Turns data      Data-retrieval-services-enabled: Stsadm
                                          retrieval       property (Office SharePoint Server)
                                          services on
                                          or off.

Data-retrieval-services-inherit           Specifies       Data-retrieval-services-inherit: Stsadm
                                          whether the     property (Office SharePoint Server)
                                          Web
                                          application
                                          inherits data
                                          retrieval
                                          service
                                          settings that
                                          are located
                                          on the
                                          SharePoint
                                          Central
                                          Administratio
                                          n Web site.

Data-retrieval-services-oledb-providers   Obsolete.       Not applicable

Data-retrieval-services-response-size     Specifies the   Data-retrieval-services-response-size:
                                          response        Stsadm property (Office SharePoint
                                          size of the     Server)
                                          data source
                                          that is
                                          returned to
                                          the data
                                          retrieval
                                          service.

Data-retrieval-services-timeout           Specifies the   Data-retrieval-services-timeout: Stsadm
                                          request time    property (Office SharePoint Server)
                                          out setting.

Data-retrieval-services-update            Turns the       Data-retrieval-services-update: Stsadm
                                          support for     property (Office SharePoint Server)
                                          update
                                          queries on or
                                          off.

Data-source-controls-enabled              Turns the       Data-source-controls-enabled: Stsadm
                                          data source     property (Office SharePoint Server)
                                          controls on
                                          the server
                                          on or off.

Database-command-timeout                  Retrieves or    Database-command-timeout: Stsadm
                                          sets the wait   property (Office SharePoint Server)
                                          time before
                                          terminating
                                          the attempt
                                          to execute a
                                          command
                                          and
                              generating
                              an error.

Database-connection-timeout   Retrieves an     Database-connection-timeout: Stsadm
                              open             property (Office SharePoint Server)
                              connection
                              or sets a
                              connection
                              to a
                              Microsoft
                              SQL Server
                              database.

Days-to-show-new-icon         Specifies the    Days-to-show-new-icon: Stsadm property
                              number of        (Office SharePoint Server)
                              days to
                              display the
                              "New" icon
                              for items
                              added to a
                              Web site.

Dead-site-auto-delete         Turns on or      Dead-site-auto-delete: Stsadm property
                              off the          (Office SharePoint Server)
                              setting to
                              delete the
                              site
                              collection

Dead-site-notify-after        Specifies the    Dead-site-notify-after: Stsadm property
                              number of        (Office SharePoint Server)
                              days to wait
                              before
                              sending
                              notifications

Dead-site-num-notifications   Specifies the    Dead-site-num-notifications: Stsadm
                              number of        property (Office SharePoint Server)
                              notifications
                              to send

Defaultquotatemplate          Specifies the    Defaultquotatemplate: Stsadm property
                              default quota    (Office SharePoint Server)
                              template to
                              be used
                              when
                              creating new
                              site
                              collection on
                              a specified
                              Web
                              application.

Defaulttimezone               Specifies the    Defaulttimezone: Stsadm property (Office
                              time zone for    SharePoint Server)
                              sites that are
                              created in a
                              Web
                              application.

Delete-web-send-email         Deletes the      Delete-web-send-email: Stsadm property
                              site             (Office SharePoint Server)
                              collection if
                          use is not
                          confirmed

Irmaddinsenabled          Specifies a      Irmaddinsenabled: Stsadm property
                          rights           (Office SharePoint Server)
                          management
                          platform
                          other than
                          Windows
                          Rights
                          Management
                          Server.

Irmrmscertserver          Specifies the    Irmrmscertserver: Stsadm property
                          location of      (Office SharePoint Server)
                          the Windows
                          Rights
                          Management
                          Services
                          server.

Irmrmsenabled             Controls         Irmrmsenabled: Stsadm property (Office
                          whether the      SharePoint Server)
                          server
                          should use
                          the Windows
                          RMS
                          infrastructur
                          e instead of
                          another
                          rights
                          management
                          platform.

Irmrmsusead               Specifies        Irmrmsusead: Stsadm property (Office
                          that             SharePoint Server)
                          Microsoft
                          Office
                          SharePoint
                          Server 2007
                          should use
                          the location
                          of the RMS
                          server that is
                          stored in
                          Active
                          Directory,
                          rather than
                          an
                          administrato
                          r manually
                          specifying
                          the location
                          of the
                          Windows
                          RMS.

Job-ceip-datacollection   Specifies the    Job-ceip-datacollection: Stsadm property
                          time             (Office SharePoint Server)
                          schedule for
                          when
                          Customer
                            Experience
                            Improvemen
                            t Program
                            (CEIP) data
                            is collected.

Job-change-log-expiration   Specifies the    Job-change-log-expiration: Stsadm
                            time             property (Office SharePoint Server)
                            schedule
                            when the
                            change log
                            timer job
                            occurs.

Job-config-refresh          Specifies the    Job-config-refresh: Stsadm property
                            schedule for     (Office SharePoint Server)
                            the
                            configuration
                            refresh job.

Job-database-statistics     Specifies the    Job-database-statistics: Stsadm property
                            time             (Office SharePoint Server)
                            schedule
                            when
                            database
                            statistics are
                            collected.

Job-dead-site-delete        Specifies the    Job-dead-site-delete: Stsadm property
                            frequency        (Office SharePoint Server)
                            interval and
                            time range
                            to delete
                            unused Web
                            sites
                            automaticall
                            y, for
                            example,
                            "Weekly at
                            Sat
                            0:00:00".

Job-gradual-site-deletion   Added in the     Job-gradual-site-deletion: Stsadm
                            April            property (Office SharePoint Server)
                            Cumulative
                            Update to
                            perform
                            gradual
                            deletion of
                            site
                            collections.
                            Lets a site
                            collection to
                            be marked
                            as deleted,
                            which
                            immediately
                            prevents any
                            further
                            access to its
                            content.

Job-immediate-alerts        Specifies the    Job-immediate-alerts: Stsadm property
                          frequency to    (Office SharePoint Server)
                          check for
                          alerts that
                          are to be
                          sent
                          immediately.

Job-recycle-bin-cleanup   Specifies the   Job-recycle-bin-cleanup: Stsadm property
                          time            (Office SharePoint Server)
                          schedule for
                          a cleanup of
                          the Recycle
                          Bin to occur.

Job-usage-analysis        Lets an         Job-usage-analysis: Stsadm property
                          administrato    (Office SharePoint Server)
                          r set the
                          time interval
                          for usage
                          processing.

Job-watson-trigger        Displays the    Job-watson-trigger: Stsadm property
                          time            (Office SharePoint Server)
                          schedule of
                          the Windows
                          SharePoint
                          Services
                          Watson
                          Upload job.

Job-workflow              Sends the       Job-workflow: Stsadm property (Office
                          workflow        SharePoint Server)
                          events that
                          have been
                          queued and
                          delivers
                          them to
                          workflows.

Job-workflow-autoclean    Specifies the   Job-workflow-autoclean: Stsadm property
                          time            (Office SharePoint Server)
                          schedule for
                          when a scan
                          occurs to
                          delete
                          workflow
                          instance
                          data.

Job-workflow-failover     Specifies a     Job-workflow-failover: Stsadm property
                          schedule for    (Office SharePoint Server)
                          restarting
                          workflow
                          operations
                          that fail
                          because of
                          external
                          reasons.

Large-file-chunk-size     Specifies the   Large-file-chunk-size: Stsadm property
                          amount of       (Office SharePoint Server)
                          data that can
                          be read from
                                       the server
                                       running
                                       Microsoft
                                       SQL Server
                                       at one time.

Max-file-post-size                     Specifies the    Max-file-post-size: Stsadm property
                                       maximum          (Office SharePoint Server)
                                       allowable
                                       size for a
                                       single upload
                                       of content to
                                       any site.

Peoplepicker-                          Configures       Peoplepicker-
activedirectorysearchtimeout           the timeout      activedirectorysearchtimeout: Stsadm
                                       when a           property (Office SharePoint Server)
                                       query is
                                       issued to
                                       Active
                                       Directory.

Peoplepicker-                          Restricts the    Peoplepicker-
distributionlistsearchdomains          search of a      distributionlistsearchdomains: Stsadm
                                       distribution     property (Office SharePoint Server)
                                       list to a
                                       specific
                                       subset of
                                       domains.

Peoplepicker-                          Specifies not    Peoplepicker-
nowindowsaccountsfornonwindowsauthen   to search        nowindowsaccountsfornonwindowsauthent
ticationmode                           Active           icationmode: Stsadm property (Office
                                       Directory        SharePoint Server)
                                       when the
                                       current port
                                       is using
                                       forms-based
                                       authenticatio
                                       n.

Peoplepicker-                          Displays only    Peoplepicker-
onlysearchwithinsitecollection         users that       onlysearchwithinsitecollection: Stsadm
                                       are members      property (Office SharePoint Server)
                                       of the site
                                       collection.

Peoplepicker-searchadcustomfilter      Enables a        Peoplepicker-searchadcustomfilter:
                                       farm             Stsadm property (Office SharePoint
                                       administrato     Server)
                                       r to specify a
                                       unique
                                       search
                                       query.

Peoplepicker-searchadcustomquery       Permits the      Peoplepicker-searchadcustomquery:
                                       administrato     Stsadm property (Office SharePoint
                                       r to set the     Server)
                                       custom
                                       query that is
                                       sent to
                                       Active
                                       Directory.
Peoplepicker-searchadforests     Permits a        Peoplepicker-searchadforests: Stsadm
                                 user to          property (Office SharePoint Server)
                                 search from
                                 a second
                                 one-way
                                 trusted
                                 forest or
                                 domain.

Peoplepicker-                    Enables a        Peoplepicker-
serviceaccountdirectorypaths     farm             serviceaccountdirectorypaths: Stsadm
                                 administrato     property (Office SharePoint Server)
                                 r to manage
                                 the site
                                 collection
                                 that has a
                                 specific
                                 organization
                                 al unit (OU)
                                 setting
                                 defined.

Presenceenabled                  Allows users     Presenceenabled: Stsadm property (Office
                                 of a             SharePoint Server)
                                 SharePoint
                                 site to see if
                                 other users
                                 are online
                                 and send
                                 instant
                                 messages to
                                 them.

Recycle-bin-cleanup-enabled      Specifies        Recycle-bin-cleanup-enabled: Stsadm
                                 whether a        properties (Office SharePoint Server)
                                 cleanup to
                                 the recycle
                                 bin occurs.

Recycle-bin-enabled              Turns the        Recycle-bin-enabled: Stsadm properties
                                 Recycle Bin      (Office SharePoint Server)
                                 on or off.

Recycle-bin-retention-period     Specifies the    Recycle-bin-retention-period: Stsadm
                                 retention        properties (Office SharePoint Server)
                                 period, in
                                 days, of
                                 deleted
                                 items in the
                                 Recycle Bin.

Second-stage-recycle-bin-quota   Specifies        Second-stage-recycle-bin-quota: Stsadm
                                 how much         properties (Office SharePoint Server)
                                 hard disk
                                 space is
                                 available to
                                 a second
                                 stage
                                 Recycle Bin
                                 as a
                                 percentage
                                 of the quota
                                 allotted to
                                   the Web
                                   application.

Token-timeout                      Specifies the   Token-timeout: Stsadm property (Office
                                   amount of       SharePoint Server)
                                   time before
                                   a user token
                                   times out.

Usageprocessingenabled             Configures      Usageprocessingenabled: Stsadm
                                   whether the     property (Office SharePoint Server
                                   usage
                                   analysis
                                   process is
                                   turned on or
                                   off.

Workflow-cpu-throttle              Obsolete.       Not applicable

Workflow-eventdelivery-batchsize   Specifies the   Workflow-eventdelivery-batchsize:
                                   maximum         Stsadm property (Office SharePoint
                                   number of       Server)
                                   work items
                                   that will be
                                   paged in to a
                                   processing
                                   timer job.

Workflow-eventdelivery-throttle    The number      Workflow-eventdelivery-throttle: Stsadm
                                   of workflows    property (Office SharePoint Server)
                                   that can be
                                   processed
                                   (that is,
                                   using the
                                   processor,
                                   not idle) at
                                   the same
                                   time across
                                   all Web
                                   front-end
                                   computers.

Workflow-eventdelivery-timeout     The time        Workflow-eventdelivery-timeout: Stsadm
                                   value a         property (Office SharePoint Server)
                                   workflow job
                                   must run
                                   without the
                                   job timing
                                   out.

Workflow-timerjob-cpu-throttle     Obsolete.       Not applicable

Workitem-eventdelivery-batchsize   The paging      Workitem-eventdelivery-batchsize:
                                   size for        Stsadm property (Office SharePoint
                                   events          Server)
                                   delivered to
                                   a single
                                   workflow
                                   instance.

Workitem-eventdelivery-throttle    Specifies the   Workitem-eventdelivery-throttle: Stsadm
                                   maximum         property (Office SharePoint Server)
                                   number of
                                                      work items
                                                      that can be
                                                      obtained on
                                                      a given
                                                      query for
                                                      runnable
                                                      work items.



Activatefeature: Stsadm operation (Office SharePoint Server)
Updated: 2007-04-26

Operation name: Activatefeature
Activates a feature in the feature collection. You must first determine the scope of the feature. If the scope
is Web-based or is a site collection scope, the urlparameter is required. However, if the scope is farm-
based, the url parameter is not required.


      Note:

 If you try to use the url parameter on a farm-scoped feature, you will receive the following error message:
 ―The feature ‗<feature name>‘ applies to the entire farm; the URL parameter cannot be used with farm-
 scoped features."
Syntax
stsadm -o activatefeature

  {-filename <relative path to Feature.xml> | -name <feature folder> | -id <feature ID>}

  [-url] <URL name>

  [-force]

Parameters
 Parameter    Value                             Required?    Description

 filename     A valid file path, such as        Yes          Path to feature must be a relative path to the
              "MyFeature\Feature.xml"                        12\Template\Features directory. Can be any
                                                             standard character that the Windows system
                                                             supports for a file name.
                                                                Note:

                                                             If the feature file is not found on disk, the
                                                             following error message is displayed: ―Failed to
                                                             find the XML file at location
                                                             '12\Template\Features\<file path>'.‖


 name         Name of the feature directory,    Yes          Name of the feature folder located in the
              such as ―MyFeature‖                            12\Template\Features directory

 id           A valid GUID, such as             Yes          GUID that identifies the feature to activate
              ―21d186e1-7036-4092-a825-                        Note:
              0eb6709e9280‖
                                                             If the ID is specified but the feature does not
                                                             exist, the following error message is returned:
                                                             "Feature '<id>' is not installed in this farm, and
                                                           cannot be added to this scope."


 url         A valid URL, such as              Yes         URL of the Web application, site collection, or
             http://server_name                            Web site to which the feature is being activated

 force       <none>                            No          Activates a feature. This causes any custom code
                                                           associated with the feature to rerun.



Addalternatedomain: Stsadm operation (Office SharePoint
Server)
Updated: 2007-12-13

Operation name: Addalternatedomain

Description
Adds an internal URL and maps it to one of the five URL zones of a Web application or external resource.

This operation is equivalent to the Add Internal URLs user interface setting that is located on the Alternate
Access Mappings page of the SharePoint Central Administration Web site.

For more information, see Configure alternate access mapping.

Syntax
stsadm -o addalternatedomain

  -url <URL name>

  -incomingurl <http://internal.url>

  -urlzone {Default | Internet | Intranet | Extranet | Custom}

  -resourcename <non-Web application resource name>

Parameters
 Parameter        Value                                         Required?                      Description
 name

 url              A valid URL, such as http://server_name or    No. However, if                URL of the
                  http://server_name:1234                       the urlparameter is used       Web
                                                                then                           application.
                                                                the resourcenameparamet        This
                                                                er cannot be used.             parameter
                                                                                               should be an
                                                                                               existing
                                                                                               alternate
                                                                                               access
                                                                                               mappings
                                                                                               (AAM) URL
                                                                                               that is
                                                                                               assigned to a
                                                                                               Web
                                                                                               application so
                                                                                               that stsadm
                                                                                               can
                                                                                               determine
                                                                                               which Web
                                                                                        application
                                                                                        you are
                                                                                        targeting.
                                                                                        The URL can
                                                                                        be a public
                                                                                        URL or an
                                                                                        internal URL
                                                                                        from any
                                                                                        zone
                                                                                        associated
                                                                                        with the
                                                                                        targeted Web
                                                                                        application.

incomingurl   A valid URL, such as                        Yes                           The internal
              "http://sharepoint.courses.contoso.com:12                                 URL that you
              34"                                                                       want to add.
                                                                                        This
                                                                                        parameter
                                                                                        should be
                                                                                        limited to the
                                                                                        protocol
                                                                                        scheme, host
                                                                                        name, and
                                                                                        port number
                                                                                        portions of
                                                                                        the URL. It
                                                                                        should not
                                                                                        contain any
                                                                                        other
                                                                                        portions of
                                                                                        an URL. You
                                                                                        can map
                                                                                        multiple
                                                                                        internal URLs
                                                                                        to the same
                                                                                        URL zone.

urlzone       Any one of the following values:            Yes                           One of the
                    Default                                                            five zones
                    Intranet                                                           with which
                                                                                        the internal
                    Internet
                                                                                        URL is
                    Extranet
                                                                                        associated.
                    Custom

resourcenam   A valid name, such as "Resource1"           No. However, a resource       Specifies the
e                                                         name must already exist       external
                                                          before this parameter can     resource
                                                          be used. You can create a     which the
                                                          new resource name using       internal URL
                                                          theAddzoneurl operation.      should be
                                                            Note:                       added to.
                                                                                        This
                                                          If                            parameter is
                                                          the resourcenameparamet       equivalent to
                                                          er is used, then              the External
                                                                                        Resource
                                                          the url parameter cannot be
                                                                                        Mapping use
                                                          used.                         r interface
                                                                                        setting that
                                                          .                             is located on
                                                                                                the Create
                                                                                                External
                                                                                                Resource
                                                                                                Mapping
                                                                                                page of the
                                                                                                SharePoint
                                                                                                Central
                                                                                                Administratio
                                                                                                n Web site.
Remarks
A separate zone mapping for each Web application can be performed.

In Windows SharePoint Services 2.0, an internal URL was referred to as an incoming URL and a public URL
was referred to as an outgoing URL.

For each Web request, Windows SharePoint Services 3.0 determines the protocol, host header, and port of
the request and looks for a matching internal URL that was previously entered. If a matching internal URL is
found, Windows SharePoint Services 3.0 then determines which zone will be used to format the hyperlinks in
the response. A URL zone contains one public URL and one or more internal URLs.

Alternate access mappings enable a Web application that receives a request for an internal URL, in one of
the five authentication zones, to return pages that contain links to the public URL for the zone. You can
associate a Web application with a collection of mappings between internal and public URLs. Internal refers
to the URL of a Web request as it is received by Microsoft Office SharePoint Server 2007. Public refers to the
URL of an externally accessible Web site. The public URL is the base URL that Office SharePoint Server 2007
uses in the pages that it returns. If the internal URL has been modified by a reverse proxy device, it can
differ from the public URL.

Multiple internal URLs can be associated with a single public URL. Mapping collections can contain up to five
authentication zones, but each zone can only have a single public URL. Mapping collections correspond to
the following authentication zones:

       Default

       Internet

       Intranet

       Extranet

       Custom

For additional information about zones, URLs, and to view a corporate deployment scenario for each zone,
see the Logical architecture model: Corporate deployment.

Host-named site collections cannot use alternate access mappings. Host-named site collections are
automatically considered to be in the Default zone, and the URL of the request must not be modified
between the end user and the server.

Examples
If a reverse proxy server or load balancer receives a request from the user as https://www.contoso.com and
forwards it to the server running Windows SharePoint Services 3.0 as
http://sharepoint.courses.contoso.com:1234, the administrator would configure the following URLs for a
SharePoint Web application:

Internal URL: http://sharepoint.courses.contoso.com:1234

Public URL: https://www.contoso.com

For this example, http://sharepoint:1234 is already an AAM URL that is assigned to a Web application and
the Internet zone is used.

To configure an internal URL, use the following syntax:
stsadm -o addalternatedomain -url http://sharepoint:1234 -urlzone Internet -
incomingurl http://sharepoint.courses.contoso.com:1234

To map the public URL to the URL zone, use the following syntax:

stsadm -o addzoneurl -url http://sharepoint:1234 -urlzone Internet -zonemappedurl
https://www.contoso.com


  Note:

 There can be only one public URL per URL zone. This is the URL used in Web pages or e-mail messages
 going from the Web server to the reverse proxy server or the client.
To confirm the change to the internal URL, use the following syntax:

stsadm -o enumalternatedomains -url http://sharepoint.courses.contoso.com:1234



Addcontentdb: Stsadm operation (Office SharePoint Server)
Updated: 2009-04-02

Operation name: Addcontentdb
Creates a new content database or adds a database that needs to be upgraded when
the url and databasename parameters are specified.

When a content database is created, the location of the data and log file is determined by the default
database settings established on the SQL database server. A content database is created with a primary file
group hosting one data (.mdf) file and one transaction log (.ldf) file.


   Important:

 If you detach and reattach a content database, be aware that the next time the content within that content
 database is crawled a full crawl will occur even if an incremental crawl has been requested. Because a full
 crawl re-crawls all content that the crawler encounters, regardless of whether that content has been
 previously crawled, full crawls can take significantly more time to complete than incremental crawls.
Syntax
stsadm.exe -o addcontentdb

-url <URL name>

-[-assignnewdatabaseid]

-[-clearchangelog]

-databasename <database name>

[-databaseserver <database server name>]

[-databaseuser <database username>]

[-databasepassword <database password>]

[-sitewarning <site warning count>]

[-sitemax <site max count>]
Parameters

Parameter
name and short                             Required
form                  Value                ?          Description

url                   A valid URL, such    Yes        URL of the Web application to which the content
                      as                              database is being added.
                      http://server_nam
                      e

assignnewdatabasei    A valid GUID, such   No         Creates a new database ID automatically when a
d                     as "12345678-                   content database is attached. This parameter was first
                      90ab-cdef-1234-                 introduced in the Infrastructure Update for Microsoft
                      567890bcdefgh"                  Office Servers. For more information, see Remarks.

clearchangelog        <none>               No         Clears the change log.
                                                      Forces the change log to be cleared when necessary,
                                                      for example, when restoring a content database to a
                                                      prior point in time using separate SQL Server-level
                                                      backup tools. This parameter was first introduced in
                                                      the Infrastructure Update for Microsoft Office Servers.
                                                      For more information, see Remarks.

databasename (dn)     A valid database     Yes        Database name.
                      name, such as
                      "DB1"

databaseserver (ds)   A valid database     No         Database server name. The default server is used if a
                      server name, such               value not provided.
                      as "Sales", where
                      named instances
                      are used; the
                      format may
                      appear as
                      server\server

databaseuser          A valid user name    No         Account used for SQL authentication. Must be used in
                      in the form                     conjunction with thedatabasepassword parameter.
                      "Username1"

databasepassword      A valid SQL          No         The databasepassword parameter should only be
                      password                        used where Windows authentication is not
                                                      implemented Therefore, in a Microsoft SQL Server
                                                      authentication scenario, you need to pass
                                                      the databaseuser and databasepassword paramet
                                                      ers to authenticate against the database server.
                                                      Under Windows authentication, you can omit these
                                                      parameters because the credentials are passed using
                                                      NTLM.

sitewarning           A valid integer      No         Integer number of site collections allowed in the
                      number, such as                 content database prior to generating a warning event
                      10                              in the Windows event log.

sitemax               A valid integer      No         Specifies the maximum number of site collections
                      number, such as                 allowed in the content database.
                      10


Remarks
If you are running the Infrastructure Update for Microsoft Office Servers, the identifier (ID) of each content
database is retained when you restore or reattach the database by using built-in tools. Default change log
retention behavior when using built-in tools is as follows:

       The change logs for all databases are retained when you restore a farm.

       The change log for a content database is retained when you reattach the database.

       The change log for a content database is NOT retained when you restore just the content database.

For more information, see Move content databases (Office SharePoint Server 2007) and Back up and restore
an entire farm (Office SharePoint Server 2007).

If you restore an older SQL Server backup of a content database, the Search index may contain more
entries than the restored databases in the farm. First, use the Stsadm command stsadm –o
deletecontentdb to detach the database from the SharePoint farm, and then restore the database by using
SQL Server tools. Next, use the Stsadm command stsadm –o addcontentdb –clearchangelog to
reattach the content database and clear the change log. Clearing the change log forces Search to run a full
crawl on that database so that the index no longer references items that do not exist.

As an administrator, you should always know when and if a change log should be cleared. For example, if a
content database is restored to an earlier time than the last crawl by using Microsoft SQL Server-level
backup tools, and this operation is used to reattach it to the farm, not clearing the change log causes the
index to potentially have entries for items in that content database that do not exist in the restored
database. To prevent this issue from occurring in this scenario, use theclearchangelog parameter to clear
the log. If a content database has been attached mistakenly without the clearchangelog parameter, you
should detach and then reattach the content database using the clearchangelog parameter so that the
next crawl will be able to reset the index for that content database.

When a content database is attached to the same Web application, the change log will by default be
preserved along with the database ID. If it becomes necessary to change the database ID, such as an ID
conflict, the assignnewdatabaseid parameter will force a new ID to be selected for the content database.

You will receive the following error if you are unable to attach the database to the farm due to a
conflict: The attach operation cannot continue because another object in this farm already
contains the same ID. Each object in a farm must have a unique ID. In order to proceed with the
attach operation you must assign a new ID to this database. To attach this database with a new
ID, use the "stsadm.exe -o addcontentdb" operation with the -assignnewdatabaseid parameter.
Note that if this new database and an existing database contain the same site collections,
attaching this database will likely result in orphaned site collections due to conflicts between the
two databases.



Adddataconnectionfile: Stsadm operation (Office SharePoint
Server)
Updated: 2007-09-13

Description
Adds a new data connection file to the DataConnectionFiles collection for InfoPath Forms Services.

Syntax
stsadm -o adddataconnectionfile

  -filename <Path to file to add>

  [-webaccessible] {Yes | No}

  [-overwrite] {Yes | No}

  [-category] <A string value>
Parameters

Parameter
name                Value                                           Required? Description

 filename           The name of a valid data connection file,       Yes       The full path to the file to
                    such as                                                   upload into the collection.
                    "C:\foldername\myconnection.udcx"

 webaccessible      One of the following values:                    No        Determines whether the
                           Yes                                               Universal Data Connection file
                           No (Default)                                      can be accessed by using the
                                                                              Web service. If this is No, then
                                                                              only the forms server can
                                                                              retrieve the Universal Data
                                                                              Connection files internally.

 overwrite          One of the following values:                    No        Determines whether to
                           Yes (Default)                                     overwrite the file if it exists.
                           No

 category           A valid string value, such as "Category1"       No        Sets an arbitrary category on
                                                                              the file which can be used to
                                                                              group the files.




Add-ecsfiletrustedlocation: Stsadm operation (Office
SharePoint Server)
Updated: 2008-02-14

Operation name: Add-ecsfiletrustedlocation
Lets an administrator to add a file to the trusted location list.

This operation is equivalent to the Location user interface setting that is located on the Excel Services Add
Trusted File Location page of the SharePoint Shared Services Administration Web site.

Syntax
stsadm -o add-ecsfiletrustedlocation

  -ssp <SSP name>

  -location {URL | UNC}

  -LocationType {SharePoint |UNC |HTTP}

  -IncludeChildren {True | False}

  [-SessionTimeout <time in seconds>]

  [-ShortSessionTimeout <time in seconds>]

  [-MaxRequestDuration <time in seconds>]

  [-MaxWorkbookSize <file size in MB>]

  [-MaxChartSize <size in MB>]

  [-VolatileFunctionCacheLifetime <time in seconds>]

  [-DefaultWorkbookCalcMode {File | Manual | Auto | AutoDataTables}]
 [-AllowExternalData {None | Dcl | DclAndEmbedded}]

 [-WarnOnDataRefresh {True | False}]

 [-StopOpenOnRefreshFailure {True | False}]

 [-PeriodicCacheLifetime <time in seconds>]

 [-ManualCacheLifetime <time in seconds>]

 [-MaxConcurrentRequestsPerSession <number of requests>]

 [-AllowUdfs {True | False}]

 [-Description <descriptive text>]

Parameters
Parameter                 Value                     Requir   Description
                                                    ed?

ssp                       A valid SSP name such     Yes      The name of the SSP that provides the
                          as "SharedServices1"               resources for the Excel Calculation Services
                                                             you want to configure.

location                  A valid location to the   Yes      This is the URL of the directory that is
                          folder that is trusted             trusted. The format of this parameter is
                          Valid values are:                  determined by the value of
                                  URL in the                thelocationtype parameter for a specific
                              form                           location.
                              http(s)://host/pa
                              th
                                  UNC in the
                              form
                              \\server_name\s
                              hare)
                          The maximum length
                          is 1024 characters.

locationtype              One of the following      Yes      Specifies a location type. The value of this
                          supported types:                   parameter determines the authentication
                                 SharePoint                 method for retrieving workbooks. If the
                                 UNC                        value is either SharePoint or HTTP, the
                                                             value of the location parameter is a valid
                                 HTTP
                                                             URL. If the value is UNC, the value of
                                                             the location parameter is a valid UNC.
                                                             This parameter works in conjunction with
                                                             the locationparameter.

includechildren           One of the following      Yes      True indicates that subdirectories or child
                          values:                            libraries are trusted; False indicates they
                                 True                       are not.
                                 False (Defa
                             ult value)

sessionTimeout            One of the following      No       Maximum time, in seconds, that an Excel
                          valid integers:                    Calculation Services session can remain
                                  -1: No                    open and inactive before it expires, as
                              timeout                        measured from the end of each request.
                                  0: The
                              session expires at
                              the end of a
                              single request
                                  2073600 (24
                               days)
                                  A range
                               between the
                               values, for
                               example, 1 to
                               2073600

shortSessionTimeout         One of the following     No   Maximum time, in seconds, that an Excel
                            valid integers:               Calculation Services session can remain
                                    -1: Disables         open and inactive, prior to any user
                                short session             interaction, before it is closed. Time is
                                timeout                   measured from the end of the initial open
                                                          request.
                                    0: The
                                session expires at
                                the end of a
                                single request
                                    2073600 (24
                                days)
                                    A range
                                between the
                                values, for
                                example, 1 to
                                2073600

maxRequestDuration          One of the following     No   Maximum duration, in seconds, for a single
                            valid integers:               request in a session.
                                    -1: No limit
                                    1 to
                                2073600 (24
                                days)

maxWorkbookSize            A valid integer           No   Maximum size, in megabytes (MB), of a
                           between 1 and 2000             workbook that can be opened by Excel
                                                          Calculation Services.

maxChartSize               A valid integer           No   Maximum size, in MB, of a chart that can be
                           between 1 and                  opened by Excel Calculation Services.
                           2147483647

volatileFunctionCacheLif    One of the following     No   Maximum time, in seconds, that a
etime                       valid integers:               computed value for a volatile function is
                                    -1:                  cached for automatic recalculations.
                                Calculated once
                                on load of the
                                workbook
                                    0: Always
                                calculated
                                    1 to
                                2073600 (24
                                days)

defaultWorkbookCalcMo       One of the following     No   Calculation mode for all workbooks.
de                          values:
                                   File (Default
                               value)
                                   Manual
                                   Auto
                                AutoDataTa
                            bles(same as
                            Auto, but data
                            table are not
                            recalculated)

allowExternalData        One of the following      No   Specifies the types of external data
                         values:                        connections that are allowed.
                                 None: Data
                            connections are
                            not allowed
                            (default value).
                                 Dcl: Only
                            connections
                            defined in trusted
                            data connection
                            libraries are
                            allowed.
                                 DclAndEmb
                            edded: Both
                            connections
                            defined in trusted
                            data connection
                            libraries and
                            connections
                            embedded in the
                            files are allowed.

warnOnDataRefresh        One of the following      No   True: Displays a prompt before refreshing
                         values:                        an external data source that uses the user's
                                True (Defaul           identity.
                            t value)                    False: Does not display a prompt before
                                False                  refreshing an external data source.

stopOpenOnRefreshFail    One of the following      No   True: Stops the open operation on a
ure                      values:                        workbook.
                                True (Defaul           This behavior occurs under the following
                            t value)                    circumstances: The workbook contains a
                                False                  Refresh on Open data connection and the
                                                        workbook cannot be refreshed while it is
                                                        opening, and the user does not have Open
                                                        Item permissions to the workbook.
                                                        False: Does not stop the open operation on
                                                        a workbook.
                                                        For further information about workbooks,
                                                        see Excel Services Technical Overview.
                                                        (http://go.microsoft.com/fwlink/?LinkId=11
                                                        0301&clcid=0x409)

periodicCacheLifetime    One of the following      No   Maximum time, in seconds, that the system
                         valid integers:                can use results from an external data
                                 -1: Never             query.
                             refresh after first
                             query
                                 0 to
                             2073600 (24
                             days)

manualCacheLifetime     One of the following       No   Maximum time, in seconds, that the system
                                valid integers:                      can use results from explicit manual
                                        -1: Never                   external data queries.
                                    refresh after first
                                    query
                                        0 to
                                    2073600 (24
                                    days)

 maxConcurrentRequests          A valid integer            No        Maximum number of concurrent external
 PerSession                     between 1 and                        data queries per session.
                                2147483647

 allowUdfs                      One of the following       No        True: Indicates that user-defined functions
                                values:                              can be called from workbooks in this
                                       True                         trusted location.
                                       False (Defa                  False: Indicates that user-defined functions
                                   ult value)                        cannot be called from workbooks in this
                                                                     trusted location.

 description                    A valid string value,      No        Optional description of the trusted location.
                                for example, "This is a              The maximum character length is 4096
                                trusted location"                    characters.


Remarks
A trusted location list allows the Excel Calculation Services to only load files from locations that are deemed
safe by the administrator. This list is used to load both files that are explicitly loaded by a user (browsing
and showing in the renderer), as well as those implicitly loaded when an Excel Web Access Web Part resides
on a digital dashboard.

When a file is checked to see whether it is in a trusted location, only the file or URL that is initially requested
should be checked. This may be different than the file or URL that is requested by the user, because there
may be redirects prior to determination of the file or URL that will be loaded.

The list of trusted locations is stored in Shared Service Provider database and applies to the logical server.



Add-ecssafedataprovider: Stsadm operation (Office
SharePoint Server)
Updated: 2008-02-14

Operation name: Add-ecssafedataprovider
Lets an administrator add a supported provider type to the safe provider list.

This operation is equivalent to the Provider user interface setting that is located on the Excel Services Add
Trusted Data Provider page of the SharePoint Shared Services Administration Web site.

Syntax
stsadm -o add-ecssafedataprovider

  -ssp <SSP name>

  -type {Oledb | Odbc | OdbcDsn}

  [-description <descriptive text>]

Parameters
 Parameter      Value                             Required?     Description
 ssp             A valid SSP name, such as        Yes         The name of the SSP that provides the resources
                 "SharedServices1"                            for the Excel Calculation Services you want to
                                                              configure.

 id              A valid string value             Yes         Unique identifier for the safe data provider.
                                                              Maximum length is 255 characters.

 type            One of the following values:     Yes         Specifies one of the supported data types.
                        Oledb
                        Odbc
                        OdbcDsn

 description     A valid string value             No          Optional description for a data provider.
                                                              Maximum length is 255 characters.


Remarks
Excel Calculation Services works with any provider that meets all of the following conditions:

         It is one of the supported provider types.

         It is installed on the same machine that is running SharePoint Products and Technologies.

         The administrator has added it to the trusted data provider list.

Excel Calculation Services only retrieves external data from providers that have been included in the list of
safe providers on the server. In order to determine if a provider is in the trusted data provider list, the Excel
Calculation Services parses the connection string of the external data object in order to match the
appropriate fields with the trusted data provider list.

A safe provider list allows Excel Calculation Services to only execute queries using drivers and data sources
that are deemed safe by the administrator. It allows a set of drivers to be tested and guarantees that they
work with Excel Calculation Services, but also allows customers to add additional providers needed in their
organization.



Add-ecstrusteddataconnectionlibrary: Stsadm operation
(Office SharePoint Server)
Updated: 2008-02-14

Operation name: Add-ecstrusteddataconnectionlibrary
Adds a trusted data connection to a data connection library.

This operation is equivalent to the Location user interface setting that is located on the Excel Services Add
Trusted Data Connection Library page of the SharePoint Shared Services Administration Web site

Syntax
stsadm -o add-ecstrusteddataconnectionlibrary

  -ssp <SSP name>

  -location <URL>

  [-description <descriptive text>]
Parameters
 Parameter     Value                                    Required?   Description

 ssp           A valid SSP name, such as                Yes         The name of the SSP that provides the
               "SharedServices1"                                    resources for the Excel Calculation
                                                                    Services you want to configure.

 location      A valid value, such as                   Yes         URL of a trusted data connection library.
               http://host/path                                     The maximum length is 1024 characters.

 description   A valid string value, for example,       No          Optional description of the trusted location.
               "This is a test to a trusted location"               The maximum character length is 4096
                                                                    characters.



Add-ecsuserdefinedfunction: Stsadm operation (Office
SharePoint Server)
Operation name: Add-ecsuserdefinedfunction
Adds a user-defined function, which is a custom function that extends the calculation or data-import
capabilities of Microsoft Excel.

This operation is equivalent to the Excel Services User-Defined Functions user interface setting that is
located on the Excel Services Settings page of the Shared Services Administration Web site.

For more information about UDFs, see Manage Excel Services user-defined functions

Syntax
stsadm -o add-ecsuserdefinedfunction

  -ssp <SSP name>

  -assembly <strong assembly name or file path to an assembly>

  -assemblyLocation {GAC | File}

  [-enable {True | False}]

  [-description <descriptive text>]

Parameters
 Parameter             Value                                                        Required?   Description

 ssp                   A valid SSP name, such as "SharedServices1"                  Yes         The name of
                                                                                                the SSP that
                                                                                                provides the
                                                                                                resources for
                                                                                                the Excel
                                                                                                Calculation
                                                                                                Services you
                                                                                                want to
                                                                                                configure.

 assembly               One of the following value types:                           Yes         Strong name of
                               Strong assembly name, for example, Global                       or full path to
                           Assembly Cache (GAC) location in the                                 an assembly
                           formSampleCompany.SampleApplication.SampleUd                         that contains
                           f                                                                    user-defined
                                                                                                functions,
                               File path to an assembly, for example,
                                                                                                which Excel
                           \\MyNetworkServer\Udfs\SampleUdf.dll                                 Calculation
                                                                                               Services can
                                                                                               call.
                                                                                               The maximum
                                                                                               character
                                                                                               length is 4096.

 assemblylocation      One of the following values:                                 Yes        Specifies an
                              GAC                                                             assembly
                              File                                                            location.

 enable                One of the following values:                                 No         True: Allows
                              True (Default value)                                            the assembly
                              False                                                           to be loaded
                                                                                               and used by
                                                                                               Excel
                                                                                               Calculation
                                                                                               Services.
                                                                                               False:
                                                                                               Disables the
                                                                                               assembly
                                                                                               without having
                                                                                               to completely
                                                                                               remove the
                                                                                               entry from the
                                                                                               list.

 description           A valid string value, for example, "This is a user-defined   No         Optional
                       function for calculating interest"                                      description of
                                                                                               the user-
                                                                                               defined
                                                                                               functions.
                                                                                               The maximum
                                                                                               character
                                                                                               length is 4096
                                                                                               characters.



Addexemptuseragent: Stsadm operation (Office SharePoint
Server)
Updated: 2007-09-13

Description
Adds a user agent, which is typically in the form of a search bot, to receive the XML file that contains the
data of the form for indexing, instead of the HTML rendering of the form.

Syntax
stsadm -o addexemptuseragent

  -name <User agent name>

Parameters
 Paramete    Value                Required    Description
 r name                           ?

 name        The name of a        Yes         These user agents represent search bots that are commonly
             valid user agent,                used in an enterprise environment. If a different search
             such as the                      technology is being used and InfoPath files are not being
             following default                indexed, you can add additional search bots for that technology
            values:                            to the collection. For additional information about the
                        Crawler               ExemptUserAgents, see ExemptUserAgentCollection
                        Googleb               Class (http://go.microsoft.com/fwlink/?LinkId=99645&clcid=0x
                    ot                         409) on MSDN.
                        Microsof
                    t Search
                        MSNbot
                        MSoffice
                        Slurp




Addpath: Stsadm operation (Office SharePoint Server)
Updated: 2008-03-28

Operation name: Addpath
Adds a managed path inclusion to a Web application.

Syntax
stsadm -o addpath

 -url <URL name>

 -type <explicit or wildcard inclusions>

Parameters

Parameter
name            Value                                       Required? Description

 url            A valid URL name, such as                   Yes         The URL of the inclusion you want to
                http://server_name/inclusion_name                       add to a Web application.

 type (t)       One of the following values:                Yes               Explicit: Specifies that a
                       Explicit                                          single path-based site
                       Wildcard                                          collection can be created at the
                                                                          specified URL path.
                                                                              Wildcard: Specifies that
                                                                          multiple path-based site
                                                                          collections can be created
                                                                          below the specified URL path.
                                                                         Note:

                                                                        If you do not specify
                                                                        the type parameter, an error
                                                                        message is displayed. There is no
                                                                        default for this parameter.



Remarks
The addpath operation specifies where new site collections can be created by using the URL parameter.

You cannot have both an explicit inclusion and a wildcard inclusion using the same path on a Web
application.
You may use non-ASCII characters in your inclusion path name.


  Note:

 In Windows SharePoint Services 2.0, you could only use ASCII characters.
The following table shows example URLs and explains the types of paths.


                                      Path
Path type      Example URL            name     Comments

 Explicit      http://server1/site1   /site1   Identifies the Web site at /site1 as a SharePoint site.
 inclusion

 Wildcard      http://server1/sites   /sites   Identifies all sites below the /sites/ path as SharePoint sites.
 inclusion


 Top-level     http://server1         /        Indicates an explicit inclusion for the top-level Web site. Only
 Web site                                      the top-level Web site is a SharePoint site; any sites below
 explicit                                      the top-level Web site are not.
 inclusion

 Top-level     http://server1         /*       Indicates a wildcard inclusion for the top level of the virtual
 Web site                                      server. Every directory under the specified path is a top-level
 wildcard                                      SharePoint site.
 inclusion                                       Important:

                                               Do not use ―/*‖ to indicate wildcard managed sites at the root
                                               of the site collection. Using this wildcard prevents a site being
                                               created at the root of the Web application. Many SharePoint
                                               features rely on having a site collection at the root of the Web
                                               application, and if this is missing, these features will not work
                                               correctly. For example, Explorer View will not work for a
                                               document library.


Web server performance declines linearly with the number of inclusions and exclusions. You can minimize
performance impact by using wildcard inclusions rather than many explicit inclusions, and by putting as
many excluded applications under the same excluded path as possible.



Addpermissionpolicy: Stsadm operation (Office SharePoint
Server)
Updated: 2007-06-14

Operation name: Addpermissionpolicy
Adds a user to a policy role for the Web application based on the specified permission level name and
corresponding zone. This operation is the command-line equivalent of the process used on the Policy for
Web Application page in the SharePoint Central Administration Web site.

Syntax
stsadm -o addpermissionpolicy

  -url <URL name>

  -userlogin <login name>
  -permissionlevel <permission policy level>

  [-zone] <URL zone>

  [-username] <display name>

Parameters
 Parameter         Value                               Required?   Description

 url               A valid URL, such as                Yes         The URL of the Web application to which the
                   http://server_name                              policy level is being added

 userlogin         A valid user name in the form:      Yes         The user login name
                   Domain\user_name.
                   For non-Windows accounts, a
                   valid user name in the form:
                   providerName:user_name

 permissionlevel   A valid permission policy level     Yes         Specifies the appropriate permission policy
                   to add to the permission policy.                level to grant or deny to this user. When you
                   For example, Full Control, Full                 grant a permission, it gives the user the
                   Read, Deny Write, or Deny All.                  granted permission. However, when you deny
                                                                   a permission, it prevents a user from ever
                                                                   having this permission.
                                                                     Note:

                                                                   Denying a right always supersedes granting a
                                                                   right.


 zone              A valid zone, such as "Default"     No          When the zone parameter is not present, the
                                                                   policy applies to all zones. Only Windows NT
                                                                   accounts can be applied to all zones. Accounts
                                                                   in the format
                                                                   ofproviderName:user_name cannot be used
                                                                   for the all-zone policy.

 username          A valid user name in the form       No          The user or display name for the policy. If the
                   of:                                             user name is specified, it will be used;
                   Firstname Lastname                              otherwise Active Directory is queried to
                                                                   resolve a user name.



Addsolution: Stsadm operation (Office SharePoint Server)
Updated: 2007-04-26

Operation name: Addsolution
Adds a solution file to the solution store.

Syntax
stsadm -o addsolution

  -filename <solution file name>

  [-lcid] <language>

Parameters
 Parameter     Value                       Required?    Description

 filename      Any one of the following    Yes          File name on disk
               formats:
                      *.cab
                      *.wsp
                      *.wpp

 lcid          A valid locale ID, such    No          By specifying this parameter, you stores the solution as
               as "1033" for English                  a language pack. If the core neutral solution does not
                                                      exist, the following error message is displayed:
                                                      "Cannot add a language pack resource for the solution
                                                      without adding the main solution package."



Addtemplate: Stsadm operation (Office SharePoint Server)
Updated: 2007-04-26

Operation name: Addtemplate
Adds a site template to the template gallery.

   Note:

 If you want the changes to the template list to take effect immediately, run the iisreset command after
 you run the addtemplate operation.
Syntax
stsadm -o addtemplate

  -filename <file name>

  -title <title>

  [-description] <description>

Parameters
 Parameter     Value                                                   Required?   Description

 filename      A valid file name, such as                              Yes         File name of the template
               ―C:\Templates\SampleTemplate.stp‖                                   that you are adding

 title         A valid title of a template, such as ―Sample            Yes         Title of the template that
               Template‖                                                           you are adding

 description   A valid description of the template, such as ―This is   No          Description of the template
               a sample template‖                                                  that you are adding



Adduser: Stsadm operation (Office SharePoint Server)
Updated: 2007-06-14

Operation name: Adduser
Adds a user account to the specified site collection and assigns it to the specified group or role. Use
the siteadmin parameter to register the user as the site administrator.

Syntax
stsadm -o adduser
  -url <URL name>

  -userlogin <login name>

  -useremail

  -role <role name> / -group <group name>

  -username

  [-siteadmin]

Parameters
 Parameter   Value                                 Required?                       Description

 url         A valid URL, such as                  Yes                             The URL of the site
             http://server_name                                                    collection to which the
                                                                                   user account is being
                                                                                   added

 userlogin   A valid user name in the form:        Yes                             A string that contains
             Domain\user_name                                                      the user name
             For a non-Windows account, a
             valid user name can be in the
             form:
             providerName:user_name

 useremail   A valid e-mail address in the form:   Yes                             A string that contains
             someone@example.com                                                   the e-mail address of
                                                                                   the user

 role        A permission level defined for the    Yes. Either                     Adds a user to a
             site, such as Full Control, Design,   the role or groupparameter is   permission level.
             Contribute, or Read                   required.

 group       A group configured for the site,      Yes. Either                     Adds the user to a
             such as Team Site Members             the role or groupparameter is   group.
                                                   required.

 username    A valid user name, such as "Joe"      Yes                             A string that contains
                                                                                   the display name of the
                                                                                   user

 siteadmin   <none>                                No                              Specifies whether you
                                                                                   want to add the user as
                                                                                   an administrator to the
                                                                                   site collection.



Addwppack: Stsadm operation (Office SharePoint Server)
Updated: 2007-04-26

Operation name: Addwppack
Adds a Web Part package to the server Web Part gallery.

Syntax
stsadm -o addwppack

  -filename <file name>

  [-lcid] <language>
 [-url] <URL name>

 [-globalinstall]

 [-force]

 [-nodeploy]

stsadm -o addwppack

 -name <Web Part name>

 [-lcid] <language>

 [-url] <URL name>

 [-globalinstall]

 [-force]

Parameters

Parameter Value                                           Required? Description

filename        Any one of the following formats:         Yes       Specifies the path to the cabinet file
                      *.cab                                        that contains the Web Parts and
                      *.wsp                                        associated resources.
                      *.wpp
                For example,
                ―C:\WebParts\SampleWebPart.wpp‖

lcid            A valid locale ID, such as "1033" for     No        Specifies a language for the Web
                English                                             Part package.

url             A valid URL, such as http://server_name   No        Specifies the URL of the virtual
                                                                    server on which to install the Web
                                                                    Parts. To install the Web Parts on
                                                                    every virtual server on a server,
                                                                    omit the urlparameter.

globalinstall   <none>                                    No        Use to install the Web Parts in the
                                                                    global assembly cache (GAC) rather
                                                                    than in the Bin directories of each
                                                                    virtual server. Assemblies installed
                                                                    in the GAC are available to all
                                                                    applications on the server.

force           <none>                                    No        Overwrites an existing Web Part
                                                                    package with a new version. To
                                                                    repair a Web Part package, you must
                                                                    reinstall it.

nodeploy        <none>                                    No        Does not deploy any Web Part
                                                                    package from the Web Part gallery.

name            A name of a Web Part that has already     Yes       Installs the Web Part package from
                been installed on another server in a               the configuration database by using
                server farm configuration                           thename parameter provided the
                                                                    Web Part package has already been
                                                                    installed on another server in a
                                                                    server farm configuration.
Addzoneurl: Stsadm operation (Office SharePoint Server)
Updated: 2007-12-13

Description
Configures the public URL and maps it to one of the five URL zones of a Web application or external
resource.

This property is equivalent to the Public URLs user interface setting that is located on the Edit Public Zone
URLs page of the SharePoint Central Administration Web site.

For more information, see Configure alternate access mapping.

Syntax
stsadm -o addzoneurl

  -url <URL name>

  -urlzone {Default | Internet | Intranet | Extranet | Custom}

  -zonemappedurl <http://public.url>

  -resourcename <non-Web application resource name>

Parameters
 Parameter name     Value                        Required?                       Description

 url                A valid URL, such as         No. However, if                 URL of the Web application.
                    http://server_name or        theurl parameter is used,       This parameter should be an
                    http://server_name:1234      then                            existing alternate access
                                                 theresourcenameparameter        mappings (AAM) URL that is
                                                 cannot be used.                 assigned to a Web
                                                                                 application so that Stsadm
                                                                                 can determine which Web
                                                                                 application you are
                                                                                 targeting. The URL can be a
                                                                                 public URL or an internal
                                                                                 URL from any zone
                                                                                 associated with the targeted
                                                                                 Web application.

 urlzone            Any one of the following     Yes                             One of the five zones with
                    values:                                                      which the public URL is
                           Default                                              associated.
                           Intranet
                           Internet
                           Extranet
                           Custom

 zonemappedurl      A valid URL, such as         Yes                             The public URL that you
                    http://www.contoso.com                                       want to add. It is used as
                                                                                 the base URL used in
                                                                                 hyperlinks on Web pages or
                                                                                 e-mail messages going from
                                                                                 the Web server to the
                                                                                 reverse proxy server or the
                                                                                 client. This URL is the one
                                                                                 that can be reached by the
                                                                                 end user. This step ensures
                                                                                 that the end user sees the
                                                                                 correct URL when the URL is
                                                                                 returned from the server to
                                                                                 the client.

 resourcename       A valid name, such as        No. However, if                 A new resource name with a
                    "Resource1"                  theresourcenameparameter        public URL in its default
                                                 is used, the url parameter      zone needs to be created
                                                 cannot be used.                 using
                                                                                 the addzoneurl operation.
                                                                                 Once the resource name is
                                                                                 created, you can use the
                                                                                 existing resource name to
                                                                                 add public URLs into
                                                                                 additional zones or update
                                                                                 existing public URLs.
                                                                                 This parameter is equivalent
                                                                                 to the External Resource
                                                                                 Mapping user interface
                                                                                 setting that is located on
                                                                                 the Create External
                                                                                 Resource Mapping page of
                                                                                 the SharePoint Central
                                                                                 Administration Web site.
Remarks
In Windows SharePoint Services 2.0, an internal URL was referred to as an incoming URL and a public URL
was referred to as an outgoing URL.

For each Web request, Windows SharePoint Services 3.0 determines the protocol, host header, and port of
the request and looks for a matching internal URL that was previously entered. If a matching internal URL is
found, Windows SharePoint Services 3.0 then determines which zone will be used to format the hyperlinks in
the response. A URL zone contains one public URL and one or more internal URLs.

Alternate access mappings enable a Web application that receives a request for an internal URL, in one of
the five authentication zones, to return pages that contain links to the public URL for the zone. You can
associate a Web application with a collection of mappings between internal and public URLs.

Internal refers to the URL of a Web request as it is received by Microsoft Office SharePoint Server
2007. Public refers to the URL of an externally accessible Web site. The public URL is the base URL that
Office SharePoint Server 2007 uses in the pages that it returns.

If the internal URL has been modified by a reverse proxy device, it can differ from the public URL.

Multiple internal URLs can be associated with a single public URL. Mapping collections can contain up to five
authentication zones, but each zone can have no more than one public URL. Mapping collections correspond
to the following authentication zones:

       Default

       Internet

       Intranet

       Extranet

       Custom

The Default zone must always contain a public URL.

For additional information about zones, URLs, and to view a corporate deployment scenario for each zone,
see the Logical architecture model: Corporate deployment.

Host-named site collections cannot use alternate access mappings. Host-named site collections are
automatically considered to be in the Default zone, and the URL of the request must not be modified
between the end user and the server.
Examples
If a reverse proxy server or load balancer receives a request from the user as https://www.contoso.com and
forwards it to the server running Windows SharePoint Services 3.0 as
http://sharepoint.courses.contoso.com:1234, the administrator would configure the following URLs for a
SharePoint Web application:

Internal URL: http://sharepoint.courses.contoso.com:1234

Public URL: https://www.contoso.com

For this example, http://sharepoint:1234 is already an AAM URL that is assigned to a Web application and
the Internet zone is used.

To set the public URL of an URL zone, use the following syntax:

stsadm -o addzoneurl -url http://sharepoint:1234 -urlzone Internet -zonemappedurl
https://www.contoso.com

To confirm the change to the public URL, use the following syntax:

stsadm -o enumalternatedomains -url http://sharepoint:1234




Allowuserformwebserviceproxy: Stsadm operation (Office
SharePoint Server)
Updated: 2007-09-13

Description
Determines whether a user form template (that is, a non-administrator deployed form template published to
a content type or a document library) can use the proxy. If the Web service proxy is enabled, then by
default it can only be used by an administrator-approved form template.

Syntax
stsadm -o allowuserformwebserviceproxy

 -url <URL name>

 -enable {True | False}

Parameters

Parameter
name             Value                              Required? Description

 url             A valid URL, such as               Yes           The URL of the Web application associated
                 http://server_name                               with the Web service proxy.

 enable          One of the following values:       Yes           Enables or disables the Web proxy. The
                        True (Enable)                            default setting is False.
                        False (Disable)
Checklist for Creating SharePoint Web Parts
Summary: Use this checklist to assist with the deployment and maintenance of Microsoft SharePoint
Products and Technologies Web Parts. (12 printed pages)

Dallas Tester, Microsoft Corporation

Lana Fly, Microsoft Corporation

Susan Harney, Microsoft Corporation

January 2008

Applies to: Windows SharePoint Services 3.0, Microsoft Office SharePoint Server 2007

Contents


       Overview

       Task Checklist for Testing Web Parts

       Verifying Web Part Rendering

       Verifying Web Part Functionality

       Verifying Web Part Properties

       Verifying Web Part Error Handling

       Conclusion

       Additional Resources

Overview
If you install and maintain the Web Parts for your Microsoft Office SharePoint Server 2007 Web site or
Windows SharePoint Services team site, you should help ensure that the Web Parts are secure, coded well,
and can integrate appropriately with other components on the Web Part page.

By understanding the tasks we describe in this article, you can determine whether a Web Part meets these
requirements, and help enhance the success of your Web Part deployment and maintenance.

Note For more information about authoring Web Parts, see Working with ASP.NET 2.0 Web Parts and
Windows SharePoint Services 3.0

Task Checklist for Testing Web Parts
The following checklist contains a series of tasks designed to help you determine the quality of Web Parts
you are asked to deploy or maintain.

For details about how to perform these verifications, click each link in the checklist.

Task Checklist

Task Verification Steps

        Verifying Web Part Rendering

        Verify that Web Part Renders Appropriately Based On User Permissions
          Verify that Static Web Part Renders Appropriately and Does Not Cause Web Part Page to Fail

          Verify that Web Part Appears Appropriately in Search Results

          Verify that Web Part Previews Properly

          Verifying Web Part Functionality

          Verify that Web Part Can Be Added to Web Part Zone

          Verify that Web Part Works Correctly Regardless of Web Part Page Location

          Verify that Web Part Caching Works Correctly

          Verify that Changes Made in Personal View Are Not Reflected in Shared View

          Verify that Web Part Can Handle Asynchronous Calls to Other HTTP Sites and Web Services

          Verify that Web Part Works Correctly With Different Combinations of Zone Settings

          Verify that Web Part Can Access Resources in Different Setup Configurations

          Verify that Web Part Can Be Imported and Exported Correctly

          Verifying Web Part Properties

          Verify that Web Part Property Attributes Are Correctly Defined

          Verify that Web Part Properties Displayed in Tool Pane Are User-Friendly

          Verify that Web Part Properties Are Not Dependent On Each Other

          Verifying Web Part Error Handling

          Verify that Every Public Property Can Handle Incorrect User Input

          Verify that Adding Several Instances of the Same Web Part to a Web Part Page (or to the Same Web
          Part Zone) Works Correctly

          Verify that Web Part Handles All of its Exceptions


Verifying Web Part Rendering
Use the following procedures as guidelines to verify that your Web Parts render correctly in various views.

Verify that Web Part Renders Appropriately Based On User Permissions
Because a Web Part is managed by the user at run time, the Web Part should render with a user interface
(UI) that is appropriate for each user's permissions.

To test
    1.    Test with different user accounts that have only Reader or Contributor rights.

    2.    Make sure that the UI is suppressed if the end user does not have permissions to perform a certain
          action. (For example, if a Web Part displays a Savebutton, it should be disabled or hidden if the
          user does not have permissions to perform that action.)

    3.    Turn on anonymous access for the site and browse a Web Part page that has your Web Part, but
          make sure the sign-in button is still visible on the page. (When the sign-in button is displayed on
          the page, the user has not yet been authenticated.)

Verify that Static Web Part Renders Appropriately and Does Not Cause Web Part Page to Fail
Web Parts that are placed outside of a Web Part zone, which are called static Web Parts, are contained in
.aspx pages but not in a Web Part zone. Because the static Web Part is a Web form control, ASP.NET
renders the Web Part. You cannot save changes to static Web Parts in either shared or personal view.
To test
    1.    Open SharePoint Designer 2007.

    2.    Open a SharePoint site.

    3.    On the File menu, select New, select Page, and choose ASPX in the General category.

    4.    In Design view, on the Insert menu, point to SharePoint Controls, and then click Web Part.

    5.    From the Web Parts toolbox, drag a Web Part onto the page.

    6.    Save the page.

    7.    View the page in the browser.


            Note:

           Make sure that your Web Part is within the <form runat="server"> tags.

    8.    Verify that the part renders correctly (for example, you should not be able to save changes in a
          static Web Part).

Verify that Web Part Appears Appropriately in Search Results
Because Web Parts galleries can contain numerous custom Web Parts, the search capability helps users
quickly find the Web Parts they want.

The Web Part infrastructure uses the Title and Description properties of the Web Part to build the search
result set, so when you add comprehensive information in these fields your Web Parts will be easily
searchable.

To test
    1.    Add the Web part to the Site Web Part Gallery by navigating to Site Settings, click Web
          Parts under the Galleries heading, and then click New on the toolbar.

    2.    Choose the Web Part that you are testing, and then click Populate Gallery.

    3.    Browse to the Web Part page and choose Edit Page from the Site Actions menu.

    4.    Click Add a Web Part in a Web Part zone.

    5.    In the dialog, choose Advanced Web Part gallery and options.

    6.    In the Add a Web Part pane, choose Search in the Web Part chrome drop-down menu.

    7.    Enter the appropriate search text and click Go. The Web Part should appear as one of the top
          choices.

Verify that Web Part Previews Properly
It is important to create previews for Web Parts so that administrators are able to review the parts included
in the Web Part gallery.

To test
    1.    Go to Site Settings, click Web Parts under the Galleries heading, and click the Web Part in the
          list.

    2.    Verify that there are no script errors.
    3.    Verify that the preview appears correctly.

Verifying Web Part Functionality
Use the following procedures to verify that your Web Part functions properly in typical situations.

Verify that Web Part Can Be Added to Web Part Zone
Adding a Web Part to a Web Part zone is the most common user task. Therefore, it is essential that the Web
Part works correctly to create a good user experience.

To test
    1.    Create a new Web Part page.

    2.    Click Site Actions, click Edit Page.

    3.    In the zone where you want the Web Part to appear, click Add a Web Part.

    4.    In the dialog, choose Advanced Web Part gallery and options.

    5.    In the Add a Web Part pane, choose Import in the Web Part chrome drop-down menu.

    6.    Import the .dwp file for your Web Part.

    7.    Add the Web Part to a Web Part zone.

Verify that Web Part Works Correctly Regardless of Web Part Page Location
You can add Web Parts to Web Part pages that are contained in a document library as well as Web Part
pages that are contained in the top-level Web site. They should work correctly in either location.

To test
    1.    Create a Web Part page in a document library.

    2.    Browse to the portal site.

    3.    On the Site Actions menu, click Create.

    4.    On the Create page, click Web Part Page.

    5.    In the New Web Part Page creation form, Save Location lists the document libraries in which the
          Web Part can be saved. Select a document library, type a Name for the page, and then
          click Create.

    6.    Import your Web Part from the gallery.

    7.    Next, create a Web Part page in the top-level Web site.

    8.    Open a SharePoint site in SharePoint Designer 2007.

    9.    On the File menu, select New, select Page, and choose ASPX in the General category.

    10. In Design view, on the Insert menu, point to SharePoint Controls, and click Web Part.

    11. From the Web Parts toolbox, drag a Web Part onto the page.

    12. Save the ASPX file in the top-level Web site, for example, at the same location where the
        default.aspx is located.
Verify that Web Part Caching Works Correctly
For any operation that works with a large amount of data, use a Web Part cache to store property values
and to expedite data retrieval.

Web Part authors can choose to cache data in several ways, but ultimately the farm administrator decides
the type of caching that a Web Part uses.

Following are three available cache settings:


         CacheObject — uses the ASP.NET Cache object (the default).

         Database — uses the content database (and requires all objects to be serialized).

         None — disables caching.

To test your Web Part caching, set the type of cache using the value of the WebPartCache element in the
web.config file.

To test
    1.    In the web.config file, change the <WebPartCache Storage="CacheObject"> statement to
          <WebPartCache Storage="Database"> and make sure that the Web Part still works correctly.

    2.    Next, change the same statement to <WebPartCache Storage="None"> and then make sure that
          the Web Part still works correctly.


            Note:

           By default, exceptions related to caching are not displayed by the Web Part infrastructure. For
           debugging purposes only, you can make the following changes (steps 3 and 4 below) to your
           web.config file.

    3.    In the <system.web> tag, locate the <customErrors mode="On"> tag and change it to
          <customErrors mode="Off"> to see the ASP.NET exception when an error occurs instead of being
          redirected to the error page.

    4.    In the <SharePoint> tag, locate the <SafeMode MaxControls="50" CallStack="false"/> tag and
          change it to <SafeMode MaxControls="50" CallStack="true"/>. This causes ASP.NET error
          messages to display with stack trace information.

Verify that Changes Made in Personal View Are Not Reflected in Shared View
Changes that are made in shared view are seen by all users. Changes that are made in personal view should
be seen only by the person who made them.

To test
    1.    Add the Web Part in shared view.

    2.    Edit the properties in shared view.

    3.    Change to personal view.

    4.    Edit the property in personal view.

    5.    Change back to shared view, and then make sure that the Web Part does not display any of the
          values that were changed in personal view.
Verify that Web Part Can Handle Asynchronous Calls to Other HTTP Sites and Web Services
For performance reasons, you should use asynchronous threads for any operation that works with a large
amount of data.

To test
    1.    Confirm that any calls to Web services or other HTTP sites are asynchronous.

    2.    Test your Web Part on the page to be sure that it handles asynchronous calls as you expect.

Verify that Web Part Works Correctly With Different Combinations of Zone Settings
Web Part zones have properties that control whether a user can save changes. If a user attempts to save
changes to a Web Part without the correct permissions, a broken page can result.

The following Web Part zone properties affect Web Parts in the zone:


         AllowCustomization—If false, and a user is viewing the page in shared view, the Web Part cannot
          save any changes to the database.

         AllowPersonalization—If false, and a user is viewing the page in personal view, the Web Part
          cannot persist any changes to the database.

         LockLayout—If true, changes to
          the AllowRemove, AllowZoneChange, Height, IsIncluded, IsVisible, PartOrder, Width,
          and ZoneID properties are not persisted to the database regardless of view.

To test
    1.    Create a page in the browser, and then add your Web Part into several zones, both in shared and
          personal views.

    2.    Open SharePoint Designer 2007.

    3.    Open a Web Part page on a SharePoint site and, in Design view, double-click a Web Part zone (or
          right-click over a Web Part zone, and then, on the shortcut menu, click Web Part Zone
          Properties), and then change the zone properties. Alternatively, you can switch to Code view and
          type in the attributes for the Web Part zone control.

    4.    View the page in the browser.

    5.    Verify that the part does not break the page and that the Web part functions correctly.

    6.    Verify that any UI displayed in the Web Part indicates to the user that changes cannot be persisted
          or that that the UI is disabled as appropriate for the zone settings.

Verify that Web Part Can Access Resources in Different Setup Configurations
Web Part resources cannot be part of the DLL because they must be URL-accessible. Examples of these
resources are images, .js files, or .aspx pages.


  Note:

 Because a Web Part assembly can be installed in either the bin directory
 (%SystemDrive%\Inetpub\wwwroot\wss\VirtualDirectories\%port%\bin), or the global
 assembly cache, you must go through each of these steps with the Web Part installed in the bin and again
 with the Web Part installed in the global assembly cache.

Add the Web Part to your page in all the following scenarios and make sure that it can correctly access its
resources.
To test
    1.    Add the Web Part to the top-level Web site.

    2.    Add the Web Part to a subsite with unique permissions, in which only a user has rights in the
          subsite.

    3.    Add the Web Part to a Web Part page inside a folder in a document library.

    4.    Add a Web Part to a site with Self-Service Site Creation enabled on the Web application.

    5.    Add a Web Part to a site with Host Header mode enabled.

    6.    Add the Web Part to a site where the top-level Web site is not a SharePoint site, for
          example, http://servername/customURL.

    7.    Add to the Web Part to Web Part pages that are in different subsite languages.

Verify that Web Part Can Be Imported and Exported Correctly
By default, whenever you export a Web Part, each Web Part property is included in the .dwp file. However,
because properties can contain sensitive information, for example, a date of birth, you can identify a
property as controlled, allowing you or the user to exclude the value if the Web Part is exported. But you
can only exercise control of properties that are exported when the user is in personal view; in shared view,
all property values are exported.

To test
    1.    Add a Web Part from the gallery into a Web Part page and set the properties of the Web Part.

    2.    On the Web Part chrome drop-down menu, click Export to export the Web Part. Save the .dwp file
          that is generated onto your local computer.

    3.    Re-import the Web Part by choosing Edit Page from the Site Actions drop-down menu, and then
          click Add a Web Part.

    4.    Choose Advanced Web Part gallery and options, and then select Import in the Web Part
          chrome drop-down menu.

    5.    Browse to the .dwp file, click Upload, and then click Import.

    6.    Make sure that the properties that were exported have been correctly imported.

    7.    Verify that any property that would not make sense to export (for example, a Social Security
          number) has the ExportControlledProperties attribute set correctly. (The Allow Export
          Sensitive Properties check box in the tool pane should be cleared.)

Verifying Web Part Properties
Use the following procedures to verify that your Web Part properties function properly.

Verify that Web Part Property Attributes Are Correctly Defined
You can specify Web Part properties in two ways: as an XML BLOB contained within the Web Part or as an
attribute within the Web Part.

Because of the way that the Web Part infrastructure handles property values, we recommend that you
define properties as simple types rather than as complex types so that they work properly if they are
specified as attributes of the Web Part.
To test
    1.    Crate a static Web Part in SharePoint Designer 2007 and, in Design view, right-click the Web Part,
          select Web Part Properties, and try setting every property the Web Part has as an attribute.

    2.    Browse to the page and see if the page fails or if the property setting was ignored.

Verify that Web Part Properties Displayed in Tool Pane Are User-Friendly
Because the tool pane is where users modify Web Part properties, it is important that users can work with
Web Part properties easily in the tool pane.

To test
    1.    Add the Web Part to a Web Part page. Click the Edit drop-down menu on your Web Part and then
          click Modify Shared Web Part. The tool pane should appear and display the Web Part properties.

    2.    Verify that the Friendly Name is easy to understand, for example, a property
          named MyText should be My Text (notice the space between the two words).

    3.    Make sure the Description (the ToolTip that appears) helps the user understand how and why to
          set the property.

    4.    Verify that the Category name makes sense. (Miscellaneous is used when no category is specified
          for the property, but it is not especially helpful to the user.)

    5.    Verify that the order of the properties is logical.

    6.    If appropriate, check that these properties are localized using the following method:

              a.   After installing the SharePoint language packs, create a new subsite and select a different
                   language.

              b.   Add the Web Part to a Web Part page in the new subsite and verify that Friendly Name,
                   Description, and Category are localized in the tool pane.

Verify that Web Part Properties Are Not Dependent On Each Other
Because you cannot guarantee the order that properties are set in the tool pane, you should avoid writing
Web Part properties that are dependent on each other and that both appear in the tool pane.

To test
    1.    Test different values for properties in the tool pane, such as switching a value between true and
          false.


            Note:

           If a property is not visible in the UI, or is disabled, you can open the Web Part page in SharePoint
           Designer 2007, switch to Code view, and then set the properties by editing the XML. Export the
           Web Part, save the .dwp file, and then modify the .dwp file.

    2.    Import the .dwp file back into the Web Page and check the property values.

Verifying Web Part Error Handling
Use the following procedures to verify that your Web Parts handle errors and incorrect user input.

Verify that Every Public Property Can Handle Incorrect User Input
As for any ASP.NET control or application, you should validate all user input before performing operations
with it. This validation can help to protect against not only accidental misuse, but also deliberate attacks
such as SQL injection, cross-site scripting, buffer overflow, and so on.
To test
    1.    Verify that the Web Part can detect invalid input for properties and that it informs the end user
          when incorrect data is entered.

    2.    Verify that the property is not used outside of its intended purpose. For example, if a Web Part is
          intended to allow users to link URLs, limit the protocol usage to HTTP instead of allowing any
          protocol to be saved (for example: ftp://).

    3.    Verify that the Web Part HTML encodes the property value when rendering user input to the client.

    4.    Check all the ways in which property values can be changed, including:

                 Modifying the .dwp file in a text editor.

                 Modifying properties in a tool pane.

                 Modifying properties in Code view in SharePoint Designer 2007.

                 Using the Web Part Page Services Component (WPSC), which is a client-side object model
                  that provides a way to set properties and save them in the client browser.

Verify that Adding Several Instances of the Same Web Part to a Web Part Page (or to the Same
Web Part Zone) Works Correctly
When you want multiple Web Parts to share client-side script, you should place the script in an external file
and register the script for the page, to improve Web Part page performance and to simplify maintenance.

To test
    1.    Add several instances of the Web Part to the same Web Part page. Be sure to execute any client-
          side script that is specific to the Web Part.

    2.    Add several instances of the Web Part to the same Web Part zone. Be sure to execute any client-
          side script that is specific to the Web Part.

Verify that Web Part Handles All of its Exceptions
A Web Part should handle all exceptions rather than risk the possibility of causing the Web Part page to stop
responding.

To test
    1.    Enter error and boundary cases for Web Part properties.

    2.    Verify that the Web Part handles all of its exceptions and does not break the page.

Conclusion
Web Parts are key elements of Microsoft SharePoint Products and Technologies. By using the guidelines
described in this article, you can help ensure that the Web Parts you are responsible for are secure, well-
coded, and integrate well with other components on the page.

								
To top