Friday 26 June 2015

Creating SharePoint 2010 Site Definitions in Visual Studio 2010

Overview
In Microsoft SharePoint 2010, you can create new sites from site definitions by clicking New Site on the Site Actions menu. You can create new site definitions in Microsoft Visual Studio 2010 and then deploy them to SharePoint 2010. This SharePoint Visual How To demonstrates how to create a new site definition and then add a Web Part to the site's default.aspx page. The Web Part filters tasks based on their due dates.
Code It
This Visual How To describes the following steps for creating and deploying a site definition in Visual Studio 2010:
  1. Creating a SharePoint 2010 site definition application in Visual Studio 2010.
  2. Editing the onet.xml file to include a list.
  3. Adding a Web Part to the Site Definition project.
  4. Adding the Web Part to the default.aspx page.
  5. Creating a new site based on the site definition.

To create a SharePoint 2010 Site Definition project in Visual Studio 2010

  1. Start Visual Studio 2010. On the File menu, click New, and then click Project.
  2. In the New Project dialog box, in the Installed Templates section, expand either Visual Basic or Visual C#, expand SharePoint, and then click 2010.
  3. In the template list, click Site Definition.
  4. In the Name box at the bottom, type FilteredTaskSite.
  5. Leave the default values in the other fields, and click OK.
  6. Under What local site do you want to use for debugging?, select your site. Click Finish.

To modify the onet.xml file

  1. In Solution Explorer, under the SiteDefinition node, open the onet.xml file.
  2. Add the following markup between the <NavBars> </NavBars> tags.
    <NavBar Name="$Resources:core,category_Lists;" 
    Prefix="&lt;table border='0' cellpadding='4' cellspacing='0'&gt;" 
    Body="&lt;tr&gt;&lt;td&gt;&lt;table border='0' cellpadding='0' cellspacing='0'
    &gt;&lt;tr&gt;&lt;td&gt;&lt;img src='/_layouts/images/blank.gif' id='100' alt='' border='0'
    &gt;&amp;nbsp;&lt;/td&gt;&lt;td valign='top'&gt;&lt;a id='onetleftnavbar#LABEL_ID#' href='#URL#'
    &gt;#LABEL#&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/td&gt;&lt;/tr&gt;" Suffix="&lt;/table
    &gt;" ID="1003" />
    
  3. Replace the <Lists/> tag with the following code:
    <Lists>
    <List FeatureId="00BFEA71-A83E-497E-9BA0-7A5C597D0107" Type="107" 
    Title="Project Tasks" 
    Url="$Resources:core,lists_Folder;/$Resources:core,tasks_Folder;" 
    QuickLaunchUrl="$Resources:core,lists_Folder;/$Resources:core,tasks_Folder;/AllItems.aspx" />
    </Lists>
    

To create a Visual Web Part in Visual Studio

  1. In Solution Explorer, right-click the project, point to Add, and then click New Item.
  2. In the list of items, click Visual Web Part.
  3. Ensure that the Web Part is named VisualWebPart1, and then click Add.
  4. Open VisualWebPart1UserControl.ascx, right-click the design surface, and then click View Code.
  5. Replace the code with the following.
    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint.Utilities;
    
    
    namespace FilteredTaskSite.VisualWebPart1
    {
        public partial class VisualWebPart1UserControl : UserControl
        {
            DateTimeControl filterDate;
            ListViewByQuery MyCustomView;
            SPQuery query;
            protected void Page_Load(object sender, EventArgs e)
            {
    
                filterDate = new DateTimeControl();
                filterDate.DateOnly = true;
                filterDate.AutoPostBack = true;
                filterDate.DateChanged += new EventHandler(filterDate_DateChanged);
                SPWeb thisWeb = SPContext.Current.Web;
                MyCustomView = new ListViewByQuery();
                MyCustomView.List = thisWeb.Lists["Project Tasks"];
                query = new SPQuery(MyCustomView.List.DefaultView);
                query.ViewFields = 
                  "<FieldRef Name='Title' /><FieldRef Name='AssignedTo' /><FieldRef Name='DueDate' />";
                MyCustomView.Query = query;
                LiteralControl filterMessage = new LiteralControl("Tasks due on or before:");
                this.Controls.Add(filterMessage);
                this.Controls.Add(new LiteralControl("<br />"));
                this.Controls.Add(filterDate);
                this.Controls.Add(new LiteralControl("<br />"));
                this.Controls.Add(MyCustomView);            
            }
            
            void filterDate_DateChanged(object sender, EventArgs e)
            {
    
                string camlQuery = "<Where><Leq><FieldRef Name='DueDate' />"
                  + "<Value Type='DateTime'>"
                  + SPUtility.CreateISO8601DateTimeFromSystemDateTime(filterDate.SelectedDate)
                  + "</Value></Leq></Where>";
                query.Query = camlQuery;
                MyCustomView.Query = query;
            }
        }
    }
    

To add the Visual Web Part to the default.aspx page

  1. In Solution Explorer, expand the SiteDefinition node, and then open default.aspx.
  2. At the top of the page, under the WebPartPages tag, add the following code.
    <%@ Register  TagPrefix="MyWebPartControls" Namespace="FilteredTaskSite.VisualWebPart1" 
      Assembly="$SharePoint.Project.AssemblyFullName$" %>
    
  3. Locate the <asp:content> tag that contains ContentPlaceholderId = "PlaceHolderMain", and replace the tag with the following.
    <asp:Content ID="Content1" ContentPlaceHolderId="PlaceHolderMain" runat="server">
    <MyWebPartControls:VisualWebPart1 runat="Server" />
    </asp:Content>
    

To deploy and test the project

  1. In Solution Explorer, right-click the project, and then select Deploy.
  2. Open the SharePoint Home page.
  3. Above the ribbon, click Site Actions, and on the menu, click New Site.
  4. In the list of templates, select FilteredTaskSite, and using the form on the right side, create a new site.
The new site appears with the Project Tasks list on the Quick Launch menu and the new Web Part on the default page. Add a few tasks with different due dates, and then use the Web Part on the home page to filter items that have a due date on or before the selected date.
Read It
The onet.xml file contains information about a new site definition. This example demonstrated the following tasks:
  • Creating a task list named Project Tasks and adding it to the Quick Launch navigation bar.
  • Adding a Web Part to the project that filters tasks based on their due dates.
  • Editing the default.aspx page so that it includes the new Web Part.
  • Deploying and testing the site definition.

ONET.XML

ONET.XML defines the project and list defaults, as well as the base types for fields. It contains a definition of list templates available for creating new lists, the default items on the top link bar of a project, the document templates available, and the required base fields for all list types (defined in the BaseTypes section). During provisioning, or when a new list is created, the definitions in this file combine with those in a given list's SCHEMA.XML file in order to create the list's schema in the database. ONET.XML is located in the Program Files\Common Files\Microsoft Shared\web server extensions\50\Templates\1033\xml directory.
This file can be modified to change the list defaults, add more list templates, and add more default fields for a given list base type.
The most frequent changes you will probably need to make involve four top-level elements in ONET.XML, as follows:
TopMenuItems — Allows customization of the top link bar.
ListTemplates — For making custom lists available on the Create page in a Web site based on SharePoint Team Services from Microsoft.
DocumentTemplates — Allows you to specify document types for the New Document Library page in SharePoint Team Services.
BaseTypes — For customizing the base types of all your lists. Possible settings for base types are the following:
    0 — Basic List
    1 — Document Library
    2 — unused
    3 — Discussion List
    4 — Survey
In the ListTemplates section, the SecurityBits attribute specifies the default security settings for lists, which can be set to allow full editing, read-only, or schema design roles for the members of a team Web site.

When you install Windows SharePoint Services 3.0, six Onet.xml files are placed within the setup directory, one in \Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\GLOBAL\XML that applies globally to the deployment, and five in different folders within ...\TEMPLATE\SiteTemplates that apply to each of the five site definitions that ship with Windows SharePoint Services 3.0. They are Blog sites, the central administration site, Wiki sites, Meeting Workspace sites, and team SharePoint sites. Only the last two of these families contain more than one site definition configuration in Windows SharePoint Services 3.0.
The global Onet.xml file defines list templates for hidden lists, list base types, a default definition configuration, and modules that apply globally to the deployment. The five Onet.xml files in the \SiteTemplates directory define navigational areas, list templates, document templates, configurations, modules, components, and server e-mail footer sections used in the five site definitions.

Functions of Onet.xml

Depending on its particular use, an Onet.xml file can serve multiple functions, such as the following:
  • Define the top and side navigation areas that appear on the home page and in list views for a site definition.
  • Specify the list definitions that are used in each site definition and whether they are available for creating lists on the Create page.
  • Specify document templates that are available in the site definition for creating document library lists on the New page, and specify the files used in the document templates.
  • Define the base list types from which default Windows SharePoint Services lists are derived. (Only the global Onet.xml file serves this function.)
  • Specify the configurations of lists and modules that are used within each site definition.
  • Specify Windows SharePoint Services components.
  • Define the footer section used in server e-mail.

Web Site Definition Tasks with Onet.xml

The following kinds of tasks can be performed in a custom Onet.xml to create a custom site definition:
  • Specify an alternate cascading style sheet (CSS) file, JavaScript file, or ASPX header file for a site definition.
  • Modify navigation areas for the home page and list pages.
  • Add a list definition as an option to the Create page.
  • Add a document template for creating document libraries.
  • Define one or more configurations for the site definition, specifying the lists, modules, files, and Web Parts that are included when a site definition configuration is instantiated.
Caution noteCaution
Making changes to an originally installed Onet.xml file on a server running Windows SharePoint Services can break existing sites, and the changes may be overwritten when you install updates or service packs for Windows SharePoint Services, or when you upgrade an installation to the next product version. Always create a new Onet.xml; do not modify the original file. For more information, see How to: Create a Custom Site Definition and Configuration.

File Format

The following sections define the various elements of the Onet.xml file.

Project Element

The top-level Project element specifies a default name for sites that are created through any of the site configurations in the site definition and specifies the directory that contains subfolders in which the files for each list definition reside.
NoteNote
Unless indicated otherwise, excerpts used in the following examples are taken from the Onet.xml file for the STS site definition.
<Project 
  Title="$Resources:onet_TeamWebSite;" 
  Revision="2"
  ListDir="$Resources:core,lists_Folder;" 
  xmlns:ows="Microsoft SharePoint">
NoteNote
In all the excerpts in this topic, the strings that begin with "$Resources" are constants that are defined in an .resx file. For example, "$Resources:onet_TeamWebSite" is defined in core.resx as "Team Site". When you create a custom Onet.xml file, you can use literal strings.
This element can also have an AlternateCSS attribute that specifies an alternate CSS file for style definitions, a CustomJSUrl attribute specifies an alternate JavaScript file for custom script, and an AlternateHeader attribute specifies an ASPX file for alternate headers.
The Project element does not contain any attribute identifying the site definition that it defines. Each Onet.xml is associated with a site definition by virtue of the directory path in where it resides, which (except for the global Onet.xml) is Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\SiteTemplates\site_type\XML\ , where site_type is the name of the site definition, such as STS or MPS.

NavBars Element

The NavBars element contains definitions for the top navigation area that is displayed on the home page or in list views, and definitions for the side navigation area that is displayed on the home page.
NoteNote
NavBar is not necessarily a toolbar. It can be, for example, a tree of links.
<NavBars>
  <NavBar 
    Name="$Resources:core,category_Top;" 
    Separator="&amp;nbsp;&amp;nbsp;&amp;nbsp;" 
    Body="&lt;a ID='onettopnavbar#LABEL_ID#' href='#URL#' accesskey='J'&gt;#LABEL#&lt;/a&gt;" 
    ID="1002" />
  <NavBar 
    Name="$Resources:core,category_Documents;" 
    Prefix="&lt;table border=0 cellpadding=4 cellspacing=0&gt;" 
    Body="&lt;tr&gt;&lt;td&gt;&lt;table border=0 cellpadding=0 cellspacing=0&gt;&lt;tr&gt;&lt;td&gt;&lt;img src='/_layouts/images/blank.gif' ID='100' alt='' border=0&gt;&amp;nbsp;&lt;/td&gt;&lt;td valign=top&gt;&lt;a ID=onetleftnavbar#LABEL_ID# href='#URL#'&gt;#LABEL#&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/td&gt;&lt;/tr&gt;" 
    Suffix="&lt;/table&gt;" 
    ID="1004" />
    ...
</NavBars>
NavBarLink element defines links for the top or side navigational area, and an entire NavBar section groups new links in the side area. Each NavBar element specifies a display name and a unique ID for the navigation bar, and defines how to display the navigation bar.
For information on customizing the navigation areas on Windows SharePoint Services pages, see Customizing Site Navigation.

ListTemplates Element

The ListTemplates section specifies the list definitions that are part of a site definition.
NoteNote
The ListTemplates section is not included in the Onet.xml file of the standard Windows SharePoint Services site definition, which instead uses list definition Features and element .xml files to define its list templates. The following example is taken from the Onet.xml file for the Meetings Workspace site definition.
<ListTemplates>
  <ListTemplate 
    Name="meetings" 
    DisplayName="$Resources:xml_onet_mwsidmeetingDisp;" 
    Type="200" 
    BaseType="0" 
    Unique="TRUE" 
    Hidden="TRUE" 
    HiddenList="TRUE" 
    DontSaveInTemplate="TRUE" 
    SecurityBits="11" 
    Description="$Resources:xml_onet_mwsidmeetingDesc;" Image="/_layouts/images/itevent.gif">
  </ListTemplate>
  <ListTemplate 
    Name="agenda" 
    DisplayName="$Resources:xml_onet_mwsidagendaDisp;" 
    Type="201" 
    BaseType="0" 
    FolderCreation="FALSE" 
    DisallowContentTypes="TRUE" 
    SecurityBits="11" 
    Description="$Resources:xml_onet_mwsidagendaDesc" 
    Image="/_layouts/images/itagnda.gif">
  </ListTemplate>
    ...
</ListTemplates>
Each ListTemplate element specifies an internal name that identifies the list definition. The ListTemplate element also specifies a display name for the list definition and whether the option to add a link on the Quick Launch bar appears selected by default on the New page. In addition, this element specifies the description of the list definition and the path to the image representing the list definition, which are both displayed on the Create page. If Hidden="TRUE" is specified, the list definition does not appear as an option on the Create page.
The ListTemplate element has two attributes for type, Type and BaseType. The Type attribute specifies a unique identifier for the list definition, while BaseType identifies the base list type for the list definition and corresponds to the Type value specified for one of the base list types defined within the global ONET.XML file (\TEMPLATE\GLOBAL\XML).
For a programming task that shows how to add a list template, see How to: Create a Custom List Definition.

DocumentTemplates Element

The DocumentTemplates section defines the document templates that are listed on the New page.
<DocumentTemplates>
  ...
  <DocumentTemplate 
    Path="STS" 
    DisplayName="$Resources:core,doctemp_Word;" 
    Type="121" 
    Default="TRUE" 
    Description="$Resources:core,doctemp_Word_Desc;">
    <DocumentTemplateFiles>
      <DocumentTemplateFile 
        Name="doctemp\word\wdtmpl.dotx" 
        TargetName="Forms/template.dotx" 
        Default="TRUE" />
    </DocumentTemplateFiles>
  </DocumentTemplate>
  ...
</DocumentTemplates>
Each DocumentTemplate element specifies a display name, a unique identifier, and a description for the document template. If Default is set to TRUE, the template is the default template selected for document libraries that are created in sites created with a configuration in the site definition that the Onet.xml is specifying. Despite its singular name, a DocumentTemplate element actually can contain a collection of DocumentTemplateFile elements. The Name attribute of each DocumentTemplateFile element specifies the relative path to a local file that serves as the template. The TargetName attribute specifies the destination URL of the template file when a document library is created. TheDefault attribute specifies whether the file is the default template file.
For a programming task involving document templates, see How to: Add a Document Template, File Type, and Editing Application to a Site Definition.

BaseTypes Element

The BaseTypes element of the global Onet.xml file is used during site or list creation to define the five list types on which all list definitions in Windows SharePoint Services are based. Each list template that is specified in the list templates section is identified with one of the base types: Generic ListDocument LibraryDiscussion ForumVote or Survey, or Issues List.
NoteNote
In Windows SharePoint Services 3.0 the BaseTypes section is implemented only in the global Onet.xml file (\TEMPLATE\GLOBAL\XML), from which the following example is taken.
<BaseTypes>
  <BaseType 
    Title="Generic List" 
    Image="/_layouts/images/itgen.gif" 
    Type="0">
      <MetaData>
        <Fields>
          <Field 
            ID="{1d22ea11-1e32-424e-89ab-9fedbadb6ce1}" 
            ColName="tp_ID" 
            RowOrdinal="0" 
            ReadOnly="TRUE" 
            Type="Counter" 
            Name="ID" 
            PrimaryKey="TRUE" 
            DisplayName="$Resources:core,ID" 
            SourceID="http://schemas.microsoft.com/sharepoint/v3" 
            StaticName="ID">
          </Field>
          <Field 
            ID="{03e45e84-1992-4d42-9116-26f756012634}" 
            RowOrdinal="0" 
            Type="ContentTypeId" 
            Sealed="TRUE" 
            ReadOnly="TRUE" 
            Hidden="TRUE" 
            DisplayName="$Resources:core,Content_Type_ID;"
            Name="ContentTypeId" 
            DisplaceOnUpgrade="TRUE"
            SourceID="http://schemas.microsoft.com/sharepoint/v3" 
            StaticName="ContentTypeId" 
            ColName="tp_ContentTypeId">
          </Field>
          ...
      </Fields>
    </MetaData>
  </BaseType>
  ...
</BaseTypes>
Each BaseType element specifies the fields used in lists that are derived from the base type. The Type attribute of each Field Element (List - Definition) element identifies the field with a field type that is defined in FldTypes.xml.
Caution noteCaution
Do not modify the contents of the global Onet.xml file (file (\TEMPLATE\GLOBAL\XML), because doing so can break the installation. Base list types cannot be added. For information on how to add a list definition, see How to: Create a Custom List Definition.

Configurations Element

Each Configuration element in the Configurations section specifies the lists and modules that are created by default when the site definition configuration is instantiated.
<Configurations>
  ...
  <Configuration 
    ID="0" 
    Name="Default">
    <Lists>
      <List 
        FeatureId="00BFEA71-E717-4E80-AA17-D0C71B360101" 
        Type="101" 
        Title="$Resources:core,shareddocuments_Title;" 
        Url="$Resources:core,shareddocuments_Folder;" 
QuickLaunchUrl="$Resources:core,shareddocuments_Folder;/Forms/AllItems.aspx" />
      ...
    </Lists>
    <Modules>
      <Module 
        Name="Default" />
    </Modules>
    <SiteFeatures>
      <Feature 
        ID="00BFEA71-1C5E-4A24-B310-BA51C3EB7A57" />
      <Feature 
        ID="FDE5D850-671E-4143-950A-87B473922DC7" />
    </SiteFeatures>
    <WebFeatures>
      <Feature 
        ID="00BFEA71-4EA5-48D4-A4AD-7EA5C011ABE5" />
      <Feature 
        ID="F41CC668-37E5-4743-B4A8-74D1DB3FD8A4" />
    </WebFeatures>
  </Configuration>
  ...
</Configurations>
The ID attribute identifies the configuration (uniquely relative to the other configurations in the site definition) and corresponds to the ID attribute of a Configuration element in WebTemp.xml.
Each List element specifies the title of the list definition and the URL for where to create the list. The QuickLaunchUrl attribute can be used to set the URL of the view page to use when adding a link in the Quick Launch to a list created from the list definition. The value of the Type attribute corresponds to the Type attribute of a template in the list templates section. Each Module element specifies the name of a module defined in the modules section.
The SiteFeatures and WebFeatures elements contain references to site collection and site–scoped Features to include in the site definition.
For post-processing capabilities, use an ExecuteUrl element within a Configuration element to specify the URL that is called following instantiation of the site.
For more information on definition configurations, see How to: Use Site Definition Configurations.

Modules Element

The Modules collection specifies the modules to include by default in creating a site collection. Each Module element in turn specifies one or more files to include, often for Web Parts, which are cached in memory on the front-end Web server along with the schema files. You can use the Url attribute of the Module element to provision a folder as part of the site definition.
<Modules>
  <Modules>
    <Module 
      Name="Default" 
      Url="" 
      Path="">
      <File 
        Url="default.aspx" 
        NavBarHome="True">
        <View 
          List="$Resources:core,lists_Folder;
          /$Resources:core,announce_Folder;" 
          BaseViewID="0" 
          WebPartZoneID="Left" />
        <View 
          List="$Resources:core,lists_Folder;
          /$Resources:core,calendar_Folder;" 
          BaseViewID="0" 
          RecurrenceRowset="TRUE" 
          WebPartZoneID="Left" 
          WebPartOrder="2" />
        <AllUsersWebPart 
          WebPartZoneID="Right" 
          WebPartOrder="1"><![CDATA[<WebPart 
            xmlns="http://schemas.microsoft.com/WebPart/v2"
            xmlns:iwp="http://schemas.microsoft.com
            /WebPart/v2/Image">
            <Assembly>Microsoft.SharePoint, Version=12.0.0.0, 
              Culture=neutral, 
              PublicKeyToken=71e9bce111e9429c</Assembly>
            <TypeName>Microsoft.SharePoint.WebPartPages.ImageWebPart
            </TypeName>
            <FrameType>None</FrameType>
            <Title>$Resources:wp_SiteImage;</Title>
            <iwp:ImageLink>/_layouts/images/homepage.gif
            </iwp:ImageLink>
            <iwp:AlternativeText>$Resources:core,sitelogo_wss;
            </iwp:AlternativeText>
            </WebPart>]]>
        </AllUsersWebPart>
        <View 
          List="$Resources:core,lists_Folder;
          /$Resources:core,links_Folder;" 
          BaseViewID="0" 
          WebPartZoneID="Right" 
          WebPartOrder="2" />
          <NavBarPage 
            Name="$Resources:core,nav_Home;" 
            ID="1002" 
            Position="Start" />
          <NavBarPage 
            Name="$Resources:core,nav_Home;" 
            ID="0" 
            Position="Start" />
      </File>
    </Module>
  ...
</Modules>
The Module element specifies a name for the module, which corresponds to a module name that is specified within a configuration in ONET.XML.
The Url attribute of each File element in a module specifies the name of a file to create when a site is created. When the module includes a single file, such as default.aspx,NavBarHome="TRUE" specifies that the file will serve as the destination page for the Home link in navigation bars. The File element for default.aspx also specifies the Web Parts to include on the home page and information about the home page for other pages that link to it.
For more information about using modules in Windows SharePoint Services 3.0, see How to: Provision a File.

Components Element

The Components element specifies components to include in sites created through the definition.
<Components>
  <FileDialogPostProcessor ID="BDEADEE4-C265-11d0-BCED-00A0C90AB50F" />
</Components>

ServerEmailFooter Element

The ServerEmailFooter element specifies the footer section used in email sent from the server.
<ServerEmailFooter>$Resources:ServerEmailFooter;</ServerEmailFooter>

Where are Assemblies in Sandboxed Solutions Deployed?

The assemblies in a sandboxed solution are included in the solution package (.wsp file), and the package is deployed to the site collection's Solutions Gallery. When a sandboxed solution is accessed for the first time, such as when a user navigates to a page that contains a Web Part from a sandboxed solution, any assemblies in the solution are extracted from the package in the gallery and copied to the file system of the server that is handling the sandboxed request. The location is C:\ProgramData\Microsoft\SharePoint\UCCache. The executable of this service is SPUCHostService.exe. The server that handles the sandboxed request is not necessarily the front-end web server that is handling the initial HTTP request: The Microsoft SharePoint Foundation Sandboxed Code Service can be run on back-end application servers in the farm instead. Because the sandboxed user process (SPUCWorkerProcess.exe) cannot copy anything to the file system, the copying is done by the Microsoft SharePoint Foundation Sandboxed Code Service.
The assemblies of a sandboxed solution do not stay in the file cache perpetually. When the user session that accessed the solution ends, the assemblies stay in the cache for only a short time, and they may be reloaded from there if another user session accesses them. Eventually, if they are not accessed, they are removed in accordance with a proprietary algorithm that takes into account how busy the server is and how much time has gone by since the assemblies were last accessed. If the sandboxed solution is used after that time, the assemblies are extracted again and copied to the UCCache.


Tuesday 23 June 2015

Remote Event Receivers in SharePoint 2013

In SharePoint 2010, event receivers handle events that occur on SharePoint lists, sites, and other SharePoint objects by running the code on the SharePoint server (either full-trust or in a sandbox). This type of event receiver still exists in SharePoint 2013. However, SharePoint 2013 also supports remote event receivers in which the code that runs when the event is triggered is hosted by a web service. This means that if you register a remote event receiver, you also need to tell SharePoint which web service to invoke. In Table 1, the code example on the left (SharePoint solutions) implements functionality using an event handler. The example on the right (apps for SharePoint) implements the same functionality using a remote event receiver.

 Remote event receivers are very similar to the regular event receivers we know from earlier versions of SharePoint: they are triggered when a certain event happens, we can specify which code has to run for which event and we can choose between synchronous and asynchronous events.

With remote event handlers this will all be the same. The only difference is that the code that will run when the event occurs will be served by a web service. This means that if we register a remote event receiver we will also tell SharePoint which web service needs to run.

How it works

  1. The user does an action on SharePoint (e.g. edits a list item).
  2. SharePoint talks to ACS  (Access Control Service) and requests a signed token contain information about the current user's context.
  3. SharePoint then talks to the registered web service where we can do whatever we want. We could for example update a backend system as a result of the fired event.
  4. The backend system sends succes or failure back to the web service.
  5. The web service can now also talk to the ACS to request its own signed token to do a call back to SharePoint. So using this token we can do remote actions from within the web service as a result of our earlier operation in the backend system.
If you want to know which events are supported, open up Visual Studio, create a new SharePoint hosted app and add a remote event receiver. In the next screen, as today in Visual Studio 2010, you will see the supported events.

The template code basically has two methods:
  1. ProcessEvent: which allows to do the remote call but also provides code to get a context token to do a callback to SharePoint
  2. ProcessOneWayEvent: used to do a one way call to the web service without a callback to SharePoint
Registering the remote event receiver
If you look in your app you will see that a new elements file has been added:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListTemplateId="3100">
      <Receiver>
        <Name>RemoteEventReceiver1ItemAdding</Name>
        <Type>ItemAdding</Type>
        <SequenceNumber>10000</SequenceNumber>
        <Url>~remoteAppUrl/RemoteEventReceiver1.svc</Url>
      </Receiver>
  </Receivers>
</Elements>

Using this CAML, we can specify which events we want to support and via the 'Url' tag we can tell SharePoint which web service call needs to be made.

App events
You can also make use of events at the app level. Click on the app project and checkout the properties on the bottom right hand side of the screen. You have settings for 'Handle app installed/uninstalled/upgraded'. When you set these to through, new entries will be added to the app manifest to support these events.

Coding
If you check the generated code, the most important is the default paramater for both methods:
RemoteEventProperties properties

As with regular event handlers, this RemoteEventProperties will give you access to all kinds of details about the incoming event.
Table 1. Code examples for event receivers in SharePoint 2010 vs. remote event receivers in apps


SharePoint solutions




C#
// Trigger an event when an item is added to the SharePoint list.
Public class OnPlantUpdated : SPItemEventReceiver
{
Public override void ItemAdding (SPItemEventProperties properties)
{
Properties.After.Properties.ChangedProperties.Add("Image",CreateLink(properties));
Properties.status =SPEventReceiverStatus.Continue;
}

/// When an item updates, run the following.
Public override void ItemUpdating(SPItemEventProperties properties)
{
Properties.AfterProperties.ChangedProperties.Add("Image",CreateLink9properties));
Properties.Status= SPEventReceiverStatus.Continue;
}


Apps for SharePoint


/* Trigger an event when an item is added to the SharePoint list*/
Public class OnPlantUpdated : IRemoteEventService
{
public SPRemoteEventResult ProcessEvent (SPRemoteEventProperties properties)
{
SPRemoteEventResult result =new SPRemoteEventResult();
If (properties.EventType == SPRemoteEventType.ItemAdding ||  
properties.EventType == SPRemoteEventType.ItemUpdating)
{

// Add code that runs when an item is added or updated.
}


How do remote event receivers work?



Figure 1 shows how remote event receivers work:
  • The user performs an action on SharePoint (for example, edits a list item).
  • SharePoint then talks to the registered web service. You could perform some operations—for example, update a list item property, or update a backend system.
  • The web service can also talk to the Access Control Service (ACS) to request its own signed token to do a call back to SharePoint. Using this token, you can perform remote actions from within the web service as a result of the earlier operation on the list item or in the backend system.
Figure 1. How remote event receivers work in SharePoint

How remote event receivers work in SharePoint 2013
Can I run client-side (JavaScript) code from remote event receivers?


No.

Are there any restrictions on where a remote event receiver can be hosted or on its URL?


The remote event receiver can be hosted in the cloud or in an on-premise server that is not also being used as a SharePoint server. The URL of a production receiver cannot specify a particular port. This means that you must use either port 443 for HTTPS, which we recommend, or port 80 for HTTP. If you are using HTTPS and the receiver service is hosted on-premise, but the app is on Microsoft SharePoint Online, then the hosting server must have a publically trusted certificate from a certificate authority. (A self-signed certificate works only if the app is in an on-premise SharePoint farm.)

Will a SharePoint 2010 event handler work on SharePoint 2013 after I upgrade?


If a SharePoint 2010 solution package containing an event handler is upgraded to SharePoint 2013, depending on your customizations, the solution package may work without any modifications. This will include the event handler too. If the SharePoint 2010 solution is remodeled into an app for SharePoint in SharePoint 2013, the event handler should be rewritten as a remote event receiver.