Wednesday, March 29, 2017

ADAL JS is a library which allows to write javascript code which interacts with Azure AD via MS Graph API. It uses OAuth2 flow for authenticating user against Azure AD and getting access token which then can be used for using Graph API. Samples and prerequisites for using ADAL JS are available on its GitHub page. Briefly you need to create new app in Azure AD (Azure portal > Active directory > Applications) and then update its app manifest to change oauth2AllowImplicitFlow property from default false value to true (see e.g. Azure AD OAuth2 implicit grant). But when you will try to launch the code you may get various AADSTS* errors. One of them is:

AADSTS65001: The user or administrator has not consented to use the application with ID '…'. Send an interactive authorization request for this user and resource

If you encountered with this error go to Azure AD app configuration page and set Delegated permission like shown on the picture below for scenario when we need to list O365 groups where user is a member (you will need to choose permissions appropriate for your case of course):

where AuthorizationServerProvider is your custom token provider. Note on TokenEndPointPath property of OAuthServerOptions which contains path to the token generation end point. Now if you will try to get token by accessing http://example.com/token (where instead of http://example.com you need to use your web api host) you will get the following error:

{
"Message": "No HTTP resource was found that matches the request URI 'http://example.com/token'.",
"MessageDetail": "No type was found that matches the controller named 'token'."
}

The problem is fixed by commenting out default routing configuration in WebApiConfig shown above:

1:publicstaticclass WebApiConfig

2: {

3:publicstaticvoid Config(HttpConfiguration config)

4: {

5: config.MapHttpAttributeRoutes();

6:

7:// config.Routes.MapHttpRoute(

8:// name: "DefaultApi",

9:// routeTemplate: "{controller}/{id}",

10:// defaults: new { id = RouteParameter.Optional }

11:// );

12: }

13: }

But please note that after that it will be mandatory to decorate your controllers and actions by RoutePrefix and Route attributes correspondently;

Friday, March 24, 2017

Sometimes we need to set filter in Sharepoint list view on the hidden field. As hidden fields are not shown in UI we can’t set such filters from the browser, but we can set them programmatically. E.g. suppose that we have field “IsPrivate” which is hidden so end users are not able to change value of this field and we want to show only non-private list items in the list view. List view filter will look like this in this case:

1:<Where>

2:<Eq>

3:<FieldRefName="IsPrivate"/>

4:<ValueType="Boolean">false</Value>

5:</Eq>

6:</Where>

Now if we will try to modify this list view in UI we will see that its filter section looks like there is no filter at all:

And which is more interesting is that when we will click Save button there – filter on hidden field will remain. I.e. if we will add sorting from UI ViewQuery property will look like this:

1:<OrderBy>

2:<FieldRefName="Title"/>

3:</OrderBy>

4:<Where>

5:<Eq>

6:<FieldRefName="IsPrivate"/>

7:<ValueType="Boolean">false</Value>

8:</Eq>

9:</Where>

even though Filter was shown empty in UI. Be aware of this tricky moment to not be confused in situations when filter uses hidden fields.

Monday, March 20, 2017

Recently we faced with interesting problem: there is functionality which copies documents from another site collection in Sharepoint Online via SP.RequestExecutor:

1:var sourceExecutor = new SP.RequestExecutor(sourceSiteUrl);

2:var targetExecutor = new SP.RequestExecutor(targetSiteUrl);

3:

4:// Get form digest of target site collection

5: jQuery.ajax({

6: url: targetSiteUrl + "/_api/contextinfo",

7: type: "POST",

8: headers: {

9:"Accept": "application/json;odata=verbose"

10: },

11: success: function (data) {

12:try {

13:var digest = data.d.GetContextWebInformation.FormDigestValue;

14:

15:// Build executor action to retrieve the file data.

16:var getFileAction = {

17: url: sourceSiteUrl + "/_api/web/GetFileByServerRelativeUrl('" +

18: sourceServerRelativeUrl + "')/$value",

19: method: "GET",

20: binaryStringResponseBody: true,

21: success: function (getFileData) {

22:// Get the binary data.

23:var result = data.body;

24:// Build executor action to copy the file data to the new location.

25:var copyFileAction = {

26: url: targetSiteUrl + "/_api/web/GetFolderByServerRelativeUrl('" +

27: targetFolder.get_serverRelativeUrl() + "')/Files/Add(url='" +

28: fileNameFromInput + "', overwrite=true)",

29: method: "POST",

30: headers: {

31:"Accept": "application/json; odata=verbose",

32:"X-RequestDigest": digest

33: },

34: contentType: "application/json;odata=verbose",

35: binaryStringRequestBody: true,

36: body: getFileData.body,

37: success: function (copyFileData) {

38: ...

39: },

40: error: function (ex) {

41: ...

42: }

43: };

44:

45: targetExecutor.executeAsync(copyFileAction);

46: },

47: error: function (ex) {

48: ...

49: }

50: };

51: sourceExecutor.executeAsync(getFileAction);

52: } catch (e) {

53: ...

54: }

55: },

56: error: function (ex) {

57: ...

58: }

59: });

After file is successfully copied Modified By field shown in list views displays correct value – it shows account of the user which copied the document (i.e. under which account code above was executed). However when we tried to get the value of ModifiedBy managed properly from search index we got value which original file had in the source site collection before it was copied to target site collection (i.e. person which last modified the document in the source site collection). Recrawling of the list didn’t help. Also we tried to explicitly set value of Editor field in document metadata after file has been copied and it didn’t help either.

In order to avoid this issue the following workaround was used: at first as before we get list of the files from search index using javascript object model and then when we get last n results sorted in correct way for displaying in web part we make n requests to content database in order to get correct value of ModifiedBy field (remember that in list views correct account is shown in this field and list views show data from content database):

In this code we at first create array of objects from results returned from search index (lines 3-16) and then for each object we get it’s File object and from it’s list item read Editor value (lines 18-40). Note that for getting editor’s display name here we used undocumented property $5E_1 of SP.FieldUserValue – more proper way is to get user’s id from it’s get_lookupId() method and load it in separate request from web’s user collection, so please be aware of that. Of course this approach is slower than original because it makes n requests to content database, but if data is loaded asynchronously and number of displayed files is not big, performance will remain acceptable and web part will display correct value in ModifiedBy column. Hope that this information will help someone.

About Me

I've created this blog for sharing my technical experience in software engineering. Most of posts will be dedicated to Sharepoint. But I will write also about another areas of software development for .Net platform. Hope it will be useful and will help you in your work.