XPages Tip: Adding a Bootstrap Class to All Labels via the Theme (Redux)
In this post, I showed how to set all labels in an application to include a class to pick up Bootstrap styling so it could be applied application-wide and not require touching every label control individually. However, there’s a quirk with label rendering that may make it not apply universally as desired. In this post, I’ll explain the issue and how to use another theme setting to easily fix it.
Updating all Labels via the Theme
This code in the theme will apply the control-label
class to all label components in the application. This allows me to apply a Bootstrap style class to all labels without having to update each label control individually on every XPage and custom control.
<control> <name>Text.Label</name> <property mode="concat"> <name>styleClass</name> <value>control-label</value> </property> </control>
The Bootstrap styling will be applied to label
tags that have the control-label
class.
The Problem with Label Rendering
However, there’s an issue with the way labels are rendered that may not make it work consistently.
Any labels that do not have a for
attribute specified will actually be rendered as span
tags and the styling will not be picked up. (Labels that have the for
attribute specified will be rendered as label
tags and work as expected.)
In another post, I described the effects of different modes on theme property application. In this post, we’ll see a practical example of the effects.
Theme to the Rescue (Again)
Fortunately, there’s an easy way to add another property setting to the theme to handle this.
There isn’t a tagName
attribute on a label, so you can’t directly modify the output tag this way, but for
is a property of the control, so you can use the theme to add it to all labels.
1. Overriding the Property
One option is to override the for
property on all labels. Lines 7-10 were added below to do so.
<control> <name>Text.Label</name> <property mode="concat"> <name>styleClass</name> <value>control-label</value> </property> <property mode="override"> <name>for</name> <value>dummyTarget</value> </property> </control>
This puts the for
property in place and assumes it needs to figure out the client-side ID of the element that’s been specified. This is a dummy value, but it does the job.
<label id="view:_id1:_id3:_id51:office_Label1" class="control-label" for="view:_id1:_id3:_id51:dummyTarget">Office</label>
However, it does the job too ambitiously. It removes any existing for
property, so it would break the association with the specified input control, which may cause other issues with the application and most certainly would cause issues with a screen reader.
2. Concatenating the Value
Changing line 7 to concatenate instead of overriding the value gives us a bit better behavior.
<property mode="concat">
This mode will append the property value to any value that currently exists for the attribute. It will also add the attribute and value if it doesn’t exist.
<label id="view:_id1:_id3:_id51:label17" class="control-label" for="view:_id1:_id3:_id51:dummyTarget">Payment #</label>
This also does the job, but it causes two values to be in the for property if one already existed (although it doesn’t try to generate a client-side ID when it’s appended).
<label id="view:_id1:_id3:_id51:office_Label1" class="control-label" for="view:_id1:_id3:_id51:office1 dummyTarget">Office</label>
This is better than the override method, but still may cause problems.
3. Mode not specified
You can also just not specify the mode.
<property>
In this case it only adds the property and value if the property doesn’t already exist, so it’s the cleanest solution.
This is an example of a label that already had the for
attribute specified. It does not get the new dummy value.
<label id="view:_id1:_id3:_id51:office_Label1" class="control-label" for="view:_id1:_id3:_id51:office1">Office</label>
This is an example of a label that did not have the for
attribute specified:
<label id="view:_id1:_id3:_id51:requisitionLabel" class="control-label" for="view:_id1:_id3:_id51:dummyTarget">Requisition #</label>
XPages Tip: Overriding, Concatenating, and Conditionally Adding Control Properties via a Theme
Themes are commonly-used in XPages applications to include resources needed throughout an application, but they can also be a powerful tool for consistently applying application-wide control settings. In this post, I’ll explain the difference between different modes for applying a control property and link to a corresponding post with a practical example.
1. Overriding a Control Property
In this post, I showed how to use the theme to add a class to all labels in an application to pick up Bootstrap styling without having to set the class on each individual label.
Here’s an example of the theme code to make it happen:
<control> <name>Text.Label</name> <property mode="override"> <name>styleClass</name> <value>control-label</value> </property> </control>
When a page loads, the theme is applied to the page and all label controls are updated as the page is rendered.
- Line 2 is directing it to apply to all Label controls throughout the application. (This is using a theme ID that’s predefined for the label control, as noted in the Mastering XPages book.)
- Line 4 specifies that it’s updating the
styleClass
property of the controls. - Line 5 specifies the
control-label
class to add to each label. (This is the class name that Bootstrap styling looks for.) - Line 3 is the variable for this post. This example starts with the setting the override mode. This mode will set the class to the specified value on all label controls, overriding anything that may have been set when the control was added on an XPage or custom control.
2. Concatenating a Control Property
Instead of overriding the property on all controls, another option is to concatenate the specified value to any existing value specified on each instance of the control.
<property mode="concat">
In this case, if there was a label control that already had a class specified, the control-label
class would be added to it (after a space) so the label would have both classes.
If the label control did not have a class, then the specified class would be added.
3. Conditionally Applying a Control Property
The last option is not to specify a mode at all.
<property>
In this case, it will not do anything to a label control that already has a class specified, but it will add the specified class to any label control that does not have one.
Take a look at for a practical example of each of these methods and how the distinction between these methods matters.
XPages Tip: Displaying Bootstrap Applications Properly on Mobile Devices
Do you have a Bootstrap navigation menu in XPages that collapses properly in a full browser but not on a mobile device? You may need to set a meta tag to force it to display properly. In this post, I’ll show the effects with and without the tag on a mobile device.
Navbar Collapsing
One of the great features of Bootstrap is its built-in responsive UI that scales well to work on screens of varying sizes. The navigation bars collapse nicely into the hamburger menus to make better use of available space on smaller devices.
However, in recent testing of an XPages application with a Bootstrap UI, it was noted that the navigation menus did not collapse properly when viewed on a phone. It was a little confusing because it collapsed as expected on a full browser.
When the navigation bar is set up properly, it should collapse properly on its own when the screen width is below 768 px. I verified that there are no CSS rules overruling that cutoff and that 768px is, in fact, the point where the menu collapses on the full browser.
Bootstrap Navbar Test Page
To test it out, I tried out the Bootstrap Navbar test page
On my laptop with a full browser, it showed the navigation normally.
When I shrunk the screen to be less than 768px wide, it collapsed the navigation properly.
When I checked it on my phone, it was collapsed properly.
Test Page in XPages
I copied the div that contains the navigation from that test page and pasted into an XPage in my application to see how it worked.
It collapsed as expected in a full browser but not on the phone.
It is also apparent that the page has been scaled so that it fits fully on the phone.
To verify this, I put a button on the page to tell me the screen width. As expected, it showed a width > 768 px, which is why it did not collapse the menus. It scaled the entire page to fit on the screen, so it did not fall below the threshold of the responsive design media queries.
(This is on a Samsung Galaxy. An iPhone showed it to be roughly 900px.)
And this is just a simple page. Imagine how that looks with a much bigger XPage!
The Difference
Ultimately, the main difference is that the Bootstrap test page contains a meta tag to make sure the device doesn’t shrink to fit the entire page on the screen.
<meta name="viewport" content="width=device-width, initial-scale=1">
In XPages, this can be set at the page level, but it’s easiest to do it application-wide via a theme, within a resources tag.
<resources> <metaData> <name>viewport</name> <content>width=device-width, initial-scale=1.0</content> </metaData> </resources>
Now, when I reload the Bootstrap test page, it is displayed properly on the phone.
The button showing the screen with on the phone now shows it to be 360px wide.
Efficiently Keeping an XPages Session Alive with JSON RPC
In my last post, I talked about the difference between two reasons that a user may be prompted to login again while using an XPages application: idle session timeouts and LTPA token expiration. There are a variety of ways to programmatically prevent an browser session from timing out due to inactivity. In this post, I’ll show how to do it with JSON-RPC and why I prefer it to the standard methods.
Keeping the Session Alive
The Keep Session Alive control (xe:keepSessionAlive
) in the extension library was designed to make it easy to prevent idle session timeouts; all you have to do is drop the control onto a page and optionally set the refresh period and it will send requests to keep the session alive.
In earlier versions of Notes/Domino, this would not be available without the extension library, which was a limiting factor in many situations. It’s built into version 9+, so it’s more readily available.
Other solutions popped up for those without the extension library (and to work around an earlier bug in the control, including Mark Roden’s XSnippet. In this solution, a timer is set to periodically trigger a partial refresh of an empty div in order to send a request to the server and keep the session alive.
This works well and is easy to add to any application.
However, while it can be set to run very infrequently, the partial refresh is more overhead than necessary. It only refreshes a single empty DIV tag, but it’s still posting the entire form and causing the entire component tree to go through most of the life JSF lifecycle. If the user happens to be viewing the page, the responsiveness may lag due to the synchronous processing and refresh.
(In contrast, the Keep Session Alive control appears to be efficient, sending a GET request and getting a minimal response.)
RPC Efficiency
My first thought when looking for a more efficient solution was, at minimum, to use the code to trigger an even that for which I could also enable partial execution (explained really well here by Paul Withers) to limit the scope of the processing to make it much more efficient.
However, in thinking through it further, I realized that it would be even more efficient to use JSON RPC, because the amount of information sent is minimal, the response is minimal, and the request is asynchronous, so it doesn’t have any of the aforementioned issues. (If you’re not familiar with JSON RPC — take a look at the first section of this presentation for more information.)
Without further adieu, here is a solution using JSON RPC.
<xe:jsonRpcService id="jsonRpcService1" serviceName="rpcUserSession"> <xe:this.methods> <xe:remoteMethod name="keepAlive"> <xe:this.script><![CDATA[return '';]]></xe:this.script> </xe:remoteMethod> </xe:this.methods> </xe:jsonRpcService> <xp:eventHandler event="onClientLoad" submit="false"> <xp:this.script><![CDATA[ setInterval(function(){ console.log('keeping session alive (rpc): ' + new Date()); rpcUserSession.keepAlive(); }, 1500000) ]]></xp:this.script> </xp:eventHandler>
The first 8 lines simply define an rpc service that has a single method that just returns an empty string.
The last 8 lines are an onClientLoad event handler that set a timer to write a message to the browser console and call the RPC method every 25 minutes.
The request sent to the server is minimal…
… as is the response.
No page processing occurs and the request is asynchronous, so it cannot affect the user.
This can be added to it’s own custom control and then added to your application’s page layout control so it’s available throughout. All you have to do is set the refresh duration, which should be slightly less than the idle session timeout.
Timeout Handling
In addition to being more efficient, this method also has the benefit of failing much more gracefully and also providing the ability to handle the timeout.
In my testing the Keep Session Alive control doesn’t show any error to the user or to the browser console.
The partial refresh method first shows this message…
…and then pops up a second error message, saying that there’s no element to submit, along with the client-side ID of the <div> that’s the target of the partial refresh.
This is an ugly way to fail.
One of the benefits of the RPC method is that it fails more gracefully AND you can trap the error and handle it however you’d like.
Here’s the error message that is displayed in the browser console when the session ends due to the machine going to sleep:
A different message is returned when it times out due to the expiration of the LTPA token:
The user never gets a message. They would just be prompted to login the next time they tried to run any action on the page that required server interaction.
However, as I described in a previous post, you can handle errors within an RPC call. You could use this to either display a nicer message to the user or redirect to a login page, either of which allows you to handle it much more gracefully.
Browser Session Lifespan – Idle Session Timeout vs LTPA Token Expiration
I recently spent some time investigating a client’s reports of unexpected behavior with the duration of browser sessions while testing an application on a test server. From time to time, they were required to login even while actively using an application. In this post, I’ll highlight the difference between an idle session timeout and an LTPA token expiration, which serve different purposes and, in the latter case, may cause frustration if not understood.
User Expectations
Most users are familiar with the concept of a browser session timing out if left idle for too long. In this case, websites will generally inform the user that a session has expired and require the user to login again in order to continue.
But users will generally not expect to be required to login again while actively using an application, so it’s important to understand why it might happen and what you can do about it.
Idle Session Timeout – Server
The Domino server document has a setting to define how long it will take for the session to be automatically logged out due to inactivity. This is configured on the server document: Internet Protocols... > Domino Web Engine > Idle session time-out
The default is 30 minutes.
Idle Session Timeout – Application
There is also an application-level setting for the session timeout, which can be found on the General
tab of Xsp Properties
.
This sets the
xsp.session.timeout
property.
xsp.session.timeout=30
LTPA Token Timeout
If single sign-on is configured to share the session between multiple servers, a Web Configuration document will define the SSO parameters.
The key setting in this case is the Expiration (minutes)
field on the Basics
tab of the document. This defines the lifespan of the LTPA token that is issued when the user logs in.
The important thing to understand is that this has nothing to do with how active or idle the session is.
This is a fixed length of time for which the key will be valid. Once it expires, the user will be prompted to login again. This can be very confusing to a user who is actively using the application!
Improving the Experience
There are a number of ways to implement controls to keep a session from timing out due to inactivity, but they will have no effect on the expiration of the LTPA token.
In order to prevent users from being frustrated with frequent logouts, some very smart people including Per Lausten and Sean Cull, have written about this in years past and have recommended setting the token expiration to a much larger number in order to prevent unexpected behavior. The idle session timeout can still do it’s job dealing with inactive sessions (and you as a developer can programmatically work to keep them alive if desired).
XPages Tip: Passing an Array to a Custom Control Property
Custom properties are extremely useful for modular design and reuse by sending custom values into each instance. There are a number of data types that can be selected, but no obvious way to pass an array value. In this post, I’ll describe the issue and how to work around it.
Custom Property Data Types
The default data type for a custom property is string
.
There are a number of primitive data types available in the dropdown:
If you click the folder icons, there are a number of additional options, including Converters, Validators, and other types, but there are no data types for arrays (or vectors or JavaScript objects).
String Data Type
In this case, I want a property that can accept an array of values.
To test this, I created a simple custom control with two properties, stringProperty
and objectProperty
, to test how they handle arrays. They both default to string
as the data type.
<xc:ccTest> <xc:this.stringProperty><![CDATA[#{javascript:return ['1', '2', '3', '4', '5'];}]]></xc:this.stringProperty> <xc:this.objectProperty><![CDATA[#{javascript:return ['1', '2', '3', '4', '5'];}]]></xc:this.objectProperty> </xc:ccTest>
You can leave the data type as string
, but compute an array to return. It won’t throw an error, but it will treat it like a single string.
No Data Type
You can remove the data type from the property definition and it won’t throw an error on the custom control. However, that is not a valid property, so its treated as though that property doesn’t exist.
If you’ve already set up an instance of the custom control and passed a value to it, it will throw an error on the custom control instance: Unknown property this.. It is not defined on tag .
Custom Data Type
Fortunately, there’s a really simple solution — you can manually type in a property type.
If you type in object
as the type, it does the trick. (It effectively works as desired, although it actually accepts the data as java.util.Vector
.)
XPages Tip: Beware Server-Side code in Multiple onClientLoad Events
TL;DR – Server-side code in onClientLoad causes a page refresh and prevents additional onClientLoad events with server-side code from running. In this post, I’ll show an example and describe how it behaves.
Page Ready Events
It is extremely useful to have an event trigger that executes when the page is fully loaded; many JavaScript plugins wait for the page to finish loading and then run to activate widgets on the page. Because of its importance, jQuery has $(document).ready()
and Dojo has dojo/domReady
and dojo.addOnLoad()
to make this checking easy.
The Problem with onClientLoad in XPages
XPages provides the onClientLoad
event on pages, custom controls, and panels. XPages allows you to run client-side and/or server-side code in the event. However, running server-side code can cause a tough-to-troubleshoot side effect.
Take, for example, this XPage, which has two panels. Both panels and the page itself have client-side and server-side onClientLoad
code to write a message to the browser console and server console, respectively.
<?xml version="1.0" encoding="UTF-8"?> <xp:view xmlns:xp="http://www.ibm.com/xsp/core"> onClientLoad Event Testing <xp:eventHandler event="onClientLoad" submit="true" refreshMode="norefresh"> <xp:this.script><![CDATA[console.log('Page - onClientLoad');]]></xp:this.script> <xp:this.action><![CDATA[#{javascript:print('Page - onClientLoad');}]]></xp:this.action> </xp:eventHandler> <xp:panel id="panel1"> <xp:eventHandler event="onClientLoad" submit="true" refreshMode="norefresh"> <xp:this.script><![CDATA[console.log('Panel 1 - onClientLoad');]]></xp:this.script> <xp:this.action><![CDATA[#{javascript:print('Panel 1 - onClientLoad');}]]></xp:this.action> </xp:eventHandler> </xp:panel> <xp:panel id="panel2"> <xp:eventHandler event="onClientLoad" submit="true" refreshMode="norefresh"> <xp:this.script><![CDATA[console.log('Panel 2 - onClientLoad');]]></xp:this.script> <xp:this.action><![CDATA[#{javascript:print('Panel 2 - onClientLoad');}]]></xp:this.action> </xp:eventHandler> </xp:panel> </xp:view>
Here’s what happens when the page loads:
- The page-level client-side code runs to write the message to the browser console
- The page-level server-side code runs to write the message to the server console
That’s it.
Execution on onClientLoad
handlers stops at this point because the page has posted to the server because of the server-side code; the onClientLoad
event handlers for the panels do not execute at all.
You can look in the browser’s developer tools and see the POST that is sent. It doesn’t try to update anything on the page, so there’s no response, but it’s still enough to interrupt everything else.
More details on the behavior:
- You can run multiple client-side
onClientLoad
event scripts without issue — as long as they’re not triggering partial refreshes - If the event handlers are rearranged on the page, the one that comes first in the source is the one that will run
- If there is only one
onClientLoad
event with server-side code, it will run (based on it’s order in the source), then POST, then let the rest of theonClientLoad
events on the page that only have client-side code run. (Any with server-side code will not execute — even the client-side event code on handlers that also have server-side code will not run.)
Mitigating the Problem
This may sound like an easy thing to keep in check, but if you have onClientLoad
code on multiple custom controls, it may be hard to make sure that there won’t be a conflict, especially because there won’t be any error thrown.
The strong recommendation is to just not put server-side code in the onClientLoad
event, period.
If you absolutely need it, then you may need a standard of putting any necessary onClientLoad
code in the common layout control that’s loaded on every page, but it still has the potential to interrupt anything else going on the page or annoy the user by causing a delay immediately after the page is loaded waiting for the post and response. I would try to put code in the afterPageLoad
event or use client-side code to trigger an RPC method or custom REST service if server-side code needs to run in that event.
getFragment() Doesn’t
The XSPUrl object that you can access via the XPages context
has a lot of handy methods. getFragement()
isn’t one of them.
I was looking through the help documentation for XSPUrl recently and noticed that the object includes a method for getting the url fragment (i.e. the part of the URL after the hash). It was unexpected, but I figured it could be handy since I was working with some (non-XPages) tabs on pages in a recent application.
However, as shown on Dave Leedy’s helpful XPages URL Cheatsheet, getFragment()
doesn’t return anything when referring to the URL gleaned from the current context!
This makes sense, as the hash is a client-side redirect and is not even sent to the server, so a server-side method wouldn’t be able to see it. But it’s included in the XPages Documentation which, hilariously, references Chris Toohey’s post about this from several years ago.
Fortunately, if you need to work with the hash, you can use client-side Javascript’s location.hash property and pass it to server-side code as needed.
Transferring a Bitbucket Repository
I recently needed to move control of a source control repository on Bitbucket from a personal account to a company account. Fortunately, there’s a relatively easy built-in process to transfer it between accounts. In this post, I’ll show how it’s done.
- Open the repository in Bitbucket
- Click on Settings at the bottom of the left navigation
- Click on Transfer repository under General
- Choose the new owner and click the Transfer Ownership button
- Login to Bitbucket as with the account of the new owner
- Click on the user icon in the upper right and select “Inbox”
- You’ll see a message with the transfer request. (It will also be e-mailed to the account owner.)
- Open the message and click the link that it contains
- Click the Accept button to transfer the repository
- Now that the repository has been transferred, it takes you to the Access management screen so you can add users to the repository as needed.
- If anyone already had Source Tree set up to use the repository, they will need to update the repository settings to point to the new location.
- If you try to commit to the original repo url, you get a 404 error when trying to push:
- Open the repository in Source Tree
- Click on the Settings button in the upper right hand corner (or select Repository > Repository Settings)
- Click on the default repository to select it
- Click the Edit button
- Update the URL to replace the previous Bitbucket account name to the new one in two places in the URL
Handling Errors in an XPages RPC Method
The Remote Service (aka xe:jsonRPCService) is an extremely useful control in XPages because it examples client- and server-side code interaction, runs asynchronously, performs well, and is easy to use. But if you don’t handle errors well, it can fail quietly and the user may never know. In this post, I’ll show how to handle client- and server-side JavaScript errors with an RPC method.
Remote Procecure Example
As a starting point, let’s look at an example of a simple RPC method that returns the date and time and displays it for the user.
RPC Control
Here’s the XPages component source:
<xe:jsonRpcService id="jsonRpcService1" serviceName="myRPCService"> <xe:this.methods> <xe:remoteMethod name="myMethod" script="return myLibraryFunction();"> </xe:remoteMethod> </xe:this.methods> </xe:jsonRpcService>
The service name is myRPCService. The method, myMethod takes no parameters and just calls an SSJS library function named myLibraryFunction().
SSJS Library Function
Here’s the SSJS function that it calls:
function myLibraryFunction() { var d = new Date(); return d.toLocaleString(); }
Client-Side JavaScript
Here’s the code that calls the RPC method:
myRPCService.myMethod().addCallback(function (response) { alert('response: ' + response); })
It calls the method in the RPC service and attaches a callback function to wait for the response. It then displays the response to the user in an alert.
Handling Client-Side Errors
This works well and RPC functionality is awesome, but you have to be careful about how you handle errors.
Take for example, this problematic update. This code ignores the response, but tries to display an invalid value (an undeclared variable) in an alert.
myRPCService.myMethod().addCallback(function (response) { console.log('before'); alert ('Invalid variable: ' + myUndeclaredVariable); console.log('after'); })
When you run the code, it appears that nothing happens. The console shows the ‘before’ statement, but it then fails quietly.
Putting a try-catch block around it like this doesn’t help at all.
try { myRPCService.myMethod().addCallback(function (response) { console.log('before'); alert ('Invalid variable: ' + myUndeclaredVariable); console.log('after'); }) } catch (e) { alert('Error: ' + e.toString()); }
This may seem a bit confusing, but it actually makes sense. The callback effectively runs in its own scope, so the error handling needs to be within the callback in order to fire when dealing with an RPC call.
This code does the trick:
myRPCService.myMethod().addCallback(function (response) { try { console.log('before'); alert ('Invalid variable: ' + myUndeclaredVariable); console.log('after'); } catch (e) { alert('Error: ' + e.toString()); } })
Handling Server-Side Errors
If there’s an unhandled exception on the server-side code that runs (such as an error or forgetting to return a response), it also fails quietly, although it will show a few errors in the browser console.
If you expand the POST, you’ll see that it returns a stack trace for an RPC error.
In this case, error handling in the client-side callback function doesn’t help at all, so it’s important to handle the error in the server-side code and return something that the callback can deal with.
function myLibraryFunction() { try { print (myUndeclaredVariable); var d = new Date(); return d.toLocaleString(); } catch (e) { return 'Error: ' + e.toString(); } }
Now, I’m returning a more informative message to the user about what went wrong.
I generally like to set up my server-side methods to return an object to the callback function, because that way I can add as many properties as I want in order to return all of the information that I need. I generally include a property for a boolean value for whether the method was successful and another value that contains a success or error message. In the callback, those values can be checked and appropriate action can be taken accordingly.