NW Chicago JavaScript Meetup: Setting Your Data Ablaze with Firebase – June 21

On June 21st PSCGroup will be hosting the NorthWest Chicago JavaScript Meetup in our offices from 6-8:30pm

This month’s speaker is a lecturer at Northwestern, the awesome Mark Thompson

For more information check out the Meetup site

https://www.meetup.com/Northwest-Chicago-JavaScript/events/250983909/

 

Office Add-Ins: Working with Tables in Word. Part 1: Creation

In this article I will show how the Word JavaScript API can be utilized to add tables to your word document using an Office Add-In. This will be a multi part blog post as there are a lot of nuances and interesting ways in which you can play with tables in Word.

Introduction

In previous articles I have written about how to interact with a Word document to search and replace and even save the word document to Salesforce. Going back to a more basic level we are going to look at how to build tables in word.

We will be using the new Script Lab  which is a new Playground Add-In which can be used for development and general tinkering with Add-Ins. This and other articles on the topic are for demonstration purposes and are not hardened for production use.

The reference

For more information on Tables and how what methods/properties are available check out the documentation page – Table Object (JavaScript API for Word)

Creating a table 

At the most basic level a table is created by instantiating the table object and adding values to it.

insertTable(rowCount: number, columnCount: number, insertLocation: string, values: string[][])

This can be done from a number of different parents:

  • The body
  • A range
  • A contentControl
  • A paragraph

The method requires the following:

  • rowCount – a number
  • columnCount – a number
  • insertLocation – Depends on parent – either (body: Start/End/Replace) or (range: Before/After)
  • values: 2 dimentional Array – [[“This is”, “a table”], [“this is”, “a new row”]]

Using these parameters we can create a table from within the Script lab using the following code:

$("#run").click(run);

async function run() {
    try {
        await Word.run(async (context) => {

            var body = context.document.body;
            var range = context.document.getSelection();
            var myArray = [["a", "b"], ["c", "d"]];
            var table = range.insertTable(2, 2, "Before", myArray);            

            // Synchronize the document state by executing the queued commands,
            // and return a promise to indicate task completion.
                await context.sync().then(function () {
                    console.log('Table added before the start of the range.');
                });;
        });
    }
    catch (error) {
        OfficeHelpers.UI.notify(error);
        OfficeHelpers.Utilities.log(error);
    }
}

 

 

Conclusion

Using the Script Lab we have seen how we can easily insert a table into a Word document using the Office Add-In API. In future articles we will look at looking for the table we want to modify and then manipulating tables.

 

 

The two sides of the incremental operator in JavaScript ++

I learned this last week, possibly highlighting my non-classical programming training. I have never come across this in all my years of JavaScript and apparently it is pervasive in other languages such as Java as well.

Incremental Operator ++

Many times I have seen or used the following method for incrementing an integer count

var marky = 0;
console.log(++marky);
console.log(marky);

This increments the integer marky by 1. not rocket science. In the image below you can see that the two console.log entries always return the same value

j1

What I learned yesterday was using the ++ after the variable name also increases the variable – but only AFTER the value has been evaluated…

From this image you can see that the marky++ value and the marky value are not the same. The console.log(marky++); returns the existing marky value and then increments it.

j2

var marky = 0;
console.log(marky++);
console.log(marky);

I have to ask myself “why would anyone do that?”. Why would I want to return a variable value and THEN increase it’s value, seems a little odd to me. I guess someone thought it was a good idea…..

Always makes me think “I wonder what else I don’t know? Probably best not think about that too much”….

 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators

Aborting a jQuery ajax request

In this article I will show how you can abort a jQuery ajax request, preventing your user experience from disappearing into space.

Introduction

We have all done it – opened a page which runs an infinite loop consisting of some form of while(true). But no-one means to do that on purpose….That said there may be occasions where we are making requests to pages which we know are really really slow. Keeping a long connection open on the server restricts the number of open threads and potentially causes lockups. It is also a terrible user experience more importantly.

It might not be quite as relevant nowadays as it might have been to a Domino server say 10 years ago but still – pretty cool idea.

You can abort the ajax request with .abort()

Slowly loading XPage

I created a simple XPage with a before render response page which will take a long time to finish (as you can see below is ~30 seconds)

<xp:this.beforeRenderResponse>
	<![CDATA[#{javascript:
		for (var i=0; i<50000000; i++){
			true;
		}
		return true}
	]]>
</xp:this.beforeRenderResponse>

a1

Aborting the Ajax call

Aborting the call is relatively simple – by assigning a variable to the ajax call we can  then just .abort() it

var temp = $.ajax({
  url: 'http://copper.xomino.com/xomino/jQinX2.nsf/xRunForever.xsp'
}).error(function(){
   console.log('hey what happened')
})

temp.abort()

Running it manually we can see this

a2

a3

But a more practical solution is to set a timeout function to test the ajax value and abort if it is taking too long. How long that is, is entirely up to you……

function dontRunForever(url, time){
    var temp = $.ajax({
      url: url,
    }).error(function(){
       console.log('hey what happened');
    }).success(function(){
       console.log('All Done');
       temp = false
    })

    setTimeout(function(){ //Using function() inside the setTimeout means the function is executed after the "time"
      if(temp){
       console.log('aborting')
       temp.abort()
      } else {
       console.log('ajax call completed in time')
      }
    }, time)
}

dontRunForever(
  'http://copper.xomino.com/xomino/jQinX2.nsf/xRunForever.xsp',
  5000)

So when we run this with a timeout of 5 seconds, we see the abort() trigger

a4

But when we use 50 seconds we see a successful completion and no abort message – and eventually the end of the Timeout success message

a5

This is all well and good – BUT…..

Just because the ajax request is aborted – this does not mean the task stops running on the server – this whole concept improves the user experience and nothing else. This will not stop a never ending task running on the server – only the server settings will truly kill that.

a6

 

Conclusion

When I found this and the fact that it has been around for over 4 years I was somewhat annoyed that I did not know about it earlier, but it is pretty cool still all the same 🙂

 

IBMSBT in XPages: Custom Business Cards

In this article I will introduce the JavaScript API for Social Business Toolkit and show how to make a simple custom vCard using the jQuery hovercard.js plugin.

Introduction

When you are modifying on premises Connections there is an API interface provided and described by IBM for integration of the Profiles Business Card. I could not find this piece of code however within Smartcloud. The Playground API also does not provide an example of profile vcard within Smartcloud. I guess it must be in there somewhere, but I decided to make my own. If one is available, please point me at it…….

Using the SBT JavaScript API to get Profile information

The SBT JavaScript API is REST based and provides a limited set of functionality to access information from the connections installation. I found the following example in the Playground. Looking at the example in the playground the critical URL for accessing Profile information is this

url: ‘xsp/.sbtservice/proxy/smartcloud/lotuslive-shindig-server/social/rest/people/lotuslive:user:’+userId+’/@self?format=json’,

where userId is the id of the user you wish to see the information from. In my case a JSON object called entry is returned with many options.

a1

Hovercard.js

Using the jQuery plugin hovercard.js I was easily able to create the HTML which I wanted to put within a card. This HTML is hidden on the XPage and the actual HTML I want in all within the selector class “js-vcardHTML”

<div style="display:none" class="js-vcardHTML">
	<div class="row ">
		<div class="col-sm-8">
			<div class="vcardName"></div>
			<div class="vcardOrg"></div>
			<div class="vcardEmail"></div>
			<div class="vcardPhone"></div>
		</div>
		<div class="col-sm-4 vcardImage">
		</div>
	</div>
	<div class="row" style="margin-top: 5px; border-top: 1px dashed #a6a6a6">
		<div class="col-sm-6">
			Profiles
		</div>
		<div class="col-sm-6">
			Files
		</div>
	</div>
</div>

Within the application code I instantiate the hovercard.js code in the following manner. It retrieves the HTML from within js-vcardHTML. Populates it with the data from within the “entry” JavaScript object and then displays it on hover.

$(".contacts").hovercard({
	self: this,
	detailsHTML: $('.js-vcardHTML').html(),
	width: 350,
	cardImgSrc: '',
	onHoverIn: function () {
		// set your twitter id
		var userId = 'markyId'; //calculated outside of this demonstration

		$.ajax({
			  url: 'xsp/.sbtservice/proxy/smartcloud/lotuslive-shindig-server/social/rest/people/lotuslive:user:'+userId+'/@self?format=json',
			  type: 'GET',
			  dataType: 'json',
			  beforeSend: function () {
				$(".vcardEmail").prepend('<p class="loading-text">Loading Business Card...</p>');
				$(".vcardOrg").text("");
				$(".vcardImage").html("");
			  },
			  success: function (data) {
				self.cardImgSrc=data.entry.photo
				console.log(data)
				console.log(data.entry)
				//$(".vcardName").text(data.entry.displayName);
				$(".vcardEmail").text(data.entry.emailAddress);
				$(".vcardOrg").text(data.entry.org.name);
				$(".vcardImage").html("<img src='https://apps.na.collabserv.com/contacts/profiles/photo/"+userId+"'/>");
			  },
			  complete: function () {
				$('.loading-text').remove();
			  }
			});

	}
});

a2

Conclusion

In this article I have shown how we can retrieve profile information from the Smartcloud JavaScript API and how we can create our own custom business card using the hovercard.js jQuery plugin.

Amusing that the API reference still contains a reference to Lotus – draw your own conclusions 🙂

Creating a periodic array of dates in JavaScript

So I am lazy – nothing new there. I am also a manager (nothing new there either unfortunately) and I track hours in a spreadsheet. Yes we have a proper system for hours tracking and billing but I am old school and I prefer the layout I created and have used for yeeeears.

Anyway, so it is new project time and I need to create a set of dates from this Friday – every Friday out through the next 3 months. I am sure there is a smart way to do that in Excel but I wanted to do it in JavaScript – ‘cos I can, and ‘cos I want to keep kidding myself I am a developer 😉

A quick Google search found this snippet which is almost what I was looking for http://stackoverflow.com/a/4413721/1171653 (look at the example)

I modified the sample code slightly to return the format I was looking for – starting today – 02/26/2015

Date.prototype.addDays = function(days) {
    var dat = new Date(this.valueOf())
    dat.setDate(dat.getDate() + days);
    return dat;
}

function getDates(startDate, stopDate) {
    var dateArray = new Array();
    var currentDate = startDate;
    while (currentDate <= stopDate) {
        var day = currentDate.getDate()
        var month = currentDate.getMonth()+1
        var year = currentDate.getFullYear()
        dateArray.push(day+"/"+month+"/"+year )
        currentDate = currentDate.addDays(7);
    }
    return dateArray;
}

var dateArray = getDates((new Date()).addDays(2), (new Date()).addDays(90));

console.log(dateArray)

Loaded it into the firebug console and produced the following which is easily copy/pasteable into Excel

[“28/2/2015”, “7/3/2015”, “14/3/2015”, “21/3/2015”, “28/3/2015”, “4/4/2015”, “11/4/2015”, “18/4/2015”, “25/4/2015”, “2/5/2015”, “9/5/2015”, “16/5/2015”, “23/5/2015”]

It took me longer to write this up on the blog than do it.

But now I have a reference point so that when I need it for the next project I can come and get this code 🙂

Lazy 🙂

Why learning JavaScript is more critical to XPage developers than Java

I have tried to write this article multiple times over the last 2 years, when I read it back to myself it always sounds like I am bitching. Honestly, I usually am and that is why it has not been published. This is a final attempt at a constructive argument against the insistence on many blogs that everyone should learn Java.

Many people think I hate Java; I really don’t. I can program Java (I am no expert admittedly) and have done so on multiple occasions. My concerns are always raised when community members are insistent that everyone should learn Java. I do not believe that to be the case.

Why I believe JavaScript skills are more important to a web developer using XPages than Java.

Since R4.5 Domino has been a web server – and the client side user experience has always been independent of that. The only decision to make them “tightly coupled” was that of the developer who chose to not venture beyond the bounds of the out of the box capabilities.

Just because no-one was championing client side development does not mean that it did not exist. I used IE5 <XML> islands back in 2003, pre-ajax, to make dynamic data loading views. I used jQuery in 2010, long before I experienced XPages. I have always considered myself a web developer. I am sure there are many others who do the same.

Here’s why a long long time ago one of my biggest projects failed. While it exceeded expectations of the customer and absolutely rocked on the server, the end users were never asked if they liked how it looked. It failed because people didn’t like the way it looked and it wasn’t used. It hurt. It really, really hurt. From that project forth I stopped putting the server first.

“Beginner XPage developers need to learn Java / Everyone should learn Java”

I shake my head every time I see this. It is an all out, complete, and utter fallacy. Below are my thoughts on some of the reasons touted for using Java and not SSJS:

  • Speed
    • On low to medium volume document processing the time saving still insignificant compared to network latency and browser rendering speed. I have no numbers on this but in over two years XPages developer and 4 major projects dealing with <50,000 documents in a database. Speed of response from the SSJS code on the server has never been a concern.
    • I recently worked on a database with over 1,000,000 records in it. Accessing and displaying data via SSJS using FTSearch was in the matter of 100s of milliseconds.
    • We have SSJS code getting view entries by key and returning results on 250,000 records in less than 0.5 seconds
    • As has been pointed out in the past, the server caches a large amount of frequently used SSJS code making it no slower than any Java equivalent
    • Java is faster – Yes it is. But in my experience SSJS seems perfectly fast enough.
  • n-tier architecture / Separation of  UI and business logic layers
    • When someone can demonstrate to be that they understand the UI they can lecture me about how they need to separate themselves from it. From my perspective it makes a back end developer’s life easier to separate themselves from the UI they don’t understand.
  • It’s the future
    • I guess that depends on your perspective. If you want to spend the rest of your development career developing WebSphere applications it might be. Either way it absolutely is not necessary for XPages development in the next 2 years
  • Java can do things SSJS can’t
    • Yes I agree, things like Apache POI, custom REST services or Plugin development – absolutely agree.
    • Complex data processing of significant amounts of data (not a normal use-case for a notes database)
    • Use the right tool for the right job 🙂
  • At this stage of the game anyone still resisting a move to XPages is not going to be encouraged by being told they need to learn Java – So please quantify your statements when you tell other community members “they must learn Java”. I think this is more appropriate – “Those of you with a solid understanding of XPages and the JSF lifecycle, who are wishing to take their server side programming skills to the next level, learn Java”
    Beginner XPage developers have enough to learn as it is 
  • Imagine a notes client developer who has never created a web based application before. Which is going to serve them better JavaScript or Java
    AJavaScript – the same language for CSJS and SSJS

I believe XPages web developers (using XPages) need to have a solid understanding of these technologies to be successful – *In this order*

  • Lotus Notes Object Model (assumed)
  • HTML
    • HTML5
  • JavaScript
    • Basic Programming
    • External Libraries (jQuery, dojo)
    • The XSP framework for CSJS JavaScript interaction with the XPages
    • Unique Browser deviations from the ECMA standards (looking at you old IE)
  • CSS
    • Unique browser deviations from the standards
  • XML
  • JSF Lifecycle
  • Other things I have forgetten
  • Java

In Summary: Why is JavaScript more critical to XPage developers than Java?

  • Coding in Java is not necessary to build a web based application (using XPages), JavaScript is.
  • Coding a web browser user interface requires JavaScript and cannot be done in Java
  • JavaScript skills are transferable to *any* web server/client environment, Java much less so.
  • Because no customer ever said “This website looks like crap but the pages load so fast I am in love with it.

I understand everyone has their talents in different areas, but (and I can’t stress this enough), end users don’t care about the technology that makes a website work. End users are more forgiving of a beautiful website which is slightly slow, that a blazing fast, ugly, hard to use site. Ideally it would be beautiful *and* blazing fast but that is a whole separate discussion.

I am not saying using Java is wrong. I just want to temper the expectation that everyone *needs* to learn Java. In my opinion they don’t.

Let the comments blaze on…..

PS
Every time you use a 5 year old IBM XPages out of the box dojo control and tell a customer that it is a good interface, a kitten dies.
Many thanks to Brad Balassaitis for proof-reading and bitchiness reduction assistance 🙂

How to add icons to individual items in a Select2 multi-value field

Select2 is one of the best user interface enhancers I have come across – if you do not know what it is then you need to go play with it.

It transforms SELECT boxes into dynamic, stunning, interactive UI elements and allows for all sorts of customizations and developer fun.

What I want to be able to do is select items from different categories within the select2 box and then add an icon displaying to the user which category they came from. In this article I will show how.

Example

I want to take this

s3

turn it into this with a type aheads2

And when a user selects the items – make this based on the category selected

s2

And it is really pretty simple and straightforward.

The Code

We start with our select box

<select style="width:500px" id="vehicle" multiple="multiple">
<optgroup label="Cars">
	<option class="car">Honda</option>
	<option class="car">Toyota</option>
	<option class="car">Ford</option>
	<option class="car">GM</option>
</optgroup>
<optgroup label="Bikes">
	<option class="bike">Harley Davidson</option>
	<option class="bike">Kawasaki</option>
	<option class="bike">Aprilia</option>
	<option class="bike">Ducati</option>
</optgroup>
</select>

and then we add our select2 code

$("#vehicle").select2().on("change", function(e) {
	if (e.added) {
		var icon = ""
		$('.select2-search-choice DIV').filter(function() {
		    icon = '<img src="images/'+e.added.css+'.png"/>&nbsp;';
		    return $(this).text() == e.added.id;
		}).prepend(icon);
      }
})

So what this does is:

  • select the #vehicle DOM element
  • turn it into a Select2 plugin control
  • When the control is changed and if an element is added
  • Find the DIV which has been created to display the new item
    • We use filter based on the newly added.id to make sure we only get the one just created
  • create the HTML for the appropriate icon based on the class of the selected item
  • prepend that icon HTML inside of the DIV containing the newly selected option

Conclusion

I have barely scratched the surface of what is possible with Select2. But I hope that you can see with only 9 lines of code we have significantly improved a user experience 🙂

I love Select2 and the options are endless

Enjoy 🙂