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.

Nav Collapse 1A - Full Browser Over 768px

When I shrunk the screen to be less than 768px wide, it collapsed the navigation properly.

Nav Collapse 1B - Full Browser Under 768px

When I checked it on my phone, it was collapsed properly.

Nav Collapse 1C - Phone - Collapsed

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.

Nav Collapse 2A - Phone - NOT Collapsed in XPages

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.

Nav Collapse 2B - Phone - Screen Width

(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.

Nav Collapse 3 - Phone - Collapsed in XPages

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.

Keep Alive 2A - Keep Session Alive XSP partial refresh

(In contrast, the Keep Session Alive control appears to be efficient, sending a GET request and getting a minimal response.)

Keep Alive 2B - Keep Session Alive control

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…

Keep Session Alive 2F - RPC Post

… as is the response.

Keep Session Alive 2F - RPC 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…

Keep Session Alive 2C - Partial Refresh Failure

…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.

Keep Session Alive 2C2- Partial Refresh Failure 2 - No Element to Submit

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:

Keep Session Alive 2D - RPC Post Failure Due to Machine Going to Sleep

A different message is returned when it times out due to the expiration of the LTPA token:

Keep Session Alive 2D2 - RPC Post Failure When Timed Out

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

Keep Alive 1A - Server - Idle Session Timeout

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.

 

Keep Alive 1B - Application - Idle Session TimeoutThis 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.

Keep Alive 1C - SSO Token Expiration

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:

Custom Property - Primitive Types

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).

Custom Property - Property Types

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.

Custom Property - 1 Custom Property

<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 Property - Error - No Property Type Defined

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.)

Custom Property - Object Type

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:

  1. The page-level client-side code runs to write the message to the browser console
  2. 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 the onClientLoad 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.

Follow

Get every new post delivered to your Inbox.

Join 85 other followers