Chapter 10. Remote event receivers

New to Microsoft SharePoint 2013, remote event receivers allow you to connect external software and apps to your SharePoint solutions. Through a remote event receiver, you can link to SharePoint any external software that’s capable of providing services based on a specific and predefined SOAP (Simple Object Access Protocol) service contract. You should not, however, consider remote event receivers as alternatives to Business Connectivity Services (BCS). While BCS allows consuming data from external data sources, remote event receivers allow an external system to subscribe to specific events that will occur on the SharePoint side. The external system can be an ERP, a line-of-business (LOB) system, a custom SharePoint app, or a third-party solution. Furthermore, you can implement remote receivers using potentially any programming language, as long as it is capable of providing a SOAP endpoint to receive events. Throughout this chapter, you will investigate remote event receiver architecture, capabilities, security considerations, and implementation details.

Architecture of remote event receivers

The architecture of remote event receivers uses SOAP as the protocol for communicating across the wire, because it is the most open, standard protocol for implementing cross-platform dialogs. On the SharePoint side, the remote event receiver employs a Microsoft Windows Communication Foundation (WCF) proxy for calling the remote endpoint. While working in Microsoft .NET, you can also implement the remote event receiver side of the dialog using WCF. And, as you’ll learn in the “A sample remote event receiver” section, Microsoft Visual Studio 2012 provides an item template and wizard-assisted procedure for this purpose. For now, however, you’ll concentrate on learning about the architecture and capabilities of remote event receivers.

More Info

To understand the architecture of remote event receivers, you should have a good knowledge of WCF and .NET server-side programming. If you aren’t familiar with these topics, take a lap around WCF architecture and service implementation by reading Windows Communication Foundation 4 Step by Step, by John Sharp (Microsoft Press, 2010). You can also have a quick look at the following online article on MSDN: http://msdn.microsoft.com/en-us/library/ms731082.aspx.

The new remote event receivers introduced in SharePoint 2013 are similar to the event receivers that were available in SharePoint 2010. These are still available in SharePoint 2013, but they are provided mainly for backward compatibility, even if an occasional project could still benefit from their implementation. Classic and local event receivers are suitable only in on-premises and sandboxed solutions, while remote event receivers are a better choice for Microsoft Office 365 solutions and SharePoint apps.

More Info

If you need further details about classic event receivers, consult the previous version of this book: Microsoft SharePoint 2010 Developer Reference, by Paolo Pialorsi (Microsoft Press, 2011).

Architecture and contracts

A remote event receiver is just a remote SOAP endpoint that adheres to a specific service contract. In Figure 10-1, you can see the functional schema of remote event receivers in SharePoint 2013.

A diagram that depicts the role of remote event receivers. On the left, an end user interacts with a SharePoint 2013 site or list of content. On the right is a remote system, such as an LOB system. Between them is the remote event receiver, which is a SOAP service that is published by the remote system and invoked by SharePoint 2013 upon user interaction. Windows Azure ACS provides the authentication and authorization details when the SharePoint 2013 environment is on Office 365 or is implemented on-premises via OAuth. Note that ACS is available only in Office 365 or a customized scenario.

Figure 10-1. The functional schema of remote event receivers.

A remote event receiver is registered for handling events related to a list item, a list, a website, an app, a BCS entity, or a security configuration. Whenever an event related to a registered target occurs, the SharePoint 2013 remote event receiver environment raises a remote call to a SOAP endpoint published by a third-party remote system. Any authentication and authorization task is implemented using the Windows Azure ACS for Microsoft Office 365 (or the OAuth protocol in on-premises deployment scenarios). As you will learn in the “Security Infrastructure” section of this book, the OAuth protocol manages only app authentication and authorization, while standard user authentication and authorization are managed by the standard security infrastructure of SharePoint. You can also configure an app that publishes a remote event receiver to run in a so-called high-trust, or server-to-server (S2S), configuration, which was introduced in Chapter 8 and will be explained in detail in Chapter 20

The service contract of the remote event receiver services outlines the service contract of remote event receivers, which is applied regardless of whether the target SharePoint 2013 environment is online or on-premises.

As you can see, the service contract defines just two operations, which correspond to the notification of a synchronous event and an asynchronous one-way event. The ProcessEvent operation handles synchronous events, while ProcessOneWayEvent is for asynchronous processing. Both the operations accept an argument of type SPRemoteEventProperties, which defines all the useful information for implementing the remote event receiver business logic. The definition of type SPRemoteEventProperties, which is the argument provided to the remote event receiver operations shows the definition of the SPRemoteEventProperties type.

The SPRemoteEventProperties class is a data contract serializable type and thereby transferable across the wire within the SOAP request for remote event receivers. Moreover, the type provides properties for transferring all the useful information about the current context, the event that is happening, and the related event outcome, just in case of a synchronous event. Table 10-1 shows a detailed list of the main members of the SPRemoteEventProperties type.

Table 10-1. The main members of the SPRemoteEventProperties type

Member

Description

AppEventProperties

A complex property providing information about the app that is the target of the remote event receiver, in case the remote event receiver is related to a SharePoint app

ContextToken

A property of type String representing the OAuth content token of the current request

CorrelationId

The correlation ID of the current request, presented as a GUID property

CultureLCID

An Integer property providing the LCID of the current culture

EntityInstanceEventProperties

A complex property providing information about a BCS entity that is the target of the remote event receiver, in case the remote event receiver is related to a BCS entity set

ErrorCode

A read-only String property to access an error code

ErrorMessage

A read-only String property to access an error message

EventType

A property of type SPRemoteEventType, which defines the kind of event described by the remote event receiver

ItemEventProperties

A complex property providing information about a SharePoint item that is the target of the remote event receiver, in case the remote event receiver is related to an item

ListEventProperties

A complex property providing information about a SharePoint list that is the target of the remote event receiver, in case the remote event receiver is related to a list

SecurityEventProperties

A complex property providing information about a SharePoint security principal that is the target of the remote event receiver, in case the remote event receiver is related to a security principal

UICultureLCID

An Integer property providing the LCID of the current UI culture

WebEventProperties

A complex property providing information about a SharePoint website that is the target of the remote event receiver, in case the remote event receiver is related to a website

When the operation invoked is the synchronous one, the result is of type SPRemoteEventResult. This type provides information to SharePoint 2013 about the remote event outcome. Table 10-2 lists the main members for the SPRemoteEventResult type.

Table 10-2. The main members of the SPRemoteEventResult type

Member

Description

ChangedItemProperties

A property that allows changing the values of the fields of the target item of a synchronous event. For example, you can use it to change a field of an item when the target item is going to be added or updated.

ErrorMessage

A String property to provide a descriptive error message to SharePoint when the synchronous remote event receiver needs to abort the current operation.

RedirectUrl

A property that provides the String value of the URL to which you want to redirect the target user’s browser as a result of an error raised from the remote event receiver. This property is deprecated, and you should avoid using it, unless you need to support backward compatibility.

Status

An enumerated type (SPRemoteEventServiceStatus) that allows synchronous events to abort the current operation. The available values are CancelNoError, CancelWithError, CancelWithRedirectUrl, and Continue. By default, this property assumes the value of Continue.

The SPRemoteEventResult type is serializable through data contract serialization, as well.

Scopes and types of receivers

SharePoint 2013 supports about 70 different types of events that you can raise. Depending on the type of event and the operation invoked, a remote event receiver can assume different scopes. Events with names ending in -ed are typically asynchronous events and are handled by the ProcessOneWayEvent operation, even if they can be executed synchronously, too. If an -ed event is executed synchronously, the invoked operation will be ProcessEvent. The ProcessEvent operation also handles all the events with names ending in -ing; these are synchronous events as well.

As a handy reference, this section lists all available events, divided by scope. Table 10-3 details events related to single list items.

Table 10-3. Events related to a list item

List item event type

Description

ItemAdding

An item of a list is going to be added.

ItemUpdating

An item of a list is going to be updated.

ItemDeleting

An item of a list is going to be deleted.

ItemCheckingIn

An item of a list is going to be checked in.

ItemCheckingOut

An item of a list is going to be checked out.

ItemUncheckingOut

An item of a list is going to be unchecked out.

ItemAttachmentAdding

An attachment of an item of a list is going to be added.

ItemAttachmentDeleting

An attachment of an item of a list is going to be deleted.

ItemFileMoving

A file of a library is going to be moved.

ItemVersionDeleting

A version of a file of a library is going to be deleted.

ItemAdded

An item of a list has been added.

ItemUpdated

An item of a list has been updated.

ItemDeleted

An item of a list has been deleted.

ItemCheckedIn

An item of a list has been checked in.

ItemCheckedOut

An item of a list has been checked out.

ItemUncheckedOut

An item of a list has been unchecked out.

ItemAttachmentAdded

An attachment of an item of a list has been added.

ItemAttachmentDeleted

An attachment of an item of a list has been deleted.

ItemFileMoved

A file of a library has been moved.

ItemFileConverted

A file of a library has been converted.

ItemVersionDeleted

A version of a file of a library has been deleted.

Table 10-4 illustrates events related to lists.

Table 10-4. Events related to a list

List event type

Description

FieldAdding

A field is going to be added to a list definition.

FieldUpdating

A field of a list definition is going to be updated.

FieldDeleting

A field of a list definition is going to be deleted.

FieldAdded

A field has been added to a list definition.

FieldUpdated

A field of a list definition has been updated.

FieldDeleted

A field of a list definition has been deleted.

ListAdding

A list instance is going to be added.

ListDeleting

A list instance is going to be deleted.

ListAdded

A list instance has been added.

ListDeleted

A list instance has been deleted.

A third family of events corresponds to those defined for actions related to a website. Table 10-5 enumerates these.

Table 10-5. Events related to a website

Web event type

Description

SiteDeleting

A site collection is going to be deleted.

WebDeleting

A website instance is going to be deleted.

WebMoving

A website instance is going to be moved.

WebAdding

A website instance is going to be added.

SiteDeleted

A site collection has been deleted.

WebDeleted

A website instance has been deleted.

WebMoved

A website instance has been moved.

WebProvisioned

A website instance has been provisioned.

Lastly, SharePoint provides events for app management, BCS entities, and security, which are defined in Table 10-6.

Table 10-6. Events related to security, apps, and BCS entities

Others EventType

Description

Others EventType

Description

GroupAdding

A group is going to be added.

GroupUpdating

A group is going to be updated.

GroupDeleting

A group is going to be deleted.

GroupUserAdding

A user is going to be added to a group.

GroupUserDeleting

A user is going to be deleted from a group.

RoleDefinitionAdding

A role definition is going to be added.

RoleDefinitionUpdating

A role definition is going to be updated.

RoleDefinitionDeleting

A role definition is going to be deleted.

RoleAssignmentAdding

A role is going to be assigned to a target principal.

RoleAssignmentDeleting

A role is going to be removed from a target principal.

InheritanceBreaking

Permissions inheritance is going to be broken.

InheritanceResetting

Permissions inheritance is going to be reset.

GroupAdded

A group has been added.

GroupUpdated

A group has been updated.

GroupDeleted

A group has been deleted.

GroupUserAdded

A user has been added to a group.

GroupUserDeleted

A user has been deleted from a group.

RoleDefinitionAdded

A role definition has been added.

RoleDefinitionUpdated

A role definition has been updated.

RoleDefinitionDeleted

A role definition has been deleted.

RoleAssignmentAdded

A role has been assigned to a target principal.

RoleAssignmentDeleted

A role has been removed from a target principal.

InheritanceBroken

Permissions inheritance has been broken.

InheritanceReset

Permissions inheritance has been reset.

AppInstalled

A SharePoint app has been installed.

AppUpgraded

A SharePoint app has been upgraded.

AppUninstalling

A SharePoint app is going to be uninstalled.

EntityInstanceAdded

A BCS entity instance has been added.

EntityInstanceUpdated

A BCS entity instance has been updated.

EntityInstanceDeleted

A BCS entity instance has been deleted.

You can implement and provision remote event receivers within a SharePoint app to implement custom event-handling capabilities that are related to the contents of the app website of an app, and you can also implement and provision them independently from a SharePoint app. While the remote event receivers defined in an app can be accessed both on-premises and on Office 365, remote event receivers that are not part of an app are more suitable for on-premises environments because they require some extra work during deployment.

A sample remote event receiver

Now that you know the various kinds of remote event receivers that are available, you’ll create a simple remote event receiver. Imagine that you have a SharePoint app for managing orders of products. Whenever a new order is inserted in a SharePoint list of orders, you want a SharePoint app to be activated through a remote event receiver to perform an action on a LOB system.

A detailed implementation of the LOB system on the back end of the remote event receiver is out of scope for the current sample. Instead, let’s start with creating a custom SharePoint app that simply intercepts the remote events. For example, you can define an autohosted app targeting an Office 365 environment, following the procedure you learned in Chapter 8. Then you can add a new Order content type, a list definition, and a list instance, which is based on the Order content type.

Important

A remote event receiver works only in cases when the target SharePoint environment is capable of communicating via SOAP over HTTP/HTTPS with the remote event receiver service endpoint. As you learned in Chapter 8, if you are developing a remote event receiver for an on-premises deployment, you cannot create an autohosted app. For an on-premises scenario, your only options are SharePoint-hosted and provider-hosted apps. Moreover, for developing a remote event receiver in a SharePoint-hosted app, you will need to deploy an external website, too, because the SharePoint app website cannot publish the SOAP service endpoint for the remote event receiver. Meanwhile, you can easily invoke and eventually debug a remote event receiver defined in a provider-hosted app. In an on-premises scenario, that provider-hosted app will have to be defined as a high-trust app, unless you do not use Windows Azure ACS.

On the contrary, if you plan to deploy and debug an app for Office 365, you can choose between an autohosted and a provider-hosted model. Nevertheless, by default you will not be able to debug it on your local installation of Microsoft Internet Information Services (IIS) Express, because IIS Express is not accessible from Office 365. However, you can use the Windows Azure Service Bus to communicate between Office 365 and your local environment. The Microsoft Office Developer Tools for Visual Studio 2012 provide a set of tools for configuring remote debugging of remote event receivers through the Windows Azure Service Bus.

For further details about using the Windows Azure Service Bus for this purpose, please read the article “Debugging Remote Event Receivers with Visual Studio,” which is available at http://blogs.msdn.com/b/officeapps/archive/2013/01/03/debugging-remote-event-receivers-with-visual-studio.aspx.

Lastly, consider that if you deploy the remote event receiver on your local development environment (for example, using IIS Express) or in a provider-hosted environment, and you want to publish the app via HTTPS, you will need to use an SSL certificate published by a trusted Certification Authority; otherwise, SharePoint will refuse to communicate with your remote event receiver because of certificate validation issues.

For the sake of completeness, you should provide some custom code to insert items in the newly defined list of orders. For example, you could define in the Default.aspx page of the app some HTML form fields to insert a new order item instance. The basic ASPX code of the Default.aspx page of the app, for adding new order items provides an excerpt of the HTML code for defining such a form. Here, the order content type is made of the fields Title, OrderId, OrderStatus (admitted values are Inserted, Approved, Shipped, Completed), and CustomerId.

As you can see from the code, the Default.aspx page provides both a form for inserting a new order item and a GridView control for showing the items in the list of orders. The .NET code behind the buttons for inserting a new item and for showing the list of items is based on the Client-Side Object Model (CSOM); you can find the full sample code in the companion samples for this chapter. Please refer to Chapter 7 for further details about working with the CSOM.

After creating the SharePoint app and configuring the content type, list definition, and data management business logic, right-click the SharePoint app project (the one with the AppManifest.xml file in it) and select Add | New Item | Remote Event Receiver, as shown in Figure 10-2.

A screen shot of the Add New Item dialog box of Visual Studio 2012 with the Remote Event Receiver menu choice highlighted.

Figure 10-2. Visual Studio 2012 while adding a new remote event receiver.

When you click the Add button, Visual Studio launches a wizard (see Figure 10-3) that asks you to provide information about the scope of the event receiver and the type of events you want to trap.

A screen shot depicting the UI of the wizard for creating a new remote event receiver. At the top of the screen is a drop-down list for selecting the scope of the remote event receiver; your choices are List Events, List Item Events, and Web Events. Just below, there is another drop-down list for selecting the type of the target content, which in the current example will be the list of orders previously created. Lastly, there is a multiselect list box for selecting the types of events that you want to handle with the remote event receiver.

Figure 10-3. The wizard for configuring a new remote event receiver.

For example, select a remote event receiver targeting List Item Events, selecting the Orders list you previously created in the SharePoint app, and choosing events of type An Item Is Being Added and An Item Was Added, which correspond to the ItemAdding and ItemAdded event types, respectively. When you click Finish, the Visual Studio wizard adds not only a feature element to the target SharePoint app project, but also a WCF service to the web project.

The basic remote event receiver implementation generated by the wizard of Visual Studio 2012 provides the source code of the class implementing the WCF service, which corresponds to the remote event receiver.

As you can see, the source code of the autogenerated remote event receiver handles the ProcessEvent method of the IRemoteEventService service contract. Moreover, it creates a new ClientContext instance of the CSOM, using the argument of type SPRemoteEventProperties provided to the remote event receiver operation. Notice the static method CreateRemoteEventReceiver ClientContext of the TokenHelper class, which creates a ClientContext instance based on the ContextToken property of the argument. Within the code of the remote event receiver, you can access, using the CSOM, the whole SharePoint host website and the app website, as well as their content and lists of items, in accordance with the permissions configured for you app. For more information on how to use the CSOM for interacting with SharePoint, see Chapter 7.

For the sake of simplicity, imagine that you want to retrieve information about the just-added item. You can access the argument of type SPRemoteEventProperties that’s provided, and retrieve the properties of the currently managed item through the ItemEventProperties property. Sample implementation of the ProcessEvent operation of the remote event receiver provides an example of this procedure.

As you can see in the code highlighted in bold in Sample implementation of the ProcessEvent operation of the remote event receiver, to access a field of the target item, you can query by field name the AfterProperties or BeforeProperties indexer properties of the ItemEventProperties property, which is available in the argument of type SPRemoteEventProperties received by the remote event receiver operation. Whether you query AfterProperties or BeforeProperties depends on the kind of event you are handling. For example, if you are managing the ItemAdding event, you will have only the AfterProperties values. If you are handling the ItemUpdating event, however, you will have both the AfterProperties and the BeforeProperties values.

In Sample implementation of the ProcessEvent operation of the remote event receiver, the synchronous event (the ProcessEvent operation) first checks the EventType property of the argument received. If EventType is of type SPRemoteEventType.ItemAdding, then it checks the DevLeapOrderStatus field of the target item. If the field has a value of Completed, the remote event receiver raises an error back to the SharePoint environment. To raise an error, you simply need to provide a value other than Continue for the Status property of the return value of the operation, which is of type SPRemoteEventResult. The sample raises an error and provides a description for that error in the ErrorMessage property of the operation result.

Just for the sake of example, in Sample implementation of the ProcessEvent operation of the remote event receiver, if the target order item passes the validation rule, the remote event receiver changes the Title field of the current order item, appending text with a value of - Added on, followed by the current date and time. Notice that, in order to change the field value, the remote event receiver implementation configures the ChangedItemProperties property of the operation result.

More Info

You may be wondering why the sample code does not use the CSOM to change the field value. The answer is simple: you cannot change an item during the ItemAdding event, because the item still does not exist in the content database. Thus, you should not be able to retrieve it from the target list using the CSOM. Moreover, if you are trapping another event—not the ItemAdding event, but, for example, the ItemUpdating event—changing the target item via the CSOM will raise another remote event receiver event, and you will put your code in an infinite loop, blocking the app. Moreover, while executing multiple updates on the same item, because of the loop, you could get multiple concurrency exceptions, too.

If you want to add another event to an already defined remote event receiver, you can simply click the event receiver element in Solution Explorer in Visual Studio 2012 and change the properties in the property grid, where you will find a Boolean property for each available event. Figure 10-4 shows the UI for managing this task.

A screen shot showing the property grid of a remote event receiver item, which includes many properties related to handling all the available events for the current type of receiver. You can switch any of these properties to true to enable event handling or to false to disable event handling.

Figure 10-4. The property grid of an instance of a remote event receiver.

Now put a breakpoint in the remote event receiver service code, start the SharePoint app by pressing F5 in Visual Studio 2012, add a new order to the target list of orders using the form provided in the Default.aspx page, and see the events being raised in the service code. You will see both the ItemAdding event, raised in the ProcessEvent operation, and the ItemAdded event, raised in the ProcessOneWayEvent operation.

Sample implementation of the ProcessOneWayEvent operation of the remote event receiver contains a sample of the ProcessOneWayEvent operation handling the ItemAdded event. As you can see, the event retrieves the target item by ID, using the CSOM, and changes its Title field by appending the literal value - ItemAdded Event Raised.

Deployment and registration

To deploy remote event receivers, you need to provision a specific feature element that declares the name, the event to handle, the URL of the service, the ordinal sequence of the event, and the type of source for the event. When you add and configure a new remote event receiver in Visual Studio 2012, Visual Studio defines such a feature element behind the scenes. The feature element for provisioning a remote event receiver handling ItemAdding and ItemAdded events details the XML source of that feature element for the example remote event receiver you defined.

The feature element of type Receivers, which defines one or more remote event receiver declarations shows the complete definition of the Receivers element, which can contain multiple remote event receiver registrations for the same target object.

The Receivers feature element belongs to the http://schemas.microsoft.com/sharepoint namespace. It is composed of a set of attributes, and accepts one or more Receiver child elements. Table 10-7 lists each available attribute, along with a brief explanation.

Table 10-7. The attributes of the Receivers element

Attribute

Description

ListTemplateId

Numeric value that defines the ID of the list definition to which the event receivers apply. It can assume any of the values defined in the SPListTemplateType enumeration, or it can assume a custom ListTemplateId of a custom list definition created with Visual Studio 2012.

ListTemplateOwner

GUID value that corresponds to the ID of the feature that provisioned the list template, if the list template is registered through a feature. Otherwise, it can be the name of the site definition that declares the current list template to which the event receivers apply.

ListUrl

Attribute that specifies the URL of the list instance to which the event receivers apply. Can assume the form of lists/orders, in case the target list name is Orders.

RootWebOnly

Boolean attribute to declare if the event receivers apply only to the root web.

Scope

Attribute that can assume the value of Site or Web. It defines the scope of the event receivers—they target either the site collection or the current web.

You can manually define feature elements provisioning remote event receivers. Although it is easier to let Visual Studio do the job for you, in some circumstances you may need to manually change the automatically generated files. For example, you can define whether an event will be synchronous or asynchronous using the Synchronization child element of the Receiver element. By default, all the -ing events are synchronous and all the -ed events are asynchronous, but you can configure any -ed event to be synchronous simply by setting the Synchronization child element of the Receiver tag to a value of Synchronous. If you provision an -ing event as synchronous, be careful that the ProcessEvent operation is raised on the service side, instead of the default ProcessOneWayEvent operation.

Lastly, the Url child element of the Receiver element is usually configured by Visual Studio 2012 as a URL relative to the app website, thanks to the ~remoteAppUrl token at the beginning of the URL value. However, you can configure whatever URL you like and need. For example, if your app is running in a testing environment with a specific public URL, you can simply replace the autogenerated URL with a real, direct URL of your own.

You can also manage and register the remote event receivers by using code based on the Server Object Model. A sample code excerpt for browsing and adding remote event receivers to a target list shows sample code for browsing all the already registered remote event receiver instances, as well as for adding a new remote event receiver definition.

Notice that the EventReceivers property of the SPList type serves both the remote event receivers and the local in-process event receivers. In this chapter, the latter are not discussed, because they are not suitable for a cloud scenario like Office 365. However, while browsing all the registered event receivers by code, you should pay attention about what you get out from the EventReceivers property.

Lastly, consider that a remote event receiver can also be registered using the CSOM, as you will learn in the next section.

App-related receivers

So far, you’ve seen remote event receivers defined inside and deployed through apps for trapping events related to the contents of a SharePoint app. Remote event receivers can also handle events that rely on the app life cycle itself rather than on data inside an app. For example, AppInstalled, AppUpgraded, and AppUninstalling are raised whenever an app is installed, upgraded, or uninstalled, respectively. The AppInstalled event is useful for provisioning custom content or configurations while installing an app. The AppUninstalling event handles the opposite scenario, and can save custom data before decommissioning the app website and before any data stored inside the app website is completely lost. The AppUpgraded event is handy for managing upgrades of data—for example, when an app upgrade needs to change data structures and sample data already provisioned with a previous version of the app.

The architecture and the SOAP contract of an app-related remote event receiver are exactly the same for any other remote event receiver. However, while trapping these events, you will receive a property with the name AppEventProperties and type SPRemoteAppEventProperties, available in the argument of type SPRemoteEventProperties provided to the ProcessEvent operation, which gives you information about the current app. The definition of the SPRemoteAppEventProperties type provides the definition of the SPRemoteAppEventProperties type.

Table 10-8 details the members of the SPRemoteAppEventProperties type.

Table 10-8. The members of the SPRemoteAppEventProperties type

Member

Description

AppWebFullUrl

A property of type URI that provides the URL of the app website of the current app

AssetId

A String property providing the asset ID of the current app

ContentMarket

A String property providing the source market of the current app

HostWebFullUrl

A property of type URI that provides the URL of the host website of the current app

PreviousVersion

A property of type Version, declaring the previous version of the current app if an upgrade is occurring

ProductId

A GUID property providing the product ID of the current app, which is also defined in the AppManifest.xml file of the app

Version

A property of type Version, declaring the current version of the current app

To register an app-related event, you can manually edit the AppManifest.xml file of your app. Inside the Properties element of the AppManifest.xml file, you can add three elements corresponding to the three kinds of available events. The sample AppManifest.xml file in A sample AppManifest.xml file for configuring all the available app-related event receivers configures all three event receivers.

Notice the three elements (highlighted in bold) for defining the URI of the remote service for handling AppInstalled, AppUpgraded, AppUninstalling. You can achieve the same result by editing the properties of the SharePoint app project. Figure 10-5 shows the property grid of a sample app project; the three properties are outlined in red.

A screen shot illustrating the property grid of a SharePoint app project in Visual Studio 2012. Highlighted are the three properties for enabling the three app-related events: Handle App Installed, Handle App Uninstalling, and Handle App Upgraded.

Figure 10-5. The properties for configuring app-related event receivers in a SharePoint app project.

When you enable an app-related event by setting its property value to true, Visual Studio adds a service file called AppEventReceiver.svc to the app web project. In the code of the service, you will be able to implement your custom receiver. A code excerpt of the ProcessEvent operation of a sample app-related remote event receiver illustrates a sample remote event receiver handling app-related events.

Notice that the asynchronous pattern (ProcessOneWayEvent) is not available while developing app-related event receivers, because app-related events are only synchronous. However, you will have to fully implement the service contract, providing a fake and empty implementation for this operation, too.

Consider a real scenario for using an app-related event receiver. For example, you could provision a custom remote event receiver that targets a list or library in the host website, instead of targeting the app website, as you did in the section “A sample remote event receiver.” Imagine that you want to trap an event whenever a user uploads a file in the default Documents library in the host website of your app. The goal of this receiver is to block files with the word virus in their name. A code excerpt of the ProcessEvent operation of a sample remote event receiver for a library shows a sample implementation of such a receiver.

As you can see, the implementation of this decoy receiver is really simple. If you attempt to upload a file whose name contains the keyword virus into the Documents library, the receiver will block it. Figure 10-6 illustrates how the standard UI of SharePoint behaves in this situation.

A screen shot showing the UI of SharePoint displaying an error during a file upload. The UI provides a red line with a critical error icon and the error message, identifying the file named Fake Virus as having an invalid file name.

Figure 10-6. The standard UI of SharePoint when a remote event receiver blocks a file upload with an error message.

The interesting part of this example, however, is the registration of the remote event receiver. In fact, to register the receiver, you need to link the service with the target library, using the CSOM, within the AppInstalled event. In addition, of course, you will need to remove it from the list of configured receivers when the app is uninstalled (via the AppUninstalling event). A code excerpt of an app-related receiver for registering remote event receivers for a library in the host website provides sample code for an app-related event receiver that handles these tasks.

Notice that, in order to register a remote event receiver, your app needs to have at least the right of type Manage on the target website, which is the host website.

Callback capability

Another interesting and advanced feature available through remote event receivers is the callback capability, diagrammed in Figure 10-7.

An illustration depicting the functional schema of remote event receivers with callback capabilities. On the left, an end user interacts with a SharePoint 2013 site or list of content, while on the right there is a remote system, like an LOB system. The remote event receiver is a SOAP service, published by the remote system and invoked by SharePoint 2013 upon user interaction. The remote event receiver can call back SharePoint, creating a new app-related token, through Windows Azure ACS. Windows Azure ACS provides the authentication and authorization controls when the SharePoint 2013 environment is on Office 365, while OAuth handles these tasks for on-premises deployment.

Figure 10-7. The functional schema of remote event receivers with callback capabilities.

The substantial difference from a classic scenario is that a remote event receiver using callback capabilities can acquire an app-related OAuth token if the remote event receiver is hosted by an app that runs on a farm in the cloud, like Office 365, or on-premises, but with OAuth properly configured.

More Info

For further details about configuring an on-premises SharePoint 2013 farm for using ACS and OAuth, you can read the following blog post from Steve Peschka: http://blogs.technet.com/b/speschka/archive/2012/07/23/setting-up-an-oauth-trust-between-farms-in-sharepoint-2013.aspx.

Otherwise, you can configure your on-premises app using an S2S (high-trust) security configuration, avoiding the need for the OAuth protocol. Through the acquired token, the remote event receiver can call back the SharePoint environment, typically requesting content or performing some management tasks. A code excerpt of the ProcessEvent operation of a sample app-related remote event receiver shows a code excerpt of an event handled by the ProcessEvent operations, which are consequently asynchronous.

In the highlighted lines, the sample retrieves a client context instance and communicates with the SharePoint host website, modifying some data. The client context is acquired using an S2S (also known as high-trust) deployment instead of OAuth.

Security

From a security viewpoint, remote event receivers use the standard security infrastructure of SharePoint 2013 and SharePoint apps. Thus, if you create a remote event receiver within a SharePoint app, then that remote event receiver will execute its code like any other content of the app. For example, if you create or modify an item of a list or library from within an event receiver, and then you check the Created By or Last Modified By fields, you will find something like the information illustrated in Figure 10-8.

A screen shot illustrating the properties of an item created by a SharePoint app and modified by the code of a custom remote event receiver. A red box highlights the properties of the creator and the user who last modified the item.

Figure 10-8. The properties of an item created and managed by a custom remote event receiver within a SharePoint app.

Notice that both the Created By and Last Modified By properties declare that the actions have been executed by the app DevLeap.SP2013.RER.Orders, on behalf of the current user, which in Figure 10-8 is the administrator.

If you save the context token and later execute a scheduled task with app-only credentials, the Last Modified By field will be related to the app only, without referencing a user on whose behalf the app is working.

Moreover, when SharePoint invokes a remote event receiver, it provides to it a rich set of information within the argument of type SPRemoteEventProperties. If you need to create a ClientContext instance for talking with the source SharePoint site, you can use either the CreateRemoteEventReceiverClientContext method of the TokenHelper class or the GetS2SClientContextWithWindowsIdentity method of the TokenHelper class. Both these methods give back a configured and ready-to-use ClientContext of the CSOM. The CreateRemoteEventReceiverClientContext method creates a ClientContext instance specifically for a remote event receiver running in a classic autohosted or provider-hosted scenario. The GetS2SClientContextWithWindowsIdentity method creates a ClientContext instance for an S2S (high-trust) scenario.

More Info

For further details about how to configure an S2S scenario, read Chapter 20.

Summary

In this chapter, you learned about the architecture of remote event receivers and how they work. You saw how to develop and provision a sample remote event receiver. Then you considered such advanced scenarios as app-related event receivers, receivers related to host websites, and callback-enabled receivers. Lastly, you learned about the security infrastructure that underpins the implementation and execution of remote event receivers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset