Tuesday, June 12, 2018

Dynamically load a web part from another web part

I coded a proof of concept last week on how to load a SPFx web part from another web part which I plan to use as pattern for display templates for a search web part I’m planning. By using SPFx parts as render templates we get better control of the code, and avoid script injection on the page.

I figured this approach might be useful for other scenarios so here’s the code to play with :)

The POC loads up two instances of the Modern Script Editor web part, and sets data in it. Which means the modern script editor web part has to be installed on the site you are testing on. Or replace with any of the oob web parts and set the correct properties.

Issues I haven’t gotten to yet as they are not a concern for my scenario are:

  • How to access web part properties of the dynamic loaded web parts in edit mode – can be worked around if the web part has a custom edit UI
  • How to persist the web part data and store it in the main web part – take a look at the serialize method of the ClientSideWebPartManager.
  • The text web part is a special kind of web part, so not sure how to dynamically instantiate it

Full sample can be found at https://github.com/wobba/spfx4fun/tree/master/DynamicLoad

import * as React from 'react';
import styles from './HelloWorld.module.scss';
import { IHelloWorldProps } from './IHelloWorldProps';
import { Guid } from '@microsoft/sp-core-library'
import { ClientSideWebPartManager, IWebPartManagerContext, IWebPartData } from '@microsoft/sp-webpart-base';
import { DisplayMode } from '@microsoft/sp-core-library';

import { IClientSideWebPartManifest } from '@microsoft/sp-module-interfaces';

let _webPartManager: ClientSideWebPartManager;
let _sampleIdOne = "mAdcOW" + Guid.newGuid().toString();
let _sampleIdTwo = "mAdcOW" + Guid.newGuid().toString();
export default class HelloWorld extends React.Component<IHelloWorldProps, {}> {

    public async componentDidMount(): Promise<void> {
        _webPartManager = new ClientSideWebPartManager(this.props.context.host);
        await _webPartManager.fetchWebPartManifests(); // Ensure all manifests are available
        this.addData();
    }

    private async addData() {
        // local webpart properties - in this case props for the modern script editor webpart
        let props = {
            script: "<div>Foo</div>",
            title: "The Modern Script Editor web part!",
            removePadding: false,
            spPageContextInfo: false
        }
        await this.loadWebPart("ScriptEditorWebPart", document.getElementById(_sampleIdOne), props);
        await this.loadWebPart("ScriptEditorWebPart", document.getElementById(_sampleIdTwo), props);
    }

    private async loadWebPart(alias: string, domElement: HTMLElement, webPartProperties: any) {
        let manifests = _webPartManager.getWebPartManifests();
        for (let i = 0; i < manifests.length; i++) {
            const manifest = manifests[i];
            if (manifest.alias === alias) {
                let instanceId = Guid.newGuid().toString();
                let wpManifest: IClientSideWebPartManifest<any> = manifest as IClientSideWebPartManifest<any>;
                let wpData: IWebPartData = {
                    id: wpManifest.id,
                    instanceId: instanceId,
                    title: "",
                    dataVersion: "1.0",
                    properties: webPartProperties
                };

                // Specify any as webpartLoadExtraLogInfo is not defined on the interface and has to be present
                let initialize: IWebPartManagerContext & any = {
                    domElement: domElement,
                    instanceId: instanceId,
                    manifest: wpManifest,
                    displayMode: DisplayMode.Read,
                    webPartData: wpData,
                    webpartLoadExtraLogInfo: {
                    }
                };
                await _webPartManager.loadWebPart(initialize);
            }
        }
    }

    public render(): React.ReactElement<IHelloWorldProps> {
        
        return (
            <div className={styles.helloWorld} >
                <div className={styles.container}>
                    <div className={styles.row}>
                        <div className={styles.column}>
                            <span className={styles.title}>Dynamic loading!</span>
                            <span id={_sampleIdOne}></span>
                            <span id={_sampleIdTwo}></span>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

Monday, May 28, 2018

How to reset a modern home page using PnP PowerShell


Photo by Nikita Kostrykin at Unsplash

Here’s a short snippet which will reset any modifications done to a modern home page back to the default layout.

Basically you clear out the CanvasContent1 field which stores the page layout and contents.

Connect-PnPOnline https://<tenant>.sharepoint.com/sites/mysite
# Get welcome page url
$web = Get-PnPWeb -Includes WelcomePage
# Load the page
$file = Get-PnPFile -Url $web.WelcomePage
# Get the page's item
$item = $file.ListItemAllFields
# Load the item id
Get-PnPProperty -ClientObject $item -Property Id
# Clear the content to reset
Set-PnPListItem -List SitePages -Identity $item.Id -Values @{"CanvasContent1"=$null} -SystemUpdate

Quickly clear Followed sites using PnP PowerShell

In my dev tenant I do a lot of testing with Groups and sites, and this has the effect that my demo user is following a lot of, often with the same name as seen in the image below.

image

The followed sites are actually stored in a list named Social in your OneDrive. This list was introduced with SharePoint 2013, and still alive and kicking. You can access followed sites from the following URL:

https://<tenant>-my.sharepoint.com/personal/<user site>/Social/Sites.aspx

This list also tracks followed documents and people, but that’s not the focus of this post.

First connect to your OneDrive using PnP PowerShell, then execute the code below to remove all followed sites, and be sure to set the correct URL in the first line.

$followedSitesUrl = "/personal/<user site>/Social/Private/FollowedSites"
$sites = Get-PnPListItem -List Social -Query "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FileDirRef'/><Value 
Type='Text'>$followedSitesUrl</Value></Eq></Where></Query></View>"
$sites |% { Remove-PnPListItem -List Social -Identity $_.ID -Force }

Once complete, the list is now empty.

image

Tuesday, May 22, 2018

Two SPFx manifest settings you might not be aware of

image

If you take a look at the manifest schema for a SPFx web part there are a couple of settings you might want to take a look at.

hiddenFromToolbox

If hiddenFromToolbox is set to "true", the web part will not be visible in the modern SharePoint toolbox. Very useful for web parts you provision automatically on pages, but don’t want users to add themselves.

supportsFullBleed

If supportsFullBleed is set to "true", the web part can be added to a full page width zone on a modern page in a communication site, spanning from the left margin to the right margin without any white space.

Friday, May 11, 2018

Caution when using $expand with Microsoft Graph

Using the $expand parameter with calls to the Microsoft Graph is very handy. In one API call you can retrieve both the object itself and additional properties.

Two examples are fetching a user and the direct reports, or a group and it’s members.

https://graph.microsoft.com/beta/users/061353c3-af75-4767-9b19-a5bceed85f53?$expand=directReports

https://graph.microsoft.com/v1.0/groups/79958190-024b-4c62-ab55-65dc9a066cac?$expand=members

image

The caution is that when you expand a property which has a collection of values, you will only get the first 20 items returned. This means that if you work in an organization with more than 20 people in it, you should not use $expand if you need all the values, but resort to two calls instead, one for the item, and one for the property you want to expand.

Summary

While using expand is very handy, it’s almost always better to break it into two API calls to avoid having issues if you can expect more than 20 items.

Tuesday, May 8, 2018

How to get the list item from a file URL using PnP PowerShell

image
Photo by Karly Santiago at Unsplash

This is one of the snippets I always forget, but which is very handy in cases where you have the absolute URL to an item in SharePoint. The magic is really line 6 which uses the static method WebUrlFromFolderUrlDirect to get the web URL of the file, so that you can connect properly.

$uri = [Uri]'https://contoso.sharepoint.com/sites/foo/bar/Shared%20Documents/mikael-is-cool.docx'
# Connect to the root site, or any other site
Connect-PnPOnline -Url ($uri.Scheme+'://'+$uri.Host)
$ctx = Get-PnPContext
# Get the web url for the file
$webUrl = [Microsoft.SharePoint.Client.Web]::WebUrlFromFolderUrlDirect($ctx, $uri)
Connect-PnPOnline -Url $webUrl
$fileItem =  Get-PnPFile -Url $uri.AbsolutePath -AsListItem

Sunday, May 6, 2018

Locating where a term set is used in SharePoint using search

Joanne Klein asked on Twitter if there is a way to get all places where a specific term set is used in SharePoint.

image

One way would be to iterate all site collections and check if the term set was present in the Hidden Taxonomy List, which stores all used terms on a site collection (and if you have no idea what that is, that’s ok as well).

image
Hidden Taxonomy List at /Lists/TaxonomyHiddenList/AllItems.aspx

Another option which is the solution I proposed, is to use search. Of course you need to have read access to the items where the term set is used for it to be 100% accurate as well items using terms from a term set has to be present in the search index.

Friday, May 4, 2018

Use Microsoft Flow to implement approval of site pages


Photo by Zachary Nelson at Unsplash

Again I’m late to the party, but Microsoft has released an action to Flow called “Set content approval status”. This action enables you to add content approval not only to list elements and documents in SharePoint, but also to news pages.

Microsoft has talked about content approval for ECM scenarios with communication pages for a while, but until a proper UI is in place, you can get started today!

This is how.

Thursday, May 3, 2018

Addendum to Chaks’ post “Deep dive into ‘Get items’ and ‘Get files’ SharePoint actions in Microsoft Flow”

Chaks recently wrote a post where he explained the difference between the two Microsoft Flow SharePoint actions Get items and Get files (properties only).

Behind the scenes they are both calling the following undocumented service which seems to wrap the regular OData call:

/_api/SP.APIHubConnector.GetListItems(listName='MyList',queryOptions=@q)?@q=''"

Good news is you can use both actions interchangeably. If you want to get the properties for a document library using the Get items action simply pick Custom value in the dropdown and enter the title or id for your document library and it works just fine (been using this already a while).

image

So, to me, having the Get files (properties only) action seems unnecessary, but for some users it might be easier to understand with two different actions targeted towards lists or libraries.

image

Thursday, April 26, 2018

The SharePoint Properties Pane (successor to DIP) is available for SharePoint 2013

Last year at Ignite we were all psyched that Microsoft gave us a replacement for the old Document Information Panel (DIP) in Word which allowed us to set metadata stored in SharePoint columns. DIP disappeared with Office 2016 (and you had to edit properties in the info settings page instead), and finally we got a replacement. However, it only worked for documents stored in SharePoint Online.

I did a proof on concept of this with a colleague last year as well, so it was just a matter of time until it was properly release.

The announcement slipped past me as there has not been a lot of whoo hah around it. Reading the release notes for the December 2017 CU for SharePoint 2013 it states:
  • Enables the new Document Information Panel feature that's visible in Word 2013.
Maybe a bit cryptic, and I haven’t tested if Word 2013 shows the SharePoint Property Pane, but at least Word 2016 shows it just fine against a document stored in SharePoint 2013.

So, patch away and enjoy SharePoint properties once again in Word!

Word SharePoint Properties Panel.PNG

Tuesday, April 24, 2018

How to run AzureAD PowerShell commandlets in Azure

I have a PowerShell script which today uses AzureAD commandlets to perform some write operations in Azure AD. This script is to be run on a schedule, and where better to run this than in Azure. It could be as a web job or as an Azure Function.

When running in an app service we cannot use interactive login, but have to use the connect signature below which takes an ADAL app id and a certificate:

Connect-AzureAD –TenantId <tenantId> –ApplicationId <appid> –CertificateThumbprint <thumbprint>

This means we have to create and ADAL app which accepts a certificate, as well as make sure we can access the certificate from the app service.

For this tutorial I’ll go with an Azure Function, but the steps are pretty much the same.

Pre-requisite

Install the AzureAD or AzureADPreview command lets on your local machine.

Steps covered

  • Create a self-signed certificate
  • Create an ADAL app
  • Grant the ADAL app access to write to AAD
  • Create an Azure Function
  • Load Azure AD PowerShell in an Azure Function
  • Connect to AzureAD using an ADAL app and a certificate

Sunday, April 22, 2018

Sneak peek at managed navigation for HUB sites

A granite mountain peak rising up above pink-hued clouds
Photo by Cédric Servay at Unsplash

One of the cool features of the new hub sites is that associated sites inherit the navigation of the hub. This means you have one place to configure navigation, and you don’t have to resort to any of the numerous custom solutions out there to solve this. Hub sites makes it very easy to create small hierarchies of sites with a common navigation structure.

A lesser known fact is that the hub navigation also support managed navigation, a popular way to configure navigation since its inception in SharePoint 2013, and something constantly asked for in modern sites.

This post will show that you can achieve it today, but you should probably wait until it’s properly supported.

Thursday, April 12, 2018

Expose values from an existing InfoPath field to a SharePoint field


Photo by adrian on Unsplash

Ok, I know InfoPath is not the future and all, but I happen to have one client which has an old InfoPath solution for reporting incidents at their facility. I have previously migrated this from SharePoint 2007 to 2013, which involved some XML manipulation in the process, and I did spare you a blog post on this :-)

Either way, the lists of incidents which goes back years have now been hooked up to PowerBI via the on-premises gateway, so the customer is slowly taking the leap to the cloud.

And, turns out, the date field which has the date of the incident was never exposed as a SharePoint field, a field which is pretty nice to report on for incidents.

I fired up SharePoint designer, promoted the field in question and re-published the InfoPath form. This ensured all new items would have a date in the incident date field, but all existing items were still blank. So how could I in the easiest way possible get the value from the XML files promoted to the SharePoint field? Turns out it was very very very easy.

It was a matter of looping over all list items and running SystemUpdate() on them. This ensured modified date and modified by fields were not changed, but the value got populated.

Below is my PnP PowerShell snippet which saved the day.

Get-PnPListItem -List "Incidents" |% { $_.SystemUpdate();$_.Context.ExecuteQuery() }

Wednesday, April 11, 2018

Free status bar extensions for modern SharePoint sites

Did you think we were being lazy over at Puzzlepart? Think again. This time we give you a status bar top extensions.

statusbar

Get the code at https://github.com/Puzzlepart/spfx-solutions/tree/master/Pzl.Ext.StatusBar

The above image shows two notifications, one which checks if the Office 365 Group support external member or if the site allows sharing with external users. The other highlights a classification setting if it’s a specific value, in this case sites with classification Confidential or above will show a status message.

Technically it consists of three extensions, one base extension doing the rendering, and then you can add any number of other extensions which render a message based on the logic you decide. If there are nothing to render, then the status bar will not render.

I’m not saying the communication between the parts is the most graceful one, but it’s a pattern we are trying out – and it works, and you can use the base renderer with your own logic. Take a look at the two samples provided and you should figure out how to create your own. The clue is the messageId parameter which has to be the same for all extensions, to make them aware of each other.

Get the code at https://github.com/Puzzlepart/spfx-solutions/tree/master/Pzl.Ext.StatusBar

Tuesday, April 10, 2018

Working with Hub Sites and the search API


Photo by Sunaina Kamal at Unsplash.

Hub sites are a nice way to create a virtual two level site hierarchy without using sub sites. An administrator will nominate a site as a hub site, and then other sites can associate themselves to this hub. By associating a site to a hub the site will inherit the navigation and the visual look of the hub itself, ensuring a consisting look and feel. Also items from associated sites will surface in search at the hub level (as long as you have read access to the item).

image

Note: The hub site feature is currently in preview and only available for target release tenant at the time of writing.

After playing with hub sites you might want your favorite developer to create something for your hub sites, and this is where the search API is handy.

Thursday, March 29, 2018

Quick tip: easily test SharePoint Framework web parts on modern pages (addendum to Waldek’s post)

image

Did you know that you can easily test your SharePoint Framework web parts on modern pages?

If there’s one guy who know, it’s my friend Waldek Mastykarz. Today he had a post outlining how you can debug/test SPFx web parts on a real modern page, not the SharePoint workbench.

Wednesday, March 28, 2018

Optimizing meshing with Cisco Meraki access points

image

I have had a Cisco Meraki MR-33 hooked up for a little while, which is positioned pretty centrally in an L shaped space. The issue is that the building is old with lots of brick walls. In the far room of the long leg of the L there is about 2 meters of space which gets pretty spotty connection. Not a huge deal, but enough to irritate :)

Setting up a second access point via cable is not a viable option so I decided to mesh two access points instead. The setup was easy, but the throughput was not amazing, averaging around 15mbit/s, and lower. You might think this is ok as we’re meshing, but the good thing is that it can be improved.

Note: Read the Meraki guide Manually Changing Channels in a Mesh Network for information on how you can change the channel used for meshing.

By default when you have auto channels for both the 2.4GHz and the 5Ghz radio, the 5GHz channel will be set to the same channel for both devices, and this is used for meshing. Having band steering on, where clients also use 5GHz, this will greatly reduce the speed.

What I did was this.

  • I set a dedicated channel for the 2.4GHz radio – to allow meshing to happen on the 2.4GHz radio, which also travels better though the brick walls.
  • I set the 5Ghz radio to automatic.
  • I use band steering, leading clients to the 5GHz radio.

This setup “ensures” clients use 5Ghz, while the mesh traffic have the full bandwidth itself on the 2.4GHz radio. Now my throughput is pretty consistent around 55mbit/s.

image

Office 365 logo kit available at Fasttrack for partners/customers

Ever in the need to use Office 365 icons and wonder how they can be used? Head over to https://fasttrack.microsoft.com/dl/brandingkit (requires login) and download the Microsoft Office 365 Branding Toolkit today.

The downloaded zip file has icons in different formats. Below are samples of the 256x256 icons, and the file only contains .png files.

image

image

Monday, March 26, 2018

Updated Modern Script Editor Web Part with fix for AMD modules and exposing _spPageContextInfo

image

The web part haven’t change much, but the following configuration options are now available:

  • Keep or remove padding on the web part zone – useful if you have script which does not output any markup.
  • Set the _spPageContextInfo variable – useful if you have old scripts using this variable on classic SharePoint pages.

I have also fixed the code so that it won’t fail when loading AMD module scripts – meaning the scripts will not detect themselves as module scripts, but load globally instead.

You can get the code from https://github.com/SharePoint/sp-dev-fx-webparts/tree/master/samples/react-script-editor.

SharePoint Query Tool v2.8


Image by Emily Morter on Unsplash

This is a short one, and not much has changed. Basically I removed the old browser based SharePoint Online login method as it caused too much friction on Windows 10 machines. And I fixed an issue where all properties did not show when using the new SharePoint Online login method.

Get v2.8!

Friday, March 23, 2018

Two approaches to applying a modern theme using PnP


Photo by Ash Edmons on Unsplash

Modern sites are no longer using the old theming engine directly with .sptheme, .spcolor and .spfont files. Instead you can use the Theme Generator tool to get your colors the way you want them, and this is what this post will focus on, how you can automatically set the right colors using PnP. The post has two samples, one using PnP PowerShell and one using a PnP Provisioning template.

Monday, March 19, 2018

A workaround for saving hi-res photos from PowerApps to SharePoint

Saving photos or images from PowerApps to SharePoint is not easy, but there are workarounds using for example Flow to get this to work as I’ve written about previously. The caveat with this approach is that when using the camera control you won’t get full resolution on the images you take, but a scaled down version – and adding Flow to the mix increased complexity.

With the recent release of supporting attachments with SharePoint lists in PowerApps it’s now possible to get those high resolution photos into SharePoint. But, it’s not straight forward. Even though it’s possible you should think it through before going full on production with this.

Note: This post is written based on testing on iOS.

Uploading photos is a common ask when using PowerApps on mobile device. You might create a reporting application of sorts which supports adding photos as documentation. My first thought was to utilize the new attachment support, pick the camera as input and be done with it. Turns out I should stop believing in fairy tales when a feature is just released :). When tapping the “Attach file” link, you get a dialog to browse your iCloud Drive, not an option to tap into the camera. Which makes sense as you need an attachment filename. This means we cannot use the default add attachment functionality.

20180318_124151000_iOS

What I came up with was using the “Add picture” control with a custom collection, and then binding the forms attachment control value to this collection. You also need to reset the form after you modify the collection in order for the change to be picked up in the control (which is needed for it top be submitted). The reset has a timing issue, so I had to add a timer control which reset’s the form every 1 second. It’s all in a days works of duct tape.

Oh well.. let’s build the application, and you will see for yourself.

Friday, March 16, 2018

How to display images from a SharePoint library in PowerApps

[Update: As mentioned in the comments by Paul Culmsee, this only works in the web version of PowerApps - not on devices. To make it work on devices take a look at his posts for a proxy workaround]

A while back I wrote a post about how to save images from PowerApps to SharePoint via Flow. Today  I got a comment asking how you can show images sored in a SharePoint library in a PowerApp. Turns out it’s not hard at all.

I first created a new document library named “Images” in a SharePoint site and uploaded two images.

image

Within your PowerApp add a new data source, and manually type in the name to the library containing your files, in my case “Images” and hit “Connect”. The manual typing is the crux to make this work.

image

Next add a gallery to your app and bind it to the Images data source. For the Image control, change the binding to be ‘{Link}’ and you should see your images showing up in the gallery.

image

Happy PowerApping!

How to: Embed the Yammer All Company feed on a modern page in SharePoint Online

This is not hard at all these days, as the Modern Yammer web part recently got updated and allows you to pick “All Company” as the feed to display.

First add the Yammer web part to your page.

image

Then search for “All Company” and pick it. Previously you had to paste the link to a group, but this search experience makes it a lot easier indeed.

image

Friday, March 2, 2018

My NACS2018 presentation about taking control of Office 365 Groups creation and configuration using Azure Functions and Flow

Here’s my presentation and don’t hesitate to contact me if you want to learn more.

Wednesday, February 28, 2018

You don’t get to MVP without making a few enemies

MVP-enemies_thumb1
Cover by Kim Damsleth (Puzzlepart)

If you thought becoming an MVP is as easy as 1-2-3, think again – my story is all about pushing aside those who have been in my way and claiming what is mine! Don’t like it? Tough luck – I’m here to stay!

Tuesday, February 27, 2018

One way to figure out which SharePoint Online domain you are on with an unlicensed user

Ok, someone created an account for you on their Office 365 tenant for testing, and gave it no licenses what so ever. Yet, they did grant you permissions to access SharePoint Online. So, how do you find out what the SharePoint domain is? Because you have no apps in the app launcher or search box to help you out.

We mulled this over at our Puzzlepart dev chat channel, and Ole Kristian came up with the first solution:

Once logged into office.com, crank open dev tools in your browser and type:

navBarData.SPO_RootSiteUrl

This will yield the sharepoint domain name :)

image

Do you know a different way?

Monday, February 26, 2018

Fixing the “this website doesn’t support embedding” error when using the preview Kindle web part in a modern page – read the manual :)

I decided to try out the Kindle preview web part, previewing my own Search Queries Explained book. When pasting the link I was presented with the following error:

image

And as the error message says, use the embed code instead of just the link. But would be nice if it managed to wrap this automatically, no? :)

image

When pasting the full <iframe> link it works as expected.

image

Alternative way to solve the issue where a SPFx v1.4.0 web part don’t show when upgrading.

In SPFx v1.4.1 there was an important bug fix which was introduced in SPFx v1.4.0. If you created a web part which was manually installed on a site collection, upgrading the web part would result in the web part not showing. The issue noted on the release notes for v1.4.1 says in order to fix this do the following:

  1. Remove all instances of existing SharePoint Framework solutions from site level
  2. Remove SharePoint Framework solution from app catalog
  3. Upload new SharePoint Framework solution built with 1.4.1 version to your app catalog
  4. Install SharePoint Framework solutions back to sites.

You don’t have to uninstall the solution, but can follow these steps instead:

  1. Upgrade your web part to SPFx v1.4.1 and bump the version number of the part in package-solution.json and package it.
  2. Navigate to https://<tenant>.sharepoint.com/sites/<AppCatalogSite>/Lists/ComponentManifests and remove the entry for the web part in question.
  3. Upload the updated web part to your app catalog, overwriting the old one, and ensure the app is checked in, if it becomes checked out.
  4. Upgrade the web part package on the site collection(s) where used (site contents, classic view, about on the part, then “Get it” to get the latest version.
    image
    image

Unfortunately there is no easy way to see all sites which have installed a particular SPFx v1.4.0 web part, so you have to loop over all sites in order to ensure they are all working as expected.

Tuesday, February 20, 2018

Automatically set an Office 365 Group Logo - Another free SharePoint Framework extension from Puzzlepart

image

Photo by Mikael Svenson

If you haven’t caught on already, at Puzzlepart we love sharing our small quirky workarounds. This time around it’s a run-once extension which will set the logo for an Office 365 Group when a group owner visits the site for the first time.

Get the extension code!

Monday, February 19, 2018

Minimal path to awesomeness when moving Microsoft Graph calls to SharePoint Framework v1.4.1


Image by Jeremy Bishop at Unsplash

Phew.. that title was a mouthful. When SPFx v1.4.1 was released the other day, the GraphHttpClient object in SPFx was deprecated in favor of either the AadHttpClient object or the MSGraphClient object. If all you care about is Microsoft Graph calls, then they do pretty much the same, except the MSGraphClient object allows a fluent API to build up your queries with selects, sorts and filters, whereas the AadHttpClient takes a handcrafted URL.

So, from a minimal path perspective the AadHttpClient makes more sense as it takes complete URL’s, and we don’t have to break up the call into a fluid syntax. Also, the MSGraphClient is currently in preview.

Note: If your tenant is not on Targeted Release (TR), you will not be able to grant the needed graph scopes using the SharePoint Admin UI or with SPO Management PowerShell. Uploading the app package will also not work on a normal tenant so be patient.

Thursday, February 15, 2018

Programmatic nuance in .Net and PowerShell which can wreck havoc


Photo by David Kovalenko at Unsplash

Took me an hour or so to figure out why something I had ported from C# to PowerShell was not working, and the culprit is how casting of decimals to bytes work.

In .Net: (byte)4.6 = 4, meaning it truncates

In PowerShell [byte]4.6 = 5, meaning it rounds up

The solution is to use [Math]::Floor instead in PowerShell, which of course works fine in .Net as well.

Tuesday, February 13, 2018

How to properly use the “Get Manager” Flow action with a SharePoint list

A confident man in a blue blazer
Photo by Olu Eletu at Unsplash.

This is a short one and quite easy. When you create an item in SharePoint the unique identifier for a person field is the claim, while the Get Manager action takes a UPN (user prinipcal name).

image

For Office 365 they are almost equal. The claim is actually the UPN + a claim prefix.

UPN: john@contoso.com
Claim: i:0#.f|membership|john@contoso.com

If you have a flow triggering on a SharePoint list, you would enter the following expression for the UPN field to strip off the prefix from the claim.

replace(triggerBody()?['Editor']?['Claims'],'i:0#.f|membership|','')

image

Sure you can use the e-mail address which usually match the UPN, but you would be surprised how often multiple accounts have the same e-mail address - admin accounts, test accounts etc. So using a unique identifier is always a better approach compared to the e-mail address.

Monday, February 12, 2018

Validating a number format in SharePoint – divide and conquer formulas

A modern white chair at a table with a laptop, a notebook and a calculator

Photo by Oliver Thomas Klein at Unsplash.

Validating input in SharePoint is nothing new, but I haven’t dug much into this over the years. This time around I have a list where one of the fields takes a case number. The case number should be on the format:

0000/000000 <- four digits, a slash, then 6 digits.

Using regular expression this would have been a breeze - \d{4}\/\d{6} , but that’s not an option in SharePoint. Using the official formula documentation as a lookup I ended up with the following formula. I’ve split it over multiple lines and added comments for readability, so remember to remove the comments before using. Depending on your locale you might have to use comma instead of semi-colon.

Make note of the +0 which is workaround to convert text to a number.

AND(
    LEN([Case Number])=11;                # Total length is 11 characters
    MID([Case Number];5;1)="/";           # Fifth character is a slash
    ISNUMBER(MID([Case Number];1;4)+0);   # First four characters is a number 
    LEN(TRIM(MID([Case Number];1;4)))=4;  # First four characters has no spaces
    ISNUMBER(MID([Case Number];6;6)+0);   # Last six characters is a number
    LEN(TRIM(MID([Case Number];6;6)))=6   # Last six characters has no spaces
)

Validation is entered at the columns settings.

image

And here I only have 5 digits at the end, which does not validate.

image

Monday, February 5, 2018

Appending field values into a string in Microsoft Flow

An aerial shot of brightly-colored jigsaw puzzle pieces

Photo by Hans-Peter Gauster on Unsplash

I’m working on implementing a Flow which triggers on a SharePoint list. This list has a managed metadata column where you can select multiple terms. In my Flow I want to append the terms into a single string which I’m persisting on my Microsoft Graph schema extension techmikael_GenericSchema.

The approach I’ll outline does not only apply to taxonomy fields, but for any input which has an array of objects. Below is a sample object array.

[
  {
    "TermGuid": "74c34307-80e8-4e21-a63b-81337e369a5c",
    "WssId": 29,
    "Label": "Term A",
    "Path": null,
    "Value": "Term A|74c34307-80e8-4e21-a63b-81337e369a5c"
  },
  {
    "TermGuid": "db79ec09-34ad-4c60-8f4c-d41248ee09ac",
    "WssId": 450,
    "Label": "Term B",
    "Path": null,
    "Value": "Term B|db79ec09-34ad-4c60-8f4c-d41248ee09ac"
  }
]

The output should pick the Value property and join them together with a semicolon like this:

Term A|74c34307-80e8-4e21-a63b-81337e369a5c;Term B|db79ec09-34ad-4c60-8f4c-d41248ee09ac

Testing multiple languages in SharePoint Online and forcing a modern site’s language

An office desk of a designer showing desktop screen, mouse, iphone and other things.

Image by taner ardalı at Unsplash

More often than not I encounter the following scenario (and I suspect this is quite common in a lot of European countries): When a company’s tenant was created they chose their locale as the default language. This might not be an issue, until they remember that the official language should be for example English, which differs from the locale.

A good example is a tenant which was created in Norwegian. This often(*) leads to sites and Office 365 Group modern sites to have Norwegian as the default language, while having it in English would be ideal.

This post cover how to test multiple languages, and also how to force one particular language – as you might want to force different languages for different users. And, you cannot really force the language per site, unless for site collections and communications sites when you create them via an API.

(*) depending on how the site was created