Determine MIME type from base64

In writing my new Outlook Add-in (Send to Trello), I got stuck on attachments. The first version did not include an attachments option because of two unique problems that compounded each other:

  1. The Office Add-in API no longer provides a Media Type/MIME Type with an attachment request. I am able to get the “blob()” from Office, but other than the file extension there is not a way to determine the type. But sometimes a file does not have an extension, or the extension is wrong, etc.
  2. The Trello API will not let you upload without supplying a MIME type, you cannot just give it a Base64 string as an attachment and let them figure it out.

So, I found out something interesting while researching a workaround. Most every base64 string of a specific file type starts with the same “prolog” of text. Using this, combined with the fallback of the file extensions, I was able to get attachments to work (for the attachment types supported by Trello). So, v1.02 will now include attachments.

Anway, as for the workaround I found, this might be ugly, but wanted to share it anyway:

/**
* Returns the data type based on the base64 string
* @param {String} base64String
* @param {String} fileName
* @returns {String}
*/
detectMimeType(base64String, fileName) {
var ext = fileName.substring(fileName.lastIndexOf(".") + 1);
if (ext === undefined || ext === null || ext === "") ext = "bin";
ext = ext.toLowerCase();
const signatures = {
JVBERi0: "application/pdf",
R0lGODdh: "image/gif",
R0lGODlh: "image/gif",
iVBORw0KGgo: "image/png",
TU0AK: "image/tiff",
"/9j/": "image/jpg",
UEs: "application/vnd.openxmlformats-officedocument.",
PK: "application/zip",
};
for (var s in signatures) {
if (base64String.indexOf(s) === 0) {
var x = signatures[s];
// if an office file format
if (ext.length > 3 && ext.substring(0, 3) === "ppt") {
x += "presentationml.presentation";
} else if (ext.length > 3 && ext.substring(0, 3) === "xls") {
x += "spreadsheetml.sheet";
} else if (ext.length > 3 && ext.substring(0, 3) === "doc") {
x += "wordprocessingml.document";
}
// return
return x;
}
}
// if we are here we can only go off the extensions
const extensions = {
xls: "application/vnd.ms-excel",
ppt: "application/vnd.ms-powerpoint",
doc: "application/msword",
xml: "text/xml",
mpeg: "audio/mpeg",
mpg: "audio/mpeg",
txt: "text/plain",
};
for (var e in extensions) {
if (ext.indexOf(e) === 0) {
var xx = extensions[e];
return xx;
}
}
// if we are here – not sure what type this is
return "unknown";
}

New Outlook Add-in: Send to Trello

I have been using Trello for a while now and one of the features I have found most useful is to take an email I received and turn it into a Kanban item on my backlog to address later. This allows me to archive the email but keeps it on my “Trello radar” as I work at my own pace through my personal backlog.

Recently, Trello removed their add-in from the Microsoft Office store. If you have the add-in installed, you will see this error:

Well, since they say necessity is the mother of all invention and I really had to fill the gap as it is part of my routine, I rolled my own. 🤓 To add a degree of difficulty, I wrote this in VS Code in Linux running in Windows Subsystem for Linux (WSL). See my previous post. It was a fun exercise as I am on vacation and using the time tom learn new things, engage in self-improvement and relax (coding is relaxing to me 🤓🤓🤓). In the end, I learned something and created something for everyone to enjoy.

Say hello to the recently published: Send to Trello Outlook Add-in.

Give it a try and let me know what you think.

New Trello Power-up: Demote a Card

Continuing to use Trello I found a need to take cards that had been sitting around a while and put them in a place other than Archive (and forget them). What I had been doing was copy/pasting them in checklists in another card and as needed taking the check list items and promoting them back to a card. However, after performing the manual process (which could take a lot of time) enough times, I decided it was time for another Power-Up. So, I created the Demote a Card Power-Up:

https://trello.com/power-ups/630d74e4e1bab6013d6c1160/demote-a-card

Also — while building this Power-Up, I also got a tad frustrated that there was not any IntelliSense code assistance from the Trello Library. So, I build one in JSDOC and will likely be publishing that on GitHub soon. Not sure how many other developers there are out there that write Power-Ups, but my hope is it might be useful.

Trello Writers Block – Browser Extension

I have been in full-bore developer mode of late, trying new things and writing a lot of code. One area I thought I would give a try is browser extensions. I find myself wanting to tag pages so that I can reference them later in something I am writing or working on. And because I like to store information in Trello, I wanted something that combined both. So, here is an extension I created that will do just that. It takes the page you are on and then creates an MLA or APA reference and then adds it to a card in Trello for you.

I published this to both the Microsoft Edge and the Google Chrome store:

The following screen shots show you what it looks like when you are using it:

Extension in action on my website.
The card once it is added to Trello.

This browser extension is useful if you are a student writing a paper (supports MLA and APA formats), an author writing a book, or a blogger or someone doing research and keeping track of references using notecards. Because Trello is a digital version of notecards and it is available everywhere and stored in the cloud, you don’t have to worry about the dog eating your homework. 😱

Add it to your browser and let me know what you think.

OfficeJS.dialogs version 1.0.8

I have recently updated the OfficeJS.dialogs to version 1.0.8. I have also updated the Node Package Manager version as well. You can get it by running the following command in the VSCode Terminal Window:

npm install officejs.dialogs

With this latest version comes a few bug fixes, some cleanup of the code, cleaner JSDoc documentation and a PrintPreview dialog. The PrintPreview started out as a proof of concept but it actually works for me – in the browser anyway. I am not sure how well it will work in any of the full clients as I have not tested it there yet. If anyone has a chance to test it, please let me know if you encounter any issues.

Here is a sample of the PrintPreview dialog:

print

Here is some code to implement it:


// this example takes the currently composed email message in Outlook,
// grabs its body HTML and then displays it in the Print Preview dialog.
var mailItem = Office.cast.item.toItemCompose(Office.context.mailbox.item);
mailItem.saveAsync(function(asyncResult) {
var id = asyncResult.id;
mailItem.body.getAsync(Office.CoercionType.Html, { asyncContext: { var3: 1, var4: 2 } }, function(result) {
var html = result.value;
PrintPreview.Show(html, function() {
Alert.Show("Print cancelled");
});
});
});

view raw

printpreview.js

hosted with ❤ by GitHub

 

Start Developing in OfficeJS Today with Script Lab

Recently, I have been working with a tool from Microsoft Garage which allows you to quickly develop OfficeJS projects in Word, Excel and PowerPoint. It is called Script Lab. You can find more information about it here:

Script Lab

It is also in GitHub project. You can read about it here:

https://github.com/OfficeDev/script-lab

To install Script Lab, open Word, Excel or PowerPoint and on the Insert tab, click Store.

insert

Type “script lab in” the search box and hit enter. Then select Script Lab from the list and click Add.

store

Once added, you will see a new Script Lab tab. From there, you click the Code button to open the task pane.

scriptlab

This tool comes with a lot of options:

  • If you click the hamburger menu you will see an option to Sign Into GitHub. This will allow you to create Gist’s and access and save code snippets to GitHub.
  • You can import Samples from GitHub (with a URL) and access Snippets.
  • There are options to change the color in the editor at the bottom from Dark to Light.
  • And once in your solution, you can change the template (the html page), the CSS Style and any references libraries.

NOTE:  You are dealing with a subset of the whole solution here. You cannot create Ribbon buttons or dialogs. You can only develop task pane add-ins. You can work with Script Labs in Word, Excel and PowerPoint, but not Outlook (yet).

Script Lab allows you to test things in a quick fashion. Here is what the code pane looks like:

code.PNG

NOTE: Script Lab defaults to TypeScript. It emits code in JavaScript on Export. There is no option to switch to only JavaScript. If you want to program in JavaScript that does not matter because JavaScript will work just fine as well. But in a shout out to Michael Zlatkovsky – who says Office of TypeScript are a match made in heaven – I look at this as an opportunity to get better at TypeScript.

One of the more difficult part of working in OfficeJS is to be able to quickly test how some feature of function or a block of code will work. In the VSTO and VBA days, I would pop open the Visual Basic Editor in Word, Excel or PowerPoint (ALT+F11), then open the Immediate Window (CTRL+G) and then start typing away to test specific object model items. There was nothing similar to this with OfficeJS, until now.

Script Lab is just that, a laboratory for you to test your ideas, your snippets, your work in progress. It is a way to test something before you put it into your full blown solution. You can then save code snippets as Gist (on GitHub) and export the solution.

And once you have written your code and are ready to test it, you very easily run it in the Taskpane or (my favorite) you can run side-by-side. From the Ribbon click the Run button and then you can still edit your code/html and then refresh and reload it in the side-by-side Run window. This makes developing a solution or just testing ideas VERY easy:

side-by-side.PNG

Once you are running you (kind of) have debugging tools, can see the DOM and see console messages. And my favorite part, is that once you have hacked out a basic add-in concept with buttons and text in the HTML and code in the script file, you can export your solution (Export for publishing). This will create a ZIP which will contain the XML manifest and HTML (with script inline), which is very similar to the minimalist add-in I outlined in a previous blog post:

OfficeJS: Create a (VERY) Basic Add-in for Excel

NOTE: If you do write async/await code the exported result will be very ugly and hard to follow. This is why you might want to export to GitHub if you use async/awat code (TypeScript) so you can keep the original source and then transpile to ES5 later.

However, I really like VS Code and the power of NPM and Browser-Sync, so I worked on converting a Script Lab project into an NPM project. This took quite a lot of work and that will be a topic for a future blog post, but the gist of it is to create a new Office Yeoman (yo office) project for the same application and then gut and Frankenstein it with the Script Lab code.

Bottom line, I love Script LabwlEmoticon-openmouthedsmile.png If you are working on an OfficeJS project and/or planning on creating an OfficeJS project and/or want to learn how to develop in OfficeJS, this is definitely THE tool to have.

 

easyEws v1.0.7 is now released

This has been slow coming, but I have just released v1.0.7 of easyEws. As per usual, it is on NPM and on GitHub. You can get the latest with the command:

npm update easyews

Or, you can install it into your solution with the command:

npm install easyews

In this version the JSDOC information is now full incorporated so you get great inline help with each command. I enhanced the library so that it works better with inline help and so I changed how the class is setup and exposed. I have updated the README.md on GitHub, but I still am working on examples and such, that will be done later. And I added new functionality, a moveItem command which can be used to move any item from one folder to another. This was a added due to feedback I received on LinkedIn.

Please feel free to reach out to me with any questions or suggestions.

 

Deploying OnSend Outlook Add-ins?

If you have been developing OfficeJS add-ins for Outlook Online (or Exchange 2016 Outlook Web Access) you might not know that you now have the ability to create OnSend add-ins. That is add-ins that can trap the send of an email, test for conditions (such as getBodyAsync() or getSubjectAsync() to look for content) and if they fail, prevent the message from being sent. I recently blogged about it here:

The Most Anticipated OfficeJS Feature is Here

First thing to note about these add-ins is that they cannot be created for or uploaded into the store. The second thing to note is that they MUST be configured first in order to run. The third thing to note is that if you are building an on-prem Exchange based solution, you have to have Exchange 2016 CU6 installed and a bit more. The full details of how to configure the environments (either Office Online or On-prem) are detailed here:

On send feature for Outlook add-ins

If you look this over, there is quite a lot to do. How would you like one single PowerShell command to type? Maybe something like this:

[code type=”powershell”]

Set-OwaOnSendPolicy

[/code]

wlEmoticon-hotsmile.png Well, I just published the first version of this script on GitHub:

https://github.com/davecra/Set-OwaOnSendPolicy

All the details you need to know about it are there in the README.MD. However, if you have any questions or issues, please let me know.

 

OfficeJS: Second Dialog Does not Display

I have been spending a lot of time in the Officeui.dialog lately. One of my customers has been too and it has been an adventure working out exactly the best way to get messages displayed while running code in the background asynchronously. wlEmoticon-disappointedsmile.png

I am not sure if this problem is limited to the online version of Outlook, but this is where I have been seeing the problem (and where I have spent virtually all of my time). If my code tried to open two dialogs (using Office.context.ui.displayDialogAsync()) one right after the other, the second dialog would not ever be displayed. If I waited a period and then tried again, it would. But we don’t want that. We want boom-boom, dialogs. When I looked at the console, I would see an error like the following:

Uncaught TypeError: Cannot read property ‘addEventHandler’ of undefined

Or, if I read the error object from the displayDialogAsync() function/asyncResult, I would see this:

{name: “Display Dialog Error”, message: “The operation failed because this add-in already has an active dialog.“, code: 12007}

Here is an example of some code that will reproduce the issue:

[code lang=”javascript” collapse=”true” title=”click to expand if the github.com embedding below is not visible.”]
var i = 0;
function displayDialog() {
var url = "https://localhost:3000/test.html";
Office.context.ui.displayDialogAsync(url,{height:20, width:30, displayInIframe:true},
function (asyncResult) {
var dialog = asyncResult.value; // get the dialog
var error = asyncResult.error;
if(dialog == undefined && error.code > 0) {
// log the error
console.log(error.message);
} else {
// attache the events
dialog.addEventHandler(Office.EventType.DialogEventReceived, function (arg) {
// close this dialog, open the next
dialog.close();
i++;
if(i<4) {
displayDialog();
}
});
dialog.addEventHandler(Office.EventType.DialogMessageReceived, function (arg) {
// close this dialog, open the next
dialog.close();
i++;
if(i<4) {
displayDialog();
}
});
}
});
}
[/code]


var i = 0;
function displayDialog() {
var url = "https://localhost:3000/test.html&quot;;
Office.context.ui.displayDialogAsync(url,{height:20, width:30, displayInIframe:true},
function (asyncResult) {
var dialog = asyncResult.value; // get the dialog
var error = asyncResult.error;
if(dialog == undefined && error.code > 0) {
// log the error
console.log(error.message);
} else {
// attache the events
dialog.addEventHandler(Office.EventType.DialogEventReceived, function (arg) {
// close this dialog, open the next
dialog.close();
i++;
if(i<4) {
displayDialog();
}
});
dialog.addEventHandler(Office.EventType.DialogMessageReceived, function (arg) {
// close this dialog, open the next
dialog.close();
i++;
if(i<4) {
displayDialog();
}
});
}
});
}

view raw

dialogIssue.js

hosted with ❤ by GitHub

Notice I had used dialog.close(), but it did not work as designed. What I believe is happening is that the previous dialog is still in memory and has not been cleaned up. What needs to likely happen is a closeAsync().

In order to resolve this, I created the following function: dialogCloseAsync(). This works by issuing the close() and then attempting to add an event handler to the dialog in ansyc (setTimeout) loop. When it errors, we trap the error and issue the async callback. It is a bit ugly as we are trapping an error to get around the problem, but this was the only way I could find a way around the problem. Here is what the function looks like:

[code lang=”javascript” collapse=”true” title=”click to expand if the github.com embedding below is not visible.”]
/**
* Closes the currently open dialog asynchronously.
* This has an ugly workaround which is to try to set a new
* event handler on the dialog until it fails. When it failed
* we know the original dialog object was destroyed and we
* can then proceed. The issue we are working around is that
* if you call two dialogs back to back, the second one will
* likely not open at all.
* @param {Office.context.ui.dialog} dialog The dialog to be closed
* @param {function()} asyncResult The callback when close is complete
*/
function dialogCloseAsync(dialog, asyncResult){
// issue the close
dialog.close();
// and then try to add a handler
// when that fails it is closed
setTimeout(function() {
try{
dialog.addEventHandler(Office.EventType.DialogMessageReceived, function() {});
dialogCloseAsync(dialog, asyncResult);
} catch(e) {
asyncResult(); // done – closed
}
}, 0);
}
[/code]


/**
* Closes the currently open dialog asynchronously.
* This has an ugly workaround which is to try to set a new
* event handler on the dialog until it fails. When it failed
* we know the original dialog object was destroyed and we
* can then proceed. The issue we are working around is that
* if you call two dialogs back to back, the second one will
* likely not open at all.
* @param {Office.context.ui.dialog} dialog The dialog to be closed
* @param {function()} asyncResult The callback when close is complete
*/
function dialogCloseAsync(dialog, asyncResult){
// issue the close
dialog.close();
// and then try to add a handler
// when that fails it is closed
setTimeout(function() {
try{
dialog.addEventHandler(Office.EventType.DialogMessageReceived, function() {});
dialogCloseAsync(dialog, asyncResult);
} catch(e) {
asyncResult(); // done – closed
}
}, 0);
}

I had been encountering this issue with different systems when developing the OfficeJS.dialogs library and had tried to set a timeout before I showed each dialog. That worked on some systems, but on others the timeout needed to be longer. So, setting a default timeout did not work. Using this in the original sample, provided above, the code would look like this:

[code lang=”javascript” collapse=”true” title=”click to expand if the github.com embedding below is not visible.”]
var i = 0;
function displayDialog() {
var url = "https://localhost:3000/test.html&quot;;
Office.context.ui.displayDialogAsync(url,{height:20, width:30, displayInIframe:true},
function (asyncResult) {
var dialog = asyncResult.value; // get the dialog
var error = asyncResult.error;
if(dialog == undefined && error.code > 0) {
// log the error
console.log(error.message);
} else {
// attache the events
dialog.addEventHandler(Office.EventType.DialogEventReceived, function (arg) {
// close this dialog, open the next
dialogCloseAsync(dialog, function() {
i++;
if(i<4) {
displayDialog();
}
});
});
dialog.addEventHandler(Office.EventType.DialogMessageReceived, function (arg) {
// close this dialog, open the next
dialogCloseAsync(dialog, function() {
i++;
if(i<4) {
displayDialog();
}
});
});
}
});
}
[/code]


var i = 0;
function displayDialog() {
var url = "https://localhost:3000/test.html&quot;;
Office.context.ui.displayDialogAsync(url,{height:20, width:30, displayInIframe:true},
function (asyncResult) {
var dialog = asyncResult.value; // get the dialog
var error = asyncResult.error;
if(dialog == undefined && error.code > 0) {
// log the error
console.log(error.message);
} else {
// attache the events
dialog.addEventHandler(Office.EventType.DialogEventReceived, function (arg) {
// close this dialog, open the next
dialogCloseAsync(dialog, function() {
i++;
if(i<4) {
displayDialog();
}
});
});
dialog.addEventHandler(Office.EventType.DialogMessageReceived, function (arg) {
// close this dialog, open the next
dialogCloseAsync(dialog, function() {
i++;
if(i<4) {
displayDialog();
}
});
});
}
});
}

As I found this workaround, I have updated OfficeJS.dialogs to use dialogCloseAsync(). Now, the MessageBox, Wait and Form objects will use closeDialogAsync() commands to replace the original closeDialog() commands I provided previously. I will be blogging about the updates to v1.0.6, shortly. wlEmoticon-hotsmile.png

Using NPM to Publish and Update Packages

This blog post is more for me than you. I come from an era when command line was the only way to get things done. The folks that were able to do that in the 1980’s and early 1990’s, were called…

nerd

Well, for some reason, after advancements in GUI (Graphical User Interfaces) we are back to command-line interfaces. I have heard an argument that this makes it easier to build in voice command interfaces, but I do not see myself saying: “npm install”. I believe it came about because it is easier to create a command line interface quickly for free than it is to create a graphical one. Just sayin’. wlEmoticon-winkingsmile.png

With that said, lets get down the business. I published OfficeJs.dialogs to NPM and found a few last minutes bugs and needed to update it. Well, this seemed easy enough, but I was getting some error about my git working directory:

git working directory dialogs not clean

This turns out to happen because I needed to do both a push and a pull. Not sure why, but I did a push and sync and that did not resolve the issue. I had to do a pull from git too:

menu

Next, I had to then do a version update. To do this you type this in the Terminal window in VS Code once it is pointed to the repository folder:

npm version patch

This will add a single point to the version, so for me that was from 1.0.1 to 1.0.2. Next, you issue a single command:

npm publish

This will publish version 1.0.2 (in my case) to the node module in the sky (npmjs.com). Next, I then went to my project where I am using it and then issue this command:

npm update officejs.dialogs

And just like that, I had the latest version. Seems simple enough, but it took a while for me to research this and get it working. And since these are all command lines without a graphical ability to “hunt and peck” for the right menu item, I am writing it down for posterity. I will likely be referring to this post for myself again in the future.