Activating SharePoint 2010 Sandboxed Solutions by Using Code

Learn how to programmatically activate and deactivate a sandboxed solution in Microsoft SharePoint Server 2010.

Wrox logo

Wrox SharePoint Books

Applies to: Business Connectivity Services | Open XML | SharePoint Designer 2010 | SharePoint Foundation 2010 | SharePoint Online | SharePoint Server 2010 | Visual Studio

Author: Bryan Phillips

Editors: Wrox Tech Editors for SharePoint 2010 Articles

Warning

The Sandbox Solution framework provides a mechanism for executing user-provided code outside of the IIS worker process. The Sandbox Solution framework should not be used as a mechanism for enforcing security boundaries when executing user code. Sandbox Solutions are not supported as a security boundary with user code, especially code of unknown origin. We advise against executing Sandbox Solutions of unknown origins.

Download the code

Introduction to Activating SharePoint 2010 Sandboxed Solutions

The sandboxed solution is a new feature in SharePoint 2010 that enables developers to create SharePoint 2010 functionality that runs in a separate memory space called a "sandbox." The code in the solution runs in the sandbox, and any problems in the code remain isolated and do not cause the SharePoint web application in which it is running to stop responding. In previous versions of SharePoint, developers had to add their assemblies to the global assembly cache (GAC) or to the \bin folder of the SharePoint virtual directory.

Adding assemblies to the global assembly cache introduces risk because all code in the assembly runs fully trusted. Adding assemblies to the \bin folder is safer, but if the IIS worker process that is running the SharePoint web application encounters a problem, it can sometimes stop responding. If the IIS worker process stops responding, the entire SharePoint web application might be inaccessible via browser or over web services. In addition, assemblies that are added to the GAC or to the \bin folder might include code that unintentionally deletes objects on the site, including the site itself.

Sandboxed solutions rely on a Windows service named SharePoint 2010 User Code Host. If this service is not running, SharePoint throws an exception when it deploys a sandboxed solution. Sandboxed solutions also rely on the new solution gallery document library that is present in each site collection. As with any other document library, you can upload sandboxed solutions to the solution gallery. In addition, any site templates that you create by saving a site as a template are stored in the solution gallery.

This article describes how to manage sandboxed solutions by using C# and by using Windows PowerShell. As a developer, you might be more comfortable using C# or Visual Basic, but you should consider using Windows PowerShell, even if you have no experience with it. Windows PowerShell lets you perform many SharePoint commands by using a simple batch file language, and is available on each server on which SharePoint is installed. Windows PowerShell enables you to execute simple scripts to manipulate SharePoint without having to have Visual Studio installed on the server.

Activating a Sandboxed Solution by Using C#

To activate a sandboxed solution by using C#, you must first create a console project in Visual Studio 2010. To create a console project, select File > New > Project from the menu. In the New Project dialog box (Figure 1), select Windows under Visual C# and then select Console Application from the list. Type ActivateSandboxSolution in the Name text box, and then click OK.

Figure 1. New Project dialog box

New Project dialog box

After the project is created, right-click the References folder and select Add Reference. In the Add Reference dialog box, click the .NET tab, select Microsoft.SharePoint from the list, and then click OK. If you do not have a sandboxed solution to deploy, locate the HelloWorldSolution.wsp file in the code download that accompanies this article and add it to the project. Change the value from Copy to Output Directory to Copy Always to specify that the .wsp file is located in the same directory as the compiled executable file. Changing the value ensures that your code does not throw an exception if the .wsp file is not there.

Now you are ready to start coding. Double-click Program.cs in Solution Explorer to open it. Add the following using statements to the file.

using Microsoft.SharePoint;
using System.IO.File;

In the Main method, insert the following code to get a reference to the site collection where you plan to deploy the sandboxed solution. The try catch block traps any errors that occur and outputs them to the console.

try {
    using (SPSite siteCollection = new SPSite("http://local.demo.com")) {
        // More code will go here.
        Console.WriteLine("Done!");
    }
} catch (Exception ex) {
    Console.WriteLine(ex.ToString());
}

In the preceding code example, a new Microsoft.SharePoint.SPSite object is created by passing the URL of the site collection to the constructor of the SPSite class. By using the SPSite object, you can upload a sandboxed solution to the solution gallery and activate its features. To programmatically upload a sandboxed solution, insert the following code in the using block.

SPDocumentLibrary solutionGallery = 
    (SPDocumentLibrary)siteCollection.GetCatalog(
        SPListTemplateType.SolutionCatalog);
SPFile file = solutionGallery.RootFolder.Files.Add(
    "HelloWorldSolution.wsp", File.ReadAllBytes("HelloWorldSolution.wsp"));

The first statement in the code example gets a reference to the solution gallery document library by passing the Microsoft.SharePoint.SPListTemplateType.SolutionCatalog property to the GetCatalog method of the SPSite class. The second statement adds the .wsp file to the root folder of the solution gallery document library. The Add method of the Microsoft.SharePoint.SPFileCollection class takes two parameters: the name of the file and a byte array of the file’s contents. Use the ReadAllBytes method of the File class to read the .wsp file into a byte array. Adding a file returns a Microsoft.SharePoint.SPFile instance that represents the newly uploaded .wsp file, which is needed in the next code example. To activate the sandboxed solution, add the following line of code after the last line in the last code example.

SPUserSolution solution = siteCollection.Solutions.Add(file.Item.ID);

The SPSite class has the Solutions property, which contains the activated sandboxed solutions in the site collection. To activate a sandboxed solution, call the Add method and pass in the list item ID of the .wsp file. Because you stored a reference to the .wsp file in the file variable, you can use its Item property to obtain its Microsoft.SharePoint.SPListItem object and, in turn, use the ID property of the SPListItem class to get the list item ID of the file. After the solution is activated, you must activate the features in the solution.

At this point, the features in the solution appear on the Site Features and Site Collection Features pages, which are accessed through the Site Settings page. The features are not yet activated, so you must add the following code to activate them.

siteCollection.RootWeb.Features.Add(
    new Guid("ae664cd4-2e19-4af2-927e-af5b587bb36d"), false, 
    SPFeatureDefinitionScope.Site);

In the code example, the RootWeb property is accessed to get the Microsoft.SharePoint.SPWeb object that represents the root site of the site collection. The SPWeb class has a Features property that gets a collection of the active site-level features. The SPSite class also has a Features property that gets a collection of the features activated at the site collection level. The Add method takes three parameters: the ID of the feature to activate, a value indicating whether to force the feature to activate even if problems occur, and the Site value of the Microsoft.SharePoint.SPFeatureDefinitionScope enumeration (for this example, the value of this enumeration must always be Site). The only variable should be the ID of the feature. Do not try to force activation of a feature.

To get the ID of the features in a sandboxed solution, rename the extension to .cab. .wsp files are .cab files, a proprietary compression format. By changing the extension to .cab, you can double-click the file to open it. Inside the file, locate all of the feature.xml files. One feature.xml file exists for each feature in the sandboxed solution. Open each feature.xml file, and note the values for the Id and Scope attributes of the Feature element. The following code example shows the contents of the feature.xml file inside the HelloWorldSolution.wsp file.

<Feature xmlns="https://schemas.microsoft.com/sharepoint/" 
    Title="Hello World Action" 
    Description="Adds a &quot;Hello World&quot; item to the Site Actions 
    menu." 
    Id="ae664cd4-2e19-4af2-927e-af5b587bb36d" 
    Scope="Web">
    <ElementManifests>
        <ElementManifest Location="HelloWorldAction\Elements.xml" />
    </ElementManifests>
</Feature>

The ID of the feature is ae664cd4-2e19-4af2-927e-af5b587bb36d, which matches the value that is passed to the Add method of the Microsoft.SharePoint.SPFeatureCollection class from the previous code example. Note the value for the Scope attribute. In sandboxed solutions, the value for Scope can be Web or Site. The value Web means the feature is activated at the site level. The value Site means the feature is activated at the site collection level. The value for Scope determines whether you activate the feature through the siteCollection.Features property or the siteCollection.RootWeb.Features property.

Your code is now complete. Click Debug, and then click Start Debugging to run the project. After the project successfully runs, navigate to the SharePoint site. Click the Site Actions menu; you should see a new Hello World item at the bottom of the menu.

Activating a Sandboxed Solution by Using Windows PowerShell

If you are not a developer or you do not want to use Visual Studio to deploy your sandboxed solutions, you can use Windows PowerShell. Windows PowerShell is a powerful batch environment that you can extend through Windows PowerShell snap-ins. SharePoint, Microsoft Exchange, and Microsoft SQL Server can all be managed through Windows PowerShell. To use Windows PowerShell with SharePoint 2010 select Programs > Microsoft SharePoint 2010 Products > SharePoint 2010 Management Shell from the Start menu.

When the Windows PowerShell console window opens, you can type cmdlets that upload and activate sandboxed solutions exactly as the C# code in the previous code snippets did. Study the commands in Table 1.

Table 1. Windows PowerShell cmdlets for SharePoint Server 2010 Features

Cmdlet

Description

Add-SPUserSolution

Uploads a new sandboxed solution to the solution gallery.

Install-SPUserSolution

Activates a sandboxed solution in a site collection.

Enable-SPFeature

Activates a feature.

Disable-SPFeature

Deactivates a feature.

Update-SPUserSolution

Upgrades an activated sandboxed solution in a farm.

Uninstall-SPUserSolution

Deactivates a sandboxed solution in a site collection.

Remove-SPUserSolution

Removes a sandboxed solution from the solution gallery.

For more information about the commands, see Features and solutions cmdlets (SharePoint Server 2010).

Uploading and Activating a Sandboxed Solution

To upload a sandboxed solution, use the Add-SPUserSolution cmdlet. The cmdlet takes the full path of the .wsp file and the URL of the site collection as parameters.

Add-SPUserSolution -LiteralPath c:\HelloWorldSolution.WSP -Site 
     http://local.demo.com

In this example, the .wsp file is assumed to be at the root of the C: drive and the URL of the site collection is http://local.demo.com. If the cmdlet runs successfully, no output appears in the console window. If the cmdlet does not run successfully, you receive an error message.

To activate a sandboxed solution, use the Install-SPUserSolution command. The Install-SPUserSolution command requires the name of the .wsp file and the URL of the site.

Install-SPUserSolution -Identity HelloWorldSolution.WSP  -Site
     http://local.demo.com

The value for the Identity argument is the name of the .wsp file. The value for Site is the URL of the site collection. If the cmdlet runs successfully, the following output, or something similar, appears.

Name                           SolutionId                           Status
----                           ----------                           ------
HelloWorldSolution.wsp         c49a456d-430e-4c50-9cb5-7d8cccd04747 Activated

Activating and Deactivating a Feature

After the solution is activated, you can activate its features. To determine the IDs of the features, open the .wsp file. After you have the ID of the feature, use the Enable-SPFeature command.

Enable-SPFeature -Identity ae664cd4-2e19-4af2-927e-af5b587bb36d -URL
    http://local.demo.com

The Identity argument can take either the name of the feature or its ID. The URL argument takes the URL of the site or site collection where the feature will be activated. To disable a feature, use the Disable-SPFeature cmdlet and the same arguments as before.

Disable-SPFeature -Identity ae664cd4-2e19-4af2-927e-af5b587bb36d -URL
    http://local.demo.com

Removing a Sandboxed Solution

After the feature is disabled, you can deactivate the sandboxed solution and remove it from the solution gallery. To deactivate a sandboxed solution, use the Uninstall-SPUserSolution cmdlet. As with the Install-SPUserSolution cmdlet, pass arguments for the name of the .wsp and the URL of the site collection where the .wsp is located.

Uninstall-SPUserSolution -Identity HelloWorldSolution.WSP -Site
     http://local.demo.com

Finally, remove the sandboxed solution by using the Remove-SPUserSolution command. The Remove-SPUserSolution command takes the same arguments as the Uninstall-SPUserSolution cmdlet.

Remove-SPUserSolution -Identity HelloWorldSolution.WSP -Site 
    http://local.demo.com

When the cmdlet runs, the sandboxed solution is deleted from the solution gallery.

Conclusion

Sandboxed solutions are a safe way to extend SharePoint in a controlled, regulated manner. By using the tips and techniques from this article, you can control and regulate the way that you manage sandboxed solutions. Doing so is important for any enterprise SharePoint farm in which multiple people or departments deploy solutions to SharePoint. By creating scripts and console applications, you can deploy and remove sandboxed solutions by using a consistent method, and thereby reduce the possibility of deployment errors.

About the Author

Bryan Phillips is a senior partner at Composable Systems, LLC, and a Microsoft Most Valuable Professional in SharePoint Server. He is a co-author of Professional Microsoft Office SharePoint Designer 2007 and Beginning SharePoint Designer 2010 and maintains a SharePoint-related blog. Bryan has worked with Microsoft technologies since 1997 and holds the Microsoft Certified Trainer (MCT), Microsoft Certified Solution Developer (MCSD), Microsoft Certified Database Administrator (MCDBA), and Microsoft Certified Systems Engineer (MCSE) certifications.

The following were tech editors on Microsoft SharePoint 2010 articles from Wrox:

  • Matt Ranlett is a SQL Server MVP who has been a fixture of the Atlanta .NET developer community for many years. A founding member of the Atlanta Dot Net Regular Guys, Matt has formed and leads several area user groups. Despite spending dozens of hours after work on local and national community activities, such as the SharePoint 1, 2, 3! series, organizing three Atlanta Code Camps, working on the INETA board of directors as the vice president of technology, and appearing in several podcasts such as .Net Rocks and the ASP.NET Podcast, Matt recently found the time to get married to a wonderful woman named Kim, whom he helps to raise three monstrous dogs. Matt currently works as a senior consultant with Intellinet and is part of the team committed to helping people succeed by delivering innovative solutions that create business value.

  • Jake Dan Attis. When it comes to patterns, practices, and governance with respect to SharePoint development, look no further than Jake Dan Attis. A transplant to the Atlanta area from Moncton, Canada, Dan has a degree in Applied Mathematics, but is 100% hardcore SharePoint developer. You can usually find Dan attending, speaking at, and organizing community events in the Atlanta area, including code camps, SharePoint Saturday, and the Atlanta SharePoint User Group. When he's not working in Visual Studio, Dan enjoys spending time with his daughter Lily, watching hockey and football, and sampling beers of the world.

  • Kevin Dostalek has over 15 years of experience in the IT industry and over 10 years managing large IT projects and IT personnel. He has led projects for companies of all sizes and has participated in various roles including Developer, Architect, Business Analyst, Technical Lead, Development Manager, Project Manager, Program Manager, and Mentor/Coach. In addition to these roles, Kevin also managed a Solution Delivery department as a Vice President for a mid-sized MS Gold Partner from 2005 through 2008 and later also served as a Vice President of Innovation and Education. In early 2010 Kevin formed Kick Studios as a company providing consulting, development, and training services in the specialized areas of SharePoint and Social Computing. Since then he has also appeared as a speaker at numerous user group, summit, and conference type events across the country. You can find out more about Kevin on his blog, The Kickboard.

  • Larry Riemann has over 17 years of experience architecting and creating business applications for some of the world’s largest companies. Larry is an independent consultant who owns Indigo Integrations and does SharePoint consulting exclusively through SharePoint911. He is an author, writes articles for publication and occasionally speaks at conferences. For the last several years he has been focused on SharePoint, creating and extending functionality where SharePoint leaves off. In addition to working with SharePoint, Larry is an accomplished .Net Architect and has extensive expertise in systems integration, enterprise architecture and high availability solutions. You can find him on his blog.

  • Sundararajan Narasiman is a Technical Architect with Content Management & Portals Group of Cognizant Technology Solutions, Chennai, with more than 10 years of Industry Experience. Sundararajan is primarily into the Architecture & Technology Consulting on SharePoint 2010 Server stack and Mainstream .NET 3.5 developments. He has passion for programming and also has interest for Extreme Programming & TDD.

Additional Resources