Office Development – Minimal Code in practice

MinimalCode

Returning on my last ‘minimal code’ blog post, I promised to get back on this to see how this works in practice. One of my question marks I added to the post was that I wondered why the Yeoman boilerplate was using run instead of RequestContext where run passed a context parameter as opposed to the RequestContext where actively a context is requested before accessing the Word object model.

I think I found an answer to that, but will save this to a later date as I first want to make sure the minimal code I provided would work and I found some issues in the original posted code that didn’t seem to be correct.

Here is the updated code that should work in real life:

(() => {

   async function MinimalWordmethod() {

      // Create the client request context. You’ll do this for al Word add-ins.

      var ctx = new Word.RequestContext();

      // Do your things here, such as ..

      var range = ctx.document.getSelection();

      range.insertText("Test MinimalWordMethod", "After");

      await ctx.sync();

   }

   MinimalWordmethod();

})();

How to get the minimal code running

If you go back to the Yeoman project instructions in this post (and fixed the certificate issues in post Office Development – Fixing Trusted Authority – Word Client and https://maartenvanstam.wordpress.com/2017/08/07/office-development-fixing-certificate-issue-with-openssl-certificate/) you should already have a working Word Add-in.

Open the project folder (or if you already deleted it quickly create a new one following my instructions from my earlier blogposts) and open the file app.ts in the src source folder.

Replace all the code from this file with the code above, save it and start your Add-in ‘server’ by running npm start in the root of your project.

Opening Word, with the installed Add-in (again, if you already dropped it follow my other blogposts earlier this month to install it) will show you the Add-in button:

addin7

By clicking the button the Taskpane is showing, just like we’ve seen before as we haven’t changed the Taskpane ‘web’ code, but now you should see the words “Test MinimalWordMethod” arriving in your document:

MinimalCode2

As you can see the code worked! Here is how:

MinimalWordmethod();

This line is automatically triggered when the code is running on startup of the Add-in. By doing so inside the MinimalWordmethod a context is requested in this line:

var ctx = new Word.RequestContext();

If the context is returned correctly you now can access the Word object model to access parts of the document. In this case we access the selected Range object and insert the text right after the Range:

var range = ctx.document.getSelection();
range.insertText("Test MinimalWordMethod", "After");

Instead of having this executed immediately like we’ve seen in VBA or VSTO, the text is only inserted after calling the sync method on the context. In the JavaScript APIs for Office calls to Office are handled asynchronously and to work with that the await and async keywords can be found in the code.

Very simple and basic code, but there are some drawbacks you need to keep in mind. For instance, because things are async, how do you know what the right order is how things are processed. And what about batch processing of boatloads of instructions? Will this all be handled correctly, and what if there are dependencies between the batched instructions? All of these questions arise when looking at this little piece of code, and we need to address all of that in later posts.

To be continued … It’s a never ending story Smile

Office Development – Word Add-in, minimal code

So far it has been fairly complex, installing lots of components and doing all sorts of things before you get things to work. But what do you need for code to do just the minimal thing in a Word Add-in?

Initially it is said that a context is required by requesting a new context:

var ctx = new Word.RequestContext();

With this context you can do things the things you’d like to do.

function MinimalWordmethod() {
  
// Create the client request context. You’ll do this for al Word add-ins.

   var ctx = new Word.RequestContext();

   // Do your things here, such as ..
   var range = ctx.document.getSelection();

   ctx.executeAsync()
     
.then(function () {})
     
.catch(function(error){
        
console.log("ERROR: " + JSON.stringify(error));
     
});
}

Interesting part is that this RequestContext is not to be found in the Yeoman boilerplate, so it looks like it is initialized by the framework these days …

I want to find out where this happened in the Yeoman boilerplate. As far as I can tell the documentation is not all too clear about this.

To be continued too Winking smile

Office Development – Coding in Script Lab

clip_image002

One of the nice things in Script Lab is that you can connect it to GitHub allowing you to share your code snippets or import code snippets from other people. If you opened the Script Lab Task Pane you will notice this little person icon with an even smaller plus sign.

clip_image004

With this button you can authorize Script Lab to access your GitHub account where it needs read and write access to read or write Gists. According to GitHub:

Gists are a great way to share your work. You can share single files, parts of files, or full applications. You can access gists at https://gist.github.com.

A great option to either store your scripts that you created by Script Lab for your own use but even better: to share the code with others. Get feedback, or simply make someone happy by providing the code to the community!

Clicking the button will ask you for your permission on your GitHub account. The permissions are not all that shocking, you just give permission to create, edit and get Gists from your account to be able to show it in Script Lab.

clip_image006

After providing your authorization you can go into your GitHub account and see the permission you just granted to Script Lab:

clip_image008

From there you can also revoke the permissions if you think they shouldn’t need the access anymore. In general, it is a good idea to go in there every now and then to evaluate who can access your code and are they still in the position where they need access. Over time the number of permissions can grow while maybe you don’t use many of the services anymore. If so, time to clean up while you are at it!

Now that you provided access to your Gists you’ll notice the little person icon changed into your profile icon:

clip_image010

Clicking the little profile icon will allow you to see the attached GitHub account and if you like, just to sign out of your account. Cancel will bring you back into Script Lab (I probably would have titled the button “Close” instead of “Cancel”, not it gives you the impression that Cancel will disconnect the GitHub account from Script Lab, but it doesn’t).

clip_image012

Now, your GitHub account is connected to Script Lab you can share your code snippets to Gists on GitHub. This is done through the “ Share” button. The share button has options to:

Publish a new Public Gist (for everyone to see), a new Private Gist (for your eyes only), Copy to Clipboard or to export the snippets:

clip_image014

Using the option “New public gist” will push the content you created in Script Lab to GitHub. Make sure that before you do this the title property of the Script Lab project is what you want to call it. This will be adopted by GitHub as you’ll see a bit further down in this blogpost. The confirmation looks like this and will provide you the URL of the Gist that you just created. With this URL you can import the Gist at a later time.

clip_image016

If you take the URL and open it in the browser you’ll see your code on GitHub:

clip_image018

It created a new Gist, nicely formatted on GitHub and the menu changed into “Update existing gist”. If you edit your code, push the “Update existing gist” option Script Lab will go out to GitHub again and save the changes.

clip_image020

This is how it looks like on GitHub. Going into the revisions tab you can see that the line where I changed the color was updated. The line with color red was removed and replaced by the line with the color blue in it.

clip_image022

How to restore your gist?

On GitHub if you navigate to your gist you can find on the top right the URL that comes with the gist. Obviously you can also just use the URL you just used to navigate, but GitHub will provide you several other options such an embedded url to put it on your website or clone the code. Here we copy the URL:

clip_image024

Next you go into the Script Lab menu (the ‘hamburger’ menu top left) to show you the Import option. Clicking the Import option provides you with a new dialog where you can enter the snippet URL or GitHub Gist ID:

clip_image026

Enter the URL and import the snippet. Now your Script Lab is filled with the code from the Gist, ready for you to continue your coding.

In follow-up blogposts, I will use this to test and experiment with some of the JavaScript for Office (aka OfficeJS) APIs. I really like this export option to gists. Maybe I will build a small collection of snippets for all the tested APIs for later reference.

Office Development – Installing Script Lab

Yesterday in my blog a short introduction to Script Lab, the Microsoft Garage project to work in some sort of a playground to develop your JavaScript for Office scripts so you can test-drive your code that you plan to use in your Add-in.

Today I will go over the installation process of Script Lab. Step by step I’ll follow the instructions and see what this looks like. How hard can it be ‘ey?

To start installing navigate to https://aka.ms/getscriptlab. It looks like this:

clip_image002

Click the Add button to arrive at the guided installation page:

clip_image004

To stay in the mood, we select Word again. I’ll will be using other clients like Excel or PowerPoint soon, but to be consistent I’ll select Word again. This will provide you with a comparable environment and maybe you get used to it. Now, to open in Word click the “Open in Word” option. This will ‘warn’ you that you are about to switch applications:

clip_image006

As this is the plan, you want to move into Word instead of staying in Microsoft Edge. Select ‘Yes’ to go on. This will launch Microsoft Word 2016 (assuming you have Office 2016 installed):

clip_image008

A document is opened, but not without warning. Because you open the document from the dark and dangerous Internet you are provided with a warning and start in the Protected View of Office:

clip_image010

In this case we tend to trust Microsoft in this we continue our journey by pressing “Enable Editing” but now we run into a second warning because the document also contained a Task pane that wants to run the Script Lab Add-in.

clip_image012

Again to make you feel safe, you don’t want any add-in to kick in without your confirmation, you get the option to “Trust this add-in” or “See Details”.

clip_image014

If you click “See Details” they bring you back to base. The installer page is provided where you can read information about the add-in. I guess you already did that, otherwise you wouldn’t get this far in the installation process (unless you just trusted my simple introduction and went ahead ). For now, not all that interesting, so we close this and leave it for what it is.

clip_image016

We go ahead, and decide to trust this add-in. This will bring us the Script Lab tab:

clip_image018

Showing you a balloon with the text “Code, Run and share your Add-in snippets directly from Office” and a “Got It” button to confirm:

clip_image020

Click the Script Lab and you’ll see a ribbon appear with the options:

Code, Run, Tutorial, Help, Reference Docs and Ask the Community

clip_image022

The most obvious thing to do would probably be to go through the Tutorial, at least that was what I picked as a starting point. The interesting thing is however that the Tutorial brings you to an Excel environment to explain you what you can do with the Add-in:

clip_image024

You basically go through all the same steps again, but ending up in Excel showing you all the same options. Open a script-lab-tutorial.xlsx from script-lab.azureedge.net :

clip_image026

This is an Excel starter document with more information about the Add-in and guiding you through the options:

clip_image028

Again the little Protected View warning and the Enable Editing button.

clip_image030

It didn’t provide me with the Script Lab Add-in tab though, only the instructions that you also saw when running the Word installer, except now for Excel.

clip_image032

This wasn’t really what I was looking for, probably useful if I just started from Excel but I didn’t. I went through the GitHub issues and noticed that getting a Word Tutorial is still in planning. Some patience here.

For now, at least the Word Script Lab Add-in is installed and ready to use.

To be continued

Office Development – Microsoft Garage Script Lab

clip_image002

Up to now we researched creating and deploying a simple Office Add-in in Word Online and Word on your local machine. We still need to see how this Add-in can be deployed to a so called production environment, maybe even with a dev and staging level.

We also didn’t do much development so far. We just generated a boiler-plate project using Yeoman but we need to dive in some more and look at some real code to learn how your JavaScript for Office solutions would work.

To do so Microsoft released an interesting tool as a Microsoft Garage project called Script Lab. With this tool you can code, write your test scripts and interactively test the outcome of your work. Based on the Monaco editor, yes … the one that also powers VS Code, you get a lightweight editor with in-editor-help like IntelliSense inside your Office client application. Your code snippets can use a wide variety of options such as JavaScript, TypeScript, HTML, CSS and more.

The code can run from another pane giving you options to interact with the UI, address the JavaScript for Office API and providing monitoring options such as output to a console

When you are done coding, tested it and added all the comments you now can share your snippets to GitHub right from the tool ready to share to your peer developers. With the Import function, you can do the same with code you got from shared snippets that you received from others.

Microsoft Garage Script Lab lived for a long time internally starting off a simple personal project under a different name but eventually matured by a hackathon and many other improvements to the tool you see today. The list of supported environments is huge:

The add-in works in:

Excel 2013 Service Pack 1 or later, Excel 2016 for Mac, Excel 2016 or later, Excel Online, PowerPoint 2013 Service Pack 1 or later, PowerPoint 2016 for Mac, PowerPoint 2016 or later, PowerPoint Online, Project 2013 Service Pack 1 or later, Project 2016 or later, Word 2013 Service Pack 1 or later, Word 2016 for Mac, Word 2016 or later, Word Online.

Remember that (we’ve discussed this a couple of blogposts earlier) each of the Office versions support their own subset of the APIs. When using Office 2013 your options obviously are much more limited than when using Office 2016.

How to get the tool:

You can get the tool, or look at the code by browsing to GitHub:
https://github.com/OfficeDev/script-lab

clip_image004

Install the tool:
https://aka.ms/getscriptlab

clip_image006

Demo video:

In follow-up blog posts, I’ll show how to install the Add-in and hopefully try to use and build some sample code to experiment with the JavaScript APIs for Office.

To be continued …

Office Development – Fixing Trusted Authority – Word Client

Office Development - Running Add-in Word Client

Yesterday we’ve seen an issue installing a Word Add-in when the certificate used in the Add-in is not (yet) trusted:

clip_image002

To solve this, we need to add the server certificate as a trusted authority to the certificate store. In my post Office Development – Fixing Certificate Issue with OpenSSL Certificate I already showed you how to create the certificate. I even announced that I had to add the certificate to the trusted root certificates but, in the end, never did that – resulting in the issue above.

Clean up the installed Add-in

First, let’s clean up the installed Add-in to re-do the installation later on to see if it installs correctly after adding the certificate to the trusted root certificates.

Go back to the File/Options/Trust Center/Trust Center Settings … button and click it

clip_image004

Select the Trusted Catalog Address, click Remove and click OK to close the dialog. You’ll get a message that it will be effective when you close and open Word again.

Close Word to get it done.

Now start the certificate manager:
C:\Windows\System32\certmgr.msc

clip_image006

Select the Trusted Root Certification Authorities node, right click, All Tasks, Import …

clip_image008

clip_image010

Click Next to continue

clip_image012

Select the server certificate from the Add-in folder that you created while generating the certificate. Click Open and add the certificate.

clip_image014

Click Next

clip_image016

And … Finish to complete the certificate installation.

Install the Word Add-in again

Repeating the steps from the previous post, go to File/Options/Trust Center/Trust Center Settings … button and click it.

clip_image018

Add the network share again, don’t forget to check the checkbox. Close the dialogs and if you get this message below, close Word and start it again.

clip_image020

Now go to the Insert Tab and click My Add-ins.

clip_image022

Repeating the sequence that we did in our previous post, go to the Insert tab and click My Add-ins.

clip_image024

From the SHARED FOLDER tab select your Add-in again and click Add. Immediately you see the button at the Home Tab in the Commands Group.

clip_image026

And if you now click the button, the Add-in is now loaded without issues. No more warnings for security issues or incorrectly named certificates. It just runs.

clip_image028

So, what have we learned today

– Make sure your security is in place. Prepare your certificates with the correct names on the certificate and add it to the trusted root certificates.

(Note: most of these issues are originated by creating self signed certificates. When using commercially generated certificates most of these certificates already come from trusted root certificates)

– Cleaning (removing) installed Add-ins is not so trivial as you might expect. We had to remove the Catalog entry, closing Office and reopen Office clears the Add-in. It would be easier if the user interface provided an option to remove the Add-in in an easier manner.

(Note: removing the Add-in from Word Online is even worse. I asked the question on StackOverflow where it was confirmed that there is no easy remove option)

Recap

So far, we installed NodeJS, Git, Yeoman and created a simple Add-in. Next, we tried to install it on Word Online, fixed some security issues, installed it on the Word local client, fixed some more security issues and finally installed it on the local Word client again, this time without issues.

Not much interaction yet between the Add-in and Word but we’ll look at that later.

To be continued …

Office Development–Running Word Add-in on your local Word client

clip_image002

In my last post Office Development – Running Word Online Add-in I explained how to install your Add-in to use in Word Online. Today we will bring the same Add-in into your local Word client installation, Word 2016:

clip_image004

To do so you first need to start your ‘web server’ again by calling

npm start

from the root of your Add-in folder.

Now you have your ‘web server’ up and running and we need to make this visible for Word. Word is able to ‘see’ Add-ins that are exposed by manifest files in a shared network location or web URL. Today we will use the shared network location to expose the manifest file.

To create a shared network location, you simply create a dedicated folder on your machine:

clip_image006

In this case I just created an extra folder in the Add-in project called addinshare.

Don’t forget to copy the manifest file “my-first-addin-manifest.xml” to the just created folder!

Now create the network share by opening the Explorer. Go to “This PC” and select from the menu/ribbon “Manage”

clip_image008

This will open the Computer Management tool. Browse in the left tree to Computer Management\System Tools\Shared Folders\Shares, select it:

clip_image010

Select Action, New Share:

clip_image012

Go to the folder that you dedicated for your Add-in

clip_image014

clip_image016

Click Next to continue

clip_image018

If you like change the name of the share, and click Next

clip_image020

For now, add All Users have read-only access (you might want to change the access rights later on but for demo purposes pick the default) and click Finish.

clip_image022

Click Finish again to close the dialog and close the Management Tool.

Now back to Word, goto the Trust Center under File, Options, Tab Trust Center, Button “Trust Center Settings …”

clip_image024

On the left side select “Trusted Add-in Catalog” and in the Catalog URL enter the network share from your computer \\<computername>\<sharename> that you just created in the previous steps. Click Add catalog to push it in the list.

When added to the list, check the checkbox Show in Menu to make it available in Word.

Note: Before clicking “Add catalog” it would be a good thing to check in Explorer that your folder spelling of the shared folder is correct and is opened without issues.

clip_image026

Click OK twice to close the dialogs. You may see this as well:

clip_image028

If all went right you should be able to add your Add-in to Word. Close all instances of Word and restart Word.

Go to the Insert Tab, just like you did in Word Online from the previous post and click My Add-ins:

clip_image030

Clicking the My Add-ins button in the ribbon will give you the dialog below if you select the option SHARED FOLDER (notice that Word recognized the share and provided you with this menu option. If the share wasn’t recognized the option for SHARED FOLDER would not appear).

clip_image032

What is up? Didn’t we fix the certificate issue? We had it running in the browser, didn’t we?

Well, yes … but what I forgot was to add the certificate to the list of trusted authorities. For now we can go on, we know it is safe but we need to fix this later on (food for another blogpost ).

Click Yes to confirm, select the MyFirstAddin an click Add.

clip_image034

After closing the dialog by clicking Add a new Ribbon item is added to your Word Home Tab:

clip_image036

Kinda useless information, you are already on the HOME tab … nevertheless, click the “Show Taskpane” button to get started. For me this resulted in:

clip_image038

Sh*t happens so I refreshed the page, to see what happened:

clip_image040

A bit better, but still not right. This time we recognized the “not secure” warning. My own fault, it still needs the trusted authority fix. For now, click More information:

clip_image042

This opens up the option to Go on to the webpage (not recommended). We know it is ok in this case, if the source was unknown you should just back out and close the add-in. In this case we created it, know it is secure so we go on to the website, although it was not recommended. We like to be a little bit stubborn at times and there you have it, it worked:

clip_image044

Quite a journey again, still not flawless but cause by my own doing. We now have the Add-in running in both Word Online and in Word 2016 on your local machine.

In our next step, I’ll add the certificate to the trusted authorities to redo this without issues, hopefully…

To be continued

%d bloggers like this: