Tuesday 26 November 2019

My sessions at ESPC19

The 2019 edition of the European SharePoint, Office 365 and Azure Conference takes place in Prague next week, and I'm looking forward to delivering talks there. As usual, the event is easily the most important in the Microsoft cloud space on this side of the world, and there'll be great representation from Microsoft starting with keynotes from Jeff Teper, Dan Holme, Scott Hanselman, Alex Simons, Vesa Juvonen and others. In addition, other Microsoft leaders and Program Managers will deliver sessions on Project Cortex, the Microsoft Graph, Content Services, Teams, Yammer and much more - the Microsoft at ESPC19 page has a long list of big name speakers making the journey from Redmond! Over 2500 attendees are expected, and the conference should be a great mix of sessions and networking with many experts, partners and vendors in the Microsoft cloud space.

My sessions

I'm delivering the following two talks:

Using Azure Dev Ops for development or support teams (Thursday 05 December, 14:00)

In many organisations, the workload of a technical team is still managed in SharePoint lists, Excel, Planner or Microsoft Project. However, Azure Dev Ops Boards offer a much better, more visual way for many groups – and it isn’t just for highly-technical dev teams on agile projects. Various types of backlogs and boards exist – these include a Kanban board to suit a team working on a regular pipeline of requests (e.g. a support or help desk team) and a scrum board to support agile development projects (e.g. using sprints and a sprint planning process). There’s something in there for most types of teams and work.

This session will start at the beginning by showing the different types of boards and backlog, and move on to customising things to really suit how your team works. Over the course of several demos we’ll cover various hints and tips, and also consider how to take things to the next level with automated builds (with DevOps Pipelines) that tie into work item tracking.


Top Office 365 Development Techniques to Master - The Hitlist (Tuesday 03 December, 11:45)

Things move fast in Office 365 development, and as Microsoft evolve the platform and APIs, new techniques and approaches become available all the time. As the head of a talented dev team, Chris regularly updates his list of techniques that he believes are essential to have good capability building Office 365 solutions. Between SPFx, the Graph, Teams development, coding in Azure Functions and building solutions in PowerApps and Flow, let’s walk through high-value scenarios at the end of 2019 that should be in every experienced coder’s toolbox, with a demo and code sample for each. This session will help you close any skills gaps and should be a great conversation with some bright minds in the room.

There's still time to register!

The conference will be a great opportunity to get the latest on Microsoft cloud strategy, roadmaps and tips from the field. If you're there please come and say hello, and if not you can still register at the following link!

https://www.sharepointeurope.com/pricing/

Sunday 17 November 2019

My Ignite 2019 announcement slides (plus selected roadmaps)

I recently created some "one page summary" slides of key announcements from Microsoft's recent Ignite 2019 conference and published them to Twitter - but I thought it could also be useful to compile them into one post here. Feel free to use them if they're useful to you - of course, they're my personal take on what I think is important and you might have different priorities, but given the firehose of announcements I always think consolidated summaries can help. Certainly I find the process of parsing the announcements to create the slides helps me to frame Microsoft's overall positioning and progress.

In this post I'm providing three things:
  • My one page summary images
  • Some assorted Microsoft roadmap slides I collected (images)
  • A PowerPoint deck containing all of the above (hosted on SlideShare)

My Ignite summaries  


I collated announcements for Teams, Power Platform, SharePoint and Azure:






Roadmap slides

These are some selected roadmap slides I collected for topics relevant to me:







SlideShare deck

You can download the original slides for all of the above in one PowerPoint deck below:

Tuesday 15 October 2019

Quick tip - search across sites under a SharePoint hub site

SharePoint Hub Sites are an important aspect of building a modern digital workplace on Office 365. They provide a way of relating sites to each other, and since a modern SharePoint intranet is built from a flat list of sibling site collections which are siblings, such mechanisms are useful to impose a logical structure and coherent user experience. Of course, the idea is that this model deals very well with organizational change, since the association between a site and a hub can be easily updated - if restructuring becomes necessary, it's trivial to update a site to belong to a new hub (something which could not be said of the subsite model heavily used in earlier SharePoint models).

As a reminder, hub sites provide the following:

  • Shared navigation
  • Shared branding 
  • Scoped search (i.e. the ability to search across all sites associated with the hub)
  • A 'top of the tree' destination for the hub

Search and hub sites

There are a few scenarios you might be interested in when it comes to search and hub sites. Everybody's favorite technical SharePoint search person Mikael Svenson (now a part of the search team at Microsoft) has some useful samples at Working with Hub Sites and the search API, including how to use search to list out all your hub sites, including how to filter to return only those with at least one associated site.

However, one thing that's not mentioned there is the fact that you can perform scoped searches for items within all sites associated with a hub. For example, if I have a set of project sites that live under a projects hub, perhaps I'd want to show search results (or provide a custom search page) which restricts result to pages and documents within this project site 'structure'.

This works because Office 365 does something useful here, in that each piece of content that is indexed picks up a tag to indicate which hub it is associated with - in other words, this is propagated down to the item level in SharePoint. The Managed Property 'DepartmentId' is used for this - it contains the ID of the parent hub site.

This is shown in the search query tool below:

This makes sense when you think about it, since Microsoft provide a search across all sites belonging to a hub when you use the search bar in a Hub:


...and the DepartmentId managed property is the mechanism used there.

Sample search queries

Some examples of how you might use this (once you know the ID of the hub you want to scope searches to) might be as follows. NOTE:- in these examples, the GUID specified is the Site ID of the Hub Site in my tenant I want to use. You'd need to drop the appropriate value for your scenario in there:

Show me all pages or documents from any site under this hub:

IsDocument:True AND (DepartmentId:{545621ea-2334-45c2-903b-3b9b93be38ee} OR DepartmentId:545621ea-2334-45c2-903b-3b9b93be38ee)

 Show me news from any site under this hub:

IsDocument:True AND PromotedState:2 AND (DepartmentId:{545621ea-2334-45c2-903b-3b9b93be38ee} OR DepartmentId:545621ea-2334-45c2-903b-3b9b93be38ee)

It seems that sometimes the value can contain braces and sometimes it may not (given how Microsoft themselves search using this property) - so, it may be safer to provide both formats as shown in the queries above.

Search queries used by Microsoft in hub searches

Let's take a closer look at the search terms/clauses used by Microsoft in their native functionality for searching across a hub. Taking a look in browser dev tools shows queries like those shown below (with URLs and IDs from my dev environment shown here).

Full query ("All" tab):

QueryModification: "(marketing) (-ContentClass:ExternalLink AND -FileExtension:vtt AND -Title:OneNote_DeletedPages AND -Title:OneNote_RecycleBin AND -SecondaryFileExtension:onetoc2 AND -ContentClass:STS_List_544 AND -ContentClass:STS_ListItem_544 AND -WebTemplate:SPSPERS AND NOT (ContentClass:STS_Site AND SiteTemplateId:21) AND NOT (ContentClass:STS_Site AND SiteTemplateId:22) AND NOT (ContentClass:STS_List_DocumentLibrary AND SiteTemplateId:21) AND NOT (ContentClass:STS_List_DocumentLibrary AND Author:"system account") AND NOT IndexDocId=17592721738413) AND NOT Path:"https://chrisobriensp-my.sharepoint.com/personal/cob_chrisobrien_com/" AND NOT Path:"https://chrisobriensp-my.sharepoint-df.com/personal/cob_chrisobrien_com/" AND (DepartmentId:{545621ea-2334-45c2-903b-3b9b93be38ee} OR DepartmentId:545621ea-2334-45c2-903b-3b9b93be38ee) -ContentClass=urn:content-class:SPSPeople"

 Full query ("Files" tab):

QueryModification: "(marketing) (DepartmentId:{545621ea-2334-45c2-903b-3b9b93be38ee} OR DepartmentId:545621ea-2334-45c2-903b-3b9b93be38ee) AND (NOT (Title:OneNote_DeletedPages OR Title:OneNote_RecycleBin) AND NOT SecondaryFileExtension:onetoc2 AND NOT FileExtension:vtt AND NOT ContentClass:ExternalLink AND NOT (ContentClass:STS_List_DocumentLibrary AND SiteTemplateId:21) AND NOT ((filetype:aspx OR filetype:htm OR filetype:html OR filetype:mhtml)) AND isDocument:1 OR ((ContentTypeId:0x010100F3754F12A9B6490D9622A01FE9D8F012 OR ContentTypeId:0x0120D520A808*) OR (SecondaryFileExtension:wmv OR SecondaryFileExtension:avi OR SecondaryFileExtension:mpg OR SecondaryFileExtension:asf OR SecondaryFileExtension:mp4 OR SecondaryFileExtension:ogg OR SecondaryFileExtension:ogv OR SecondaryFileExtension:webm OR SecondaryFileExtension:mov)) OR (FileType:ai OR FileType:bmp OR FileType:dib OR FileType:eps OR FileType:gif OR FileType:ico OR FileType:jpeg OR FileType:jpg OR FileType:odg OR FileType:png OR FileType:rle OR FileType:svg OR FileType:tiff OR FileType:webp OR FileType:wmf OR FileType:wpd) OR (ContentTypeId:0x012000*)) AND NOT (ContentTypeId:0x0101009D1CB255DA76424F860D91F20E6C4118* AND PromotedState:2) AND NOT Path:"https://chrisobriensp-my.sharepoint.com/personal/cob_chrisobrien_com/" AND NOT Path:"https://chrisobriensp-my.sharepoint-df.com/personal/cob_chrisobrien_com/" -ContentClass=urn:content-class:SPSPeople"

As you can see, that's a lot of exclusions needed to filter the results down to just the useful ones!

Summary

Hub sites provide a useful construct in Office 365/SharePoint Online, and understanding how to search across all sites within a hub can be a valuable technique when building solutions. The key is to take advantage of the fact that Office 365 puts the parent hub site ID into the 'DepartmentId' managed property on each item in the search index. Knowing that, you can build all sorts of custom solutions around hub sites!

Tuesday 10 September 2019

How does it affect my tenant? Questions to ask for Office 365/SharePoint solutions

I’m doing some Office 365 architecture work at the moment to ensure our clients have a clear view of our solutions and how they work. Any organisation working with a partner or deploying products based on Office 365 needs to ask “how does it affect my tenant?” – but of course, that’s just the high-level question. Underneath are a whole series of security, compliance, operational, cost and other governance considerations that should be explored for robust long-term successful use of Office 365. However, I find that many organisations don’t yet know how to ask the right questions or dig into the right areas – and this can lead to risks of compliance issues, data leakage, impact to organisational productivity or any number of other problems down the line.

So, I thought it would be good to share a starter checklist of topics and questions to ask related to solutions which extend Office 365 in some way. The focus is on SharePoint-based customisations, and it’s not a comprehensive list – you could certainly broaden the scope, or go deeper in specific areas by asking more questions. But hopefully my list gives a sense of the type of questions you should ask before accepting a solution into your environment, or on the other side, the kind of thing you should be providing as a trustworthy vendor/partner/internal development team in your documentation.

For larger enterprises, my work often involves more than documentation. Commonly, I’m walking various technical teams and service owners through the low-level detail of our solution, and each needs to grant approval before our solution can pass. I’m currently working with one of the world’s largest companies, and we need around 10-12 teams to approve their respective bits, and then to also pass a “unity review” which considers the overall picture. I’m using a combination of PowerPoint and live demos on the conference calls with the respective teams, and it’s all about socialising the concepts and ensuring the low-level detail is covered and all questions are answered. I do think the onus is on the implementation team to proactively “push” the information – as noted earlier, in-house teams don’t always know the right questions to ask. If you have your client’s best interests at heart though, you’ll want them to be well-informed.

My suggested checklist

What does the overall architecture look like?

  • Which Office 365 services are used?
  • What does the architecture diagram(s) of your solution look like?

User data/user profiles

  • Are any custom fields added to AAD profiles?
  • Are any custom fields added to SPO profiles?
  • How does data get into the fields? Is there a sync solution, or do users edit their values through native Office 365 or custom interfaces?

Security

  • Are any changes to the “Custom script” settings proposed (i.e. is there any ad-hoc JavaScript running outside of modern pages and the SPFx security model)? HINT – you really want both of these set to “prevent” if possible:



  • What SPFx permissions are required? (as shown on the Web API permissions page)?



  • Are any AAD app registrations created (related to use of the Microsoft Graph API)?





  • What 3rd party libraries are used by the solution? Can you show us a current npm audit report?
  • What certificates are used by the solution?
    • How are they managed and where are they deployed to?
    • What is the expiry date of any certificates and how is rollover handled?
  • If remote code elements are deployed (Functions or other web APIs), what authentication model is used?
  • Are any code elements or artifacts *not* hosted in our tenants/subscriptions? If so, what purpose do they serve? How can we be sure our data isn’t passed to them?

Taxonomy

  • What term groups and term sets are provisioned?
  • How are they used/what purpose do they serve?
  • Are they open or closed term sets?
  • How are they identified? Will my users confuse them for something else?
  • Are they a duplicate of something already in place?

Search configuration

  • What new managed properties are provisioned?
  • More importantly, are any mappings of existing out-of-the-box properties provisioned?
    • How can I be sure any use of RefinableStringXX, RefinableDateXX, RefinableIntXX and so on don’t clash with existing mappings in use in my tenant?
  • What result sources are provisioned?
  • What other search configuration is provisioned?

Teams

  • What aspects of the Teams dev platform are used (e.g. tabs, connectors, bots, messaging extensions)?
  • What permissions/device permissions are used?
  • What remote domains are used? What for?

Office Add-ins

  • If Office add-ins are used, what are their permission requirements (e.g. “ReadWriteMailbox”)?
  • Is Centralized Deployment used to deploy the add-ins? If not, why not?
  • Which Office applications do the add-ins surface in?

Azure

  • What is deployed to Azure? Is it just PAAS elements or are there any IAAS elements?
  • If Azure Functions are used, are they on the Consumption Plan or App Service Plan?
  • What are the forecast costs? What could vary this?

SharePoint content (see note below)

  • What site types are used (e.g. communication sites, hub sites, team sites etc.)?
  • Are any classic SharePoint elements used (e.g. classic publishing sites)

SPFx

  • What SPFx packages are used?
  • Which are deployed tenant-wide, and which are per site collection?
  • [Also see Security section for considerations on SPFx security]

Notice that the list does not focus too much on SharePoint content. If the solution gets deployed into an existing SharePoint site collection (or several), you might ask questions about the content types and site columns and so on which are provisioned. In most cases however, what goes on within individual SharePoint sites is a lower-level concern where the risks are much lower (at least in SharePoint Online).

Summary

Successful use of Office 365 in the enterprise relies on balancing productivity and agility with security and governance, and part of this involves knowing exactly what’s in your tenant and how it works.

Just because you no longer own and manage the physical servers doesn’t mean that a breach isn’t possible or your data cannot be stolen. Office 365 is designed with customisation in mind (at least, it is these days) and there are many many security features which are designed to ensure that the platform can be extended in safe, governable ways. However, you do need to make sure that you use them - and I think it’s fair to say that some older vendor/product Office 365 solutions that haven’t been updated do not.

No doubt there are some useful products which can help with solution governance in this way, but I’m not sure any of them cover all of the aspects listed here. Hopefully this checklist can help!

Thursday 18 July 2019

Office 365 dev - tips for building a custom SPFx form

One project I worked on recently involved building a custom form as an SPFx web part – and in general I think this is a great option for “high-end” forms which need to have quite specific behaviour and/or look and feel. Also, the ability to designate the page as an SPFx application page means some of the unnecessary page furniture is removed, which is helpful. When thinking about forms in Office 365, I see a spectrum of options which looks something like (in order of increasing complexity/effort):

  1. Out-of-the-box SharePoint list form 
  2. PowerApps customised SharePoint list form 
  3. Canvas PowerApp, embedded in a SharePoint page with the PowerApps web part 
  4. Custom-developed form with SPFx and React 
So, we’re talking about the last option here.

The good news is that for an adequately-skilled SPFx developer, building one of these forms can be pretty quick - there are some very powerful building blocks to help. I see the overall recipe as something like:
By combining use of these ingredients with some extra steps to help users get to your form (see later sections on this), you can get to a rich solution with less effort than you might think.

Form controls used with SPFx, and dealing with data

Thinking about the list of ingredients above, you'll find you can go a long way by bringing in those controls and integrating them with your data. I think the following arrangement might be common:

Requirement

Source

Standard textboxes, buttons etc. Office UI Fabric React
Dropdowns, including advanced formatting/behaviour Office UI Fabric React
Taxonomy picker PnP React taxonomy picker
People picker PnP React people picker
File upload control (stored as list item attachments) PnP React file upload control
File upload control (stored in another way) Other 3rd party control (you handle the upload to SharePoint)

Most likely you'll need to allow existing items to be edited with your form, as well as new items to be created. PnPJS is perfect for simplifying the operations to fetch an existing item (typically from an item ID passed to the page), and also saving back to SharePoint. In your SPFx web part, you'll use React state as the go-between in the middle of your controls on the front-end, and your service code for the data layer.

In the end, my form looked something like this (shown here zoomed-out). You might notice a series of buttons at the top - these surface functionality such as "Save as draft", and although I think use of something like Office UI Fabric's CommandBar or ContextualMenu would be nice, the client preferred straight-forward buttons in this case. Otherwise it's just use of the controls described above:


Providing the edit item experience


Assuming your custom form stores items in a SharePoint list, you'll probably want to take some steps to integrate the default list experience with your form. A good example is ensuring that when a user edits an item, they are taken to your form rather than the out-of-the-box SharePoint list edit form. This can be accomplished by adding a column to your list with some JSON formatting defined to provide the link. Simply take the URL for your page (i.e. a page that you created and added your web part to), and use it in the JSON for the link. You should end up with something like this:

I used JSON like this:

Notice that I'm passing the current list item ID to my form. Within my SPFx web part, I have code which is looking for a value being passed in the 'itemId' URL parameter - if one is found, as described above I use PnPJS to:
  • Fetch data for this item
  • Set React state with these values, so that my form controls get set to these values
So that takes care of the edit experience.

Providing the 'new item' experience or customising new/edit/disp forms in modern lists


In my case, the new item experience can be provided simply by a big visual representation on the home page. Regular end-users do not use the list, and won't be pressing the 'new' button. In this case, things are simple. Chatting to colleagues (thanks Leo!), it *is* possible to override the new/edit/disp forms of a modern list, but currently there are issues if a modern page is the target and you want to pass any parameters in the URL (e.g. the item ID for the edit experience) - apparently something breaks completely and your form is unlikely to load. One approach which can work is to create a classic page, set the new/edit/disp form URLs of your list accordingly, and add JavaScript on the classic page to redirect on to the modern page hosting your SPFx form. You may need to hash/further encode any ID you're passing, and consider adding CSS to hide some page elements in case the user briefly sees them during the redirect process. That's about as good as it gets in summer 2019 apparently, and there's a UserVoice entry Allow us to develop custom modern forms with custom edit experience to request better integration - the good news is the status of this has recently changed to "Thinking about it". So, hopefully this story will be improved soon for those needing tight integration between your custom form and the out-of-the-box list UI.

Setting the page to be an SPFx app page


Once you've developed your web part, you'll want to make sure it works well on the page - and typically you'll want to remove some of the "page furniture", so that your form is the focus and there are fewer distractions. On a modern page, you can do certain things like set the title area to the "Plain" layout - this will reduce the header area, but if your form has some kind of header/title you'll still get duplication between this and the page title.

And what about the problem that a page author could accidentally edit the page and remove the web part?

Both of these problems can be solved by converting the page to be an SPFx app page. On one of these, only a single web part can be used, it's properties cannot be edited and the title area is removed. The two images below compare my form before being converted to an app page (left) and afterwards (right):

As you can see, the title area is removed. Also, if I flick the page into edit mode, the web part cannot be removed and the only options I see relate to the page title:

So, less chance of an authoring 'accident' happening to your form now. If the page wasn't originally created as an app page, converting can be done by PowerShell or even by some quick JavaScript in the browser console as a one-off. See here for more details - https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/single-part-app-pages. Of course, you could also remove the left navigation if you like too.

Using the PnP Taxonomy Picker control in such a form


One area I wanted to talk about here was a quirk in the PnP Taxonomy Picker control (a common control for these forms). Like many others in this toolkit, the control itself is excellent and would be a significant task on it’s own if you had to write it. Let’s all buy Elio a(nother) beer next time we see him 😉

The taxonomy picker is easy to add to your web part, and it takes care of populating itself with terms from a term set that you provide (by name or ID). A typical declaration looks something like this:

<TaxonomyPicker allowMultipleSelections={false} termsetNameOrID="b2a79b4b-9d64-46d9-8a94-38f8809f8d12"
  panelTitle="Select Region"
  label=""
  initialValues={this.state.selectedRegion}
  context={this.props.context}
  onChange={this._onRegionTaxPickerChange}
  isTermSetSelectable={false} />

That would give something on your page like this:

A couple of other notes would be:
  • initialValues – use this property to set the value of the control. So if your form is being used to edit an existing list item, fetch the value from data and set this property – since I’m using React, this simply comes from a value in my web part state
  • onChange – what should happen when a term is selected. In React, you’d usually store the value in state at this point, ready for later insert/update to SharePoint
So far, so straightforward. However, something to be aware of is that the onChange() method provides the item in the form of an IPickerTerm object – something provided by the PnP code. However, such an object cannot be passed to SharePoint using PnPJS or REST, since the REST API expects a different format. IPickerTerm has the following properties:
  • name
  • path
  • key
  • termSet
  • termSetName
However, PnPJS or the SharePoint REST API expect an object with the following properties (this is for a single-value taxonomy field):
  • TermGuid
  • Label
  • WssId
Sidenote - things are a bit more complex if your field stores multiple values. Alex Terentiev has an article on this that may help you out.

So, you’ll need to some mapping between the two object types if you’re reading/writing data to SharePoint from the PnP taxonomy control (including setting the selected value of the control to the current value stored in a SharePoint list item).

Some important things to know here are:
  • A value of -1 can be used for the WssId value – you don’t need to do anything more, SharePoint will sort this out
  • The TermGuid property maps to the IPickerTerm.key property
  • The Label property maps to the IPickerTerm.name property
With that in mind, we just need some code to map between the two object types - I found that having two methods such as the following is needed (to convert in each direction):

Summary


Hopefully this post has been a useful round-up of considerations when building custom SPFx forms. I think this approach works great for more complex forms, and the building blocks listed here really do help reduce the amount of code required. Setting the page to be an app page to eliminate unnecessary page furniture helps, as does integrating with the SharePoint list UI for the new/edit/display experience. In addition to Office UI Fabric, the PnP React controls are all extremely useful in SPFx forms and the TaxonomyPicker is no exception. If you use that one, you'll probably find you need some code like my sample above to help you map between the format used by the control and that used by the SharePoint REST API or PnPJS, but that's not too complex. Happy coding!

Wednesday 19 June 2019

Office 365 dev tips – working effectively with the Microsoft Graph and other APIs

I’ve been speaking at various conferences recently about key skills for extending Office 365 – things that an effective architect or developer needs to have in the toolbox these days. Clearly the ability to work with the Microsoft Graph needs to be high on this list, given that it is after all, “the API for Office 365”. It’s great to have one (mainly!) consistent way to work with Teams, SharePoint, mail, calendar, Planner, OneDrive files and many other functions too, but between the various authentication options and coding styles, there’s quite a bit to know.

One thing I find is that developers are perhaps not effective enough with the Graph yet – partly because some things have changed recently, and partly because some devs are only now coming to the Graph from use of say, the SharePoint REST/CSOM APIs and other service-specific APIs.

So my key messages here are:

  • The Postman collections provided by Microsoft can help answer your questions about the Graph and integrate calls into your code
  • The SDKs help more than you’d expect in your code – having types in TypeScript being one example
Why are these things important?

Tip 1 - Using Postman collections instead of Graph Explorer


Graph Explorer (GE) is great for developers to start seeing some calls that can be made to the Graph and what kind of data comes back. If you’re new to the Graph, check it out at https://developer.microsoft.com/en-us/graph/graph-explorer. However, for intermediate and advanced developers, I recommend using Postman over Graph Explorer. Here’s why:

Downsides of Graph Explorer
One drawback of GE is that even though you can sign-in with your account and therefore work with your own Office 365 tenant, this is still not the same thing that your code will be doing. An Azure AD app registration is always needed for code to call the Graph, and GE does NOT use your app registration – meaning different permissions are used. So, it’s common to run into issues when you move from Graph Explorer to your code, usually related to not having correct permission scopes allowed on the app registration. Using Postman allows you to use your app reg, so it’s exactly the same as your code.

Something that makes Postman very powerful with the Graph is that Microsoft have released Postman collections for all the current Graph methods – including those in beta. You can import these into Postman and you’ll then see an item for every method, broken into two folders for app-only calls and on-behalf-of-user calls:

This is great for discoverability! Now, every time I wonder if the Graph allows me to get something, instead of clicking through pages of documentation I just come here and start expanding folders:
I get to see all of the Graph workloads and what data can be retrieved very quickly indeed. The process of getting started with Postman and the Graph collections is a little bit involved - it's outlined on the Github repo where you can obtain Microsoft's Postman Graph collections, but I think it can be helpful to watch someone go through the process, so I made a video with some captions:


The process starts by obtaining the details of an AAD app registration which I'll use, so you should create one (with the appropriate permission scopes defined) if you don't have one already. Overall, the process is:
  • Import the collections
  • Configure various Postman variables
  • Obtain access tokens for app-only and "on behalf of user" calls, and store in other Postman variables
  • Enjoy your new quick access to the Graph! You can start executing the calls and seeing data coming back at this point

It's fairly straightforward to integrate the call into your code, and you won't have any security/permission issues because you've already tested the same thing your code will do.

UPDATE - actually, I realise now that Jeremy also has a video. See https://www.youtube.com/watch?v=4tg-OBdv_8o for that one.

So that's great - we can now see all the URL endpoints in the Graph, what data they expect and what data they return. But how do we ensure we're working effectively with the Graph once we're in code?

Tip 2 - ensure you're using TypeScript types


For many of us, the place that we'll be coding against the Graph will be SPFx or other TypeScript code - perhaps even an Azure Function based on node.js. The key thing to avoid here is use of “any” in TypeScript – we can do better than that, whether it’s another 3rd party API or the Graph itself. It’s common for APIs to return fairly complex JSON structures, and we can avoid lots of coding errors by ensuring we get type-checking through the use of types (interfaces or classes) representing the data. Additionally, having auto-complete against these data structures makes the coding process much faster and more accurate.

Using the Graph in TypeScript

When using the Graph in SPFx, the first thing to note is that your project will not have the Graph types added automatically (e.g. when the Yeoman generator creates the files) – you have to install a separate npm package. To do this, run one of the following:
  • npm install @microsoft/microsoft-graph-types --save-dev
  • npm install @microsoft/microsoft-graph-types-beta --save-dev
Yes, Microsoft kindly provide types even if you’re working the beta Graph endpoints. For most production scenarios, you’ll be using the first option (and staying to release endpoints) though. Once you have the types installed, you can import them to your SPFx classes with:

import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';

It’s a good idea to only import specific entities that you’re actually using rather than *, but that needs some digging (to find the module name). You’ll be rewarded with a smaller bundle size however. Either way, once you’ve got the types imported you can start using them in your code – this changes things from having no zero support at all:
..to having full auto-complete as you type:
Hooray! Things are now much easier.

Wherever possible, don't settle for coding without this kind of support! But what if you're working with an API that isn't the Graph?

Using 3rd party APIs in TypeScript

The first thing to do in this case is establish if the vendor supplies TypeScript types (usually in the form of a npm package or similar). If so, just install that and you should get the support. If not, I like to use Postman to obtain the JSON returned and then use a Visual Studio Code extension such as QuickType to auto-generate types for me, based on that JSON. So you’d make the call to the API in Postman, and then copy the returned JSON to your clipboard.

In the example below, I'm using the Here Maps API. I set up the call in Postman by pasting in the URL endpoint to use, and setting up any authentication. I hit the send button, and then copy the returned JSON (in the lower pane) to my clipboard):
In Visual Studio code, I create a file to hold the interface types from the API, and then find the QuickType "paste JSON as code" option in my command palette:
I supply the name of the top-level type:
..and then QuickType generates the type structure which maps to the JSON. I might want to rename some of the types, but essentially I get interfaces for everything in the structure:

So that's great - this saves me a lot of cross-referencing and typing, and I can now use these interfaces in my calling code and get type-checking and auto-complete.

Summary


Whether it's the Graph or a 3rd party API, you should always code against defined TypeScript interfaces where possible. For the Graph, you should use Microsoft's supplied types by installing their 'microsoft-graph-types' npm package. For a 3rd party API, if no types are supplied then you can generate your own easily with help from something like QuickType.

Whatever you're doing, Postman is a hugely useful tool. In terms of the Graph, it's use gets you around the problem of Graph Explorer not executing with the same permissions as your code, and so is as valuable there as it is with 3rd party APIs.

Happy coding!

Wednesday 12 June 2019

Quick tip - filter SharePoint items by date in Flow

A quick post on working with dates in Microsoft Flow, because I know I'll need this again and I didn't immediately find something on this when I looked.

When using Flow actions such as "SharePoint Get Items", it's frequently the case that you want to filter items by a date/time field. Often you want to grab items older (or newer) than a certain timestamp - perhaps to delete/archive/take other action on them.

The easiest way is to use the getPastTime function, ensuring you format it in the right way. A clause such as the following can be used in the "Filter Query" property of "Get items":

formatDateTime(getPastTime(1, 'Month'), 'yyyy-MM-dd')

Note that this format is designed to work with a date/time field in SharePoint which is configured for "date only" format:

For dates which include the time, you'll probably need to use formatDateTime with an alternative format (sorry, I didn't test that).

Notes on using getPastTime and similar functions


The signature of the "getPastTime" method is:

getPastTime(<interval>, <timeunit>, <format>?)

The list of possible values for "timeUnit" include:

"Second", "Minute", "Hour", "Day", "Week", "Month", "Year"

As you might expect, there's also a corresponding function called getFutureTime(). To use one of them in the "Get items" action, provide a filter query in OData format which uses the internal name of your date field - something like:

MyDateFieldInternalName lt formatDateTime(getPastTime(1, 'Month'), 'yyyy-MM-dd')

That would filter items to only those older than one month for example. In the Flow designer, this should look like this:



Hope that's useful. May all your Flows execute on time and without error!

Wednesday 8 May 2019

Speaking at the European Collaboration Summit 2019 and SharePoint Saturday London!


In a few short weeks I'll be speaking at the European Collaboration Summit in Germany. This is a fantastic event with stellar speakers and quite a few folks from Microsoft. The event team go out of their way to make the show a fantastic learning event for attendees, and I highly encourage Office 365/SharePoint/Azure folks based in Europe to try and get there. Topics covered in depth will include Teams, Azure, SharePoint, Yammer and more - covered from business and technical viewpoints.

My session is:

Top Office 365 Development techniques to master - the hitlist


Things move fast in Office 365 development, and as Microsoft evolve the platform and APIs, new techniques and approaches become available all the time. As the head of a talented dev team, I regularly update my list of techniques that I believe are essential to have good capability building Office 365 solutions. Between SPFx, the Graph, Teams development, coding in Azure Functions and building solutions in PowerApps and Flow, let's walk through some high-value scenarios in mid-2019 that should be in every experienced coder's toolbox, with demos and code sample for each. This session will help you close any skills gaps, and should be a great conversation with some bright minds in the room. 

Some of the techniques I consider to be on the list include:
  • Working effectively with the Microsoft Graph from Postman (and coding against the JSON returned)
  • Calling a back-end API (e.g. an Azure Function) securely from SharePoint, with SPFx isolated web parts and AAD auth
  • Templating SharePoint sites effectively with Site Designs and PnP templates
  • Rich PowerApps which can capture images or signatures 
Of course, there are a *million and one* scenarios you could consider for such a list! However, I think any developer with those in the toolbox is quite well-equipped across some important building blocks. I'll also talk about some other techniques such as templating Teams, calling APIs from Flow, offline support in PowerApps and more.

Overall, I think it's important to be quite well-rounded these days - if you're purely a code-oriented developer with little knowledge of PowerApps and Flow, then frankly you (and your clients) are missing out. As ever, being able to select the right architecture and solution approach is vital, and knowing how the technologies fit together (in some detail) is important here.

More details on the European Collaboration Summit 2019:
ECS 2019 is being held in Wiesbaden, Germany (near Frankfurt) between May 27-29. Ticket prices are *extremely* reasonable for an event of this level! Read more at: www.collabsummit.eu

Also available in London!


If you can't make it to ECS, another great event where I'm giving the same talk is SharePoint Saturday London 2019! This is my home turf, and just like past occasions, there are lots of top-ranked speakers from around the world presenting.

For more details on SharePoint Saturday London:

The event is being held on June 1st in central London - and it's free of course! Read more at www.spsevents.org/city/London/home

Hope to see you at one of the events!

Tuesday 23 April 2019

SPFx isolated web parts – the right way to connect to your back-end API

It’s now possible for SharePoint/Office 365 developers to create *isolated* web parts, thanks to the recent release of SPFx 1.8. If your web part needs permission to talk to a back-end API or the Graph, you should strongly consider making your web part isolated. Simply having the Azure Function or other API secured with AAD authentication isn’t enough. In this post, I’ll talk through some of the details of an SPFx web part which can perform a privileged operation in your Office 365 environment (creating a Microsoft Team from a template in this case) – and therefore is something we should take steps to secure. Specifically, we want to protect the access token which is used behind the scenes, and ensure no other web parts can “piggy-back” onto the permissions we are using. Without isolated web parts:

  • Any other code on the page (perhaps from a 3rd party supplier) can sniff the access token, and potentially use it maliciously, depending on what permissions it has
  • Any standard SPFx web part can use the permissions from any other – meaning it’s a “highest common denominator” situation, where all standard SPFx web parts in the environment have the same permissions i.e. the highest that have ever been granted
These can be very valid security concerns – you’d want to be very sure about which permission levels have been granted to SPFx otherwise, and exactly what code you have in your environment. Isolated web parts can often be part of the answer in ensuring your Office 365 environment is not inadvertently insecure.

But how exactly do isolated web parts help?

Isolated web parts explainer

Web parts from an isolated SPFx package run on a unique domain, hosted within an iFrame - the permissions granted apply only to code hosted on that domain. Since regular SPFx web parts run on your *.sharepoint.com domain, the granted permissions do not apply there. And since any other SPFx isolated web parts run on a different unique domain, they don't apply there either. Essentially, the shared application principal for SPFx is not used – instead, an AAD app registration dedicated to this SPFx solution is created and used for authentication. Note this scope isn’t the individual web part, but the containing solution package. This is fine however - if you have an untrusted source contributing code to the very same solution/codebase, then you probably have bigger security and governance challenges to deal with quite frankly.

So when an isolated web part is added to your pages, you’ll see the containing iFrame – notice the source:

The source is a dynamically-created domain to represent this solution package – similar to how the old “SharePoint-hosted apps” model used to provide a separate domain for code-hosting for those who remember that. In the AD portal, you’ll also see the app registration that has been created on your behalf for this SPFx solution package:


It has a bunch of redirect URIs automatically configured, to support SPFx calling from the domain your iFramed web part code will use:

The combination of the unique domain/iFrame and dedicated AAD app registration gets around the previous trade-offs that came with SPFx and AAD integration, where a permission request for a given security scope (say, Group.ReadWrite.All – which would allow new Office 365 Groups or Microsoft Teams to be created or existing ones updated, as well as a bunch of other operations) would apply to *all* SPFx web parts and extensions in the tenant, not just the one that needed it.

So, you can see that any web part that performs a highly-privileged operation (e.g. creating a Team in my case, to continue that example) really should be isolated – especially if there’s a chance that your tenant could host web parts from different teams or providers. In this way. I am guaranteed that the only thing that can call my API is the web part(s) that are intended to - no other code in my Office 365 tenant will be able to.

Of course, without the iFrame that comes with isolated web parts, the auth token is right there in the page to be sniffed by anything else on the page:

So, isolated web parts are a good thing.

Before we talk about what configuration is needed where, let’s consider some user interface things for a second.

UI considerations with isolated web parts

Imagine you want to use some Office UI Fabric (OUIF) components within an isolated web part. That’s fine, but you need to consider the fact that your content is displayed within an iFrame which has certain dimensions – and certain UI components don’t play well with that. Let’s say we want to use a Dialog from OUIF React. In the example below, I have a button to pop the dialog, and for illustration I’ve also added a black border to my web part so you can see how big it is in the page:


When the button is pressed we get this:


Whoah – doesn’t look right. Of course, that’s because the Dialog is appearing within the iFrame only. If I extend the web part dimensions, the Dialog can be fully shown – effectively I almost need to “reserve” space on the page for any elements which are initially not visible:


And it’s the same with a Fabric React Panel. With a small web part, it’s not clear what’s going on at all:


But in this case, even using a taller web part doesn’t really help – you can see a bit more of the Panel, but since a Panel uses the full height of the screen you still won't see it all:


So, perhaps isolated web parts work better when the content is right there in the page, rather than with any elements that appear on user interaction. You’ll need to design the UI of isolated web parts accordingly.

Creating an isolated web part

Isolated web parts are created by specifying “isDomainIsolated” is true in the package-solution.json file in your SPFx project. This tells SPFx that all web parts in this package should be isolated from other web parts (but not from each other – you’d need separate projects for that):


You can specify this at any time, but the Yeoman Generator helps you out by asking this question when you’re creating a new SPFx project. A “yes” to the following question will result in the config above:


Key elements

I was slightly confused as what values I need in certain config values at first. Knowing that a new AAD app registration is created for me in AAD, is it THAT client ID that I need to use in my code? Or is it the client ID of the AAD app registration that my Azure Function uses internally to actually make calls against the Graph (since the pattern in my case is SPFx web part -> Azure Function -> Graph calls)?

The documentation essentially says that, “everything is done as normal”, but I was still a bit confused.

Here’s a summary of what you need to do:
  • Create your Azure Function app and secure with AAD authentication
  • Create your SPFx project and answer “yes” to the question about isolated web parts (or add “isDomainIsolated” : true in your existing package-solution.json file)
  • Add an appropriate “webApiPemissionRequests” section to your package-solution.json file (more on this next)
  • Write code in your SPFx web part using AadHttpClientFactory to perform the authentication against your API
  • Deploy the package to the app catalog (even if only debugging at this stage)
  • Approve the permission requests on the API management page in tenant administration
Let’s go into a bit more detail:
In package-solution.json
Add an entry into the “webApiPemissionRequests” section which corresponds to your server-side API/Function, with a scope of “user_impersonation”. IMPORTANT:
  • The AAD app reg/API to list is the one for your function app, NOT:
    • The dynamically-created AAD app for your isolated web part (e.g. “cob-teamcreatorwp” in my case)
    • Some other AAD app you have which you may be using inside your Function, but has no bearing on communication from the web part to the API (e.g. “COB Graph Access” in my case)
Your package-solution.json should therefore look something like this:

In your SPFx code
In your code, you’ll have something like this – notice that the Client ID to pass to AadHttpClientFactory is (again) the one for the Function app:

Approving the permissions:
The solution package then needs to be deployed to your tenant, and consent granted.
  • Add the package to the app catalog – notice the message that further action is needed on the Permissions Management Page, with a note about the specific permission to approve:

  • If you then head to that page, you’ll see the permission to approve:  

  • Hit the approve button if you’re satisfied with the permissions being granted. In this case, the permission will be scoped only to web parts within this SPFx package – other web parts in the tenant will not be able to use it.
Reverting back from using an isolated web part
Occasionally you might need to revert a web part back to a standard web part after it was initially defined as an isolated web part - I found myself having to do this one time after writing this article. Note that in addition to changing "isDomainIsolated" to "false" in package-solution.json and repackaging, you'll need to *remove* the SPFx solution completely from the App Catalog and then upload the new version - a simple version upgrade is not sufficient to switch. Hope that helps someone!

Summary

There are lots of ways you can stay assured of what custom code can do in your Office 365/SharePoint Online environment, but isolated web parts can be really helpful in minimising the potential for exploits. Without them, maybe something else could call your back-end API without you realizing it. Notably, Microsoft still have some work to do in lowering the code permissions required for certain operations (e.g. posting a message in a Teams channel requires Group.ReadWrite.All, and certain Planner actions are similar), but hopefully that will come soon.

It’s also worth considering exactly what permissions are required where. If you make calls to the Graph via a back-end API, then maybe SPFx only needs permissions to call *your* API, and the separate AAD app registration used by your back-end has the permissions to take real action. Obviously that can reduce the surface area considerably.

Either way, isolated web parts can play an important role in balancing security with functionality in Office 365. I'll publish the full source code for my Teams Creator web part and Azure Function API in a future article.

Further reading:
https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/isolated-web-parts

Friday 8 March 2019

Create Microsoft Teams from a template

One thing we’ve been waiting for is the ability to create many Teams from a template, in the same way that many organisations do with SharePoint sites. Microsoft have now released this (in preview at the time of writing), and we can define a template in JSON defining exactly what the Team should look like, including the channels, tabs, installed apps, owners and various configuration settings. This is great, because we can now work on scenarios such as a project team, which might have channels for “Technical”, “Account management”, “Project delivery”, “Client success” and so on. You can imagine various tabs being defined in the different channels - perhaps the Account Management channel would have a tab with a widget to bring in summary data from CRM. Maybe the Technical channel would have a tab displaying current work items from Azure Dev Ops too. Apps being made available across many Teams could be 3rd party apps available in the Teams store, or something custom that has been developed in-house.

The things you need to work with templated teams can be summarised as:



So this is all quite developer-led. It isn’t as though the template is being stored in the Teams service somewhere for example - ultimately a dev is writing code to pass some JSON to a call to the Graph. And this JSON contains all details for team creation – the name, the description, the channel settings, installed apps and so on. As I’ve been working with the API, I’m finding that some code which splits out building the JSON somewhat is useful. In particular, it seems useful to split it into two parts:

  • Things that change for every team being created (name, description, owners)

    ..and..

  • Things that stay the same and are considered part of the template (channel settings, installed apps and so on)
So this post is to provide some simple code around that in case others find it useful. There’s nothing too complex here, but I’m trying to get more in the habit of sharing little bits of code via Github.

For details on the JSON structure and the Graph call, see https://docs.microsoft.com/en-us/graph/api/team-post?view=graph-rest-beta. As the documentation shows, the sample JSON to create a team might look like this (this is the very sample from docs):

So, although we’re constructing this JSON and passing it to the Graph, a developer working with this might choose to:

  • Create a static JSON file with the non-changing parts, and treat this as the “template”
  • Write some code to append JSON representing the team name, description and owner(s)

You might notice from the extract above that the owner needs to be specified in the form of a GUID, rather than what you most likely have (the user’s account name/e-mail address). This GUID is the user identifier in AAD. Consequently, we’ll also need a method in our code to lookup a user GUID from an account name.

What exactly can we define in a Teams template?

Here’s a summary:

Setting Example
Visibility Public/Private
Installed apps [Any app from app catalog]
Owners [List of users]
Channel details Tabs, favourite by default
Member settings Allow create channels, allow add apps etc.
Guest settings Allow create channels, allow delete channels
Fun settings Allow giphys, stickers and memes, content rating
Messaging settings Allow edit/delete of messages, allow team and channel mentions

The code

The main helper code I wanted was a method I could call which would accept parameters for the team name, description, and owner(s) so I could call it many times. Perhaps it could become the core code behind something that reads from an Excel file to create many Teams in bulk. Or perhaps it would be behind a custom form in a nice end-user self-service request process. In terms of authentication, this code uses app-only auth to create the Team (using an AAD client ID and client secret), rather than delegated auth (in the context of the user). But, you can take either approach depending on your needs.

So, the core code I came out with is (shown here in the context of a simple console app - but you can drop the core method into whatever you need):


You might notice that I have a “TeamDetails” class which is also doing some of the work. This is where the code to manipulate the JSON is, providing methods to append the team name, description, and owner(s) to the other details being specified:


Of course, the full code is available in Github – it’s at the following address: https://github.com/chrisobriensp/TeamsProvisioning

The result

We can now create as many teams as we like wih the CreateTeam() method shown above. Each one will be created with the channels, tabs and other properties specified in the template. For example, here are the channels and tabs as defined in the sample JSON shown above:



Summary

Creating many Microsoft Teams in a consistent way with the right set of tools is now possible, and we can do it with app-only permissions too (so no need to do anything dodgy around storing details of a high-privilege account). You might find the code in this article useful if you start working with the Graph API methods to do this. In addition to creating Teams with the 'standard' template, note that Microsoft themselves are also providing some specific base templates baked-in to the service - and these might suit your needs out-of-the-box. For now, these base templates are targeted at education, retail and healthcare scenarios - but more will come in the future no doubt.

Either way, we have some new options for rolling out Teams with specific functionality. Hopefully the Graph methods which underpins this will come out of preview very soon, so this approach can be used in production solutions.