HowTo: Create an STSADM Command Using the SpaDev STSADM Extensions Library

Prerequisites:
  • .NET 3.0
  • Visual Studio 2008
  • Windows SharePoint Services 3.0 or MOSS 2007

NOTE: The completed sample is included in the Source Code download of the latest release. You can follow the instructions in the next section to create the sample from scratch or follow along in the completed source code project.

Create an STSADM Command

  • Step 1: Create a Visual Studio 2008 Class Library Project named SpaDevStsAdmHowTo
  • Step 2: Add a reference to SPaDevToolkit.StsAdm and Microsoft.SharePoint
NOTE: How you add the reference depends on what format you dowloaded the SPaDevToolkit. If you downloaded and installed the Runtime Binary, you can add reference to the GAC dll. If you dowloaded the source code, you can add a reference to the dll after you build the project.
  • Step 3: Create the Command Interpreter Class
    • NOTE: The Command Interpreter Class is the STSADM entry point for all commands you create in your project
1) Add a class to your project. By convention (not required) name the class CommandInterpreter (You will use this class name in the STSADM config file for the commands you create in your project).

2) Add using statements in the newly created "interpreter" class file. The file should resemble the following code;

using SPaDevToolkit.StsAdm;
using Microsoft.SharePoint;

namespace SpaDevStsAdmHowTo
{
    public class CommandInterpreter
    {
    }
}

3) Dervive your "interpreter" class from SPaCommandInterpreter:
public class CommandInterpreter : SPaCommandInterpreter
  • Step 4: Create a command template
    • NOTE: A command template is a class that defines parameters and behaviour for one or more commands. Each command that uses the template will have the same parameters (including attributes such as "IsRequired", "IsFlag" etc.).
1) Create a new class for your template. In this example, we call the template MyCommands.

2) Add using statements in the newly created class file. The file should resemble the following code;

using SPaDevToolkit.StsAdm;
using Microsoft.SharePoint;

namespace SpaDevStsAdmHowTo
{
    public class MyCommands
    {
    }
}

3) Implement the ISPaCommandTemplate interface:

public class MyCommands : ISPaCommandTemplate 

4) Add a default constructor:

public MyCommands()
{
}
  • Step 5: Define parameters for your command template
    • In this examaple we define a url parameter with the following charactersistics
      • Required=true
      • Display Name="SiteURL"
1) Create a read-write property (we name it URL) that represents the url parameter:

        private string _URL;
        /// <summary>
        /// URL parameter
        /// </summary>
        public string URL
        {
            get { return _URL; }
            set { _URL = value; }
        }


2) Decorate the property with the SPaParameterAttribute. This indicates to the interpreter that this is a declared parameter.

        private string _URL;
        [SPExParameter("url", IsRequired=true, DisplayName="Site Url")]
        /// <summary>
        /// URL parameter
        /// </summary>
        public string URL
        {
            get { return _URL; }
            set { _URL = value; }
        }

3) Add parameter-specific validation. In this case, our parameter value must be a valid Url. Therefore, we decorate the parameter property with the SPaUrlValidatorAttribute.
        private string _URL;
        [SPExParameter("url", IsRequired=true, DisplayName="Site Url")]
        [SPaUrlValidatorAttribute]
        /// <summary>
        /// URL parameter
        /// </summary>
        public string URL
        {
            get { return _URL; }
            set { _URL = value; }
        }

  • Step 6: Define your commands
    • You need to specify information about commands that will use your template. A command is the name of the operation that will be registered with STSADM and that you will use on a command line:
stsadm -o commandname


1) To define a command, decorate the command template class (MyCommands) with the SPaCommandAttribute:

[SPaCommand("listsiteinfo", HelpMessage="-url <site Url>")]
public class MyCommands : ISPaCommandTemplate

In this example we specify the name of the command as "listsiteinfo" and the Help message that STSADM will display is "-url <site Url>".
  • Step 7: Implement your command logic
    • You implement command logic by implementing the Run() method of the ISPaCommandTemplate. This method takes two arguments:
      • command - name of the command
      • output - out parameter to which command output will be written
1) Implement the Run() method:

public int Run(string command, out string output)
{
	output = null;
}

For the this sample we will implement only one command. Therefore, the Run() method assumes it is executing the "listsiteinfo" command as indicated on the SPaCommand attribute. The complete Run() method is shown below:
        public int Run(string command, out string output)
        {
            output = null;

            using (SPSite site = new SPSite(_URL))
            {
                StringBuilder sbOutput = new StringBuilder();

                sbOutput.AppendFormat("Property\t\tValue").AppendLine();
                sbOutput.AppendLine("----------------------------------------------------------");
                sbOutput.AppendFormat("HostName\t\t{0}", site.HostName).AppendLine();
                sbOutput.AppendFormat("ID\t\t{0}", site.ID.ToString()).AppendLine();
                sbOutput.AppendFormat("IISAllowsAnonymous\t\t{0}", site.IISAllowsAnonymous).AppendLine();
                sbOutput.AppendFormat("Created\t\t{0}", site.RootWeb.Created.ToShortDateString()).AppendLine();
                sbOutput.AppendFormat("Description\t\t{0}", site.RootWeb.Description).AppendLine();
                sbOutput.AppendFormat("Name\t\t{0}", site.RootWeb.Name).AppendLine();
                sbOutput.AppendFormat("# SiteUsers\t\t{0}", site.RootWeb.SiteUsers.Count).AppendLine();
                sbOutput.AppendFormat("# ContentTypes\t\t{0}", site.RootWeb.ContentTypes.Count).AppendLine();
                sbOutput.AppendFormat("# Groups\t\t{0}", site.RootWeb.Groups.Count).AppendLine();

                output = sbOutput.ToString();

                return 0;
            }
        }


  • Step 8: Sign the assembly
1) Sign the assembly by adding a strong name key file to the project.
  • Step 9: Create the command configuration file
    • This file is used by STSADM to load the assembly and run the command
1) Add an XML file named stsadmcommands.SPaDevStsAdmHowTo.xml to your project. By convention, the format of STSADM config file names is "stsadmcommands" followed by a unique name identifying the commands in the file and seperated by a period.

2) Add the following XML to the file
<?xml version="1.0" encoding="utf-8" ?>
<commands>
	<command name="listsiteinfo"
	  class="SpaDevStsAdmHowTo.CommandInterpreter, SpaDevStsAdmHowTo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=[public token]" />
</commands>
  • For each command we include a <command> element that identifies the name of the command and the class and assembly that implements the command. The format of the "class" attribute is:
<assembly-qualified class name>, <assembly name>, Version=<version number>, Culture=<culture>, PublicKeyToken=<public token>


where <assembly-qualified class name> is the name of the class that implements the ISPStsadmCommand (See http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.stsadmin.ispstsadmcommand.aspx) interface. In the SPaDev framework this interface is implemented by the SPaDevToolkit.SPaCommandInterpreter class. Since the CommandInterpreter class in our sample derives from SPaCommandInterpreter we can specify the CommandInterpreter class as the name of the ISPStsadmCommand interface implementation.
Note that in this manner, the CommandInterpreter (and it's base class) serve as a "boot-strap" for all the commands defined in the same assembly. Therefore, a number of <command> elements may use the same class attribute value but different name attribute values.

3) Build the project

4) Retrieve the public token for the assembly (Use the strong name tool sn.exe or Reflector)

5) Replace <public token> in the XML config file with the public token value from the previous step.
  • Step 10: Deploy and Test the Command
NOTE: This step assumes that SPaDevToolkit has been installed including commands defined in the toolkit.

1) Open a command prompt window

2) CD to the build output directory <projectdirectory>\bin\debug and register the command assembly with STSADM using the spa-regsitercommands operation:
stsadm -o spa-registercommands -file SpaDevStsAdmHowTo.dll -overwrite

This adds the command assembly to the GAC and creates the STSADM command configuration file, stsadmcommands.SPaDevStsAdmHowTo.xml, in the CONFIG directory of the SharePoint installation - C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\CONFIG


4) Test the command
  • stsadm -help listsiteinfo
returns

stsadm -o listsiteinfo
        -url <site Url>
  • stsadm -o listsiteinfo
returns

Required parameter missing: url.
  • stsadm -o listsiteinfo -t
returns

Command line error. Invalid parameter: t.
  • stsadm -o listsiteinfo -url <siteurl>
returns output similar to:

Property                Value
----------------------------------------------------------
HostName                <servername>
ID              	<site guid>
IISAllowsAnonymous      True
Created         	1/30/2007
Description
Name
# SiteUsers             24
# ContentTypes          77
# Groups                10

Last edited Jul 18, 2008 at 12:23 AM by drudolph, version 13

Comments

No comments yet.