Showing posts with label SharePoint. Show all posts
Showing posts with label SharePoint. Show all posts

Tuesday, 25 April 2017

Using TypeScript async/await to simplify your SPFx code

I recently learned about the Async/Await functionality in TypeScript and I was really surprised how easily you can simplify your code with it. Using Async/Await, you can get rid of spaghetti code as well as long chains of Promises and callbacks in your asynchronous functions.

The Async/Await functionality has been around since TypeScript 1.7 but back then it was only available for the ES6/ES2016 runtime. Since TypeScript 2.1, async/await works for ES5 and ES3 runtimes as well, which is very good news. I am kicking myself that I did not start using it sooner.

As with anything new I learn, I have tried to apply it to SharePoint as well to see how I can improve my development experience. Turns out using async/await can really make your SharePoint Framework code simpler and more readable. Lets have a look at some examples and compare between using Promises and Async/Await in your code.

Also, an important thing to note is that although I am making comparisons between using Promises and using async/await, ultimately the aync/await code is downleveled to using Promises by the typescript compiler. If the runtime does not have a native Promise object, we should make sure we have the right polyfills available.

The comparison here is more around code readability and conciseness.

All the code I am using is running inside a SharePoint Framework webpart. So, when you see the 'this' keyword in the code, it refers to my SPFx webpart which inherits from the BaseClientSideWebPart class. Since I am calling the code from inside my webpart, I have access to 'this'.

Here is my import statements for the code:


Simple example using Promises and 'then' callbacks:



Same code using async/await:



Here is a slightly more complex example with code which accepts an array of SharePoint login names and uses the batching framework to get the user profile properties of each user in the array.

You will need the IPerson interface for this:


Complex example using Promises and 'then' callbacks:



Same code using async/await:



As you can see, there is significantly less callbacks when using async/await and the code is also a lot more readable.

Hope you found this post useful. Thanks for reading!


Monday, 22 August 2016

Making a POST request to SharePoint from an SPFx webpart

In this post, let's see how to make an HTTP POST request from an SharePoint Framework (SPFx) web part. There are lots of posts out already which show you how to make a GET request so I will not cover that here. It is fairly straightforward once you understand all the moving parts.

Import the necessary modules in your SPFx webpart code:

Now, the code which makes a POST request to create a list:

And my "Developer workbench" list is created:



Hope this helps.

Sunday, 14 August 2016

Upload changed display templates to SharePoint using Gulp

Here is a quick tip which might be helpful when working with display templates. A typical SharePoint solution can have a large number of display templates but while working with them, you might me modifying/customizing only one at a time. Here is a quick gulp task I have put together which watches for changes in the HTML file of the display template and uploads only the changed display templates to the Master Page gallery.

Then I just start the watch task and change/save a display template:



Whenever I save an HTML file of my display template, it gets uploaded and checked-in in the Master Page Gallery. That causes a corresponding JS file to get generated automatically so I don't have to worry about managing it. 



If you are maintaining your Display Template JS files in source control, you will have to remember to copy the generated JS file back into your solution. 

Hope this helps you speed up your Display Template development. I have uploaded this project on GitHub here: https://github.com/vman/Gulp.DisplayTemplates

Thanks for reading!



Monday, 18 July 2016

Getting started with TypeScript, Browserify and Gulp in SharePoint

In my previous post Simple bundle, minify and upload JS to SharePoint using Gulp we saw how Gulp tasks can be used to simplify our JavaScript development experience in SharePoint. I am really impressed with Gulp as it has increased my productivity and I don't remember the last time I used SharePoint Designer :)

Now let's see how can we bring TypeScript into the mix. I have been playing around with TypeScript for a while now and here is my basic development workflow:

1) Create a main app.ts file which will contain the primary code for my application or "WebPart". In addition, app.ts will also have import references to any custom or third party modules e.g. jQuery

3) Use tslint to check the quality of my TypeScript

4) Use browserify and tsify to parse my TypeScript file and create a single JavaScript file (app.js) which includes all the dependencies required to run my app.

5) Minify my app.js using gulp-uglify and rename it to app.min.js using gulp-rename

6) Upload the debug and minified files to the Style Library in SharePoint using gulp-spsave

7) Then the JavaScript files can be used any way I like e.g. embed it using a Custom Action or in a Script Editor or a Content Editor WebPart.

Before we begin, if you are using Visual Studio 2015 like me, make sure you have the latest version of Node installed and Visual Studio is configured to use it. Here is an excellent tutorial on how to do this: How to configure Visual Studio 2015 with the latest version of Node.js and NPM

Now let us have a look at the important bits of my solution. I have uploaded the entire solution on GitHub here: https://github.com/vman/MyTypeScript

1) app.ts file:


At the top, the import statements are used to indicate that the code in this file is dependent on these modules. The first being jQuery and the second being my custom User module. Next, we simply create an object of the User class and call it's getDetails and displayDetails methods.

2) User.ts


There is a bit more going on in my User.ts class. Just like my app.ts, the first line indicates, with an import statement, that this file is dependent on the jQuery module. The getDetails function gets the AccountName, DisplayName and Email of the current user from the SharePoint REST API and stores them as properties of the current instance. The  displayDetails function logs the same properties (of the current instance) to the console.

3) package.json


Here is a list of all npm packages used in my solution. Notice the jQuery package, browserify and tsify use it to include jQuery in the final bundle as it is requested by my app.


4) gulpfile.js


And finally, here is my gulpfile.js which does all the heavy lifting:


5) Gulp tasks:


The watch-ts-upload-to-sp task looks for any changes in the .ts files (app.ts and User.ts). If any changes are noticed, it runs the upload-to-sp task.

The upload-to-sp task has dependencies chained up so that the tasks are run in the following order:

1) lint-ts to check the code quality of TypeScript
2) browserify to import all the required modules and create a single app.js bundle file
3) minify-js to create a minified file.
4) Finally, the upload-to-sp task runs to upload the app.js and app.min.js files to the Style Library.

(click to zoom)


A note on Typings:


TypeScript uses TypeScript definition '.d.ts' files to provide intellisense while writing a file. The TypeScript Definition Manager "Typings" is the current recommended approach of including definition files in your project: https://github.com/typings/typings

I have included typings as an NPM package in my solution (have a look my package.json file) and then used the following commands to get the required typings in my project:

Thanks for reading!

Sunday, 26 July 2015

JSOM Provisioning: Creating SharePoint artifacts without declarative XML

The recent guidance from Microsoft regarding the provisioning of SharePoint artifacts is pretty clear. The recommendation is to completely move away from declarative creation of Site Columns, Content Types etc. and instead, create them completely from code.

To support this approach of programmatically creating artifacts, a lot of work is being done on the "Provisioning Engine" in the OfficeDev Patterns and Practices Library on GitHub. To put it very simply, the Provisioning Engine reads a predefined XML file called the "PnP Provisioning Schema" and creates all the SharePoint artifacts using CSOM. Since this engine predominantly uses C#/.NET, it is expected to be run from somewhere like an Azure Web Job, a Web Application on an IIS server or a simple console application.

This method of provisioning is great for clients who opt for Azure subscriptions or IIS servers along with their SharePoint roll-outs. But this is not necessarily true with clients who only want to go for SharePoint or who do not have enough budget for additional Azure or IIS installs. So far, the only option in these cases is to go with the traditional declarative XML based provisioning using No Code Sandbox Solutions (NCSS). This approach is still valid at this time and Microsoft has stated that No Code Sandbox Solutions continue to remain supported:
http://blogs.msdn.com/b/sharepointdev/archive/2014/01/14/deprecation-of-custom-code-in-sandboxed-solutions.aspx

Still, in this post I am going to explore another form of provisioning SharePoint artifacts completely based on the JavaScript Object Model (JSOM). Since the provisioning is done completely from JavaScript running in the browser, there is no need for a platform like Azure or IIS to run this code. I came across the following project in Office Dev PnP which shows how to use a SharePoint hosted Add-In (App) to create artifacts like Site Columns and Content Types etc. in the host web.

https://github.com/OfficeDev/PnP/tree/master/Samples/Provisioning.Jsom

Some code examples from the project:

1) Create Site Column:




2) Create Content Type:




Here are my observations about this approach:


1) This project uses a SharePoint Hosted Add-In (App) to run the JSOM code. But with a few modifications, it can be made to run from a JavaScript file provisioned to a document library with a No Code Sandbox solution. The readme file of this solution mentions an additional project "Provisioning.Jsom.Ncss" which seems to be missing from the solution. My guess is this project did the exact same thing. With this approach, we remove the dependency on the Add-In (App) Model for provisioning.

2) Currently for values like site column names, types, content type names etc hard coded strings are being used. This can be modified to be read from an XML file, preferably the PnP Provisioning Schema. The schema XML file can be deployed with the Provisioning JavaScript file in the NCSS itself.

3) This approach can be used to create sub sites but not site collections as there is no way right now to create site collections through JSOM. So the deployment process will have to be manual creation of a Site Collection with an empty web template, and then to upload the WSP which will deploy the JS file to the SharePoint site. This file will then do the artifact provisioning.

I am going to explore these options and will post something in the future around this approach.

Thanks for reading. Hope you find this information useful in some way!