Utilizing SPFx serveConfigurations

Recently a new serveConfigurations section was added to the serve.json config file in new SPFx Extension projects. These are a huge help when it comes to debugging extensions and are especially helpful when testing ClientSideProperties.

Robot-Tennis--33121

Background

Prior to the introduction of serveConfigurations, you couldn’t just run the gulp serve command like you do for webparts since that launches the local workbench where extensions couldn’t (and still can’t) be tested.

So the advice was to use gulp serve –nobrowser and then just navigate manually to a page in O365 and paste an ugly (and easy to screw up) set of querystrings.

Waldek Mastykarz even created a gulp task, gulp serve-info, that made this a little easier. I used it in my extensions and it was a huge leg up, but the whole thing was still clunky and a significant complexity preventing new developers from getting into extension development (or at least frustrating them).

What was needed was something as simple as gulp serve that took into account your custom locations and unique property settings. Fortunately, that’s where serveConfigurations comes in!

Setting up your serveConfigurations

When you generate a new SPFx Extension you’ll find a couple of initial serveConfiguration entries were created for you automatically in the config/serve.json file:

Default serveConfigurations

The values of these configurations should remind you of all of those querystring parameters because that’s exactly how these are going to be used. These values will build the URL for you when you serve your solution. The IDs and properties all match what was generated (although you are unlikely to keep the testMessage property for long).

The first thing you should do is replace the pageUrl property with the page address in your O365 tenant where you want to test the extension. Keep in mind these values are NOT used in the final package and are only for testing.

The sample above is for an Application Customizer (which is why the location property exists). Each type of extension will have slightly different properties (same as the debug querystrings), but will be added for you with your extension.

Multiple serveConfigurations

If you’re only doing a single extension in your solution and you aren’t using ClientSideProperties then all you need is the default entry using your own pageUrl value. If however, you have multiple extensions, then you’ll want an entry for each so that you can selectively decide which one you are serving when running gulp serve.

It is also comes in handy when you want to test different ClientSideProperty configurations. For my Field Customizer sample SPFx Item Order I allowed users to specify an OrderField property. When it was present the extension did one thing and when it wasn’t it did another.

To make this easy I included 2 serveConfigurations entries (one with the property and one without):

custom serveConfigurations

Using the serveConfigurations

Text in a json file! WOW! But how does this help?

Now when you run gulp serve the default serveConfiguration entry will be used and the browser will go to the pageUrl you specified and the debug querystring will be built using the values you provided!

Even better, you can specify which serveConfiguration you want to use using the –config parameter. So for the Item Order Field Customizer shown above, I could test the custom field configuration by entering this at a command prompt:

gulp serve --config=customField

Now the browser will be launched and my custom property will be set!

You can even see the URL that the browser will be sent to directly in the command output:

GeneratedURL

Aren’t you glad you didn’t have to type that (and get it right)? So, if you’re doing SPFx Extension development, serveConfigurations makes your life much easier!

Join us at Cincinnati SharePoint Saturday on October 14th!

Matt Jimison and I will be presenting Getting Started with the SharePoint Framework (SPFx) on Saturday, October 14th, 2017 in Cincinnati as part of ScarePoint Saturday (SPS Cincinnati)!

SPSCinci17-TitleSlide

Bill Baer will be delivering the keynote: SharePoint, OneDrive, and Digital Transformation – and there are a ton of other great speakers (plus it’s free)!

Our session is at 10:40 and will introduce you to the SharePoint Framework (both web parts and extensions). We’ll actually walk you through getting the various tools installed and ready (bring your laptop) so that by the time you leave you’ll know not only what the SharePoint Framework is, what it can do, and when to use it – you’ll be ready to start experimenting immediately!

Join me at Kansas City SharePoint Saturday on September 16th!

I will be presenting 10 Ways SharePoint Online Will Benefit Your Intranet on Saturday, September 16th, 2017 in Kansas City as part of SPS Kansas City!

There are 20 different sessions across 5 tracks presented by some great speakers and MVPs. All of that for the low low price of free!

1400-hero-kansas-city-mo-dusk-city-view-imgcache-rev1394030674270-web-1400-720

My session:

While many companies have already initiated transformation around their products and customers, that same level of transformation is often not happening around employees. Yet increasing employee productivity can come with an enormous ROI, by streamlining collaboration, reducing the amount of time employees search for content, eliminating manual tasks, and creating faster decision-making that leads to more agile employees and companies.

Discover how you can build a Digital Workspace for your employees by utilizing Office 365 and SharePoint Online to take your Intranet to the next level. By moving to the cloud, we’ll cover how your organization can start delivering more value at an even lower cost. Whether you’re considering a full migration to SharePoint Online or looking at a hybrid scenario, this session will help you envision an even more powerful Intranet for your company.

Key Takeaways:

  • Keep your team connected
    • Access your Intranet from any location and any device, with the ability to also include external parties. Keep information at the fingertips of your employees
  • Embrace an Agile Environment
    • Capitalize on regularly scheduled enhancements to the platform, as well as powerful development capabilities, such as the SharePoint Framework, Microsoft Graph API, PowerApps, and Flow
  • Safe and Secure
    • Discover how SharePoint Online meets security and compliance requirements in even the most demanding environments, while also providing a high level of reliability

What are you waiting for? Go get Registered!

SPFx Extension Toastr Notifications Demo

Applies To: SharePoint Framework

I had the honor of taking part in the PnP JS SIG call (Patterns and Practices JavaScript Special Interest Group) earlier today. On the call I was able to demo a sample I contributed for the SharePoint Framework Extensions called jQuery-Application-Toastr.

You can find a great write-up of the call on the Tech Community. You can also just watch the video directly on YouTube. You can even watch it right here, conveniently queued up to my demo, wowee!

Here are some related links:

Scroll SharePoint Search Results Back to the Top on Paging

Applies To: SharePoint 2013+

By default, when you click on a different page using SharePoint’s Search Results web part’s paging links (shown underneath the search results) the next page of results is shown but you remain at the bottom of the page. This is super dumb.

Paging

This is really easy to fix and requires no custom code at all! There is a property (not exposed in the UI for some reason) called ScrollToTopOnRedraw that is False by default.

To apply this setting to your Search Results web part, simply export the web part. You can do this by choosing to Edit the page and choosing Export… in the web part dropdown menu:

ExportWP

Now, open the .webpart file in a text editor like Notepad and do a quick find for ScrollToTopOnRedraw. Then change the value from False to True and save the file:

ScrcollToTopOnRedraw

Now, choose Delete in that same web part dropdown menu on the current Search Results web part. Then click the Add a Web Part button. Choose Upload a Web Part under the list of categories, then click Choose File and pick the .webpart file we saved a minute ago. Finally click the Upload button:

UploadWebPart

You’ll probably be asked if you want to leave the site. It’s safe to choose Leave.

Click the Add a Web Part button again. Choose the Imported Web Parts category and find your newly uploaded Search Results web part and click Add. You’ll likely have to update the Refinement Target for any refinement web parts on the page as well.

Now, when you page results you’ll be taken back to the top of the results each time!

Join me at Charlotte SharePoint Saturday on August 26th!

I will be presenting Understanding SharePoint Framework Extensions on Saturday, August 26th, 2017 in Charlotte, NC as part of SPS Charlotte!

I’m sure you’ll all attend just for my session – but stay for everything else. Just look at this lineup!

SPSCLT

Andrew Connell will be delivering the keynote, Where are We and Where are We Going?

My session is at 11:15 am and will focus is on understanding how the SharePoint Framework (SPFx) and the Extensions fit within the historical and modern approaches to SharePoint development. The goal is for attendees to know what SPFx is and when to use it, how the extensions fit in the framework, and to know where to go to get additional details. This session is perfect for power users, managers, and developers new to SPFx.

After my session, stick around for the unofficial “Part 2” at 2:15 pm, Andrew Connell’s Modern UI Extensions with the SharePoint Framework – Command Sets, Application, and Field Customizers where he’ll be providing additional depth, details, and demos.

After attending these 2 sessions you should have everything you need to dive into SPFx extensions just in time for the upcoming Release Candidate 1 and General Availability coming later this year!

Extending SharePoint Framework Build Tasks

Applies To: SharePoint Framework

The SharePoint Framework (SPFx) uses gulp as the task runner that builds your solution. You can find out what tasks are available by typing gulp --tasks in the console in the root of your solution. But what if you want to extend these tasks?

There’s an excellent tutorial by Chaks Chandran that demonstrates how to do this: Integrate gulp tasks in SharePoint Framework toolchain. You can find the corresponding sample here: js-extend-gulp.

In this post, I’m going to demonstrate a few items that weren’t addressed in that tutorial including:

  • Checking for a custom parameter
  • Ending your task without a stream and not killing the pipeline
  • Getting a value from one of the Config files
  • Copying a solution file to another location

What Are We Building

I previously discussed how to specify your SharePoint Framework App Icon and in that post I noted that you should not only specify your icon in the solution package itself, but you should make it available outside as well so that you can set the App Catalog Icon URL property.

The best place to host this image is with the rest of your assets in your CDN. So, wouldn’t it be nice if the App Icon image file was copied to the dist folder when the rest of your solution was bundled? Let’s do it!

Basic Rigging

If your familiar with gulp you know that generally gulp tasks are defined in the gulpfile.js file in the root of your solution. More likely, however, you’re not familiar with gulp and don’t really know what a gulp task is for outside of the idea that they do things when you type them in the console.

A gulp task is just a JavaScript function that gets registered with a name (the command) and you can make it do whatever you want. In SPFx, however, all the gulp tasks are defined deep within the node_modules/@microsoft/gulp* folders. You don’t need to do anything with these (although they are worth checking out if your curious how they’re doing all this magic).

To jump in on the fun, you’ll need to use the build object and either rig your task into the pipeline or register it as a standalone task. Again, more detail can be found in the official tutorial. For our purposes, we don’t want a standalone task that we would have to call separately. We want our task to be executed along with the build.

Defining the Task

Open up your gulpfile.js file. Before the build.initialze(gulp) command add your sub task definition:

'use strict';

const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');

let appIconToBundle = build.subTask('app-icon-to-bundle', function(gulp, buildOptions, done) {
	this.log('Wowee!');
});

build.initialize(gulp);

In line 6, we’re simply calling the build.subTask function provided by Microsoft to register our function with the name app-icon-to-bundle (there’s nothing special about this name, just following the same over-hypenation as the default sub tasks).

This doesn’t actually do anything yet because we’ve neither registered it as a standalone task or integrated it into the build pipeline.

Rigging the Task to the Build

You can “rig” your task in 3 spots: PreBuild, PostTypescript, and PostBuild. You can think of these as specifying an event handler and the handler is your sub task. We’re going to add ours to the end of the build by adding line 10 below:

'use strict';

const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');

let appIconToBundle = build.subTask('app-icon-to-bundle', function(gulp, buildOptions, done) {
	this.log('Wowee!');
});

build.rig.addPostBuildTask(appIconToBundle);

build.initialize(gulp);

Now if we execute one of the building tasks (like “bundle” for instance) you’ll see our amazing task getting executed:

Basic Run

Properly Ending Your Task

Some of you may have noticed that there is a message about terminating early. In fact, if you run the gulp serve command you may be surprised to see it stops at the same spot and does none of the actual fanciness of serving your solution. WHAT DID YOU DO!?

The easiest way to fix this is by returning a stream and that’s exactly what is demonstrated in the official sample. But what about when you aren’t doing that? For our task we want to check some things and only proceed when it makes sense. This is hard to do in the context of a stream. The other option is to simply take advantage of the done callback parameter you are provided:

let appIconToBundle = build.subTask('app-icon-to-bundle', function(gulp, buildOptions, done) {
	this.log('Wowee!');
	done();
});

Now when you run the standard tasks you’ll still see our message but the pipeline doesn’t come to a screeching halt. Wowee, indeed.

Checking for a Custom Parameter

For our task, we only want to move the icon file if the --bundleicon parameter is specified. This is a custom parameter and detecting it is surprisingly easy:

let appIconToBundle = build.subTask('app-icon-to-bundle', function(gulp, buildOptions, done) {
	var bundleIcon = (process.argv.indexOf('--bundleicon') !== -1);
	this.log(bundleIcon ? 'Bundling!' : 'Nope!');
	done();
});

In line 7, we simply check for the presence of our custom parameter in the arguments and set a Boolean value. In line 8, we change the message based on the parameter’s inclusion. This could “easily” be extended to actually pull in values after your parameter.

To test this, simply run gulp bundle and then gulp bundle --bundleicon to see the 2 different messages. Our custom parameter works!

Getting a Value From One of the Config Files

Now we know when to actually move the icon based on the parameter, but how do we know where the icon actually is? The App Icon is an image file stored somewhere in the sharepoint folder. It is specified as the solution.iconPath property in the config/package-solution.json file.  More details here: SharePoint Framework App Icon

So, how do we get a value from one of the config files? First, we’ll need 2 helper objects. These objects are already included in your node_modules folder since they are used by the Microsoft build tasks. To gain access to them simply add some require statements below the existing require statements:

const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');

const path = require('path');
const fs = require('fs');

let appIconToBundle = build.subTask('app-icon-to-bundle', function(gulp, buildOptions, done) {
...

Specifically line 6 and 7 above add the path and fs objects which make it easy to work with file paths and reading files. Here’s how we use them:

let appIconToBundle = build.subTask('app-icon-to-bundle', function(gulp, buildOptions, done) {
	var bundleIcon = (process.argv.indexOf('--bundleicon') !== -1);

	if(bundleIcon){
		//Get the config file path
		var psConfigPath = path.join(process.cwd(), 'config', "package-solution.json");

		//read the config file into a JSON object
		var psConfig = undefined;
        try {
            var content = fs.readFileSync(psConfigPath, 'utf8');
            psConfig = JSON.parse(content);
        }
        catch (e) { }

		//Verify an iconPath has been provided
        if(psConfig && psConfig.solution && psConfig.solution.iconPath){
			this.log('./sharepoint/' + psConfig.solution.iconPath)
		}
	}

	done();
});

In line 14 we use the path object to get an absolute path to the package-solution.json config file. Then in line 19 we use the fs object to read the text of the config file. Since the config files are all JSON files, we can simply parse it into an object in line 20.

In line 25 we verify that the property was actually set and has a value. If so, we write it to the log in line 26. We are adding the ‘./sharepoint/’ because the iconPath property is relative to the sharepoint folder in the root of our project.

Copying the App Icon to the Dist Folder

Copying the file to the dist folder can be done using standard gulp:

        if(psConfig && psConfig.solution && psConfig.solution.iconPath){
			gulp.src('./sharepoint/' + psConfig.solution.iconPath)
				.pipe(gulp.dest('./dist'));
		}

The Final Solution

Here’s the final gulpfile.js:

'use strict';

const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');

const path = require('path');
const fs = require('fs');

//When the --bundleicon parameter is used, copies the App Icon image file (when specified) to the dist folder
let appIconToBundle = build.subTask('app-icon-to-bundle', function(gulp, buildOptions, done) {
	//Look for the --bundleicon parameter
	var bundleIcon = (process.argv.indexOf('--bundleicon') !== -1);

	if(bundleIcon){
		//Get the config file path
		var psConfigPath = path.join(process.cwd(), 'config', "package-solution.json");

		//read the config file into a JSON object
		var psConfig = undefined;
        try {
            var content = fs.readFileSync(psConfigPath, 'utf8');
            psConfig = JSON.parse(content);
        }
        catch (e) { }

		//Verify an iconPath has been provided
        if(psConfig && psConfig.solution && psConfig.solution.iconPath){
			//Copy the icon to the assets destination
			gulp.src('./sharepoint/' + psConfig.solution.iconPath)
				.pipe(gulp.dest('./dist'));
		}
	}

	done();
});

build.rig.addPostBuildTask(appIconToBundle);

build.initialize(gulp);

You can find the full solution here: https://github.com/thechriskent/spfx-AppIcon