Contents tagged with SharePoint Framework

  • SharePoint Framework and Microsoft Graph access – convenient but be VERY careful

    Tags: SharePoint Framework, Office 365, Azure AD, Microsoft Graph, SharePoint Online, Security

    SharePoint Framework (SPFx) is a fantastic development model on top of (modern) SharePoint, for user interface extensibility, and it have evolved tremendously over the last year since it became general available. The framework is based on JavaScript extensibility in a controlled manner, compared to the older JavaScript injection mechanisms we used to extend (classic) SharePoint, that comes with a lot of power.

    Using SharePoint Framework our JavaScript has access to the whole DOM in the browser, meaning that we can do essentially what we want with the user interface – however, of course, we shouldn’t, only certain parts of the DOM are allowed/supported for modification. These areas are the custom client-side Web Parts we build (that squared box) or specific place holders (currently only two of them; top and bottom). For me that’s fine (although there’s a need for some more placeholders), but if you want to destroy the UX it is all up to you.

    In our client-side solutions we can call out to web services and fetch data and present to the user and even allow the end-user to manipulate this data. For a while now we’ve had limited access to Microsoft Graph, where Microsoft has done the auth plumbing for us, and now in the latest version (1.4.1) a whole new set of API’s to both call Microsoft Graph, with our own specified permission scopes, and even custom web services protected by Azure AD. Very convenient and you can build some fantastic (demo) solutions with this to show the power of UX extensibility in SharePoint Online.

    However – there are some serious security disadvantages that you probably don’t think or even care of if you’re a small business, a happy hacker or just want to build stuff. For me – designing and building solutions for larger enterprises this scares me and my clients…a lot!

    castle-1461009_640

    Some perspective

    Let’s take a step back and think about JavaScript injections (essentially SPFx is JavaScript injections – just with a fancier name and in a somewhat controlled way). It’s all very basic things, but from recent “social conversations” it seems like “people” forget.

    JavaScript running on a web page, has all the power that an end-user has, one could say even more power, since it can do stuff the user doesn’t see or is aware of. I already mentioned that JavaScript can modify the DOM – like hiding, adding or moving elements around. But it can also execute code, that is not necessarily visible. A good example is for instance to use Microsoft Application Insights to log the behavior of the user or the application – seems like a good thing in most cases (although I don’t think that many users of AppInsights understand how GDPR affects this – but that’s another discussion). We could also use JavaScript to call web services, using the information we have on the page to manipulate the state of the page, and also send data from our page to another page. All without the user noticing it. For good or for bad…let’s come back to the latter in a minute or so.

    No Script sites and the NoScript flag

    Before SharePoint Framework Microsoft introduced “No Script” sites to mitigate the issue with arbitrary JavaScript running in sites and pages. All modern Team sites, based on Office 365 Groups, and OneDrive sites are No Script sites. You can as an admin control the behavior of newly created SharePoint Sites using the settings in the SharePoint admin center (under settings):

    Bad settings for this...

    Depending on when your tenant was created (before or after the addition of this setting) your default settings may be different. My recommendation is, of course, to Prevent users from running custom scripts, to ensure that you don’t get some rogue scripts in there (see below).

    This setting can also be set on individual sites using the following SharePoint Online PowerShell command:

    Set-SPOsite https://contoso.sharepoint.com/sites/site 
    -DenyAddAndCustomizePages 0
    

    More information here: “Allow or prevent custom script

    This setting on a site not only affects JavaScript injections it also prohibits the use of Sandbox solutions and the use of SharePoint Designer – all good things!

    Script Editor Web Part – the wolf in sheep clothes

    “Our favorite” SharePoint extensibility mechanism, specifically for the citizen developers (or whatever you prefer calling them), has been the Script Editor Web Part (SEWP). As an editor of a site in SharePoint we can just drag the SEWP onto a page and add arbitrary scripts to get our job done and we’re done.

    The aforementioned No Script setting will make the Script Editor Web Part unavailable on these sites.

    The Script Editor Web Part does not exist in modern SharePoint. The whole idea with modern SharePoint and SPFx is that we (admins/editors) should have a controlled and managed way to add customizations to a site – and of course SEWP is on a collision course with that. Having that option would violate the whole idea.

    You can read much more about this in the SharePoint Patterns and Practices article called “Migrate existing Script Editor Web Part customizations to the SharePoint Framework”.

    But, there is now a “modern” version of the Script Editor Web Part available as a part of the SharePoint Patterns and Practices samples repository (which is a bit of a shocker to me). This solution is bypassing the whole idea of SharePoint Framework – controlled and governed JavaScript in SharePoint Online. And of course this is being used by a lot of users/tenants – since it’s simple and it works. If  you do use this solution you really should continue reading this…

    SharePoint Framework and Microsoft Graph = power?

    How does this relate to SharePoint Framework then? As I said, with SharePoint Framework we now have a very easy way to access the Microsoft Graph (and other Azure AD secured end-points) with pre-consented permission scopes. As a developer when you build a SharePoint Framework solution you can ask to be granted permissions to the Microsoft Graph and other resources. The admin grants these permissions in the new SharePoint Online admin center under API management.

    API Management in new SPO admin center

    For instance you want to build a Web Part that shows the e-mail or calendar on your portal page, you might want to have access to read and write information to tasks. The possibilities are endless and that is great, or is it?

    I think this is a huge area of concern. Imagine these user stories:

    As a user I would like to see my calendar events on my Intranet” – pretty common request I would say. This requires the SPFx Web Part developer to ask for permissions to read the users calendar.

    “As a user I would like to see and be able to update my Planner tasks” – another very common request. This requires the SPFx Web Part developer to ask for Read and Write access to all Groups (that’s just how it is…).

    Both these scenarios opens up your SharePoint Online solution for malicious attacks in a very severe way. Of course the actual permission has to be approved by an admin – but how many admins do really understand what’s happening when the business cries “we need this feature”.

    Note: this is not just a SharePoint Framework issue, but SPFx makes it so easy that you probably don’t see the forest for the trees. And this is also true for many of these “Intranet-in-a-box” vendors that has made their similar service to access mail/calendars etc from the Graph. It’s still JavaScript and if you allow a single user to add a script it can be misused.

    Rogue scripts

    Once you have granted permissions to the Microsoft Graph, by a single request from that fancy calendar Web Part, all other scripts in the whole tenant has those permissions. So your seemingly harmless Web Part has suddenly exposed your calendar for reading to any other Web Part. Assume that now the admin installs a weather Web Part (downloaded or acquired from a third party). This weather Web Part is now also allowed to read the users e-mail, even though it did not request it. And if that vendor goes rogue or already is, he or she can without the users knowing send all the calendar or e-mail details away to a remote server, while just displaying the weather. This requires some social engineering of course to make the admin install this Web Part. But what about allowing the modern Script Editor Web Part! And you piss an employee off…with just some simple JavaScript knowledge this user can then create a sweet looking cat-of-the-day web part or even a hidden one with the Modern Script Editor Web Part. Then send the boss to that page, and read all the bosses calendar events or e-mails, sending them to some random location somewhere…

    You still think this is a good idea?

    activist-anonymous-ddos-attack-38275

    And what about the second user story; where we need full read and write to all the groups, just to be able to manipulate tasks in Planner. It’s not much you can do, if you’re building this web part – you are opening up for so many more possibilities for “working with” groups and its associated features. This is not a SharePoint Framework thing, but a drawback in how Microsoft Graph works with permissions and the lack of contextual or fine-grained scopes in Azure AD. Same goes for reading/writing data from SharePoint sites – Azure AD/Microsoft Graph cannot restrict you to a single site or list – you have access to all of them.

    Remember how SharePoint Add-ins have Site Collection or list scoped permissions. I guess you all remember how we complained back then as well. That was some sweet days and we really want those features back. Well, we still have them – SharePoint add-ins are probably the best way to protect the users and your IP still…

    As I stated above, of course all SPFx solutions has to be added to the tenant app catalog – but, we also have the option of a site collection scoped catalog. So that’s another vector for insertion of seemingly nice solutions that can take advantage of the permissions you granted on a tenant level.

    The grey area between modern and classic sites

    Currently most SharePoint Online tenants is in a transition period between classic and modern sites. That is, they have built their SharePoint Online environment based on the “classic way” of building stuff, most often requiring script enabled sites. And now they want to transition to modern sites, without these scripting capabilities. Should they just add the new modern Script Editor Web Part or should they turn of scripting for all sites?

    If you turn this off I can almost guarantee that a lot of your sites will be useless. And in many cases your whole Intranet – specifically this happens with many of the “Intranet-in-a-box” vendor solutions. So be careful.

    So, what should I do?

    If you still think it is very valuable to build solutions with SPFx and Microsoft Graph the first thing you MUST do is to ensure that there is not a single site in your tenant with scripting enabled. You can do a quick check for this with this sample PowerShell command:

     get-sposite | 
      ?{$_.DenyAddAndCustomizePages -eq 'Disabled'}

    This will list all the site collections which still allow JavaScript execution using the Script Editor Web Part for instance. If there’s a single site in here, stop what you’re doing and don’t even consider granting SPFx any permissions.

    I wish we had this kind of notification and warning in the permission grant page in the new SharePoint Admin center. To make it very obvious for admins.

    Secondly, be very thoughtful on what solutions you are installing in your app catalog. Do you know the vendor, do you know their code, is their code hosted in a vendor CDN (warning signs – since they can update this without you knowing) etc? Do you have multiple vendors? Who have access to do this?

    So, you really need to do a proper due diligence of the code you let into your SharePoint Online tenant.

    A note on the CDN issue; when you add a SPFx solution to the app catalog all “registered” external script locations are listed. But this is not a guarantee. It’s only those that are registered in the manifest. As a developer you can request other resources dynamically without having them show up on this screen.

    Summary

    I hope that this gave you the chills, and that you start reflecting on these seemingly harmless weather web parts that you install. You as an admin, developer or purchaser of SharePoint Online customizations MUST think this over.

    1. Do we have a plan to move from script enabled sites to ALL sites with no custom scripts enabled
    2. Do we have the knowledge and skill to understand what our developers and vendors are adding to our SharePoint Online tenant
    3. Do we understand the specific permission requirements needed

    I also hope (and know) that the SharePoint Framework product team listens, this is an area which needs to be addressed. We want to build these nicely integrated solutions, but we cannot do it on behalf of security concerns. And it’s NOT about security in SharePoint or SharePoint Framework it is about how web browsers work. What we need is:

    1. Visibility – make it visible to the admins what is really happening in their tenant; script enabled sites, SEWP instances etc.
    2. Isolation – we need to be able to isolate our web parts, so that they and their permissions scopes cannot be intercepted or misused. In the web world I guess that Iframes is the only solution
    3. Granularity - Azure AD permission granularity – it’s not sustainable to give your applications these broad permissions (Group Write All). I want to give my app access to write in one Planner plan only and not in all groups.

    Thanks for reaching the end! I oversimplified some parts, but if you have any concerns, questions or issues with my thinking – don’t hesitate to debate, confront, question or agree with this post.

  • How to generate SharePoint Framework bundles for multiple tenants

    Tags: SharePoint Framework, npm, SharePoint

    If you are an ISV or SI with multiple clients and are interested in building SharePoint Framework (SPFx) solutions that you would like to re-use you will face a huge issue when it comes to reference SharePoint JavaScript files and reference your SharePoint Framework bundles. All these URL's are hardcoded into your solution configuration files and requires you to update these files and rebuild for each and every client environment. And not only that even in your own development team this will cause issues if you don't have a shared development environment.

    This causes a lot of issues and headaches. Each and every developer needs to update the configuration files in the SharePoint Framework - meaning that they will check-out the files and then eventually check them back in with their specific tenant information, which will break the solution for another developer. Same goes if you want to deploy a solution to another client; you check the files out update with the new client information and the more clients you have the worse it gets.

    The SharePoint Framework is essentially built so that you should NOT reference any SharePoint JavaScript files (think CSOM/JSOM) and always host your bundled SPFx files in a public CDN. In practice this doesn't work. There are tons of features in JSOM that you would like to use, such as managed metadata. Also very few clients really want their JavaScripts to be hosted in a location they don't own or have control of.

    So, SharePoint Framework as of now is very limited and it is a mess for you as a developer, SI or ISV. I know, that's exactly where I've been, until now!

    Introducing the spfx-build-url-rewrite node package

    To sort this issue out I've built a node.js package called spfx-build-url-rewrite that helps you re-write those URLs at build time. All it requires is that you in your config files use a specific URL that the package knows about (currently it's contoso.sharepoint.com - I know, I'll make it configurable/better later) and when building you specify the URL you want to replace it with, and voila - you can now automate builds for any number of clients/environments.

    How it works

    First of all you need to install the node module into your SPFx solution using npm:

    npm install spfx-build-url-rewrite --save

    Then you need to modify the gulpfile.js to use this module. Just before the initialize method you need to add two lines so it looks like this:

    const rewrite = require('spfx-build-url-rewrite');
    rewrite.config(build);
    
    build.initialize(gulp);

    Whenever you want to reference a script inside SharePoint, such as the JSOM files or you want the SPFx CDN to be in SharePoint you modify the config.json or write-manifest.json files to use https://contoso.sharepoint.com instead of your tenant URL.

    config.json

    externals in config.json

    write-manifest.json

    cdn base path in write-manifest.json

    Now when you build the solution you append the argument --target-cdn <url> to replace the URLs in your solution, as follows:

    gulp build --target-cdn https://fabrikam.sharepoint.com
    gulp bundle --target-cdn https://fabrikam.sharepoint.com
    gulp package-solution

    If you don't want to specify this for each and every command you can create an empty file called .env and specify the substitution URL in it like this:

    TargetCdn=https://fabrikam.sharepoint.com

    Summary

    I hope this small node package makes your life easier, it sure makes mine! If you have any feedback please use the Github repository.

    And as a final note, even though it is supported to extend the build pipeline of SPFx this is possibly in the grey zone - but it works…on my machine.

  • SharePoint Framework has now reached General Availability - such a great journey

    Tags: SharePoint Framework, Office 365, SharePoint

    Let me start with congratulating the SharePoint Framework team on an amazing job and an amazing journey reaching this GA milestone.

    The SharePoint Framework plays a significant part of the SharePoint future, yes - this is only the first version with a lot of new features on the way, and it is a part of the new SharePoint wave. I've haven't seen this interest in SharePoint for many years and I'm glad I'm still in this business. Delivering top notch collaboration solutions for our clients at Avanade. The SharePoint Framework will make it easier for us to customize SharePoint and it will also bring a lot more value for our clients in the end allowing them to stay evergreen and not being tied into "workarounds" and pesky SharePoint Designer hacks or arbitrary JavaScript snippets.

    I'm extremely glad that I've been a part of this journey, seeing the team making the awesome stuff they've done. For me it started back in the fall of 2015 when we we're shown some very early ideas on where to go next and also some whiteboard sessions where we had an open and frank discussion about what the requirements were from the field. This openness is something that I think has made the difference this time and made the SharePoint Framework into what it is. All discussions was kept very secret and I'll tell you it was hard not to cry out to everyone how excited I was on the progress.

    Early 2016 I was part of the first DevKitchen, where we had the opportunity to use SharePoint Framework for the first time. The team had only in a couple of months created something that actually worked! It was very satisfying to build that first web part (I do think that I was the first outside of Microsoft that actually built a client-side Web Part!).  The framework had its quirks and issues back then, but they kept the speed up and delivered. A few more DevKitchens were hosted and finally in May they revealed the SharePoint Framework to the public.

    Just after the summer everyone could get their hands on the first public release of the SharePoint Framework and the SPFx Team opened the floodgates of feedback through their Github repository. It has been fantastic to see all the support, wishes, bugfixes, samples and documentation that the public (and specifically Waldek) has produced to support the SharePoint Framework. And how fast and agile the team has responded to all the requests and issues. This is how Microsoft should build more stuff!

    I've tried to do my best giving feedback as a consultant, developer and things my clients need. I'm particular proud of the enterprise guidance documentation that I've helped with. I absolutely love being part of this community.

    Now, we're here, within a few weeks all tenants in Office 365 should be able to use the SharePoint Framework to build great stuff and awesome client-side Web Parts. We're already in the midst of porting our solutions to take advantage of the SharePoint Framework and getting it in the hands of our clients.

    Thank you to the SharePoint Framework Team - I'm so looking forward to what's happening next. See you in a few weeks in Redmond ;-).

    Let's make SharePoint great again!

  • SharePoint Framework: how to properly dynamically populate dropdown property pane fields

    Tags: SharePoint Framework

    One of the key parts of SharePoint Web Parts is the ability to have them configurable using the Web Part properties. This story is still true with client-side Web Parts in the new SharePoint Framework. In this post I will show you one of the more common scenarios; how to populate drop downs (and other fields) in the property pane dynamically. But also show you how what's wrong with the current implementation.

    Client-side Web Part Property Pane basics

    The Property Pane in client-side Web Parts are defined by the propertyPaneSettings method. It's a method that returns an IPropertyPaneSettings object representing the pages, groups and fields. This method is invoked whenever you click to edit the Web Part. The method is "synchronous" meaning that you should return a static set of pages, groups and fields - there's no option to wait for it to load (SPFx issue #127).

    Defining the Dropdown

    For a Dropdown we use the PropertyPaneDropdown field and specify for instance it like this, in the propertyPaneSettings method.

    PropertyPaneDropdown('listName', {
      label: strings.DescriptionFieldLabel,
      options: this._options
    })

    In this case the options property references a local variable defined as below:

    private _options: IPropertyPaneDropdownOption[];

    Loading the data…

    But when do we load this data into the local variable. We do have a couple of options to do this, but there really is only one viable option at the moment and that is to use the onInit<T>() method. This method always runs when the Web Part is loaded or is added to a page, and it only runs once and it is the only option we have if we want to load something using a promise and make sure to have it loaded before we have the chance of rendering the property pane. The onInit method returns a Promise and that allows us to actually block the loading of the Web Part until we have the data.

    To load data, mock or live, I've created a simple list data provider, that you can find in the following Gist. Pay attention to the fact that I have set a delay on the mock loading to 5 seconds, this is to simulate a slow request and show you how bad this current implementation actually is. https://gist.github.com/wictorwilen/0bf866ee4fda2f9611f43ee17b9127d5

    Then I implement the onInit method as follows:

    public onInit<T>(): Promise<T> {
      let dataService = (this.context.environment.type === EnvironmentType.Test || this.context.environment.type === EnvironmentType.Local) ?
        new MockListsService() :
        new ListsService(this.context);
    
      this._options = [];
    
      return new Promise<T>((resolve: (args: T) => void, reject: (error: Error) => void) => {
        dataService.getListNames().then(lists => lists.forEach(list => {
          this._options.push(<IPropertyPaneDropdownOption>{
            text: list,
            key: list
          });
          resolve(undefined);
        }))
      });

    First of all I create my data service object (mock or real one). Then I create a new Promise that uses my list service and once the list data is read it populates the local variable holding the data for our dropdown and finally I resolve the promise.

    There are some articles and Github repos that uses another approach, they just return a resolved promise and let the call to the external data service run in the background. If that background request takes to long time (the simulated 5 seconds for instance) or fails then the user might have time to open the property pane and see an empty dropdown.

    Now when the web part is added to a page or a page a loaded with that web part the onInit method will "block" the web part from rendering until it has the data for the property pane. Well, that's not good, but that's how it is at the moment. There is however a possibility that we might be able to use displayMode property of the web part and only do this when we are in edit mode. I have not been able to verify this as the workbench always are in edit mode and none of my tenants actually loads the client side web parts in the modern pages - I'll get back on this.

    Another annoying thing is that since this is blocking the rendering, not even showing a spinning wheel or something, the user experience is quite bad if you have long running calls since nothing is shown (SPFx issue #228).

    Summary

    I've now shown you how to pre-load data for your property pane fields, yes same approach works for other field types than dropdowns as well. But is this the proper way then? Nope, it isn't but I have great hopes that this will be fixed in a better manner (see linked issues). If not we still have the option of creating completely custom property pane fields that allows us to do basically whatever we want.

  • SharePoint Framework Nuggets: working with GUIDs

    Tags: SharePoint Framework

    SharePoint developers - we do like GUIDs, don't we. We all read RFC4122 both once and twice. And now with SharePoint Framework and the goal to embrace all them Macintosh and open source people - they gotta have their fair share of GUIDs.

    And to aid with that the SharePoint Framework got some really nice GUID features, although a bit unpolished as you might notice - but this is all preview bits at the time of writing.

    SharePoint Framework Nuggets - GUIDs

    The Guid class

    First of all we must have the option to create GUIDs. There might be a situation that you need to store something really, really unique - to help with the we do have the Guid class in the @microsoft/client-sp-base module. This class both allows you to create new Guids, parse Guids and validate Guids.

    This is how you import the Guid class:

    import { Guid } from '@microsoft/sp-client-base';

    Then to create a Guid, you use the code below. The newGuid method can take an optional parameter if you need to create a custom random generator. By default it generates a version 4 UUID, also known as a pseudo random UUID, which can be generated in a browser. I suggest you skip passing in custom random generators.

    var guid: Guid = Guid.newGuid();

    What if someone gives a "GUID" to you, can you trust it is a proper Guid, no you can't you need to validate it. That can be done using the isValid method, which takes a string as in input.

    if( Guid.isValid(' f0a1f189-dae4-49f5-8846-3a17429fd52') ) { alert('Valid') };

    Then we finally also have a method to parse a string potentially containing a Guid, tryParse. The method will either return a Guid object or undefined.

    var guid: Guid = Guid.tryParse('f0a1f189-dae4-49f5-8846-3a17429fd52');

    The GuidHelpers class (@internal)

    [Update 2016-09-20] - The GuidHelpers class is marked internal and will be removed in future builds of the SharePoint Framework.

    There's also another class in SharePoint Framework for Guids, the GuidHelpers class. This class lives in the @microsoft/sp-client-preview module. It has a set of similar function to generate and validate Guids, but it does not work with Guid objects, it uses strings instead. For instance the GuidHelpers.generateGuid() returns a string. Another issue is that the GuidHelpers.isValid() does not validate Guids the same way as the Guid.isValid does (issue #201 in the SPFx Repo).

    GUID validation issues

    At the moment (drop 3 of SPFx) I would stay away from the GuidHelpers class.

    As usual there's some code samples of this to be found in this Github repo: https://github.com/wictorwilen/spfx-nuggets

    Happy GUIDing!

  • SharePoint Framework Nuggets: logging like a pro

    Tags: SharePoint Framework, SharePoint

    I guess that almost every application or solution you ever built has contained some portions of a logging mechanism. And how many of you have written your own - yup, all of you! But what about the SharePoint Framework - yes, it has built-in logging!

    SharePoint Framework Nuggets - logging like a pro

    How to log in the SharePoint Framework

    Logging is a very convenient and easy way to keep track of events happening, instead of having breakpoints, or in JavaScript even worse - alerts. The SharePoint Framework (SPFx) has as all decent frameworks a built-in logging mechanism, albeit very simple, but still yet valuable. It's contained in the @microsoft/sp-client-base module and the class is called Log. To use it in your SharePoint Framework solutions you need to import it as follows:

    import {
      Log
    } from '@microsoft/sp-client-base';

    The Log class contains four static methods for logging:

    • info
    • warn
    • error
    • verbose

    The names are exactly what you expect, the info is used for information, warn for warnings, error for errors and verbose for when you just have to much on your mind and want to spit it out.

    In the SharePoint Framework implementation all logging is done to the JavaScript console and you can see the logging using the developer tools of your favorite browser. It can take some searching to find them as SPFx spits out quite a lot of logging by itself.

    All static methods have the same signature, except the error method - they take three arguments:

    • source: the source of the logging information (max 20 characters), such as method or class name
    • message: the actual message to log (max 100 characters)
    • scope: an optional service scope (more on this one later)

    The error method takes an Error object instead of the message string, otherwise they are the same.

    This is how it could be used in client side web part:

    public render(): void {
      this.context.statusRenderer.clearError(this.domElement);
      this.context.statusRenderer.displayLoadingIndicator(this.domElement, strings.Loading);
      Log.verbose('SpFxNuggets', 'Invoking render');
    
      this._webInfoProvider.getWebInfo().then((webInfo: IWebInfo) => {
        if (this.properties.fail) {
          throw new Error('Mayday');
        }
        Log.info('SpFxNuggets', 'Service OK', this.context.serviceScope);
        this.context.statusRenderer.clearLoadingIndicator(this.domElement);
        this.context.domElement.innerHTML = `<h1>${webInfo.title}</h1>`;
    
      }).catch((err) => {
        Log.error('SpFxNuggets', err);
        this.context.statusRenderer.clearLoadingIndicator(this.domElement);
        this.context.statusRenderer.renderError(this.domElement, err);
      });
    }
    

    In the example above I use the verbose method to log that we're in the render method. Just verbose information. I also added logging to when the service returns (the promise is fulfilled) to log information that it has returned. In that info method I use the service scope of the web part, and when using the service scope, it replaces my source with the real name (JavaScript name) of the web part. Finally I log the error in the catch method. The image below shows the console output.

    Console output

    As usual you can find all the source code in this repository: https://github.com/wictorwilen/spfx-nuggets

    Happy logging!

  • SharePoint Framework Nuggets: render error messages

    Tags: SharePoint Framework, SharePoint

    Do you write code that potentially can throw an error or an exception? Oh, you don't - but sure you use a web service or external service or something that can throw an error. Well, it is you responsibility to handle the error and make sure to inform the user in a good way that something bad happened. With that I mean, do not show just a Guid.

    With the SharePoint Framework being all client side I think it is important to have control of your client side Web Parts and make sure that you properly handle and display error messages in a consistent way. In this short post I will not go in to the JavaScript error handling details, but rather show you another nugget in the SharePoint Framework that helps you render error messages in a standardized and consistent way.

    SharePoint Framework Nuggets - Render error messages

    Render Error messages

    Just as in the last post on the loading indicator the SharePoint Framework actually has built-in functions for rendering messages in SharePointy way. In the same class (and interface) as we had the loading indicator functions we also have two methods for managing error messages, found in the context of the current client side Web Part.

    • renderError(domElement: HTMLElement, error: Error | string): void;
    • clearError(domElement: HTMLElement): void;

    The renderError  method is used to display an error message in an HTML element. It has one parameter for the error message, which can either be a string or an Error object. And the clearError removes any rendered errors in the specified DOM element.

    Here's an example on how we could use it:

    public render(): void {
      this.context.statusRenderer.clearError(this.domElement);
      this.context.statusRenderer.displayLoadingIndicator(this.domElement, strings.Loading);
    
      this._webInfoProvider.getWebInfo().then((webInfo: IWebInfo) => {
        if(this.properties.fail) {
          throw new Error('Mayday');
        }
        this.context.statusRenderer.clearLoadingIndicator(this.domElement);
        this.context.domElement.innerHTML = `<h1>${webInfo.title}</h1>`;
    
      }).catch( (err) => {
        this.context.statusRenderer.clearLoadingIndicator(this.domElement);
        this.context.statusRenderer.renderError(this.domElement, err);
      });
    }
    

    It's the same render method that was in the loading indicator demo but with the difference that we have added the clearError method at the beginning of the render method (once again a redundant operation since the displayLoadingIndicator will override anything inside the DOM element, but you get the point). Then I introduced a property on the Web Part that when set it will throw an error and in our catch method we use the renderError method to render the error, as shown below.

    SPFxNuggets-error

    Fully working code can be found at this repo: https://github.com/wictorwilen/spfx-nuggets

    If you carefully explored the latest drops of the SharePoint Framework (yes, this is all still beta and bits and pieces are moving around) you might notice that the BaseClientSideWebPart contains direct access to these methods (clearError and renderError). The clearError is just calling out to the statusRenderer while the renderError method first clears the loading indicator, as I do manually above, then renders the error and finally also logs the error.

    Good luck!

  • SharePoint Framework nuggets: the loading indicator

    Tags: SharePoint Framework, SharePoint

    SharePoint Framework is all about rendering stuff on the client side, avoiding the long overdue ASP.NET Web Forms technology that SharePoint (Online) is still fundamentally based on. When rendering things client side everything is done asynchronously, to avoid locking down the UI threads and having a user experience that is fluent.

    In order to give the user good feedback that things are happening in the background, you need to have some kind of visual cue that tells the user - hey I'm doing stuff now, gimme a minute. There are thousands of different ways to do this and everyone does it differently; ranging from animated gifs to "loading" texts. And everyone using different methods does not always help with the user experience - so why don't we have a common way to do this?

    We actually do have this built into the SharePoint Framework!

    SharePoint Framework Nuggets - The Loading Indicator

    The SharePoint Framework Loading Indicator

    The SharePoint Framework contains a set of nifty methods that we can use to show a loading indicator in standardized and common way.

    The SharePoint Framework contains a special interface and corresponding implementation that is called IClientSideWebPartStatusRenderer. This interface defines two methods:

    • displayLoadingIndicator(domElement: Element, loadingMessage: string): void;
    • clearLoadingIndicator(domElement: Element): void;

    The first one, displayLoadingIndicator, is used to create a loading indicator with a spinning wheel and a loading text and then replace the inner contents of a HTML element with that code. For instance, for client-side Web Parts that is loading data dynamically should use this as one of the first things in the render() method. The second one, clearLoadingIndicator, does the opposite, it removes the loading indicator.

    The IClientSideWebPartStatusRenderer is always accessible through the IWebPartContext, that is on the context object of your Web Part.

    Here's an example on how to use it:

    public render(): void {
      this.context.statusRenderer.displayLoadingIndicator(this.domElement, strings.Loading);
    
      this._webInfoProvider.getWebInfo().then((webInfo: IWebInfo) => {
        this.context.statusRenderer.clearLoadingIndicator(this.domElement);
        this.context.domElement.innerHTML = `<h1>${webInfo.title}</h1>`;
      });
    }
    

    As you can see the first things we do is to replace the whole client side Web Part with the loading indicator and a loading message. Then once our Web Part is done and have data to render, we clear out the loading indicator before rendering our stuff. In this case it is a redundant operation to clear the loading indicator, since we are replacing the whole Web Part HTML with our custom rendering. If we had a more advanced user interface we could put the loading indicator in another of our elements and then remove it.

    And this would be how it looks like in the SharePoint Workbench, when loading for 2 seconds.

    SPFxNuggets-loading

    You can get a copy of all the code at this Github repository: https://github.com/wictorwilen/spfx-nuggets

    Happy Web parting!

  • Conference season, fall 2016, and where I'll be

    Tags: Presentations, SharePoint Framework

    Summer is over, slacking time is over, it's time to get up to speed and learn some new stuff. There's very much to talk about this fall if you're interested in SharePoint. And this fall I will do a couple of conferences as a speaker, which I very much looking forward to.

    TechDays 2016, Amsterdam

    For the first time I will attend and present at the TechDays 2016 in Amsterdam, the 4th and 5th of October. A local conference hosted by Microsoft. I will present three sessions:

    • Introducing the SharePoint Framework
    • Deep dive building client-side Web Parts using SharePoint Framework
    • SharePoint Futures - Christmas came early this year!

     

    The SharePoint and Office 365 track will be outstanding with where you also can listen to Waldek Mastykarz and Albert-Jan Schot.

    SharePoint and Exchange Forum, now SEF Unity Connect

    I don't know for how many years I've done this show, SEForum, 26th to 28th of October. It's the best conference for SharePoint, Office 365 and Exchange in Sweden, the Nordics, Scandinavia. And you'll find all the experts here, such as Spencer Harbar, Eric Schupps, Jesper Ståhle just to mention a few. This year I'm honored to do the keynote, together with Dan Holme (Microsoft). It will be a blast! And I will also do the following break-outs:

    • Building Modern Solutions with the SharePoint Framework
    • SharePoint as an Intranet

     

    If you're planning to attend, please use this code SEFWICW10 to get 10% off!

     

    If you're around, come by and say hi, looking forward to meeting you all out there on the road.

  • The SharePoint Framework (SPFx) is here!

    Tags: SharePoint, SharePoint 2016, SharePoint Online, SharePoint Framework

    Today is the day many of us have been waiting for since the big SharePoint event at May the 4th. The highly anticipated SharePoint Framework (SPFx) is here and announced in at the SharePointFest, in this blog post, as well as in the new Github repo for SharePoint. Personally I've been waiting for this even longer after being involved by the product team to give early feedback and also attending the first top secret DevKitchen "hackathons" where we could try out very early bits.

    That feeling when you use the SharePoint Framework the first time...

    The first release of many to come…

    This is the initial public preview release, officially christened the SharePoint Framework Developer Preview, is a beta, maybe an alpha, of the SharePoint Framework. This is by no means something you should use or deploy to production. Things will change! Period. There are several known issues at the moment and some of them will likely incur breaking changes. But please, build stuff and give feedback to the product team, use the Issues feature in the Github repo.

    This initial release focuses on client-side Web Parts which can, once released, be used in you classic SharePoint sites and pages as well as in the new modern user experience that is slowly being rolled out throughout the suite. As some of you know, I've spent quite some time on Web Parts and written a book on the topic, so this is something that gets me really excited.

    How and where to get it!

    All you need to do to get your hands on it is to follow the instructions on the Github repo. I'm sure we'll see tens and hundreds of blog posts on how to do it, but I recommend you to follow the one in the repo to start with. And, if you can't follow it, create an issue, make a pull request with an update - make sure we get good official documentation! Heck, I'm pretty sure I will write a couple of posts on the topic, but I will also continue to provide feedback on the framework and the documentation.

    You will find samples, documentation and all you need in a set of brand new repositories in Github, also under a brand user/organization called…SharePoint (yes, no more generic Office dev, SharePoint is back!).

    Need to know more?

    Keep the conversation going on Twitter, SharePoint Stack Overflow, the new Office 365 Community network and other social media, and do use the #SPFx hashtag. I'll try to hang around at the SharePoint Stack Overflow as much as possible, since that is the best platform of the above mentioned ones.

    I've previously written a Q&A on SharePoint Framework and will continue to update that post with details and changes in the current preview release.

    Now, go, build something awesome!

About Wictor...

Wictor Wilén is the Nordic Digital Workplace Lead working at Avanade. Wictor has achieved the Microsoft Certified Architect (MCA) - SharePoint 2010, Microsoft Certified Solutions Master (MCSM) - SharePoint  and Microsoft Certified Master (MCM) - SharePoint 2010 certifications. He has also been awarded Microsoft Most Valuable Professional (MVP) for seven consecutive years.

And a word from our sponsors...