Sandboxed solutions are packaged as SharePoint solution package (WSP) files that contain assemblies, other non-compiled components, and an XML manifest file. A site collection administrator, or another user with sufficient permissions, uploads the solution package to a specialized library—the solution gallery—in the root site of the site collection. Every sandboxed solution is executed in a unique application domain. Because the application domain is unique to your solution, SharePoint is able to monitor your solution for performance issues and resource use, and it can terminate your code if it exceeds the boundaries set by the IT team. The application domain runs within an isolated process, using an account with a lower set of permissions than the Web application service account, and is subject to various restrictions on functionality and scope.
The remainder of this topic explains the technical details behind the execution model for sandboxed solutions. It describes in detail what you can and cannot do in the sandbox environment, and it explains how IT professionals can manage, configure, and constrain the execution of sandboxed solutions. It also identifies some of the key execution issues that you should consider when you work with sandboxed solutions.
How Does the Sandbox Execution Model Work?
When your solution runs within the sandbox environment, requests that invoke your code are first directed to the Internet Information Services (IIS) worker process that runs the Web application associated with the request. The request is handled by the Execution Manager, a component that runs in the same application pool as the Web application.
The Execution Manager routes the request to a server that runs the SharePoint User Code Service (SPUCHostService.exe). Depending on your farm configuration, this could be a Web front-end server or it could be a dedicated application server. When the user code service receives a request, it will either start a new sandbox worker process (SPUCWorkerProcess.exe) or route the request to an existing sandbox worker process. More specifically, the execution manager routes the request to a specific sandbox worker process if that process is already hosting an application domain for the solution in question. If no loaded application domain is found, the execution manager will route the request to the sandbox worker process that is under least load. The worker process then creates a new application domain and loads the solution assembly. If the worker process has reached the maximum number of application domains it is configured to host, it unloads an existing application domain before it creates a new one.
After the sandbox worker process loads the solution assembly into an application domain, it executes your code. Because the assembly runs in the context of the sandbox worker process, it has a limited set of permissions to use the SharePoint object model and it is prevented from interacting with any other APIs, services, or resources.
The code access security policies that limit access to the SharePoint object model are described by the configuration file associated with the sandbox worker process. When your sandboxed code makes calls into the permitted subset of the SharePoint API, the sandbox worker process forwards these requests to a proxy process (SPUCWorkerProcessProxy.exe) that executes the SharePoint object model code. A sandbox worker process and a sandbox proxy process always work as a pair.
The following illustration shows the different components of the sandbox execution architecture.
The following are the three key processes that drive the execution of sandboxed solutions:
- User Code Service (SPUCHostService.exe). This is responsible for creating the sandbox worker processes that execute individual sandboxed solutions and for allocating requests to these processes. You must start this service through the SharePoint Central Administration Web site on each server that will host sandboxed solutions.
- Sandbox Worker Process (SPUCWorkerProcess.exe). This is the process in which any custom code in your sandboxed solution executes. When a sandbox worker process receives a request that invokes a particular solution, it loads an application domain for that solution (unless it is already loaded). If the worker process reaches the limit on the number of application domains that it can host, it will unload one of the application domains for another solution and load the application domain required to serve the current request. The sandbox worker process throttles the resources accessed by your solution and destroys processes that take too long to execute. Each sandbox worker process is monitored by the SharePoint environment against the criteria specified by the IT team.
- Sandbox Worker Process Proxy (SPUCWorkerProcessProxy.exe). This provides a full-trust environment that hosts the SharePoint API. This enables sandboxed solutions to make calls into the subset of the SharePoint object model that is accessible to sandboxed solutions. These calls are actually executed in the proxy process.
Note: |
---|
The executable files that drive sandboxed solutions are stored in the folder 14\Usercode on each SharePoint server. |
What Can I Do with Sandboxed Solutions?
When you develop solutions that target the sandbox execution model, you need to understand the constraints that apply to the sandbox environment. This section reviews some common SharePoint development scenarios for their compatibility with the sandbox execution model. The following table shows several common development scenarios together with the execution models that are available to you in each case. This is not an exhaustive list; however, it serves to give you a feel for the types of scenarios that you can implement with a sandboxed solution.
Scenario
|
Sandbox
|
Hybrid
|
Full-Trust
|
---|---|---|---|
Create a Web Part that aggregates data from multiple SharePoint lists within the same site collection. *
| |||
Create a Web Part that aggregates data from multiple SharePoint lists from different site collections within the same SharePoint farm.
| |||
Create a Web Part that aggregates data from multiple SharePoint lists from different site collections from different SharePoint farms.
| |||
Create a Web Part that displays data from an external list.
| |||
Create a Web Part that interacts with a Web service or a Windows Communication Foundation (WCF) service.
| |||
Create a workflow in SharePoint designer.
| |||
Create a sandbox workflow action (a method call).
| |||
Create a full-trust workflow activity.
| |||
Create a workflow in SharePoint designer that uses a full-trust custom coded workflow activity.
| |||
Create a fully coded workflow.
| |||
Deploy a new list definition.
| |||
Deploy a new list definition with list item event receivers.
| |||
Deploy a list definition with list event receivers.
| |||
Deploy a site definition.
| |||
Create a content type.
| |||
Create an external content type.**
| |||
Create a new ribbon element.
| |||
Create a new Site Actions menu item.
| |||
Create an instance of a SharePoint list.
| |||
Programmatically create a SharePoint subsite.
| |||
Bind a content type to the home page of a SharePoint subsite.
| |||
Deploy a new application page.
| |||
Create a timer job.
| |||
Create a service application.
|
*The Visual Web Part supplied with Visual Studio 2010 will not run in the sandbox. You must use the Visual Studio Power Tool in the sandbox.
**External content types are typically created by using the External Content Type Designer in SharePoint Designer 2010. However, they must be deployed using a farm solution or through the Central Administration Web site.
Note: |
---|
The standard Visual Web Part is not supported in the sandbox environment. The reason for this is because Visual Web Parts effectively host an ASCX user control within the Web Part control. The ASCX file is deployed to the _controltemplates virtual directory in the physical file system on each Web front-end server. The sandbox environment does not allow you to deploy physical files to the SharePoint root, so you cannot use a sandboxed solution to deploy a Visual Web Part based on the Visual Studio 2010 Visual Web Part project template. A Visual Studio Power Tool is available that addresses this issue. A Power Tool is a plug in for Visual Studio. The tool will generate and compile code representing the user control (.ascx) as part of the assembly. This avoids the file deployment issue. You can download a Power Tool for Visual Studio 2010 that supports Visual Web Parts in the sandbox from Visual Studio 2010 SharePoint Power Tools on MSDN. |
Code Access Security Restrictions
The execution of sandboxed solutions is governed by a restrictive code access security policy. This limits sandboxed solutions to the use of a specific subset of the Microsoft.SharePoint namespace. The code access security policy also prevents sandboxed solution code from accessing external resources or systems. The directory 14\Usercode contains the Web.config file that specifies the CAS policies that apply to sandboxed solutions as a trust level. For a complete list of the namespaces and classes that are available in the sandbox environment, together with details of the code access security policies that apply to sandboxed solutions, see the following articles in the SharePoint Foundation SDK:
Note: |
---|
If you attempt to use a SharePoint method that is not permitted in the sandbox environment, the method call will throw a MissingMethod exception. This occurs for all methods in the blocked namespacesThe Visual Studio 2010 SharePoint Power Tools has a Sandbox Compilation extension that generates build errors when the sandbox solution project uses types that are not permitted. |
There are various nuances that apply to these API restrictions:
- Within the sandbox, you can use an assembly that includes blocked types and methods, as long as those blocked types and methods are not used within the sandbox environment.
- Any methods that are called from the sandbox must not include any blocked types or methods, even if those blocked types or methods are not actually invoked when the method is called from the sandbox environment.
Permission Restrictions
In addition to code access security policy restrictions, the sandbox worker process uses an account with a limited permission set. Using a low-privileged account further limits the amount of harm that a compromised sandboxed solution can do within the production environment. This further restricts the actions that you can perform from sandboxed code.
Because sandboxed code is executed in a partial trust environment, any assembly that contains code that will be called from the sandbox must include the AllowPartiallyTrustedCallersAttribute.
Retrieving User Identity
Within your sandboxed solutions, you can programmatically retrieve the SPUser object associated with the current request. However, you cannot access the underlying authentication token for the current user. In most cases, this is not a problem, because the restrictions of the sandbox environment generally prevent you from performing operations in which the underlying identity is required, such as impersonating a user in order to access an external system.
Using Event Receivers
You can create event receiver classes within sandboxed solutions for events that fire on list items, lists, and individual sites—in other words, events that fire within the boundaries of a site collection. Specifically, you can only create event receivers that derive from the following classes:
- SPItemEventReceiver
- SPListEventReceiver
- SPWebEventReceiver
You cannot use the object model to register event receivers within sandboxed solutions. For example, you cannot use a feature receiver class to register an event receiver on feature activation. However, you can register event receivers declaratively in your feature elements file. For more information about how to register an event receiver declaratively, see Registering an Event Handler on MSDN.
Note: |
---|
To determine whether your application code is running in the sandbox process, check whether the application domain name contains the text "Sandbox". You can use the following code to accomplish this: if(System.AppDomain.CurrentDomain.FriendlyName.Contains(“Sandbox”)) { // Your code is running in the sandbox. } In the SharePoint Guidance Library, the SharePointEnvironment class contains a static method namedInSandbox that returns true if this condition is met. |
Accessing External Data
Broadly speaking, there are two main approaches that you can use to access external data in SharePoint 2010 solutions:
- Business Data Connectivity Object Model (BDC OM). You can use this to work with external content types and external lists.
- SharePoint Object Model. You can use this, namely the SPList API, to work with external lists.
You can use both the BDC OM and the SPList API to access data from external lists. In fact, the SPList API actually uses the BDC OM to perform CRUD (Create, Read, Update, and Delete) operations on external list data. However, the SPList API is available in the sandbox environment, whereas the BDC OM is not.
The SPList API performs well when the external list contains simple field types and when the built-in BDC formatter is able to "flatten" (serialize) more complex types. However, there are certain scenarios in which the SPList API will not work; for example, it will not work when you need to retrieve custom data types or binary large objects, when a list has bi-directional associations, or when they back-end system uses non-integer identifier fields. For a complete list of these scenarios, see Using the SharePoint List Object Model and the SharePoint Client Object Model with External Lists. In these cases, you must use the BDC OM. The BDC OM is not directly available within the sandbox environment; instead, you need to create a full-trust solution or a hybrid solution that uses a full-trust proxy to access the BDC APIs. For more information about this approach, see Hybrid Approaches.
Note: |
---|
The BDC OM is present in SharePoint Foundation 2010, SharePoint Server 2010, and Office 2010. For more information, see Business Connectivity Services Object Model Reference on MSDN. |
Using Workflows
You can use sandboxed solutions to deploy declarative workflows that were created in SharePoint Designer. These declarative workflows are stored in the content database. Like with any declarative logic, declarative workflows execute with full trust, regardless of whether you define them in a sandboxed solution or a farm solution. However, you cannot deploy coded workflows to the sandbox environment.
As you probably already know, you can define custom-coded workflow activities that run in the full-trust execution environment. You can also create sandboxed code that is invoked by a workflow action.
Note: |
---|
Workflow activities and workflow actions are related concepts. A workflow activity is any class that derives from System.Workflow.ComponentModel.Activity. A workflow action is a SharePoint Designer concept that describes any activity or group of activities that can be composed into a human-readable sentence in the SharePoint workflow engine. A workflow action is represented by an Action element in a feature manifest file or an .actions file, as you will see in the code examples that follow. Technically, you cannot create a workflow activity that runs in the sandbox. However, you can create a sandboxed method that is packaged as a workflow action. In the case of sandboxed workflow logic, the workflow activity is the SharePoint-provided wrapper class that calls your sandboxed code. For the sake of readability and simplicity, this topic refers to sandboxed code that is invoked by a workflow action as asandboxed workflow action. |
To create a sandboxed workflow action, you must create a class with a method that accepts aSPUserCodeWorkflowContext as the first parameter. You can also have additional parameters, which will be defined in the Elements.xml file for the solution. The following example is taken from the workflow reference implementation.
public Hashtable CopyLibraryAction(SPUserCodeWorkflowContext context, string libraryName, string targetSiteUrl) { // This is the logic to copy a library to a target site. }
The action is then defined in the Elements.xml file, which tells SharePoint about the action and the implementing class. It also enables SharePoint Designer to use the activity in a declarative workflow for the site collection.
<Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <WorkflowActions> <Action Name="Copy Library" SandboxedFunction="true" Assembly="..." ClassName="..." FunctionName="CopyLibraryAction" AppliesTo="list" UsesCurrentItem="true" Category="Patterns and Practices Sandbox"> <RuleDesigner Sentence="Copy all items from library %1 to site %2"> <FieldBind Field="libraryName" Text="Library Name" Id="1" DesignerType="TextBox" /> <FieldBind Field="targetSiteUrl" Text="Target Site" Id="2" DesignerType="TextBox" /> </RuleDesigner> <Parameters> <Parameter Name="__Context" Type="Microsoft.SharePoint.WorkflowActions.WorkflowContext, Microsoft.SharePoint.WorkflowActions" Direction="In" DesignerType="Hide" /> <Parameter Name="libraryName" Type="System.String, mscorlib" Direction="In" DesignerType="TextBox" Description="The library to copy" /> <Parameter Name="targetSiteUrl" Type="System.String, mscorlib" Direction="In" DesignerType="TextBox" Description="The URL of the target site" /> </Parameters> </Action> </WorkflowActions> </Elements>
The workflow execution environment calls the method specified in the Action element to launch your sandboxed workflow action.
Suppose that you have deployed a declarative workflow and a sandboxed workflow action to the sandbox environment. SharePoint executes the declarative workflow with full trust, because all the actual run-time code invoked by the workflow is deployed with full trust; therefore, it is considered safe. SharePoint defines asandboxed activity wrapper that executes with full trust and provides a wrapper for all sandboxed actions. The sandbox activity wrapper makes the method call into your sandboxed method. The method defined in the sandboxed solution—CopyLibraryAction in the previous example—actually executes within a sandbox worker process. The following illustration shows this, where the details of the user code service processes have been omitted for brevity.
When you create the declarative workflow, SharePoint Designer hides the relationship between the sandbox activity wrapper and the sandboxed action implementation. SharePoint Designer also enables you to define parameters and field bindings as inputs to the custom sandbox action.
Sandboxed workflow actions offer advantages in many scenarios, particularly because you can deploy these actions as sandboxed solutions without access to the server environment. However, there are limitations on the tasks that a sandboxed workflow action can perform. Declarative workflows can also use certain approved full-trust workflow activities. For information about how to add custom full trust workflow activities that can be consumed by a declarative workflow, see Hybrid Approaches.
How Do I Manage Sandboxed Solutions?
Farm administrators can customize many aspects of how sandboxed solutions are executed, validated, and monitored. As a solution architect or a senior developer, it is important to have an awareness of these features because they can impact how your solutions behave and perform.
Understanding Operational Modes
The IT team can configure the SharePoint farm to execute sandboxed solutions in one of two operational modes. The operational mode determines where the sandbox worker process that executes each sandboxed solution actually resides:
- When the farm is configured in local mode, each sandboxed solution executes on the Web front-end server that receives the request.
- When the farm is configured in remote mode, sandboxed solutions can execute on servers other than the server that receives the request.
When you configure the farm to run sandboxed solutions in remote mode, you can use dedicated application servers to run sandboxed solutions. Alternatively, the server farm can use load balancing to distribute the execution of sandboxed solutions across Web front-end servers. You must start the user code service on each Web front-end server that will run sandboxed solutions.
The following illustration shows the difference between these approaches. When your farm is configured in local mode, sandboxed solution code executes on the Web front-end server that receives the request. The Web front-end server will spin up a new sandbox worker process and load the solution, unless a process already exists for that solution's unique application domain.
When your farm is configured in remote mode with dedicated sandbox servers, the Web front-end server that receives the request will first establish whether any of the sandbox servers are already running a sandbox worker process for the required solution. If this is the case, the Web front-end server will route the request to that sandbox server. This is known as solution affinity. If the process is not running on any of the sandbox servers, the Web front-end server will route the request to the sandbox server currently experiencing least load. This sandbox server will spin up a sandbox worker process and load the solution.
When your farm is configured in remote mode, and the user code service is running on more than one Web front-end server, the Web front-end servers will distribute requests that invoke sandboxed solutions according to server load. If one of the Web front-end servers is already running a sandbox worker process that has loaded the required solution into an application domain, the request is routed to that server. If the solution is not loaded on any of the Web front-end servers, the request is routed to the Web front-end server currently experiencing least load. This server will spin up a new application domain in the sandbox worker process and load the solution.
The IT team should use capacity planning to select the best operational mode for a particular SharePoint environment. In general, it is recommended to use remote mode. However, if you expect a small number of sandboxed solutions, and response latency is a major concern, local mode may be preferable. This is because there is a minor latency cost in cases where the request is received on one server and the sandbox processes run on a different server.
As your server farm grows larger, or the expected number of sandboxed solutions increases, remote mode can become increasingly advantageous. When more than one server runs the user code service, load balancing and solution affinity mean that each server needs to host only a subset of the deployed sandboxed solutions. This is important because every server that runs the user code service can host only a finite number of sandbox worker processes and application domains. When a server hits these limits, what happens when it receives a request for a sandboxed solution that is not already loaded? To serve the request, it must recycle an existing application domain to be able to load the new application domain. This results in requests queuing for a free application domain and increased recycling of application domains. In addition, it becomes increasingly unlikely that there will be an already loaded ("warm") application domain for particular solutions. These factors can substantially impact server performance and response times. Using remote mode to distribute application domains across multiple servers clearly mitigates these issues.
In addition to simply setting the operational mode to local or remote, the IT team can make various configuration changes that will impact on the performance issues described here. For example, farm administrators can configure the number of sandbox worker processes and application domains that can be hosted on each server that runs the user code service. They can also constrain the number of connections allowed per process. Finally, the user code service includes a flag named AlwaysRecycleAppDomains. By default, this is set to false. When it is set to true, the user code service recycles application domains after every request. This reduces the response time of the server as a "warm" application domain is never available, but it can reduce the risk of data crossover in poorly designed sandboxed solutions.
Deploying and Upgrading Solutions
Sandboxed solutions are deployed as SharePoint solution package (WSP) files to the solutions gallery, a specialized library in the root site of each site collection. You can find the solutions gallery at the site relative URL _catalog/solutions. The site collection administrator can activate and deactivate the solutions within the gallery.
If you need to deploy a sandboxed solution to multiple site collections, you must upload it to each site collection gallery separately. Alternatively, you could create a central repository for sandboxed solutions and register a custom solution provider with the solution galleries on each site collection. Site collection administrators can then choose which centrally-available solutions they want to activate on their individual site collection. The custom provider approach essentially allows you to upload and manage a solution in a single location while making it available to multiple site collections.
You can upgrade sandboxed solution packages through the user interface. If you upload a solution package with a new file name but the same solution ID as an existing solution, SharePoint will prompt you to upgrade the existing solution. Alternatively, you can use the Update-SPUserSolution command in Windows PowerShell to upgrade your solutions. However, this requires access to the server environment, which is not necessarily available to sandboxed solution developers or site collection administrators.
For more information about managing sandboxed solutions in the solutions gallery, see Sandboxed Solutions Architecture in the SharePoint Foundation SDK.
Understanding Solution Monitoring
SharePoint 2010 monitors the performance and resource use of your sandboxed solutions through a system ofresource points. Farm administrators can set limits on the number of resource points that a site collection containing sandboxed solutions may consume daily. Because these limits are set on a per-site collection basis, the available resources are effectively shared between every sandboxed solution in the site collection. Site collection administrators can monitor the resource points used by individual solutions from the site collection solution gallery. If the solutions in a site collection exceed the daily resource point allocation for that site collection, SharePoint will take every sandboxed solution in the site collection offline for the rest of the day.
Resource points are calculated according to 14 different measurements known as resource measures, including CPU execution time, memory consumption, and unhandled exceptions. Each resource measure defines a property named Resources per Point. This is the quantity of that particular resource that constitutes an individual resource point. For example, suppose you deploy a solution named Contoso Project Management to the sandbox environment. The following table shows a hypothetical example of the resources it consumes across two sample resource measures.
Resource measure
|
Resources per Point
|
Used by Contoso Project Management solution in one day
|
Points consumed
|
---|---|---|---|
SharePointDatabaseQueryCount
|
20 queries
|
300 queries
|
15
|
SharePointDatabaseQueryTime
|
120 seconds cumulative
|
240 seconds cumulative
|
2
|
SharePoint counts the most expensive resource measure toward the total for the solution, instead of the sum of all measures. In this example, because the number of database queries represents the highest resource point usage, the Contoso Project Management solution consumes 15 resource points from the total allocated to the site collection.
To prevent rogue sandboxed solutions from causing instability SharePoint also monitors individual sandboxed solutions per request. Each of the 14 resource measures includes an AbsoluteLimit property that defines a hard limit of the resources that a sandboxed solution can consume in a single request. If an absolute limit is exceeded, SharePoint terminates the request by stopping and restarting the Sandbox worker process. For example, the CPU execution time resource measure has a default absolute limit of 60 seconds. If a single request takes more than 60 seconds to execute, the user code service will stop and restart the sandbox worker process that is executing the request. Individual solutions will not be disabled for violating an absolute limit, although the utilization will count toward the resource points for the site collection; therefore, they will be expensive.
In addition, the user code service includes a property named WorkerProcessExecutionTimeout with a default value of 30 seconds. If this time limit is exceeded during a single request, the user code service will recycle the application domain in question and the request will return an error. These two settings are measured independently by different parts of the system but they effectively measure the same thing. In general, setting theWorkerProcessExecutionTimeout is preferred over the absolute limit because it will only recycle the application pool instead of the entire process. Exceeding an absolute limit will result in a worker process recycle. When a worker process is recycled, any requests running within the process will fail. In production installations, it is likely that multiple solutions will be running within multiple application domains within one process, so a single rogue solution can disrupt users of more benign solutions. For more information about configuring sandbox environments for resiliency in a production environment, see the Performance and capacity management (SharePoint Server 2010) on TechNet.
Farm administrators can use Windows PowerShell to change the Resources Per Point for a Resource Measure. However, the default measurement weightings were carefully chosen, and understanding the impact of adjustments to these weightings can be complex. You should carefully consider the impact of changing these weightings before you make any modifications.
You can also use Windows PowerShell to investigate how many resource points are being used by specific individual solutions. Resource point consumption depends on the capacity of your server farm and on how you configure measurement weightings, so it is hard to provide an absolute recommendation on where to cap resource point allocations for sandboxed solutions. Instead, you should determine limits by testing against a representative production environment.
For full details of the measurements used to calculate resource points, see Developing, Deploying, and Monitoring Sandboxed Solutions in SharePoint 2010 andPlan sandboxed solutions (SharePoint Server 2010 on MSDN.
On a final note, farm administrators use the Central Administration Web site to block poorly performing or otherwise undesirable sandboxed solutions. This ensures that the solution in question cannot be deployed to any site collection in the farm.
Understanding Solution Validation
In SharePoint 2010, farm administrators can install solution validators to provide additional verification of sandboxed solutions. SharePoint 2010 runs these solution validators when you attempt to activate a sandboxed solution package. Each solution validator can run various validation checks on the solution package and can block activation if your solution fails any of these checks.
By default, SharePoint 2010 includes a single default solution validator that simply sets the Valid property of each solution to true. To create your own custom solution validator, you must create a class that inherits from the SPSolutionValidator abstract class. This class includes two key methods:
- ValidateSolution. This method validates the solution package and its contents. This method has access to the name of the solution package and any files that the package contains.
- ValidateAssembly. This method validates each assembly in the solution package.
Both methods enable you to set an error message, together with an error URL to which the user should be directed if validation fails.
To register a solution validator with the SharePoint farm, you can use a feature receiver to add your class to theSolutionValidators collection in the local SPUserCodeService object.
What Are the Core Issues for Sandboxed Solutions?
Sandboxed solutions introduce a fresh set of challenges for SharePoint developers. When you develop a sandboxed solution, you should pay particular attention to the areas described in the following sections.
Scope and Capabilities
Sandboxed solutions can only interact with resources within the site collection in which they reside. If your application must access data in multiple site collections, you can rule out a sandboxed solution at an early stage in the design process. Similarly, the restricted capabilities of the sandbox environment may prohibit the use of a sandboxed solution.
Security (Authentication)
Sandboxed solutions do not maintain the full identity of the user originating the request, and they cannot impersonate a different user account or provide credentials to authenticate to other systems. The SPUser object is maintained, but the related security tokens are not. With this in mind, you should consider whether a sandboxed solution is capable of accessing the data or resources that your application requires.
In particular, the constraints on authentication prevent you from executing your code with elevated permissions. In farm solutions, developers will often use the SPSecurity.RunWithElevatedPrivileges method to execute a method with full control privileges, even if the user has a lesser set of permissions. However, you should consider carefully whether elevated permissions are really necessary before you reject a sandboxed approach altogether. Although there are scenarios in which you need to elevate permissions, there are also many cases where proper management of user groups and permission sets within the SharePoint site allow your logic to execute from the sandbox environment.
Performance (Throughput)
If a sandbox worker process runs for more than 30 seconds, the user code service will terminate the process. If you need to use long-running processes to deliver your functionality, a sandboxed solution is unlikely to be the best choice. However, in these circumstances, you should probably be using an asynchronous execution mechanism instead. For example, use a timer job, a workflow, or a service application to execute your logic as a background task within a farm solution.
Executing code within the sandbox environment also incurs a small amount of performance overhead. This is only likely to have a noticeable impact in high volume applications, such as in Internet-facing portal environments. In these cases, you may want to consider deploying your code within a farm solution.
Logging
Logging functionality is unavailable within the sandbox environment. Sandboxed solutions cannot write entries to the Windows Event log or the Unified Logging Service (ULS) trace log, nor can they create or retrieve diagnostic areas or categories. This should not come as too much of a surprise—writing to the Windows Event log has always required a relatively permissive code access security policy, and creating diagnostic areas requires access to the Windows registry.
Exposing logging functionality to sandboxed solutions is a good example of a scenario in which you might consider creating a full-trust proxy. For example, the SharePoint Logger component includes a full-trust proxy to enable developers of sandboxed solutions to use the full range of logging features in SharePoint 2010.
Configuration Settings
Your ability to read and write configuration settings is somewhat restricted in the sandbox environment. The following are some examples:
- You cannot read configuration settings from or write configuration settings to the Web.config file.
- You can store and retrieve settings in the SPWeb.AllProperties hash table, but you cannot use property bags at any level of the SharePoint hierarchy.
- You cannot read or write settings to the hierarchical object store, because you do not have access to anSPWebApplication object or an SPFarm object.
- You can read or write settings to a SharePoint list within the same site collection as your sandboxed solution.
Deployment
Sandboxed solutions are deployed and activated to a single site collection. If you need to deploy a solution to multiple site collections, the sandbox approach can be less convenient. You can either manually distribute solution packages to individual site collection administrators, or you could implement a custom centralized solutions gallery to make solutions available to individual site collection administrators.
When you use a sandboxed solution to deploy document templates, you cannot deploy the document templates to the file system. The sandboxed environment does not permit you to deploy any files to the server file system. To solve this issue, use a Module element with a Type attribute value of Ghostable or GhostableInLibrary to deploy your templates. This indicates that the templates are deployed to the content database instead of to the server file system.
Similarly, you cannot deploy JavaScript files or modal dialog Web pages to the server file system. Instead, you might choose to deploy Web pages to the Pages document library and scripts to a subfolder within the Master Page Gallery. By deploying JavaScript files to the Master Page Gallery, you ensure that all users, even anonymous users, have the permissions required to access the file at run time. This approach is especially useful in Internet-facing deployments where anonymous users have read access to the site.
No comments:
Post a Comment