This post was written with my colleague Cas van Iersel. You can find more of his blogposts on www.casvaniersel.com or you can follow him on twitter @casvaniersel
Since Microsoft has moved to a Cloud first approach with Office 365 some challenge came to light when it comes to the handling of events in SharePoint 2013 (Online). In the good ol’ days we would open up our Visual Studio and without hesitation write an awesome Event Receiver and deploy it as a Farm Solution. These days are over as we all well know. Microsoft now gives us a different set of Tools and Platforms to build these kind of Event Handlers called “Remote Event Receivers”. In this Post we would like to share some practical information to get started building these RERs quickly. But before we get technical first some ingredients to the RER recipe.
Skills: CSOM is the new SSOM
In case some of you missed the memo; the reason why programming in CSOM (Client Side Object Model) should be one of the Key Skills a modern SharePoint / Office developer should have is that we are NOT able to upload Farm Solutions into SharePoint Online. So the code that is going to handle a certain Event must be written in the CSOM. In this case the Managed CSOM .NET library.
Platform: Azure is not just a shade of Blue
So obviously here Azure is THE platform to host these kind of solutions. In order to get us started building a remote event receiver we are going to need an Azure environment. This is just a heads up, we will elaborate further on.
Tools: Visual Studio Power
The one tool you’re definitely going to need is Visual Studio. Microsoft Developers best friend. Besides Visual Studio most developers have their own preferences. Building RERs here’s a favorites list of tools that helped us build:
- Azure SDK
- OfficeDev Patterns & Practices (Okay, not really a tool, but nonetheless it is awesome)
My first RER
Skills: Check! Tools: Check! Azure Account: Not yet. No worries, we can start building RERs already without using Azure for now. Let’s start with opening Visual Studio shall we.
Creating a RER Project
We start by creating the right type of project: App for SharePoint. Then the app needs to be a Provider Hosted app and for the sake of Cloud I hooked it up with my Office 365 Tenant.
A RER is basically just a piece of code that runs whenever an event goes off. Now that doesn’t require a fancy UI or even a Front End. But because this code is wrapped inside a Provider Hosted App we need to choose a type of Front End web application. We choose MVC just because we like the MVC framework. The only reason we might actually need a UI is to work with settings for the App.
Click Next and select Azure to use for Access Control and click Finish. Visual Studio will create a nice Solution with 2 projects for the SharePoint hosted App.
The First Event
In order to hookup SharePoint events later on, first we need to enable the App Installed event. This event will enable us to execute code when the App is properly installed. That is the right moment to hookup all other events using code. Click on the App Project and observe the properties window. Change the “Handle App Installed” property to True. Automatically Visual Studio will create a service in de MVC application to handle this event.
We also want to remove the RER in case the app is deleted, so we’ll go ahead and enable ‘Handle App Uninstalling’ as well.
The created AppEventReceiver contains a method called ‘ProcessEvent’. That method gets fired when the app is installed and that is the point where you can hookup your custom RER. Another option would be to add a button to your apps’ interface and perform actions on the button click. All App Events are handled through the same method, so it is important to distinct between them. Since we have two different events, installed and uninstalling, the ProcessEvent method might look something like this (the code provided here are taken from the OfficeDev PnP examples):
In this blog we’ll create a new list, and add a custom RER to that particular list. The creation of the list is demonstrated in the below image:
At this point we have a list that we want to add a custom RER definition to. This can of course also be done with an already existing list. All you need is a List object.
In the above code snippet, the RER Definition is created and the important properties are filled. First you specify the EventReceiverType. Next you have to specify the receiver URL or endpoint. Retrieving the WCF URL based on the current method execution is a smart way of finding the proper endpoint for your receiver URL, especially when deploying an app in multiple environments. You could also use web.config properties or something similar to that which you can defer from across the different environments.
Handle the actual RER execution
Similar to the App Installed and Uninstalling events, the RER also has a method that is called on execution, the ‘ProcessOneWayEvent’. You are responsible for filtering out the correct list or EventType that is being triggered, and based on that you can have your code do different things. The ProcessOneWayEvent can look like this:
In the HandleItemUpdated event you can retrieve the list and ListItem through the SPRemoteEventProperties and perform the required actions after that. That method can look something like this:
Clean up after yourself
We don’t want to end up with RER’s that call out to non-existing endpoints. When a user removes the app, we’ll want to remote the associated Event Receivers that have been created during the app installed event. We’ve already enabled the handling of the AppUninstalling event, and hooked it up with a method ‘HandleAppUnInstall’. All that remains is filling this method with the removal of the RER. We do that by retrieving the list, and then retrieving any RER that match the specified name. If a RER has been found, we delete it. The code to achieve this, is shown below:
That’s it! You now have a working Provider Hosted App, that adds a RER to a list in your hostweb upon installation. The next step is moving to a production-ready environment, and deploying your App to Azure.
Deploy a Provider Hosted App to Azure
After you have created and tested your App with Remote Event Receivers, it is time to deploy it to Azure and make it available to other users as well. While you could also choose to host your app somewhere other than Azure, this blog focuses on Azure because that just makes so much more sense. Azure Web Apps are free to use, quick and easy to set up and configure, and takes away the hassle of creating an externally available SSL website by you (or your network team), because Azure does all this magic for you.
- The first requirement is an actual Azure account. If you don’t have one yet, you can create a free trial for a month over on http://azure.microsoft.com/en-us/pricing/free-trial/. Everything demonstrated in this blog is included in the trial, and you can create up to 10 Azure Web Apps for free.
- After you have created your Azure account, log in to the management portal (https://manage.windowsazure.com). Create a new Web App by clicking on the + icon in the lower left corner, choosing Compute –> web App –> Quick Create.
Choose a URL that describes your app and click on Create.
- The next step is to register your app in SharePoint. You can do so by going to the page _layouts/15/appregnew.aspx. The app registration is a Tenant-wide administration, so it doesn’t really matter on which site you perform this registration.
You can generate a Client ID and Client Secret, and fill in a title that suits your app. For the app domain, pick the same URL as the one you created in step 2, but without the protocol. The redirect URI is the URL with the protocol included.
- Depending on how you created your Remote Event Receivers, you’ll need to update the URL of the EventReceiver to point to Azure instead of your localhost. If you’ve created your RER through XML declaration, you’ll need to update that URL to also point to the URL from step 2. If you’re creating RER’s on the fly throughout your app, a good practice would be to have an App Setting in your web.config that contains the URL from step 2. Then, when creating the RER, you can read that app setting to dynamically hook up your RER to the proper deployment.
Azure actually also allows you to create App Settings that your Provider Hosted App can read. That way you can have a different App Setting per environment (Deployment / Test / Acceptance / Production) without having to change your code. In order to create an app setting in Azure, click on your newly created Web App and click on ‘Configure’ in the top navigation bar. Scroll down until you reach the App Setting section and insert/modify your desired app settings.
- Update the web.config for the Web Project to include the new Client ID and Client Secret. When deploying locally, Visual Studio automatically updates these values for you. Since we’re deploying to Azure, Visual Studio won’t be able to update these values. You have two choices here and both are completely valid. You can choose to either include the Client ID and Client Secret in the App Settings directly in Azure, or you can add them to the web.config file. The choice is yours.
- The final step before we can deploy our projects is to download the Publish Profile from Azure. Navigate to your Web App, and at the Dashboard you can click on the link to download the publish profile.
This publish profile can be used to deploy your visual studio project to Azure, directly from Visual Studio. You can download multiple publish profiles (for example, for the different environments) and hook them up to the same Visual Studio project. That way you can quickly deploy your project to different environments.
- Now that we have all our prerequisites set up in both Azure and in our Visual Studio Solution, it is time to deploy the two projects. Right click the Web project and select Publish. In the popup window select ‘Import’ and choose the Publishing Profile you downloaded in the previous step.
Click finish and your Provider Hosted Web Project is now deployed to Azure. If you have multiple publish profiles, you can click on Publish again, return to the first screen of the dialog, and choose import again. The new profile will now be added to the list of available deployment locations, and you can easily switch between them.
- The last step in the process is to deploy the SharePoint App. Right click the App project and select Publish. In the next screen select ‘Package the app’. A dialog window will ask you for two things:
- Where is your website hosted? Enter the URL including the protocol you have created in step 2;
- What is the app’s Client ID? Enter the Client ID you generated in step 3;
When the publish has been done successfully, the local folder containing your .app file should open. Upload this app file to the App Catalog site in the library ‘Apps for SharePoint’. You can then add the app through the Site Contents screen. Doing so will redirect you to the *.azurewebsites.net provider hosted app, where you can confirm your app works as expected. In case you get an error that ‘The assembly cannot be loaded’, and you didn’t get that error when developing against your localhost; that means Azure is missing some DLL’s (which will happen for instance if you have the Office Dev PNP included in your references). Open the provider hosted app and click on References. For each DLL included there, make sure the ‘Copy Local’ attribute has been set to true.
That’s it! Congratulations, you have now successfully deployed your Provider Hosted App to Azure. In the next paragraph we’ll show you how to debug your remote code after it’s been deployed to Azure.
Debug the app using Azure Servicebus capabilities
Now that we have the app deployed to Azure and it’s running in a test environment, what if you there are some bugs and you want to debug against that specific deployed code? Luckily, Microsoft has enabled us with a powerful tool that makes debugging an Azure app quite easy: the Azure Servicebus. Please note, the Servicebus does have additional pricing, which can be found here.
In order to debug your remote code, you can follow the steps below:
- Log in to the Azure management portal to create a new Servicebus. Do this by clicking on ServiceBus in the left navigation and then click on Create at the center bottom of the screen. A window will pop up:
2. After the Servicebus namespace has been created, select it and click on the Connection Information icon at the bottom of the screen.Copy the connection string that is displayed there. It will look something like this:
3. Open the properties of your SharePoint App Project and click on the SharePoint tab. Scroll down until you find the information regarding Debugging. Check the box that says ‘Enable debugging via Microsoft Azure Service Bus’ and fill in the connection string from the previous step.
4. That’s it, you are now set to enable debugging through Microsoft Azure! To actually debug the code without having the press F5, you can also Attach a debugger on the fly. Do this by opening the Server Explorer in Visual Studio and adding a connection to your Microsoft Azure environment. That connect button looks like this:
After you have logged in with your account, open the Website section, right click your App and select ‘Attach debugger’.
Your debugger should now fire up and start debugging against the remote code. If you get the following warning:
You’ll need to disable the ‘Just My Code’ debugging feature. You can do this by clicking on debug in the Visual studio menu, and select ‘Options and Settings’. Under the Debugging tab, with subtab General you have a checkbox to enable Just My Code debugging. Uncheck that box and save the settings.
Everything should now be working as expected.
Congratulations! You have just created your first app containing Remote Event Receivers and deployed it to Azure! We’ve also shown you how to debug the code once it has been deployed to Azure. You now know everything in order to get started writing your own cool apps: the possibilities are endless!
For further information regarding RERs, be sure to also check out the OfficeDev Patterns & Practices section which you can find here. They have several working examples that not only show how to add your RER, but also have some kick ass implementations.