Showing posts with label SharePoint Online. Show all posts
Showing posts with label SharePoint Online. Show all posts

Friday, 5 January 2018

Use Azure Functions as remote event receiver in SharePoint

SharePoint webhooks are a new way of building event receivers for SharePoint. However, webhooks are only enabled for SharePoint list items at the time of writing this. https://docs.microsoft.com/en-us/sharepoint/dev/apis/webhooks/overview-sharepoint-webhooks

Recently I was required to write a event receiver for ListAdded event in a web. I decided to try and use Azure functions to achieve this instead of writing the traditional provider hosted app remote event receiver. Came across this great post  from Sergei Sergeev for reference.

Lets create a ListAdded event receiver using Azure Functions.

To Begin with, create a Azure Function project in Visual Studio and created a Function App in Azure through the Azure Portal. Add a function to the function app and select the HTTP trigger type of function since the event receiver needs to send the event payload to a HTTP endpoint. Publish your Azure function to the function app created through Azure Portal. The Azure function is now ready to receive events from SharePoint.

The Azure Function will have an endpoint. This can be fetched by clicking on the function in the Azure portal and clicking on the Get function URL link





The URL will look something like this :

https://<functionAppName>.azurewebsites.net/api/<AzureFunctionName>

The domain may be different based on your tenant configurations. We need the domain part of this URL in the next steps.

Now we need to register a event receiver on a WEB in SharePoint. We will use a simple console app for this. The console app will use SharePoint App credentials. So, head over to the "/_layouts/AppRegNew.aspx" page in your site and register a new app. Remember to provide the domain of this app as the domain of your event receiver Azure function noted above. We will need this in the future. Provide full control permissions to this APP on the site collection.


































Here is the code for installing an event receiver on the web. Replace receiverAzureFuncUrl, webUrl, ClientID and ClientSecret and run the console app. The console app users PnP Sites Core to get app-only client context.



Now the Azure function is ready to receive event of a list being added to the WEB. We need one more thing in our code and that is "TokenHelper". This is used to validate the context token received in the event payload and communicate with SharePoint through from within Azure function (which is our event receiver). I created a class library project in my Azure Function solution in Visual Studio and installed the "AppForSharePointOnlineWebToolKit" nuget package. Add a reference of this class library in your Azure Function APP project


NOTE : I had to add the reference of the DLL of this class library. Adding the project reference made the publish operation to fail.































Since the token helper fetches the ClientID and ClientSecret from webconfig, modify the code to fetch these values from the Azure Function APP settings.












Change the code of your Azure function to handle the incoming request from List Added event. This code reads the event payload and parses the XML to fetch the values that are of our interest. You can log the entire XML and see what are the values received through the Event payload. Once we have the "ContextToken" string, we can Validate the token and also get the client context of the site using "TokenHelper".  The "GetClientContextWithContextToken" method internally validates the token as well.



Hope this helps !

Monday, 30 October 2017

Work with Multi-value lookup fields in Microsoft Flow and SharePoint - Part 2

Part I of this post explains a couple of limitations of working with Microsoft Flow and SharePoint Multi-value lookup field.

Work with Multi-value lookup fields in Microsoft flow and SharePoint - Part 2

To overcome the challenge I decided to use SharePoint REST API to retrieve the field values. As you may already know, flow provides HTTP Trigger action which we can use to call the SharePoint REST API. The idea is to get an access token and retrieve the values through this HTTP trigger action. There are two great posts that helped me get an Access token, SharePoint scribblings and Shantha Kumar's blog

To start with, register an app in your SharePoint site through the "_layouts/15/AppRegNew.aspx" page. Provide the appropriate permissions so that it can access the multi-value lookup field data.

You'll have the client ID and client secret of the app. Also find out the TenantID of the tenant you are working on.

We create a new flow which is triggered when a new Item is created. Initialize the variables TenantID, ClientID, ClientSecret and a placeholder variable for AccessToken.








































Next, add a HTTP trigger action, to get the access token





























The body of this request is of the format

grant_type=client_credentials&client_id=<Client-ID>@<Tenant-ID>&client_secret=<Client-Secret>=&resource=00000003-0000-0ff1-ce00-000000000000/<tenantdomain>.sharepoint.com@<Tenant-ID>


Run the flow once till this step and see the history of the execution. Copy the body of the response. We will need it in the next steps.

Now we return to our flow and add a parse JSON action. Provide the "Content" as the body of the response from the previous HTTP trigger action. Use the body value copied in the previous step and paste it in the "Use sample payload to generate schema". This provides parse JSON action a sample format of the JSON that must be parsed.























Once this step executes, we are ready to use the access token. Next, use another HTTP trigger action to call SharePoint REST endpoint (here I have used a hard coded item ID) and retrieve the multi-value lookup field values. Along with the Title, you may also want to retrieve the ID of the looks. That might help you query other lists where these values may have been used.


































The results show the lookup values that were selected for the item.





















Now, we can then use these values as we would like to


Work with Multi-value lookup fields in Microsoft Flow and SharePoint - Part 1

I was recently working on a requirement to implement Microsoft Flow on a list that had a multi-value lookup field in it. The requirement was to fire a Flow when an item is created in the list and run a loop for each of the value selected in the multi-value lookup field.

At the time of writing this article, multi-value look-up fields are not supported in Microsoft Flow. This means that I could not straight away use the values from this multi-value look-up field and apply a loop.

If you would like to jump to how we can retrive the multi-value lookup column in Flow, here is the second part of the post

Work with Multi-value lookup fields in Microsoft flow and SharePoint - Part 2

The setup :

For this post, I am using a very simple setup, a "LookupRefList" with some 'Colours'  in it and another list "LookupUsedList" which has two fields which lookup data from "LookupRefList"

1) Colour : Single value lookup (just to show the difference in Flow values)
2) Colours : Multi-value lookup


























Flow with a single-value lookup field :

We can retrieve values from a single value lookup straight away

Flow setup :























Result :























Multi Value Lookup field : 

When we to fetch the multi-value column in Microsoft flow, the flow runs successfully, however, when you try to see the execution log, you see an error











































Click to see the log




















We cannot straight away use the multi-value look-up  in a apply to each loop.


























In the next part of the post, we retrieve multi-value lookup field values.

Work with Multi-value lookup fields in Microsoft flow and SharePoint - Part 2

Saturday, 14 January 2017

Change SharePoint online site language

As a SharePoint online site administrator, you can let your users display a site in language of their choice. Changing the display language of a site involves a couple of steps, both from the site administrator and also the user.

Site collection administrator steps:
To let users of your site use different language, you can change the available languages from the Site settings. Navigate to your site -> Site settings. Under the site administration section, select "Language settings"




This will show open a page that displays a bunch of languages.




Notice the text under Alternate language(s). Users will be able to change the site language from the languages that the site administrator makes available to the user. For now, I'll select HINDI here and click OK





Now, this will not have any effect on the site. The site will still be displayed in the default language. The administrator just made the site available in Hindi. Now, as a user, if I want to see the sites in Hindi, I need to modify a property in my user profile.

User profile language preference :

From the ribbon, click on your profile picture and click on "About Me"




Select "Update Profile"




Select the below option and click on


Click on Language and Region




From the preferences, select a language and click Add.



These are the language preferences of a user. I'll move Hindi the be my preference by using the little arrows beside the language.




Click on Save and close. It will display a dialog with information. Click OK.





You will notice that your profile page is shown in the language of your preference. Now navigate to the site where we made the language Hindi available to the users.













Wednesday, 23 September 2015

Export a term set to 'Importable' CSV using JavaScript in SharePoint online

It is a well known fact that we can import term set in SharePoint using a CSV file. This is particularly helpful when you are working in multiple on-premise environments/multi-tenant environment and you want to replicate a deep and complex term hierarchy everywhere. This can be very tedious if done manually. Also, you may not always have the liberty to use server side code with SharePoint online to export the term set. Here, we'll explore a way to export a term set in CSV file using JavaScript only.

Note, the implementation does not work in IE (I have tested this in IE 9) because of the way we export data to CSV from client-side. But it works very well in Chrome. I did not have much time to explore the reason for this but I plan to do so in the near future :)

The format of CSV which is acceptable during import is provided to us as a sample file in SharePoint. To see the format, navigate to Term store management and click on the Taxonomy node.















The columns in the CSV are in the following order

"Term Set Name", "Term Set Description", "LCID", "Available for Tagging", "Term Description", "Level 1 Term", "Level 2 Term"......"Level 'n'  Term".

You can see from the test file to write each term, a proper hierarchy has to be maintained.

















For testing purpose, I have created two term groups, one to Export a term set and one to import from CSV. The term set contains 'Regions'























get_pathOfTerm() : 

Before going into the code, I want to mention this method which has made writing the hierarchy of term set to CSV so easy !! When we use the "getAllTerms()" method on a term set, the terms are returned without its hierarchy details. So if we have to write the terms according to the hierarchy, we might have to take the longer route and iterate through each term and its children. This is where "get_pathOfTerm()" comes to our rescue. This method returns the hierarchy of a particular term, with each level separated by a semi-colon ';'. What this means is, referring to the above screenshot (term set hierarchy) if I get the path of the term "New York", the value returned is

North America;USA;New York

Now, we anyway need the values as comma separated since we are writing it to a CSV. Just replace the semi-colon with comma and you have the string for the entire hierarchy of a term you want to write.

I have developed a simple SharePoint hosted app to demo this. We will provide the GUID of a term set to our app which then exports that particular term set. To get GUID of a term set, click on the term set that you want to export in Term Management and in the right pane you'll find the unique identifier at the bottom.




































Import this into a term set.








































Here is the full code of the functionality



I found the method to export data to CSV using JavaScript on Raymond Camden's blog.

Hope this helps !

Tuesday, 1 September 2015

Index web property bag using JavaScript object model-AngularJS in SharePoint online

SharePoint 2013 added a new capability to index the property bags. Indexing property bag through the server side object model code is pretty easy. The WEB object has a property called "IndexedPropertyKey" which is a collection of all the web properties that should be indexed. Here is a reference article . However, doing this through client object model is tricky because we do not have access to IndexedPropertyKey through CSOM. Vesa Juvonen has made our life easy by documenting a work-around to do this through CSOM.

Basically the way this works is - all the properties that need to be indexed are encoded and stored in a "vti_indexedpropertykeys" property. In a scenario where multiple properties need to be indexed, the encoded values are separated by a PIPE "|" character. In this post we are going to index the web properties using JavaScript object model on a SharePoint online site. We will develop a SharePoint hosted app to add and index a property. Here is how our application will look like.
















Lets go ahead and add a couple of new properties to be indexed.




















The checkbox facilitates the user to choose whether the new property should be indexed or not. As we have chosen to index the properties , the vti_indexedpropertykeys is created in the web properties with the encoded values of property keys separated by PIPE character










Once the incremental crawl completes, the web properties that we just added are indexed.





















Lets go through the code


The AngularJS code has a controller "SPWebPropertiesController" and an AngularJS service "WebPropertiesService" which contains function to fetch and add new web properties. The function $scope.GetWebProperties uses AngularJS defer and on success, it populates the keys and values of the properties. It also checks whether the key "vti_indexedpropertykeys" exists and sets the flag $scope.vtiIndexedPropertyKeysExists accordingly.

All the AngularJS and Javascript code below is a part of single JavaScript file. It is separated here in this post and GIT for the ease of understanding.

  


FetchWebProperties function:

This function gets all the properties from the property bag and returns it to the controller where the key and values are populated in $scope.WebProperties=[];

AddNewProperty function: 

- This function adds a new property to the property bag using the set_item(Property_Key, Property_Value) function. If you want to modify the value of a property, use "webProps.set_item(Existing_Property_Key, New_Value)".
- If we have chosen to index the property using the checkbox, we must get the encoded value of the property key. This is done using the EncodePropertyKey function.
- Checks whether the key "vti_indexedpropertykeys" exists, using the flag that we have set in GetWebProperties function of the controller. If it exists, it adds the encoded property key.
- If the "vti_indexedpropertykeys" is not present, it creates this new key and then adds the encoded property key that has to be indexed.

EncodePropertyKey function : 

This function converts the property key to an encoded string. Initially I observed the bytes array in C# console application and Javascript conversion and noticed that the '0's from JS conversion were missing. So I added those (line 5 in the below function)


WebPropertiesService code :