Sunday, September 7, 2008

Extending STSADM Command set

Scenario:
You want to extend STSADM by including a new operation for enumerating all the features for a given site.

Code(GAC):


using System;
using System.Collections.Specialized;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.StsAdmin;

namespace TrainingSamples
{
public class SimpleCommandHandler : ISPStsadmCommand
{
public string GetHelpMessage(string command)
{
return "-url <full url to a site in SharePoint>";
}

public int Run(string command, StringDictionary keyValues, out string output)
{
command = command.ToLowerInvariant();

switch (command)
{
case "enumfeatures":
return this.EnumerateFeatures(keyValues, out output);

default:
throw new InvalidOperationException();
}
}

private int EnumerateFeatures(StringDictionary keyValues, out string output)
{
if (!keyValues.ContainsKey("url"))
{
throw new InvalidOperationException("The url parameter was not specified.");
}

String url = keyValues["url"];

SPFeatureCollection features = null;
SPWeb web = null;

try
{
SPSite site = new SPSite(url);

web = site.OpenWeb();

features = web.Features;
}
catch (Exception e)
{
throw new InvalidOperationException("Error retrieving url '" + url + "'. Please check the format of your url, and ensure that the site exists. Details: " + e.Message);
}

StringBuilder sb = new StringBuilder();

sb.AppendLine("Features at '" + web.Url + "':\n");

foreach (SPFeature feature in features)
{
sb.AppendLine(feature.Definition.DisplayName + " (" + feature.DefinitionId + ")");
}

output = sb.ToString();

return 0;
}
}
}


STSADMCommands.TrainingSamples.xml(12\Config):


<?xml version="1.0" encoding="utf-8" ?>

<commands>
<command
name="enumfeatures"
class="TrainingSamples.SimpleCommandHandler, [full 4-part assembly name]"/>
</commands>



Usage:

stsadm -o enumfeatures -url http://localhost

0 comments: