Tuesday, 19 June 2018

Running a PowerShell script in the cloud with an Azure Function, PnP and the Graph

We all know that Azure Functions are really useful in many Office 365 scenarios, and this goes beyond developers. IT Pros can certainly benefit from the ability to run a script in the cloud – perhaps it’s something you want to run every hour, day or week on a schedule, and maybe you want to use PnP PowerShell too for its awesome commands around managing Groups/Teams, provisioning of SharePoint sites and more. This post is aimed at anyone who has such a need – we’re going to use Visual Studio Code (not full Visual Studio) for some bits, but that’s just because it’s becoming a great PowerShell editor even for non-coders. In fact, I’m now convinced that VS Code is the best option for PowerShell scripts regardless of who you are. If you’re a dev, you’ll probably like the way VS Code can deploy your files to an Azure Function, but for IT Pros or anyone less comfortable with this, I’ll also show how you can drag and drop the script (and related files which make it run as a function) to the cloud. In both cases, we’ll benefit from VS Code’s support for creating the function with the right set of files, the code formatting/coloring and the ability to debug our script.

The scenario we’ll use is creating Office 365 Groups (but if you’re interested in a Flow approach to this, also see my Control Office 365 Group creation – a simple no-code solution post) – I like this scenario because with a tiny tweak, in the future it will be possible to create a Microsoft Team also, which is arguably more useful. We’re just waiting for the app-only APIs for that one, although you could do it today with user context if you needed to.

There are many ways of creating an Azure Function these days, and I’ll cover these in a future post. So as mentioned, IT Pros shouldn’t be scared of this, but we’ll use:

You should follow these links to download/install those things if you don’t already have them.

Steps we’ll go through

I’m going to try to be fairly comprehensive in this post with lots of screenshots. Here’s what we’ll cover:

  • Overview of PowerShell script contents
  • Installing the PnP PowerShell module
  • Registering an Azure AD app to talk to the Graph
    • Granting admin consent to this app by constructing and hitting a consent URL (which is interesting if you’ve haven’t seen this process before)
  • Create the Function locally using VS Code, using PowerShell as the language
    • Debugging/stepping through the function
  • Prepare for running in the cloud - copy files from SharePointPnPPowerShellOnline module into local folder
  • Create the Azure Function app in the portal
  • Publishing the files to the function:
    • Using VS Code
    • Using drag and drop with Kudu
  • Testing the function
  • Final step – storing App ID and Client Secret securely
Update – consider storing credentials in Azure Key Vault now it has hit General Availability
Later in this post I’ll show how we register an app in AAD to talk to the Graph, which has credentials in the form of an app ID and secret. I show storing these away from the code in Azure environment variables, but there’s a better option now. Azure Key Vault provides the ability to securely store these, where you define “who” can access them (e.g. which Azure functions, or other things which provide a service principal).
Two of my friends have great articles on this:

    Overview of PowerShell script contents

    Let’s start with the script, just so you can see how simple it is. We won’t do anything with it yet, but here it is for your info – notice that the example we’re using (creating an Office 365 Group) is very simple if you’re able to use the PnP command (New-PnPUnifiedGroup) and have an AAD app registered.

    Here are the script contents I used:

    With that in mind, let’s deal with the prerequisite steps such as obtaining the PnP PowerShell module and registering the AAD app to be able to create Groups.    

    Installing the PnP PowerShell module

    There are a couple of ways to install this, but the PnP PowerShell page has everything you need - full instructions and links to installers. See:

     https://docs.microsoft.com/en-us/powershell/sharepoint/sharepoint-pnp/sharepoint-pnp-cmdlets?view=sharepoint-ps

    Registering an Azure AD app to talk to the Graph

    If we’re using a PnP PowerShell command that talks to the Graph (as I am to create Office 365 Groups), then we need an AAD app registration which our script/code will use to authenticate. We define this with appropriate permission scopes for the actions we’re actually performing – the process below shows what I need to do to create Groups, but if you’re using a different script which does something else, then most likely you’ll need other permission scopes.

    1. In the Azure portal, go to the “Azure Active Directory” section and find the “App registrations” area:
      SNAGHTML41e995b
    2. Click the “New application registration” button:
      SNAGHTML41f91c4
    3. Complete the details – note in this case the sign-on URL can be anything that uniquely identifies your function:
      SNAGHTML42f55f6
    4. Hit the “Create” button.
    5. We now need to grant the appropriate permissions to this app registration:
      1. Go in to the “Settings” area, and select “Required permissions”:
        SNAGHTML4379a0d
      2. Click the “Add” button, then “Select an API” and find and select “Microsoft Graph”:
        SNAGHTML43a2fcb
      3. In the “Application Permissions” section of this list, check the box for “Read and write all groups”:
        SNAGHTML43bb969
      4. Click “Select” and then “Done” to save this config.
    6. Now we need to obtain the app ID for our PowerShell script – it can be copied from the settings area. Store it somewhere safe for later pasting into our PowerShell script:
      SNAGHTML435dc21
    7. We also need to obtain a key. This can be done by:
      1. Going into the “Keys” area:
        SNAGHTML43e1c6f
      2. Give the key a name – when you click “Save”, the key value will appear in the box:
        SNAGHTML4337eb8
        SNAGHTML4346511
      3. Again, store it somewhere safe for later use in our PowerShell script.

    Grant admin consent to the app

    Now that we’ve defined our AAD app registration, a tenant admin needs to grant admin consent to the app. This is the security gate which means that the organization is permitting this access to Office 365 data. What happens is that you construct a URL in the form of:

    https://login.microsoftonline.com/[tenant].onmicrosoft.com/adminconsent?client_id=[App ID]

    So for my app, the URL looked like this: https://login.microsoftonline.com/chrisobriensp.onmicrosoft.com/adminconsent?client_id=348841f1-6c9d-4044-b014-ed346f2572f2

    When the tenant admin hits this URL, he/she sees the list of permission requirements for this app and can make a decision whether to grant consent or not:

    SNAGHTML45a381c

    Once consent is granted, the app can request auth tokens which can perform actions related to the selected permission scopes. Read more about this process at Tenant Admin Consent if you need to.

      Create the Function locally, using PowerShell as the language

      OK, now the pre-reqs are in place, we’re ready to create an Azure Function to run our PS script from.

      1. First, create a folder on your machine to host the files – I named my folder “COB-GroupCreator-Function” to reflect what we’re doing here.
      2. Open VS Code to this folder.
      3. Hit CTRL SHIFT + P for the VS Code command bar, and start typing “Azure Functions” to pull up those commands. Select the “Create New Project” command:
        SNAGHTMLfff7b5
      4. Follow the prompts in the command bar to select the folder – accept the default if you’re already in the folder you created earlier:
        SNAGHTML1568088c
      5. When it comes to selecting a language, select any for now – but in this case we said we’d use PowerShell. PowerShell doesn’t appear in the list currently because support is only experimental (as at June 2018), but we can switch to it later:
        SNAGHTML1569e4bf
      6. Now let’s add an individual function. Hit CTRL SHIFT + P again, and find the “Create Function” command under Azure Functions:
        SNAGHTML156d23fb
      7. Accept that we’ll use the current folder:
        SNAGHTML156f43bf
      8. In the next step we can change the language to PowerShell:
        SNAGHTML1572184b
      9. Select PowerShell from the list:
        SNAGHTML1574f870
      10. In the next step, we need to include “non-verified” templates whilst PowerShell support is still experimental – select the “Change template filter” option:
        SNAGHTML15764032
      11. Select “All” from the list:
        SNAGHTML15778ca8
      12. And now additional templates appear – in this case, our function is going to be a simple function which runs once per day, so we’ll select “Timer trigger”:
        SNAGHTML159ee9ae
      13. Now enter the name for your function:
        SNAGHTML15a0bb42
      14. For a function which runs daily at 10am, the CRON expression would be “0 0 10 * * *”, so let’s enter that when we’re asked for the schedule for the function by the way, here’s a good cheat sheet for other CRON expressions):
        SNAGHTML15a49c1e
      15. A bunch of new files will now be added to your folder, including the “run.ps1” file which is the PowerShell script for your function implementation:
        SNAGHTML15a731ad

      We’re now ready for our function implementation. Except to say, if you’re following these steps when PowerShell support is still experimental, you may still have some leftover JavaScript config if you did this. Let’s fix that next.

      Debugging our PowerShell script locally with F5

      VS Code works great as a debugger for PowerShell scripts. The best approach is to get your PowerShell script 100% correct by developing and debugging locally before publishing it to the cloud as an Azure function. You’ll be able to stop on breakpoints, see variables and so on – doing this locally is much easier than when you’re running in Azure on a daily schedule (although you have options for that too).

      So, all we need to do is remove the JS config from our launch.json file. Find it in the .vscode folder:

      SNAGHTML15bee9e2

      Remove the section for the JS configuration – before:

      SNAGHTML15c009c9

      after:

      SNAGHTML15c08ed7

      VS Code is now smart enough to do the right thing based on your .ps1 file extension. You’ll find that you can hit add a breakpoint to your script (which is currently still just a single line of boilerplate code) and hit F5 to debug locally:

      SNAGHTML449f5a3

      You can actually do lots more to customize what happens when F5 is pressed – for example, if your PowerShell scripts accepts parameters and you want to pass some values in when debugging. This is done by adding back some PowerShell specific configurations into your launch.json file – see Using the launch.json file in VS code for improved PowerShell debugging for some examples of this. But even without this, we’re now able to step through our script locally and get the feedback we need to develop and test it properly.

      Prepare for running in the cloud - copy files from SharePointPnPPowerShellOnline module into local folder

      We now need to copy the files from the SharePoint PnP PowerShell module into our local folder. This isn’t necessary for running locally – the files will be loaded from your local modules path for that (which can be found using $Env:PSModulePath in PS) – but it is necessary for when the script runs as an Azure Function. So, let’s find the files on your local machine by running $Env:PSModulePath – you should see a bunch of paths in there, but one of them will be for the SharePointPnPPowerShellOnline module: 

      SNAGHTML4763bbe

      Open that folder on your machine and copy the “Modules” subfolder and all it’s contents into the folder containing your PS script for your function.

      Your set of files should now look like this:

      SNAGHTMLfd0159

      When your script runs in the cloud, the Azure Functions runtime will now load any modules stored in this folder and you can therefore use the PnP commands successfully.

      Paste the script contents into run.ps1

      Now we're ready to deal with the script implementation. Paste in the script we've seen already (repeated below for your convenience), or implement your own steps.

      You’ll need to substitute in values for your AAD app ID, AAD app secret (key) and Office 365 tenant prefix into the placeholders/variables in the script – for now, let’s do that in a hard-coded way to test our script. Later on, we’ll swap out these hardcoded values and fetch them from config in Azure instead.

      As a reminder, here are the script contents I used:

      Once you've pasted those details in, run your script to check it works (by pressing F5 in VS Code). If your AAD app is registered with the right details and permissions, and you have the PnP PowerShell module installed properly, things should work just fine when running locally. Hooray! If not, you should work through the issues until you're successfully running locally before publishing to an Azure Function.

      Create the Azure Function app in the portal

      We need an Azure Function app to host our script in the cloud. You can actually create this through VS Code (use the command “Azure Functions: Create Function App in Azure”), and it works great! However, for simplicity let’s do it the normal way through the Azure portal. Even there, we have a couple of options but anything that gets you to the create function app process is good – for example:

      1. Click “Create a resource”:
        SNAGHTMLe7bd811
      2. Start typing “function app” to search for the item – select it when you find it, and then hit the “Create” button:
        SNAGHTMLe7cfece
      3. Then complete the details – you can see in the image below I’m reusing some things I already have in Azure (e.g. a Resource Group, Storage Account etc.) – but just create new ones if you need to. Of course, be aware of the selections you make if you’re doing this for real in production (especially whether you’re choosing the Consumption Plan or App Service plan). Hit the “Create” button when you’re ready:
        SNAGHTMLe7eade6
      4. Your function app, as well as an App Insights instance if you selected that option, should now have been created and are ready to host code:

        SNAGHTMLe83a189
      A note on authentication
      In this case, our function won't actually have *any* authentication for callers, because we're never going to call it over HTTP in this case (which might be different to other functions you create). This one is purely a timer trigger function.

      Publishing files to an Azure Function from VS Code:

      The next step, once we’re sure the script is working correctly, is to publish it to an Azure Function. You can do this in a variety of ways, but VS Code makes this easy:

      1. Switch to Azure tab in VS Code (bottom icon):

        SNAGHTMLbf4881
      2. Find the Function App you created earlier. Right-click on it, and select “Deploy to Function App”:
        SNAGHTML1ea4112d
      3. Step through prompts in the VS Code command palette – the defaults are generally what you need:

        SNAGHTMLc1f726
      4. Accept the prompt:

        image

      5. VS Code will then start the publish operation:

        SNAGHTMLc9b489
      6. You’ll then find that your files have been deployed as a Function to the selected Function App:

        SNAGHTMLe32952

      ALTERNATIVE – DEPLOY FILES A DIFFERENT WAY

      Of course, you don’t *have* to use VS Code to publish files up to your function app. Anything that gets your files there (FTP, manual copy via Kudu, web deploy, sync from source control) is fine – you just need to ensure the files end up in the right structure. This is what you need to end up with:

      SNAGHTMLe3dca72

      SNAGHTMLe3e7ccb

      To deploy the files using Kudu, simply drag and drop them from Windows Explorer into the site/wwwroot folder within Kudu:

      SNAGHTMLe49905d

        Final step - Storing App ID and Client Secret securely

        At this point, you should now have your script running successfully in the cloud. It should execute on the schedule you defined for the function or from using the “Test” button in the Azure portal. But remember that we hard-coded some values for the app authentication into the script – we need to fix that.

        A better option than having these values hard-coded in your script is to add App Settings to your Azure Function app, and read them from there. They are stored securely by Azure, although you could take this further and use Key Vault or similar if preferred. Either is better than having secrets/passwords in code or scripts! In the next steps, we’ll define them as app settings in Azure and tweak the script to pick them up from there:

        1. Go to the Platform Features tab, then select “Application Settings”:

          SNAGHTMLcdcce0
        2. Scroll down to the “Application Settings” section, then click the “Add new setting” link:

          SNAGHTMLd053c9
        3. Add the App ID and secret for the Azure AD app registration which has permissions to do the work (create an Office 365 Group in our case):

          SNAGHTMLd282fd
        4. Also add an item for your tenant prefix and name it “Tenant”.
        5. Don’t forget to click “Save” back at the top of the page:

          SNAGHTMLd30906
        Accessing App Settings from PowerShell in a Function
        App Settings can be retrieved by use of the $env:[MyAppSetting] syntax in PowerShell, similar to an environment variable. So in our script, we simply use the following to match up with the keys we added our config values with:

        $env:AppID 
        $env:AppSecret 
        $env:Tenant

        What this means is that our final script should look like this:

        Voila! Your script should now run from the cloud and be implemented in the way it should be. I won’t show end end result of this example (an Office 365 Group) because you most likely know what that looks like, but hopefully you get the overall idea and the steps involved.

        Summary

        The idea of running PowerShell scripts from the cloud is very useful, especially for scripts which should execute on a schedule. Our scenario of creating an Office 365 Group isn’t necessarily something you’d want to do on a schedule (or maybe it is, if you need a collaboration space for a weekly meeting or other periodic event?) However, the power of PnP PowerShell means that there are many scenarios you could deal with in this approach. We showed how to get external modules like PnP running in your Azure Function, and also how to deal with the authentication to the Graph if needed – overall, it’s a powerful approach that can be useful to both IT Pros and developers. I recommend using Visual Studio Code to work with PowerShell these days, especially since it helps package and deploy Azure Functions as well as providing debugging support. Happy coding!

        Wednesday, 23 May 2018

        Updating your SPFx web part/extension – the nuclear approach

        SNAGHTML2356ad3One situation that Office 365 and SharePoint developers will encounter more and more is the need to upgrade an existing SharePoint Framework (SPFx) project to a later version of the framework. SPFx gets updated fairly regularly, and as more and more development moves over to this approach, you’ll find that when you go back to enhance or maintain an existing solution, more frequently it’s SPFx code that you’re going back to. When you do, you have a decision – should you upgrade the SPFx version of the web part/extension while you’re making your code changes? Of course, you don’t have to (and maybe there hasn’t even been a new version of SPFx since your original release). But maybe you want to take advantage of some newer SPFx features – or maybe you just want to stay current and benefit from some possible performance or developer enhancements.

        The pains of upgrading a project

        Unfortunately, updating an SPFx application is often not as easy as it should be – you’ll often run into build errors when you run a gulp serve or gulp bundle until you’ve got everything straight. Most of the guidance you’ll see advises you to use ‘npm outdated’ to identify packages with newer versions, and then updating them individually (with npm install [package]@[version]) – indeed the SPFx docs have a useful page on this approach at Update SharePoint Framework packages. I recommend always trying this process first. However, I find that sometimes you need some extra steps too. I upgraded a project yesterday and ended up using a slightly different process to get to a working build, so I thought that would be a good topic to briefly discuss.

        One issue you can hit with the npm outdated/npm install [package]@[version] approach is if there are new or removed packages which make up the new SPFx version you are moving to. In this case, simply updating your existing packages isn’t enough.

        The nuclear approach – a recipe

        Sometimes the right thing to do is to be a bit more drastic. You could certainly create an entirely new SPFx application and merge your code into that – but that’s too drastic. It’s a lot of work, and I’ve yet to see a case where it’s actually necessary. The process below is somewhere in between – it’s based on creating a new SPFx project on the latest version, merging the package.json files to ensure you end up with all the right packages at the expected versions and then rebuilding the node_modules folder based on that. I’d use it when:

        • Updating existing packages using npm outdated/npm install@version doesn’t work (still getting build errors)
        • I was confident the previous build is in source control, including a package-lock.json file (so I could revert everything back if needed)

        The process would be:

        • Install the latest Yeoman generator version
        • Create a new temporary SPFx app (web part or extension, to match the application you’re updating)
        • Merge the package.json from the temporary app into yours
          • The aim is to have all packages needed – all the SPFx packages for the new framework version, AND any other packages you have previously installed for this web part/extension
        • Remove any package-lock.json or npm-shrinkwrap.json files from local directory (but do not remove from source control - you still might need to go back to a previous build)
        • Delete everything from node_modules
        • Run npm install
        • Make any tweaks to tsconfig.json if needed - newer SPFx versions sometimes need a change here too
          • Build errors should point you to the solution for these. When running an upgrade to SPFx 1.4.1 recently, I needed to add an entry in my “lib” section for “es2015” – but look for build errors for the specific tweak you need
        • Run gulp clean (to delete previous build outputs)

          At this point, you should have a working build again when you run gulp bundle or gulp serve. If you do, and you’re comfortable everything is working, you should:

          • Commit to source control
            • Ensure your package-lock.json file is included – this represents the node_modules tree for this build, and you need it to recreate the build (since you won’t be checking-in the node_modules folder itself)
          • Continue making the code changes you actually came here to do :)

            Other notes

            • Extra care needs to be taken for on-prem SPFx projects. The npm repository holds latest versions of packages, but remember that when you’re on-prem you’re frozen at a certain version of SPFx packages (not what the npm repository holds as the latest version). So, your package.json file needs to reflect the appropriate versions for your on-prem build.

            Good luck!

              Thursday, 10 May 2018

              Licensing for push notifications in PowerApps/Flow

              If you’re doing more with PowerApps and Flow in Office 365, sooner or later you might hit an interesting question if you want to use a premium connector – just who needs the P1 or P2 license? Premium connectors require extra licensing to what comes with Office 365 E1, E3 and even E5, and the licensing requirements can vary depending on the connector and how it is used – meaning costs can vary too. The one I’m focusing on here is push notifications – let’s say you’re building a PowerApp or using a Flow, and you want to send a notification to a mobile device when something happens (i.e. an alert on the device, rather than an e-mail or SMS). In this case, you’ll most likely find your way to the PowerApps push notification action (a premium connector). Whilst there is also a Flow push notification, that one can only send to the Flow owner – but frequently, you want to send the notification to some kind of approver or recipient, not the person who created the Flow. So, the PowerApps Notification is probably what you need – but don’t be fooled by the name. This thing isn’t constrained to use with in a PowerApp (e.g. a button click) - it can also be used within a Flow (e.g. when the Flow gets to a certain stage). Here’s what it looks like there:

              PowerApps notification - in picker

              [SNAGHTML109f23cb%5B5%5D]

              Who needs the license?

              So the question you get to when you need to notify many people is “who exactly needs a P1/P2 license?”

              • Is it just the user/sender? (which in this case, would be the user who the Flow runs as)?
              • Is it every recipient?
              • Is everyone who could be a recipient?

              It’s an interesting one and I couldn’t find the answer in the documentation. We had the situation come up in some work for a client, so I reached out to a friendly contact in Microsoft (thanks Dan!), and he did some digging internally to find out.

              The answer

              In fact, it depends on how your Flow is triggered – since it can be done by a user action, or indirectly through an event:

              Triggered

              Who needs the license

              License type required

              Manually Any user of the app which triggered the Flow (e.g. your PowerApp, Flow button or other app)
              • Flow is triggered by PowerApp –> PowerApps P1
              • Flow is triggered by Flow button –> Flow P1
              By an event (e.g. new item in a SharePoint list, new file in OneDrive etc.) Just the Flow author
              • P2 (Flow) – * but see my caveat below

              It’s worth being aware that these P1 and P2 additive licenses come in both PowerApps and Flow flavors – but PowerApps licenses always include Flow capabilities. PowerApps licenses are correspondingly more expensive since you unlock the whole, um, power of PowerApps too. Broadly the idea is that:

              • Users creating “basic” PowerApps (e.g. canvas apps) need a P1 license - currently $7 per user per month for PowerApps P1
              • Users creating “advanced” PowerApps (e.g. model-driven apps, business process flows, entities in CDS etc) need a P2 license (currently $40 per user per month for PowerApps P1

              For many PowerApps, that will mean the P1 license is sufficient though (in my view).

                Also note that if you’ll only use Flow and never PowerApps, maybe you just need Flow P1/P2 licenses. These are much cheaper than PowerApps P1/P2 licenses (currently $5 per user per month for Flow P1, $15 per user per month for Flow P2).

                * By the way, with reference to my table above, my understanding is that if you have a PowerApp which adds a SharePoint list item (or file to OneDrive etc.), then a PowerApps license is required for the user – not just a Flow license. After all, the event is really being triggered by the PowerApp – rather than it being a purely indirect thing, from a manually added list item/file for example.

                If you need to know up-to-date pricing, see the PowerApps plans pricing and Flow plans pricing pages. Another good resource (along with licensing examples) is the PowerApps licensing overview page – this has some great info, but it just didn’t have the detail I needed around premium connectors and recipients.

                Other scenarios

                Maybe you want to use the PowerApps push notification purely within PowerApps (i.e. not in Flow). In this case, there are similar considerations:

                • Makers of the app which has the Push Notifications connection need a PowerApps P1 or P2 license (as you’d expect)
                • Users of the app need a PowerApps P1 or P2 license (also as you’d expect, since this is a premium connector remember)

                But there’s an interesting possibility if it’s a different PowerApp which receives the notification (in the PowerApps world, it’s possible for one app to send the notification and another to be receive it). In this case:

                • Users of the recipient app do NOT need a PowerApps P1/P2 license – their Office 365 license is sufficient
                  • (This is because this app does not use the Push Notifications connection)

                So, that’s definitely a trick which might be helpful, so long as the implementation details are OK with your requirements (i.e. you are able to split your app in this way).

                Summary

                There are definitely a few complexities around licensing of PowerApps and Flow, and as you build more solutions with them there are more scenarios to consider – in fact, . I’m really not trying to be the man to answer all your licensing questions here though :) You’ll need to contact Microsoft if the above links don’t have the detailed information you need, as they’ll give a better answer than I ever could. However, I thought some folks might run into the same questions that I did, and I figured some of this info needs more prominence.

                Have fun building your solutions!

                Wednesday, 4 April 2018

                Control Office 365 Group creation – a simple no-code solution

                In the Microsoft view of the world, every user in an organization using Office 365 should be able to create Groups – and remember that they can be created from Outlook, Microsoft Teams, Planner, Power BI, SharePoint and so on. However, in the real world it seems there are few large enterprises willing to go with that. Personally I’m not surprised. I think there are many reasons to introduce more governance – perhaps you want to collect some metadata about the requestor/group/business unit/division, or perhaps you just want an admin to check this is a genuine/justified request. Or maybe you want to check if a SharePoint site already exists for this, because you’ll do something different if it does (e.g. “Groupify” that site instead). Of course, it’s possible to lock down Group creation to a central admin team using the "GroupCreationAllowedGroupId" approach (see Manage who can create Office 365 Groups) - however, unless you supplement this with something else (such as have users raise a support ticket when they need a new group) you have no real user-facing “request process”.

                So what if we could have a really simple no-code solution using purely out-of-the-box things in Office 365, based on a simple SharePoint list which we could point users to, with Microsoft Flow providing the approval steps to get the control we need?

                Of course, you might not care too much about the concept of Office 365 Groups itself. But you might care about providing Microsoft Teams or SharePoint sites to the business, or one of the other more functional things built on top of Groups. The solution outlined here may become even more valuable when Office 365 allows a Team to be provisioned alongside a Group – we’re currently waiting for APIs around this, but it’s on the way soon. So, consider the solution outlined here to be a Teams provisioning solution in the future, not just the Groups provisioning solution it currently is.

                In implementation terms, I’ve seen many articles showing slightly different ways of provisioning Groups and sites in Office 365, but nearly all use some custom code e.g. an Azure Function. One of the nicer ones is Martina Grom’s series starting here, but I was wondering if there was a simpler approach. Azure Functions are great of course (I’m giving a talk on them at the European Collaboration Summit 2018 in Germany soon) – but unless the organization is already using Azure for code hosting, it can introduce some barriers. This is because an Azure subscription is suddenly needed, someone is asking about forecast costs (even though us devs know they are low on a consumption plan), someone needs to sign-off and so on. Or, you might just prefer a no-code solution for other reasons. So..

                Implementing controlled Group provisioning with a SharePoint list, a Flow, and the Graph

                The ingredients for this solution are:

                • A SharePoint list
                • A Flow (with just a few actions)
                • An Azure AD app registration (to allow calling the Graph)

                Yes, we do need to do *something* in Azure. We need to register an application and grant it permissions to create Groups and add users to them. But you don’t need any pay-for Azure for this, since Azure Active Directory is bundled with Office 365 and you’re just registering an application there so that your Flow can call the Graph. As we said before, there’s no code running anywhere – so no Azure Functions, queues, databases, storage or anything like that.

                Our completed Flow looks like this:

                Group creation Flow

                As you can see, there are a couple of extras beyond simply creating the Group, which I think you would want in the real world:

                • Groups get added to a separate “Created Groups” list – otherwise, our ‘requests’ list wouldn’t help us understand if any Groups actually failed to create and don’t exist. In the Created Groups list, we add the Group ID (which might be useful to administrators), and you could easily extend this to add other data
                • We add the person who requested the Group to be Group owner – otherwise, he/she doesn’t have permission! This is something of a gotcha, since you’d either need I.T. to do a manual step for each one (which kind of defeats the purpose of an automated Group provisioning system).
                  • N.B. there is some complexity to this in Flow, and that’s what the latter steps of the Flow are all about – parsing some JSON to obtain the ID of the created Group and the user who requested the Group, and then making a separate call to the Graph to add this user as Group owner. But still, it *can* be done without code.
                Approval step

                NOTE – one thing I’m excluding in my Flow/the details in this article is the actual approval step which gives you the control. This is an exercise for the implementer, since it’s trivial to implement in Flow and everyone’s requirements might be a little different (e.g. one-level/two level approval, different recipients etc.). This is typically done with the “Start an approval” step in Flow.

                The key – calling the Graph with Flow’s HTTP action

                As I showed in 5 ideas for using Flow in your applications, it’s possible to easily create an Office 365 Group (or do MANY things around users, mail, calendar, files and so on in Office 365) by having your Flow call the Microsoft Graph. For many developers, this is simpler than code because there is none of the complexity around obtaining an authentication token (which varies depending on where you are calling from). The simple HTTP action in Flow can be used for this:

                SNAGHTML61e70c

                This works because it has a way of providing authentication details to the specified endpoint – to be precise, we use the Client ID and Client Secret of our AAD app registration. This is one way of authenticating with the Graph (known as the OAuth “Client Credentials” grant), which itself works from code, a Flow, or anything else which can call over HTTP. The config steps are simple. But let’s start with the SharePoint list..

                Step 1 – create a SharePoint list for Group requests

                All that’s needed here is a simple list for users to visit when they need a new workspace for their team. Add columns for:

                • Group short name
                • Group display name
                • Group description

                N.B. You could combine the ‘Title’ field of the list with the Group display name or similar – I kept them separate (to perhaps use the Title for some other descriptive text), but up to you. So my list looks like:

                SNAGHTML2514c402

                ..and then the form looks like this:

                SNAGHTML25cdc45c

                OPTIONAL – create a 2nd SharePoint list named something like “Created Groups” to track successfully created Groups. The steps I provide later to configure the Flow are based on this approach – I simply add a field for “Group ID”, although you could extend this to include the URL, owner and whatever other fields are useful:

                SNAGHTML3a4a197e

                Step 2 – configure an Azure AD app registration

                The other thing we need is an AAD app registration. You’ll need permissions in Azure to do this, but the following screens walk you through:

                SNAGHTML25d10dea

                In the next screen, the sign-on URL can be anything you like when being used with Flow – just use something logical:

                SNAGHTML25d1c718

                Then go into the Settings for the App Registration, and select ‘Required permissions’:

                SNAGHTML25d30574

                Click ‘Add’, and then select ‘Microsoft Graph’.

                In the next screen that appears, find the ‘APPLICATION PERMISSIONS’ area and in that section, select the following:

                SNAGHTML25d5651e

                Click ‘Done’ to complete.

                You’ll also need to ensure the user that the Flow runs as has consented to the permissions. The simplest way to do this is actually grant permissions to all users in the tenant, since this can be done easily with the Grant Permissions button:

                SNAGHTML3a32a299

                Otherwise you need to write some code which uses this AAD registration and can prompt the user to consent (in a browser session logged in as the user who owns the Flow). In this case, you might legitimately decide that the permissions that this app has are not too far-reaching, and applying the consent to all users is fine. 

                Step 3 – implementing the Flow

                OK, so let’s move to the main config step – configuring the Flow. There are two ways you could do this:

                • Import the Flow that I’m providing at the link below, and reconfigure a couple of things
                • Create the Flow yourself, and configure the same actions – I provide some info in the table below if you choose this route
                Option 1 – import the Flow I provide:

                You can download my Flow from this link:

                https://github.com/chrisobriensp/COBGroupCreationFlow/blob/master/COBGroupCreationFlow.zip 

                To import, go into the Flow area in Office 365 by finding the Flow icon in the app launcher. Once in there, you should see an option to import:

                SNAGHTML3a5a3c99

                You’ll need to do the following once the Flow has imported:

                1. Define a new SharePoint connection (or use an existing one) so that the Flow can connect to your SharePoint lists
                2. Edit Flow – overwrite the following settings:
                  1. Edit all the HTTP actions (the green ones) – for each, enter YOUR AAD app registration details:
                    1. Tenant (this is also known as the Directory ID of the AAD directory you’re working with – you can get this from the Azure portal, in the “Properties” area for your Azure Active Directory)
                    2. Client ID
                    3. Secret
                  2. Edit the “When an item is created in Group Requests list” action – for this, you need to select the “Group Requests” SharePoint list you created earlier. There’s a slightly non-obvious thing here – you need to select “Enter Custom Value” from the dropdown, and you will then be allowed to type/paste in the the site URL where your list is. Once this is done, the 2nd dropdown should display all the lists in the site, and you can pick the right one
                3. Save the Flow
                4. Test!
                Option 2 – create your own Flow, and configure the right actions:

                If you prefer to create the Flow yourself, you’ll need to go to the “Group Requests” SharePoint list you created first. Click the “Flows” button on the command bar, then create a new Flow. Select the “when an item has been added” option. Here’s a high-level view of the actions to add to the Flow:

                Action to add Purpose/name Steps you need to take
                HTTP Create Office 365 Group (team space)

                In this action, you’re making a POST request to the following Graph endpoint:

                https://graph.microsoft.com/v1.0/groups 

                Reference the Create Group documentation in the Graph to understand the headers and body to pass. Make sure to drop in variables for the values for the mailNickname, displayName and description of the Group.

                Also specify details for your AAD app registration:

                - Tenant ID

                - Client ID

                - Secret

                Parse JSON Parse JSON (created Group details)

                Parse response body from previous action - the purpose is to get the ID of the Group that was just created (so that we can add a Group owner later, and also to log the Group ID to the “Created Groups” list).

                Paste the following into the ‘Schema’ box:

                {

                "type": "object",

                "properties": {

                "id": {

                "type": "string"

                },

                "description": {

                "type": [

                "string",

                "null"

                ]

                },

                "displayName": {

                "type": [

                "string",

                "null"

                ]

                },

                "groupTypes": {

                "type": "array",

                "items": {

                "type": "string"

                }

                },

                "mail": {

                "type": "string"

                },

                "mailEnabled": {

                "type": "boolean"

                },

                "mailNickname": {

                "type": "string"

                },

                "securityEnabled": {

                "type": "boolean"

                }

                }

                }

                SharePoint - add item to list Add item to Created Groups list

                Add an item to the other list (“Created Groups”) to log that the Group was created. Once you have selected the site, you should be able to select the list and reference columns.

                Drop in variables from the previous “parse JSON” action to obtain the Group ID and display name.

                HTTP Get user

                In this action you’re making a GET request to the following Graph endpoint:

                https://graph.microsoft.com/v1.0/users/ [UserID]

                Reference the Get User documentation to understand how to call, but this one is simpler since no body or headers are required.

                Make sure to drop in the variable for the UserID at the end of the URL – you’ll need the ID or UPN of the user. If your e-mail addresses are the same as UPNs, you can use the “Created by e-mail” variable from the first action in the flow (when a new item is added to the “Requested Groups” list).

                Also specify details for your AAD app registration:

                - Tenant ID

                - Client ID

                - Secret

                Parse JSON Parse JSON (Group requester)

                Parse response body from previous action - the purpose is to get the user ID (in AAD) of the Group requester, so that we can add this user as a Group owner.

                Paste the following into the ‘Schema’ box:

                {

                "type": "object",

                "properties": {

                "businessPhones": {

                "type": "array",

                "items": {

                "type": [

                "string",

                "null"

                ]

                }

                },

                "userPrincipalName": {

                "type": "string"

                },

                "id": {

                "type": "string"

                }

                }

                }      

                HTTP Add owner to created Group

                In this action, you’re making a POST request to the following Graph endpoint:

                https://graph.microsoft.com/v1.0/groups/[Group ID]/owners/$ref

                Reference the Add Group Owner documentation in the Graph to understand the headers and body to pass. Note that you need the Group ID in the URL, and the User ID to be passed in the body of the request – drop in variables from earlier actions as appropriate.

                Also specify details for your AAD app registration:

                - Tenant ID

                - Client ID

                - Secret

                Summary

                With the right combination of calls to the Graph and parsing the responses returned, it’s possible to create new Office 365 Groups and (add the requesting user as the owner) purely through Flow, with no need for custom code such as an Azure Function. Since Flow has great support for approvals, it’s easy to add whatever approval steps you need to get the control which is right for your organization – and approvers can approve/reject directly from the e-mail they receive, the Flow app on their phone or tablet, or the Flow approvals center. Perhaps some items in my 5 ideas for using Flow in your applications article could also be useful in helping you build out a really nice Group provisioning process – in some cases you might want to put a lot more effort in (e.g. to produce a custom form and user experience), but if you want something at the simpler end, the approach described here might be helpful. And if you do need a richer solution, perhaps consider that this Flow/Graph approach to provisioning Groups could be dropped in as the core mechanism in something bigger too. Good luck!

                Sunday, 4 March 2018

                5 ideas for using Flow in your applications

                Like many others, my team and I have been doing more and more with Microsoft Flow recently. It’s true that it does have some limitations, especially when you get into longer running processes which are more “state machine” than “take this set of actions” (or you want to understand more around update of items in SharePoint, or respond to delete events, rather than new), but overall the capabilities are incredible. In particular, it’s the connectors to other services that make Flow – and the resulting set of things you can do with them. Chatting to some other developers recently, it occurred to me that lots of Office 365 technical people are probably unaware of what Flow can do these days - and so that motivated this article. My list of cool things you can do for this article is:

                • Send a message on Skype for Business
                • Post into a Microsoft Team
                • Add a row to Excel
                • Create an Office 365 Group (via a call to the Graph)
                • Send a push notification to a mobile device

                A few days earlier, I found myself doing strange things in a Flow I was building – I just needed to do some basic debugging to find out why my process was going down one branch, when I expected to be going down another. Why was the value I was testing in my “if/else” condition not what I was expecting? I figured I would add some quick and dirty logging somewhere so I could get better visibility of things (and probably remove or change this later) – but then I couldn’t find something logical to log with. My initial thought was to use Azure Application Insights – I recently talked about using this in intranets and page widgets to track events in your code i.e. particular actions that users take. How often is your app launched? How often are users clicking that special button? How many users ever switch to the second tab of your user interface? Or, perhaps in site provisioning – how many sites are being requested, and how long do things take? I figured that you could log to App Insights at particular points of your Flow, and that would be a great way of analyzing the most common path through a Flow, or perhaps doing some debugging during the build.

                Unfortunately, there is no “Track event in Azure App Insights” action yet :(

                I added a UserVoice item here if you also think this would be a good thing and feel like voting.

                Anyway, this led me to having some fun with other possibilities – you could use them for quick and dirty debugging like me, but I think there are a lot of true business possibilities here and so it’s worth being aware of them.

                Send a message on Skype for Business

                This one could be useful if a person/team needs to be notified *immediately* when something is added or changes somewhere in Office 365, and for some reason an e-mail notification isn’t a good fit. Arguably this one works best if the recipient is a desktop/PC user – later I talk about options for notifications to mobile workers. Anyway, it certainly gets the user’s attention, and it can be configured in your Flow very quickly. Here’s the end-user experience:

                SNAGHTMLae4a2ce

                SNAGHTMLae8cb91

                Here’s what it looks like in Flow:

                SNAGHTMLaed16de

                Post a message to a Microsoft Team

                But enough of Skype for Business, the future for most organizations (in the Microsoft cloud) is Teams of course. As you’d expect, there’s good integration between Flow and Teams. Saying that, it’s not currently possible to send a chat message in Microsoft Teams, but we can post to a channel – which is arguably more useful in the real world. Here’s what it looks like in Teams:

                SNAGHTMLaf32cbb

                Here’s what it looks like in Flow:

                SNAGHTMLaecbb70

                Add a row to Excel

                Of course, half of the world’s critical processes are still running in Excel. Fortunately, you can easily use Excel as a data source from Flow, whether that means reading from or writing to workbooks – it’s trivial if the Excel file is somewhere in Office 365. In the example below, I’m adding a row to an Excel workbook every time an expense report is submitted to SharePoint. This could be used by a finance team for reporting or to help with some month-end processes perhaps. The end result is an Excel spreadsheet which is being built up automatically over time, and I can pull details from the SharePoint item into Excel:

                SNAGHTML532992d

                Here’s what it looks like in Flow:

                SNAGHTML528ddc8

                SNAGHTML5296150

                SNAGHTML528413a

                HTTP call to the Graph (with AAD auth) – e.g. to create an Office 365 Group

                Some really interesting possibilities come with calling the Microsoft Graph from Flow. Obviously the Graph is the gateway to all things related to mail, calendar events, contacts, documents in SharePoint/OneDrive, Planner tasks, Teams and more. In this case I’m focusing on Office 365 Groups. How about a way to control Group requests and creation through a SharePoint list with approval? I implemented this in 20 minutes flat, and I think many organizations in Office 365 would get a lot of bang for buck from such a process. The ingredients are:

                • A SharePoint list for users to request a new Office 365 Group – this provides the form
                • A Flow with a ‘Start an Approval’ action – this provides the controlled creation/approval by an administrator step
                • A HTTP action added to the Flow (when it goes down the “approved” condition branch) – this calls the Graph, in this case, a POST to the /Groups endpoint with the details of the Group to be created
                  • An AAD app registration for to authenticate with the Graph – this must have permissions to create Groups (e.g. Group.ReadWrite.All)

                So, if you imagine a SharePoint list where items get added:

                SNAGHTML6cf84d

                We add a Flow to respond when a new item is added to the list, and somewhere in there we add the simple HTTP action (e.g. after an approval step):

                SNAGHTML61e70c

                We configure this to point to the correct URL in the Graph API, and pass the appropriate JSON for Group creation:

                SNAGHTML667c82

                There’s actually a bit more to it than that – we need to specify authentication details for the call, in this case specifying the Client ID and Secret for our AAD app registration which has the appropriate permissions (done separately in the Azure portal):

                SNAGHTML6a6369

                ..and then, when an item is added to the list and it is approved by an admin, the Group is created along with the corresponding mailbox, calendar, SharePoint site and so on:

                SNAGHTML6ed412

                image

                Not bad for 20 minutes work! Of course, the ability to easily call the Graph means you could do a bunch of things – I can certainly imagine lots of business processes where it would be useful to do things like:

                • Create a calendar item
                • Create a task in Planner
                • Update a user profile
                • Add a new contact

                ..and so on. A quick look at the Graph documentation should give you lots of ideas.

                Send a push notification to the Flow owner on their mobile device

                What if you need to get an immediate notification out to some users or administrators who are typically mobile or out in the field when something is changed in Office 365, and e-mail or SMS aren’t the right solution? We’re used to getting push notifications from certain apps on our phone/tablet these days, but developing a custom app and getting this in the hands of all your users can be expensive and time-consuming. If you can get the iOS/Android versions of the PowerApps or Flow mobile apps in their hands instead – and remember, users can install those right now from the respective app stores – then you can send push notifications to these apps very easily.

                Caveats!

                OK, so there are some caveats with this one, partly because there are two ways you can send push notifications. The caveats are:

                • The standard Flow push notification can only send *to the Flow owner*
                • The PowerApps push notification can send to anyone, but your app users need to be on a premium (paid) plan – remember this doesn’t necessarily need to be everyone in the org though

                It’s also worth considering that if you need a notification that something needs to be approved by the recipient, Flow can do something even better for that – Flow approvals work great in the Flow mobile app. The task details are shown fairly clearly, with big “Approve” and “Reject” buttons:

                SNAGHTMLd17167a

                Nothing special is needed for this, just regular use of the Flow ‘Start an Approval’ action. If the recipient has the Flow app installed on their device and is logged-in, they’ll receive the notification and be able to approve/reject extremely easily from inside the app.

                But what about other types of notifications? Perhaps someone has submitted something, and you need to confirm to them that it has been logged and a process has been started? Well, if you can use the PowerApps push notification option, this works great and you can even prompt the user to open your PowerApp (and pass parameters to load a particular item/take the user to a particular screen etc.):

                SNAGHTML109d618a

                When the user opens the notification, your particular PowerApp can open. Here’s what it looks like in Flow:

                SNAGHTML109f23cb

                Pretty nice stuff really.

                Summary

                I think it’s a good idea for all developers, architects and technical business folks working in Office 365 to be aware of the possibilities of Microsoft Flow. There’s a significant leap forward here in terms of what can be accomplished for the amount of effort involved – and so many organizational processes can benefit from this stuff. I’ve presented 5 ideas here of some things that might be useful, but I’m focusing mainly on taking other actions in or communicating via Office 365. Consider also that Flow has a LONG list of connectors to 3rd party applications – and although all the top enterprise productivity vendors have a similar list, I don’t believe anyone is taking it as far as Microsoft are. The image below shows a small selection (just those starting with letters P to W!):

                SNAGHTML10a176b4

                Even in this set you can see Salesforce, ServiceNow, WorkDay and lots of other enterprise systems.

                I think some of this stuff is killer for Office 365 personally. Happy process building!

                  Thursday, 15 February 2018

                  PowerApps – implementing offline support in your app

                  In the previous article I talked about my views on the good, the bad and the ugly of PowerApps at the present time (early 2018), but today I want to focus on a particular scenario – ensuring your app can be used offline. Not all apps will require this capability, but for some scenarios it will be vital. Unfortunately there is no magic button when building the PowerApp which makes it support offline – the implementer has to build it in his/herself, and this can make a simple app quite a bit more complication.

                  When we talk about an app working when offline, I’d say the general expectation is that:

                  • The app is usable (e.g. any dropdowns which pull data from somewhere continue to work)
                  • If the app is focused on writing data to somewhere (e.g. a SharePoint list/database/Excel file stored somewhere online etc.), then it should be possible to submit the record whilst offline – even if the connection needs to be resumed for it to actually be saved to the back-end
                    • I think lots of PowerApps fall into this category (e.g. log a new incident/I.T. request/holiday request/expense claim etc.), so I’m going to focus on this aspect today
                  • If the app reads existing data (e.g. show existing incidents/requests), then it should be possible to access at least some of this data offline (e.g. most recent 20 records, say)

                  The PowerApps blog has some good info in Build offline apps with new PowerApps capabilities, but I found myself doing some things differently – so thought it worth discussing here.

                    Understanding the deal with offline

                      A big thing to recognize here is that *the app must be opened for a while once the connection is resumed for data to be submitted*. It’s not like the “fire and forget” experience with the e-mail application on your phone (and one or two other native or “tier 1” applications), where you can hit send and trust the data to be sent even if your phone stays in your pocket. Instead, your users need to have your PowerApp open for a while – and the specifics depend on how you implement offline. In my case I used a timer which checks every 5 seconds if the device is connected to the internet, and then saves the record to SharePoint Online if so – this means the user doesn’t have to DO anything in the app (e.g. press a button), which is something. And, of course, as these things are happening in the background it’s important to communicate the status to the user, so it’s clear when their record has been saved to the back-end.

                      By the way, this deal isn’t specific to PowerApps. I’m no expert here, but it seems nearly all 3rd party app (including other apps you might use for such a use case e.g. Nintex Mobile) require this due to constraints on the background processing apps can do when not in use. Even with the right settings in place on your device (e.g. “Background App Refresh” enabled on iOS), this isn’t enough for these apps to push data it seems. So, prepare to coach your users in having the app open for a while once re-connected – and as I show below, you could consider making this really clear in the user experience.

                      A sample experience (from my POC app)

                      Here’s a video of offline support in an app I built recently, recorded from my iPhone – the holiday/leave requests app I mentioned in the last post. This simulates a user submitting a leave request without a connection (flight mode enabled), and then the record actually being saved to SharePoint Online once the connection is back (flight mode disabled):

                      The recipe for offline in PowerApps

                      In this section I’ll go through the different bits which are making the offline behaviour work, and provide some starter PowerApps formulas where appropriate (with the important functions highlighted). Remember my case focuses only on adding a new item to a SharePoint list, so it’s the PATCH function which is doing this work. Overall, the recipe I used was:

                      • Two info screens within the app:
                        • Pending screen
                        • Confirmation screen
                      • Formula behind submit button:
                        • If connected, PATCH record to SharePoint
                        • If not connected, CLEARCOLLECT to save record locally
                        • RESET form (to clear existing values)
                        • NAVIGATE to pending screen

                          If(Connection.Connected, Patch('My SharePoint list', Defaults('My SharePoint list'), {Title:Concatenate("Leave Request - ", User().Email, " - ", Text(Now(), "[$-en-GB]dd/mm/yyyy hh:mm:ss" )),SomeField1:SomeControl1.Value, SomeTextField1.SomeTextControl1.Text,SomeChoiceField: {    '@odata.type':"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference", Value: SomeDropDownListControl.Selected.Value, Id: 1 });
                          ResetForm(MyForm);
                          Navigate(ConfirmationScreen, ScreenTransition.Fade),
                          ClearCollect(LocalRecord, {Title:Concatenate("Leave Request - ", User().Email, " - ", Text(Now(), "[$-en-GB]dd/mm/yyyy hh:mm:ss" )),SomeField1:SomeControl1.Value, SomeTextField1.SomeTextControl1.Text,SomeChoiceField: {    '@odata.type':"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference", Value: SomeDropDownListControl.Selected.Value, Id: 1 });
                          ResetForm(MyForm);
                          Navigate(PendingScreen, ScreenTransition.Fade))
                      • Formula for Timer control (implemented on both “start” and “pending” screens – so user can have app open in any logical location, and record will be submitted). In the OnEnd event:
                        • If connected and have record(s) in “LocalRecord”, iterate each record with FORALL and then PATCH to SharePoint
                        • NAVIGATE to confirmation screen
                        • CLEAR “LocalRecord”

                          If(Connection.Connected,ForAll(LocalRecord, Patch('My SharePoint list', Defaults('My SharePoint list'), {Title:Concatenate("Leave Request - ", User().Email, " - ", Text(Now(), "[$-en-GB]dd/mm/yyyy hh:mm:ss" )),SomeField1:SomeControl1.Value, SomeTextField1.SomeTextControl1.Text,SomeChoiceField: {    '@odata.type':"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference", Value: SomeDropDownListControl.Selected.Value, Id: 1 }});
                          Navigate(ConfirmationScreen, ScreenTransition.Fade));
                          Clear(LocalRecord))

                      • A “status bar” within the app indicating whether the device is connected or not (as a simple reminder to the user)

                      WARNING – those formula extracts are edited/simplified versions of my real ones, and maybe the closing brackets aren’t exactly right. Take care if you try to use them for your formulas – really I’m just trying to convey the concepts!

                        Dealing with reading from data sources when offline (e.g. for dropdowns)

                        One thing to look out for is if your SharePoint list has choice or lookup fields – you might be presenting the options in a dropdown list or with radio buttons in your app. Since November 2017, you can now have multi-select on such fields, but unfortunately if the user happens to use your app for the first time in offline mode, the dropdown list will not be populated (it will display “Find items”, but no list appears when the user clicks). The user can type in an option, but since they are not selecting from a list of valid choices this will generally go horribly wrong and the item will not be added to SharePoint.

                        Also consider that you are most likely not using taxonomy/managed metadata fields, because they are still read-only (as at February 2018).

                        So, you need to work around this. One option, especially if you’re already using the PATCH command or similar to update SharePoint, is to bind your control to some static data which can be accessed offline. This is a bit lame, as you’re essentially duplicating the items as hardcoded data within your app – you lose the benefits of your choice/lookup field, i.e. the form dynamically fetching the right options based on what is defined in SharePoint. You could probably do something clever with a formula which refreshes a collection when the app has a connection, but it would be nice if this was handled in a better way by the PowerApps infrastructure. Maybe in the future :)

                        Summary

                        PowerApps can work just great offline, but it’s all down to the implementer. The PowerApps framework provides the ability to detect if the device currently has a connection, a timer control (so that actions can be taken automatically), and the various functions for adding/updating data in a data source (e.g. PATCH, UPDATE etc.). These are the ingredients to use when implementing offline support in your app – there’s work to do, but you can control the experience and make sure it makes sense in your context.

                        Further reading - https://powerapps.microsoft.com/en-us/blog/build-offline-apps-with-new-powerapps-capabilities/

                        Tuesday, 6 February 2018

                        PowerApps–the good, the bad and the ugly (early 2018)

                        I’ve been doing quite a lot of work with PowerApps for clients recently, and it’s been an interesting time. No doubt I’m still not the world’s most capable PowerApps implementer by any stretch of the imagination, but I feel like I’ve been through the usual denial/anger/acceptance phases that often come with a new technology ;) Some of my work has centred on a proof-of-concept application for one of the big airlines – specifically, building an app that pilots should be able to use whilst offline on an iPad. The project was to digitise some forms related to booking leave, which is an important part of flight crew scheduling. We effectively rolled 3 forms into one app:

                        SNAGHTML24ecc4ef

                        I gave a presentation on this recently to my colleagues at Content and Code, but I’ve also genericised some of the information so it can be shared more widely (Contoso Airlines!). The deck shared below is a combination of some typical lessons learnt and tips, but also has my thoughts on where PowerApps is a technology, structured into “the good, the bad and the ugly”.

                        Potentially transformative, but with a learning curve..

                        My conclusions are that it’s a great technology and although it’s aimed at forms-type applications in general, it really shines for relatively simple mobile apps. The organization just has to deal with getting users to have the PowerApps app installed (either from the app store, via an MDM solution such as Intune or Airwatch, or another approach) and then all the PowerApps forms and applications the organization provides will show up there. This is *far* easier and cheaper than developing individual native apps on iOS and Android, which each need to be distributed to users once the build is complete. In contrast, it’s feasible that you could have your Office 365 users working with a simple PowerApp on their mobile device within hours. Think about that for a moment! Sure, PowerApps doesn’t give you the richness that a high-end native app can have, but the barrier to entry is much lower.

                        However, it’s not always the simplest for the app implementer to work with. Frequently, things can get into a territory that I’d argue most power users would struggle with. An example in my case was having to abandon the default SharePoint integration/data-handling, and craft my own formulas which use the Patch() function to add an item to a SharePoint list (necessary because my form used multiple screens). This is fiddly work if you have lots of form fields and columns in the underlying list, even for a developer used to such things.

                        Customizing SharePoint lists vs. creating a standalone PowerApp

                        The implementer must choose between two approaches – customizing the form of a SharePoint list, or creating a “standalone” PowerApp (which might talk to the very same list). Conceptually these are quite different, and have different behaviours. This decision is expressed in the PowerApps menu on a SharePoint list:

                        SNAGHTML24dcbcbf

                        A key thing here is that customized SharePoint forms do not show up in the PowerApps app:

                        SNAGHTML26996c8

                        If users need to work with a customized SharePoint list on their mobile device, then using the SharePoint mobile app instead provides a reasonable experience – in fact, the SharePoint app should hand-off to the PowerApps app when you go to the list, and the customized PowerApps form should then be loaded. However, this currently seems to be a bit hit and miss – most often, I actually just get a web rendered view of the PowerApp, and here it seems that the experience isn’t as optimized for mobile as a true PowerApp – some pinching/zooming is often necessary.

                        I’m sure things will be straightened out here eventually, but I still think I’d prefer a different model – what about if certain customized SharePoint lists could be flagged to appear within the PowerApps app (perhaps by a tenant administrator)? That would seem a better arrangement to me at least.. 

                        Other interesting aspects

                        The presentation includes some high-level detail on other things I’ve worked with that might be interesting:

                        • Installing the on-premises Data Gateway to connect to on-premises data (SQL Server in my case)
                        • Implementing offline support in a PowerApp (using a Timer control to submit data once reconnected)
                        • Some implementation details around using a Gallery control for navigation, and the 10 PowerApps functions I found most useful from the 150+ functions which are available

                        My “good, bad and ugly” summary:

                        If you’re not that interested in the presentation and want to skip straight to the summary, here are my conclusion slides:

                        image

                        image

                        image

                        By the way, if you’re wondering what I mean by “web experience (upscaled phone/tablet view)”, let me try to explain. Certainly a form/app looks good on a mobile device, and is optimized for that form factor – all the controls are very “thumb-able”, and even typing into a textbox works fine (shown here at tablet/iPad size):

                        4 - BA PowerApp - paternity leave screen

                        But when a PowerApp is accessed on a PC, there is no responsive design or optimization for the device – the very same rendering for phone/tablet is used, which is just plain weird in my view:

                        PowerApps - PC 800 - msg

                        And no, I don’t know the Office 365 suite bar displays “Dynamics 365” either (particularly since Dynamics is not even in use in this tenant). But I’d happily live with that if I could have a better experience than the strange “phone screen in a PC browser” deal that we currently get. Nintex Forms does a better job of this, so I’m not sure why PowerApps went down this route. Again, I’m hopeful some enhancements to this will appear at some point.

                        So that's some headlines from what I spoke about. I'll most likely publish some other PowerApps articles which dive into more detail on implementing offline/using the on-premises Data Gateway etc., but essentially I just wanted to share the slide deck in case it’s useful to anyone:

                        The slide deck: