Steps to write Remote Event Receivers – O365 SharePoint Online

The purpose of this blog to,

  • Associate remote event receivers to host web.
  • Manipulate the host web items remotely when events are raised.
  • Debug remote event receivers in the cloud.

Open the pre-created structure and set the SharePoint app permissions and url

  1. Start Visual Studio 2013
  2. Click File | Open Project
  3. Go to Labs/HostWebEvents folder and open the existing solution named HostWebEvents.sln.
    Notice that the actual folder location id dependent on where you copied the files to in your local computer.                             1
  4. Provide your tenant login information when the Connect to SharePoint dialog is prompted.                                                                                                  2
  5. Ensure that the Site URL property is correct for the App project by first activating the OneDriveCustomizer project in solution view.
  6. Confirm the Site URL from the property window. This this should be pointing to your personal Office365 tenant and to existing developer site collection which you could use for the exercise creation.
    If you get prompted with the Connect to SharePoint dialog, provide the appropriate login information to the window.
  7. Open AppManifest.xml from the SharePoint App project.4
  8. Adjust the permission to require Manage in Web scope.5
  9. Press F5 or choose Debug | Start Debugging to ensure that application can be properly deployed.
  10. Login to your test tenant by providing the right user ID and password, if required.6
    Notice that if you have any challenges to logout from your corporate tenant, you should be following guidance from following support article: http://support.microsoft.com/kb/2507767.
  11. Click Trust It, when the trust notification is shown.7
  12. You should now see the initial design for the app as follows.
    Notice that we will implement the most functionality in an event receiver, so there won’t be much functionality in default.aspx9
  13. Move back to Visual Studio side and press Shift+F5 or choose Stop Debugging from the Debug menu.

Add-in the AppInstalled event receiver and customize it to add-in an ItemAdded event receiver on a host web list

Move to Solution View, select the SharePoint app project and set the Handle App Installed property to true.                                  10

In the Solution view open the newly added AppEventReceiver.svc by double clicking it11

Add the below constants to the AppEventReceiver class

private const string ReceiverName = “ItemAddedEvent”;

private const string ListName = “Remote Event Receiver Lab”;

Add the below methods to the AppEventReceiver class

  private void HandleAppInstalled(SPRemoteEventProperties properties){

using (ClientContext ctx = TokenHelper.CreateAppEventClientContext(properties, false))
{

if (ctx != null)

{

//Add a list to the host web

List eventReceiverList = LabHelper.AddList(ctx, ctx.Web, Microsoft.SharePoint.Client.ListTemplateType.GenericList, ListName);

//Remove existing event handlers

ctx.Load(eventReceiverList, x => x.EventReceivers);

ctx.ExecuteQuery();

foreach (var rer in eventReceiverList.EventReceivers)

{

if (rer.ReceiverName == ReceiverName)

{

System.Diagnostics.Trace.WriteLine(“Found existing ItemAdded receiver at ” + rer.ReceiverUrl);

try

{

//This will fail when deploying via F5, but works when deployed to production

rer.DeleteObject();

ctx.ExecuteQuery();

}

catch (Exception ex)

{

System.Diagnostics.Trace.WriteLine(ex.Message);

}

}

}

//Get WCF URL where this message was handled

OperationContext op = OperationContext.Current;

Message msg = op.RequestContext.RequestMessage;

//Create a new event receiver

EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation();

receiver.EventType = EventReceiverType.ItemAdded;

receiver.ReceiverUrl = msg.Headers.To.ToString();

receiver.ReceiverName = ReceiverName;

receiver.Synchronization = EventReceiverSynchronization.Synchronous;

//Add the new event receiver to a list in the host web

eventReceiverList.EventReceivers.Add(receiver);

ctx.ExecuteQuery();

}

}

}

private void HandleItemAdded(SPRemoteEventProperties properties)

{

using (ClientContext ctx = TokenHelper.CreateRemoteEventReceiverClientContext(properties))

{

if (ctx != null)

{

try

{

List eventReceiverList = ctx.Web.Lists.GetById(properties.ItemEventProperties.ListId);

ListItem item = eventReceiverList.GetItemById(properties.ItemEventProperties.ListItemId);

ctx.Load(item);

ctx.ExecuteQuery();

item[“Description”] += “\nUpdated by RER ” + System.DateTime.Now.ToLongTimeString();

item.Update();

ctx.ExecuteQuery();

}

catch (Exception ex)

{

System.Diagnostics.Trace.WriteLine(ex.Message);

}

}

}

}

Add the following using statements to the AppEventReceiver class

using System.ServiceModel;

using System.ServiceModel.Channels;

Replace the ProcessEvent method in the AppEventReceiver class by below code

public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)

{

SPRemoteEventResult result = new SPRemoteEventResult();

switch (properties.EventType)

{

case SPRemoteEventType.AppInstalled:

HandleAppInstalled(properties);

break;

case SPRemoteEventType.ItemAdded:

HandleItemAdded(properties);

break;

}

return result;

}

 

Add code to delete item event handlers from a host web list

In the Solution view open the Default.aspx.cs code behind file by double clicking it12

Add the below constants to the Default class

private const string ReceiverName = “ItemAddedEvent”;

private const string ListName = “Remote Event Receiver Lab”;

Add the below code in the btnDetachEventHandler_Click method of the Default class

var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

using (var ctx = spContext.CreateUserClientContextForSPHost())

{

List myList = ctx.Web.Lists.GetByTitle(ListName);

ctx.Load(myList, p => p.EventReceivers);

ctx.ExecuteQuery();

var rer = myList.EventReceivers.Where(x => x.ReceiverName == ReceiverName).FirstOrDefault();

try

{

System.Diagnostics.Trace.WriteLine(“Removing ItemAdded receiver at ” + rer.ReceiverUrl);

//This will fail when deploying via F5, but works when deployed to production

rer.DeleteObject();

ctx.ExecuteQuery();

}

catch (Exception ex)

{

System.Diagnostics.Trace.WriteLine(ex.Message);

}

}

Press Ctrl + Shift + B and check that the solution builds correctly. Do not yet run the sample!


 

Prepare the solution for debugging

  1. Open a Microsoft Azure PowerShell command prompt13
  2. Download your Azure publish settings by entering the following command, an Internet Explorer window will open and you will be asked to log into the azure management portal, then your publish settings file will be downloaded
    • Get-AzurePublishSettingsFile14
  3.  Import your Azure publish settings by entering the following command replacing mysettings.publishsettings with the path to the file that was downloaded in the previous step.
    •  Import-AzurePublishSettingsFile mysettings.publishsettings15
  4. Create a new Azure Service Bus Namespace by running the following PowerShell command, replacing [MyNamespace] with your own chosen namespace. Copy the ConnectionString from the created NameSpace. You may also change the location property.
  5. New-AzureSBNamespace -Name ‘[MyNamespace]’ -Location ‘Central US’16
  6. Switch back to Visual Studio 2013. Right click the SharePoint add-in project and choose properties. In the screen that opens click on SharePoint in the left navigation to open the SharePoint specific project settings.17
  7. In the SharePoint project settings scroll down to the end and configure the Debugging settings by checking Enable debugging via Windows Azure Service Bus property and by providing the Windows Azure Service Bus connection string that you’ve copied in step 4.  18

Debug your application

  1. In the Solution view open the newly added AppEventReceiver.svc by double clicking it:19
  2. Add a breakpoint in the HandleAppInstalled method and press F5 to start debugging
  3. Click Trust It, when the trust notification is shown.20
  4. Visual Studio will show the break point being hit. Press F5 to continue.21
  5. The default.aspx page opens. Click on Back to Site in the top navigation to navigate back to the host web22
  6. In the host web go to the newly created Remote Event Receiver lab list by clicking on it in the Recent left navigation node23
  7. Add a new entry to this list24
  8. After pressing save the result will be a modified Description field due to the ItemAdded event receiver that updated the description value25

.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s