SharePoint Saturday NL 2015 Slidedeck now available

On the 6th of June I had the pleasure of presenting at the SharePoint Saturday NL event. It was the first time presenting for me, and I had a blast doing it.

Thanks everyone who attended! If you have any feedback I would love to hear it, either here or through twitter @vverbeek87.

Below you’ll find the slides used for the session:

 

Handling Events in a SharePoint Online environment

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:

  • Fiddler
  • 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.

ESPC-1

ESPC-2

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.

ESPC-3

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.

ESPC-4

ESPC-5

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.

Handle It

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.

  1. 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.
  2. 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.

ESPC-6

Choose a URL that describes your app and click on Create.

  1. 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.

ESPC-7

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.

  1. 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.

ESPC-8

  1. 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.
  2. 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.

ESPC-9

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.

  1. 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.

ESPC-10

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.

  1. 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:
    1. Where is your website hosted? Enter the URL including the protocol you have created in step 2;
    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.

ESPC-11

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:

  1. 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:

ESPC-12

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:

Endpoint=sb://mycustomapp.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;
SharedAccessKey=UjdD7khUOe2uKVb939a4hJd2uuFRjuEP81CEcdNvTtE=

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.

ESPC-13

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:

ESPC-14

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:

ESPC-15

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.

ESPC-16

Everything should now be working as expected.

Summary

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.

Client Side People Picker with HTML5 Placeholder text

Lately I have been working with the OfficeDev Patterns & Practices samples a lot. The amount of quality examples provided in that project is amazing, and a huge thanks should go out to all that contributed. One of the components created in the Patterns & Practices is a client side people picker that can be used in Provider Hosted Apps. This component creates a people picker inputbox that closely resembles the one you get in OOTB SharePoint.

In this blog post I’ll guide you through the steps required to extend this component to be able to add a placeholder text that describes what the field’s value should contain, using the HTML5 placeholder attribute. This allows for a much nicer UX, and makes your client side people picker go from this:

peoplepicker4

To this:

peoplepicker2

Before we get down to business, it’s important to note that this post assumes you already have your client side people picker up and running, using the Core.PeoplePicker solution. You can find out how to do just that here.

The first step is to actually include the placeholder text in the input element. That part is relatively easy. The sample dictates a certain HTML structure, because the javascript file is dependent on that structure. You need a surrounding div, span element, input textbox, search area and a hidden field that ends up containing the actual selected people value. This structure is shown below:

In order to add the placeholder text, change the Width of the asp:Textbox to 155 (or a different value based on the length of your placeholder text), and add the attribute placeholder=”your placeholder text”. If you fire up the page, the initial result is exactly what you want. However, if you add a user, you want the placeholder text to disappear, and only adding the placeholder attribute doesn’t do that:

peoplepicker3

The reason it doesn’t hide the placeholder text is because the value for Test User 1 isn’t stored inside the input box, but rather inside the hidden field. And because the input box doesn’t have any value, the default behavior is to show the placeholder text.

In order to fix this, we’ll need to add a change event to the hidden field that stores the people picker value. In case the value is changed, we want to adjust the placeholder attribute on the input field accordingly. And secondly, we need to make sure the change event is fired when a user is added or deleted (default behavior for a hidden field is that value change events do not fire, because it’s not the user that executes the change, but rather the javascript).

To add a change event to the hidden field, you can include the following line of javascript in your $(document).ready function:
$(‘#hdnSiteOwner’).change(changeSiteOwnerPlaceholder);

The function that is executed on the value change is shown below:

It looks at the value for the hidden field. If the value does not equal ‘[]’ (which is the value set by the control in case a user is cleared out), a user has been selected and the placeholder text is emptied. If the value does equal ‘[]’, no user is selected and the placeholder text is restored.

The last step is to make sure the change() method gets executed when a user is selected or removed. To do that, we need to add several lines of code to the peoplepickercontrol.js file. The methods ‘RemoveResolvedUser’, ‘RecipientSelected’ and ‘DeleteProcessedUser’ need to have the following line included at the end:

this.PeoplePickerData.change();

Which makes the methods end up like this:

And that’s it! Now you have a fully functioning client side people picker with a placeholder text that is cleared after a user has been selected, and returns in case all users are cleared. Your end users will certainly appreciate the informative description that you have just added! Happy coding.

Debugging a solution with multiple SharePoint Apps

In a very large environment it is not uncommon to have Visual Studio solutions that contain multiple different projects. However, when you’re working with these individual projects, you want to be able to quickly debug your specific project. I recently discovered, that when you do this in a solution that contains a Provider Hosted App, switching to and from the Provider Hosted App for debugging purposes, has some very specific gotcha’s…

Let’s create an example to see what I mean. I create a new solution with a provider hosted app (ASP.Net Web Forms Application). After the solution has been created, I add an additional project. This time it’s a console application. The solution structure, still very basic, now looks like this:

SolutionStructure

Let’s say I’m going to work on the Console Application first. So I right click on the project and select ‘Set as startup project’. I hit F5, and the console app launches and everything is working great. The debugger is properly attached, and my breakpoints (if I’d have any) are properly hit.

ConsoleAppDebug

Now the Console application is absolutely perfect, and I want to continue working on my Provider Hosted Application. This is where the trouble begins… Which project do I set as startup project? First let’s see what happens when I set the PHApp project as startup and hit F5. So far so good… Visual Studio installs my app in my SharePoint site, launches IE and reverts us back to the apps default page. However… None of the breakpoints set in my PHAppWeb projects are being hit. Sure, IIS Express launches the web and handles the execution, but not being able to debug through your code makes things quite difficult doesn’t it?!

Breakpoint not hitting

Let’s see what happens when we set the PHAppWeb project as the StartUp project. I hit F5 once again, and great; my symbols have now been loaded! But wait… nothing else happens. Your default browser is not starting, and there is no way for us to reach the code unless we want to manually browse to the apps’ start page. That’s no good either!

So, what other choice do we have? The answer is in the solution properties. Right click on the solution and select ‘Properties’. In the ‘Startup project’ tab, you have the option to select multiple startup projects at once. So let’s select that option, and specify the PHAppWeb first with a ‘Start’ action, and the PHApp second, also with the Start action configured. The end result should look like this:

StartupProjects

Now when we hit F5, the PHAppWeb is launched, symbols are loaded, and then the app is installed to SharePoint. Once that is done, the browser will start up and asks you to trust the app and then redirects to the apps’ start page. Exactly the way we want it to! Unfortunately, you’ll have to manually change this every time you set a different StartUp project.

So, in short, if for whatever reason your Provider Hosted debugging experience is a bit buggy, make sure to check the Solution Properties and check if both the AppWeb and the App project are configured with a ‘Start’ action. Gotcha!

Using REST to query data by filtering on Taxonomy Field

The new SharePoint Api is a powerful thing. It lets you query for items by using REST. However, there is an important thing to note when you are querying items using a SPQuery combined with a taxonomy field filter. Considering you have a taxonomy field that is named ‘CategoryField’ which contains the different categories for certain pages. You would expect the method below to work properly:

However, when you execute this function, the data returned is empty! It turns out that the field you use in your SPQuery has to be the hidden field that actually stores the content of your taxonomy field. So in the above method, change the FieldRef Name=’CategoryField’ to FieldRef Name=’CategoryTaxHTField0’ and try to execute it again. This time, the method will work and you get some functional data back that you can actually use. By the way, did you notice that &$expand=File&$select=Title,File/ServerRelativeUrl bit? More on that later…

Dynamically changing MasterPages in SharePoint 2013 when using Device Channels

Suppose you have a public facing website that has about 40 different page layouts. You are also using the Device Channel functionality, which is new to SharePoint 2013. Basically this means you can set multiple MasterPages, one for each device channel you use. But what if you want to have a different MasterPage for one of the page layouts you use. You have to take into consideration, that when updating the MasterPage from the code behind file, the MasterPage is updated for any and all device channels you use. But what if you only want to change the MasterPage for a certain device channel, but keep the default for all others? That’s where this post comes in.

First let’s take a look at how you can change the MasterPage from the code behind file of a Page Layout. This post by Kirk Evans shows you how to deploy a Page Layout and how to create a code behind file for this Page Layout. This post by Eric Overfield gives us a hint on how to change the Masterpage from the code behind file. As noted, you can only change this property in the OnPreInit method, otherwise the MasterPage will have already loaded and changing the property would result in an error message. MSDN shows the following example:

This would however change the MasterPage for all device channels and remember that we only want to change this MasterPage for a specific device channel. This post advices you to use a HttpContext variable that is called ‘EffectiveDeviceChannel’. The post also warns that this property might not be available everywhere because it is loaded on demand. I have tried to use this property, but unfortunately, as you would have guessed, it was not yet available during the OnPreInit method so I had to find a different solution. Browsing the web didn’t do me any good, and since most of the Mobile classes in SharePoint are sealed, those weren’t of any help either. After inspecting the entire HttpContext, there was one property that I could ‘misuse’ and was the solution to my problem. The HttpContext.Current.Items[‘MasterPageUrl’] was there, and it was showing the URL to the MasterPage that was about to be loaded. Since the device channels all have different Masterpages, this became a solution for me to change the MasterPage only for a specific Page Layout. The code used for this is displayed below:

So, when changing the MasterPage from a Page Layout file when also using Device Channels – resort to using the HttpContext variable MasterPageUrl, because the EffectiveDeviceChannel variable is not yet loaded at that point in the life cycle. Gotcha!

Sequence Dropdown Box using javascript and HTML

Have you ever come across that scenario where you have more than a few input fields and you want to go the user the ability to sort these fields, without having to copy + paste the input several times? In these cases, multiple dropdown boxes next to the input fields specifying the order of these fields can be very useful. This got me thinking, “Well, doesn’t SharePoint already implement something like that, for example when modifying a list view?”. In this post I’ll describe how Microsoft has implemented this and how it can work for you. This example uses only javascript and html, so if you want to do some server side action with it, be sure to modify the code accordingly.

First off, here’s an example of modifying a list view, where you will find these dropdown boxes:

listView

In order to retrieve the code that Microsoft uses for this, I’ve inspected the page and rebuild the same scenario. Here’s the pure HTML that is used:

As you can see, this is nothing fancy. Just a simple HTMLSelect item containing a few options. The onchange method calls a certain Javascript function. This javascript function does all the magic for us, and makes sure that all the other dropdown boxes get their values changed accordingly. The javascript that is used for this is:

The second value specified in this javascript call is the HTMLSelect number of your current item. So for the first dropdownbox, that would be item 0. For the second it would be item 1, etc. The third value is the number of dropdownboxes that are there in total.

So there you have it! A simple HTML and Javascript example of making your website that much more user friendly.