Build JSON from NotesView, support for multiple value fields

The problem

An old-fashioned NotesView can be a fast way to define JSON objects. Here is a xsnippet that give you some inpsiration.

If you have fields with multiple values then the formula does not work anymore. You want to store an array in the JSON.

The fix

The following formula checks if the desired output fields contains more than 1 value  and if so transforms it to an array if not, then you get a normal key:value pair returned.

_fld:=”refName”:”refSub”:”refStrength”:”refWeakness”;

json:=””;

@For(n :=1; n<=@Elements(_fld); n:= n + 1;

@If(
@Elements(
@GetField(_fld[n])
)>1;
json := json + @Transform ( _fld[n]; “_fn” ; “\”” + _fn + “\”:”) + “[” + @Implode(@Transform( @GetField(_fld[n]) ; “_fn” ; “\”” + _fn + “\”” ) ; “,”) + “],” ;
json := json +
@Transform (
_fld[n]; “_fn” ; “\”” + _fn + “\”:\”” + @Text ( @GetField ( _fn) ) + “\”” + “,”)
)
);
“{ \”unid\”:\””
+@Text(@DocumentUniqueID)+”\”,” + @LeftBack(json;1) + + “}”

Test

I added my formula to a column and calling several single and multiple text fields. Here is my output in a browser:

notesview-as-json

If I validate the json it says it is valid:

valid-json

I added my code to the XSnippets database.

Add 20 years of experience to your workforce

You can 20 years of experience within IBM Notes and Web development to your workforce by hiring me.

Interested? Read my curriculum vitae on LinkedIn: http://www.linkedin.com/in/patrickkwinten and get in contact.

I am happy to work WITH you !

A modern commenting view in XPages

Introduction

In the old days you a typical commenting feature was something with a form and a view. Typically you could read a list of comments in a historical (flat) order and on the bottom you had the form to enter your comment. Something like in the IBM Domino blog template.

domino-blog

With the rise of social and mobile it became more important to be able to comment-only so the form moved to the top and the list of comments became sorted in the opposite order (Youtube).

Discussions are still displayed in a thread but since threads are less friendly on a mobile device a more what’app like chat display. But these are more instant messaging apps, similar to Slack or IBM’s upcoming Toscana.

slack

My idea: welcome to the bubble

So what can/should we do to modernize the display of the comment feature in our Notes/XPages application?

Well mainly we still have a top level object (TLO) where people comment on. To stimulate people to comment the form should be close to this TLO. We can promote the interaction between a user and others and provide some form of “bubble speech” experience and (ofcourse) the option to “like” a comment.

That would bring us to something more like this:

social_comment

 

Notice on the left you see the comments I have made and on the right comments made by others. The latest comment is displayed first and mines are a bit more outstanding using a background-color.

Now how it’s made

To come to this solutions I am using the following technologies:

  • XPages
  • Java
  • SSJS
  • Bootstrap
  • PrettyTime
  • CSS
  • JavaScript / mention JS

Note that in a previous post I described how to add @mention autocomplete like Facebook, Twitter & Google+ to your XPages app. So I will not discuss in this post how to build the form to comment.

Here is a general outline of what we are going to build:

outline

Step 1 – basic structure; a repeater with a panel

step01

First I have a repeat control which is bound to an ArrayList containing JsonObjects. This approach you can find in my Bildr project on OpenNTF (shameless plug).

I also added an infinite scroll function. You can read about how to set that up in this post.

The panel has a computed styleclass. The style defintion “right” does nothing more than a  text-align: right. This makes sure the text in the content is … aligned right.

Step 2 – adding a user icon

Humans are visually oriented and idle so nothing wrong making our display attractive with a user icon.

step02

In this example I am just displaying some random icons, but if you have a corporate directory with user profiles containing icons you should embed them here.

The pull-left and pull-right classes are from Bootstrap. My comments are pulled to the left, comments from others to the right.

Step 3 – the media body

Next item that we add is a div with a media-body class. It contains out of 2 sections: the content of the comment (text written) and some meta-data (date, author). I also added a “like” link which is inspired by Thomas Adrian’s Intrapages app also available on OpenNTF.

step03

(Guess I don’t need the attributes here…). Here is the part of the meta-data:

step03b

First I display the Author name, only for comments written by others. In order to make the date more human friendly to read I am using PrettyTime. In the past I have blogged about how to use it.

For the remove link I am using the userbean to check if I can delete documents in the database and if the comment is mine: (@UserName() == obj.From) && (userBean.canDeleteDocs == true)

For the event I check and ask if I am sure that I want to remove the entry and then I simply remove it by UNID:

step03c

For the “like” button I would like to point to Adrian’s example in his Intrapages project. I made however the exeption to store the likes in a separate document, so not in the comment. By this way I can tighten my security model. Everybody has the role of [liker] and author access. So everybody can update a like document and not the original comment document.

The like function uses the cookie management principles described here. It stores the username:

userCookie = new javax.servlet.http.Cookie(“userid”, @UserName());

I have set the duration of the cookie as long as the session is active:

//Cookie.setMaxAge(-1) will make the cookie expire after the browser is closed
userCookie.setMaxAge(-1);

But beware that the cookie still exists when users logout and login with a different username-password combination !!

So I have a counter for the number of likes, and depending on my activity I have a like or unlike link.

Ready! Some CSS whistles

After we have added some more (basic) CSS we are done! As a result we have created something much more modern that the old school comments display as we know from the IBM Domino Blog template.

If you are interested and want to receive the details of this setup I welcome you to send me a message and we can exchange code.

Add 20 years of experience to your workforce

You can 20 years of experience within IBM Notes and Web development to your workforce by hiring me.

Interested? Read my curriculum vitae on LinkedIn: http://www.linkedin.com/in/patrickkwinten and get in contact.

I am happy to work WITH you !

 

 

 

 

DevTip: using the latest font-awesome CSS toolkit in your XPages application

Tired off or you feel restricted by the Bootstrap Glyphicons? I bet you do. So you fancy to use Font-awesome as addition? Excellent choice. But after you have added them to your web-content folder and place them on an XPage you will notice the desired font does not appear.

Luckily for you other people have bumped into this before and allocated the problem and come with a fix.

So now you started to load the libraries your XPage application is depending on into ODP/NSF by using Bower or another package manager. If you do not specify a specific version but go for “latest” you will notice that in the suggested fix a version is specified for the font, so which each new release (which you are not aware of due to the “latest” option) your fix is out of sync.

CDN to the resque you might think. Since they handle the URL complication you are good to go as a consumer. Try to add a style sheet resource to an XPage without the http/https protocol is not allowed. If you modified it by hand in the source code like:

href=”//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.css”

in the browser something as

link rel=”stylesheet” type=”text/css” href=”/apps/customerx/fontawesomecdn.nsf//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.css”

will be produced which won’t work. You can add the protocol only once and you can not make the protocol conditional here.

Themes to the rescue! In a Theme design element you can check against what scheme the application runs and if so go for the corresponding protocol:

<theme>
<!– FontAwesome –>
<resource rendered=”#{javascript:context.getUrl().getScheme().equals(‘http’)}”>
<content-type>text/css</content-type>
<href>http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css</href&gt;
</resource>
<resource rendered=”#{javascript:context.getUrl().getScheme().equals(‘https’)}”>
<content-type>text/css</content-type>
<href>https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css</href&gt;
</resource>
</theme>

Here I have choosen to go against maxcdn which provides a “latest” option. If I check in the browser if delivers me

/*!
* Font Awesome 4.6.3 by @davegandy – http://fontawesome.io – @fontawesome
* License – http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
*/

Summary: problem solved.

  • I have the latest version of font-awesome
  • I have not an URL problem
  • I respect the protocol my application runs under

Unfortunately, my library is gone from my package manager file.

If you have a better suggestion then please drop a comment here below.

Update – Use Grunt

After writing this post I thought that their might be customers who block CDN resources. What to do then?

In Brad Ballasaitis example he created an additional CSS to overwrite the default font-family specification, one without the URL ?v= parameter.

In case you use a tool like Bower to download and install 3rd party libraries or plugins the original CSS with the URL ?=v parameter will be installed. You could write a simple Grunt task (I am new to this) that picks up your custom font-family CSS file from a temporary (fixes?) directory and copy it into the font-awesome CSS directory. A simple example would be:

/*
Copy font-awesome fix
Author Patrick Kwinten
All rights reserved
*/
‘use strict’;

module.exports = function (grunt) {

    require(‘load-grunt-tasks’)(grunt);
grunt.initConfig({
copy: {
main: {
src: ‘fixes/font-awesome-fontFamily.css’,
dest: ‘WebContent/libs/font-awesome/css/font-awesome-fontFamily.css’,
options: {
process: function (content, srcpath) {
return content;
},
},
},
}
});
};

If you run this task you are back to a state where you can now overwrite the default font-family selector again.

Load the CSS files via a Theme design element e.g.:

<!–
Not the following is not working in conjuction with the
XSP Property ‘runtime optimized resources’.

Therefor the following workaround is applied:
– Move the @font-face part into 2 new CSS e.g.
./font-awesome/css/font-awesome-fontFamily.css
./font-awesome/css/font-awesome-fontFamily.min.css

Note the paths to the fonts differ in these files.

– Load 1 of the css via the Theme based upon the context.getProperty(‘xsp.resources.aggregate’) property
–>
<resource rendered=”#{javascript:context.getProperty(‘xsp.resources.aggregate’).equals(‘false’)}”>
<content-type>text/css</content-type>
<href>font-awesome/css/font-awesome-fontFamily.css</href>
</resource>
<resource rendered=”#{javascript:context.getProperty(‘xsp.resources.aggregate’).equals(‘true’)}”>
<content-type>text/css</content-type>
<href>font-awesome/css/font-awesome-fontFamily.min.css</href>
</resource>
<resource>
<content-type>text/css</content-type>
<href>font-awesome/css/font-awesome.min.css</href>
</resource>

Add 20 years of experience to your workforce

You can 20 years of experience within IBM Notes and Web development to your workforce by hiring me.

Interested? Read my curriculum vitae on LinkedIn: http://www.linkedin.com/in/patrickkwinten and get in contact.

I am happy to work WITH you !

From Windows 10 to Linux Mint 18

This week I decided to move over my Development host environment from Windows to Linux Mint after a post of a friend in which he stated that he had abandoned his long love with Linux Mint 17… for version 18. If you are unfamiliar with Linux Mint here is a good review on Linux Mint 18.

For the last decade I have been the regular corporate developer, so I did not mind too much about OS and when my pc became slow I just looked for a solution in newer hardware. 2 years ago I bought a new laptop (Lenova), Intel i7 processor, SSD disk, lots of GB for storage and 16GB of RAM. Oh and Windows 8. For Development I use Virtualbox with a Windows 7 guest OS where my Domino server runs on and the client programs (DDE mostly).

Things were running fast in the beginning and the update to Windows 10 was not a problem. But after a while, performance became less due to unknown reasons so I could re-install the whole thing over again (and get in trouble with my fellow users on the machine) or look for an alternative. That alternative became a dual boot option between Windows and Linux Mint.

The installation and re-installation (too small partition at first) went smoothly and within minutes I was running my Development environment hosted on Linux Mint (thanks to the Software Manager). The whole adaption of Linux Mint is a piece of cake. To me Mint desktop reminds me of Windows XP.

The long-term support of Linux Mint 18 (2021) and the possibility of Windows 10 turning from a purchase model into a subscription model is a consideration for the future. Also having features installed from scratch such as an image editor (Gimp) and Office software (Libre Office) is nice. Now I just have to consider switching over from our beloved multi-purpose client (Notes) to something more basic (Thunderbird)…

Rather would I move away my guest environment away from Windows too, but Domino Designer / Administrator is bound to Windows. #WWYT?

In the pipeline I have a Macbook, which delivery takes a bit longer than expected. I am curious how your development environments look like. Perhaps I could take a little tips from them.

Happy development =)

 

I’ve got the bower

As I am trying to get my XPages development workflow more in line with other development teams, my next step was to implement bower so I can skip dragging, copying, removing, updating (too many verbs already) in order to manage my projects.

First stop was Frank van der Linden’s post on bower4xpages. Most of the commands are described in his post so I skip to repeat them here..

Step 1 – Install Node.js

You can install bower with the Node package manager.  So step 1 was to install Node.

Step 2 – Install Bower

With the node package manager I installed bower.

Web sites are made of lots of things — frameworks, libraries, assets, and utilities. Bower manages all these things for you.

Step 3 – Setup the bower files

When Bower runs it needs 2 files: bower.json and .bowerrc file. In the json file you list the dependencies and the rc file points to the location where the files will be copied to. Here is a tip how to create a nameless file in notepad.

Having placed these files in the root of my repository location I was ready for the next step.

Step 4 – Install Git

Since I have been using SourceTree as Git client for Windows I needed to install Git client because Bower makes use of it.

Post Step 4 – Set Windows Environment Variables

When trying to run bower I got message that Git was not installed. Here is a description how to set your Windows environment variables.

Step 5 – Run bower run

Now with everything installed and set the last thing to do was to open the Command Prompt and cd to the root directory of my repository and run the ‘bower install’ command.

As a result I got all the dependencies in my project downloaded and installed.

bower_result

Once again achieved “a new(er) way of working”.

A new way of working: SCM

A new company, a new pc (mac), a new way of working. Change brings opportunity so I decided to move some of my OpenNTF projects, lab projects and code to GitHub.

So far it works just fine and I feel kinda stupid to stick myself for a long time in the old way of working (application templates, shared drives, post code to this blog). Switching between machines/virtual environments has become much nicer.

As tools I choose for DDE, Swiper, SourceTree and Github. I have not come so far with the command line, although the Try Git tutorial on Code School demonstrates it should not be that difficult.

Next step is probably setup a package manager in combination with a task runner.  A bit inspired by Keith Strickland’s presentation at Engage.

Probably I am missing something in my setup but I am happy to read about that in the comments🙂

Modernizing a Notes application

Introduction

The quickest way of modernizing your application build on Notes is probably by keeping it on that sublime application platform and provide a new user-interface and updated business logic to it.

As a demonstratable example I would like to bring up my own Bildr project on OpenNTF.

A brief history

The application started initially as a web browser display only and create content via the Notes client application in the early 2000’s. From that the application was updated in a create content via the web browser too features.

Later the oneUI was implemented in a later step also utilizing the Application Layout control. With the Bootstrap4XPages plugin a responsive UI could be delivered a couple of years ago.

Nowadays the Application Layout control is no longer used but the Bootstrap responsive features and components are used further through the application.

The application still relies on XPages and Notes data (allthough used mainly in JSON format). The business logic resides mainly in Java Classes. With the separation of design and data the application could be hosted on Bluemix (not tested, please do).

Modernization

Looking back at this application story I believe the application will change also in the future (or die) perhaps a challenge could be to have the data optional in a different source (e.g. MongoDB) or exchange XPages for Angular and run it on Node.js.

So if you have experience moving data from Notes to MongoDb, applying a similar ACL and Roles security model on your application I would be happy to hear your experiences.

Or if you are still on the Notes client only level and want to bring your application to a (mobile) browser I am happy to exchange ideas with you and learn from your situation.

New release

Why am I saying this? Today I uploaded a new version on OpenNTF and for many Notes developers who a) not have taken the XPages path yet b) unfamiliar with Java and JSON the application could be a great starter example.

Lately there are not that many (new, updated) projects (applications) available at OpenNTF so the chance to find a working demo to see and understand the code and data running are a bit scarce (I am sorry).

I remember in the days of Superhuman Software a quote about Notes and collaboration was “dare to share” so I would challenge more developers to do so. We can learn a lot from examples from others and I thank those people who (still) do and from which I can learn from!

I wish you a wonderful learning experience at IBMConnect 2016!

Capture04

 

Beware when removing ID’s of controls

In an exercise to maximize performance of an Xpages application we decided to remove as much as redundant ID’s of controls as possible, as described in this best practice.

In summary the ID of an control gets rendered in a much longer ID when the HTML page is rendered. A simple label with ID ‘label1’ could become ‘view:_id1:_id2:_id11:label1’ and if you put that label in a repeat control the generated ID could become even much longer.

A downsize of removing the ID I found out that some properties like tagName for example does not get applied anymore. Of course you can replace the tag around the control, but I found that out afterwards.

Nevertheless a good best practice removing ID’s but do it with caution. Read the comments in the post to update yourself on the subject.

Managed properties

For an application we aggregate the data from several servers and databases. In SSJS applications I tend to save such properties in Notes configuration documents and store them in scoped Variables during initialization. Something like was provided in the XPages Framework a while ago.

In episode 182 of Notes in 9 David Leedy gives a great demonstration how to work with Notes documents via Managed Beans. However for properties that should not be altered likely by an application administrator (could be the application owner, a regular Notes user) I tend to work with managed properties. With managed properties you more or less configure your managed bean.

So how could this look like?

In the faces-config.xml I set the properties for a managed bean e.g.

<?xml version=”1.0″ encoding=”UTF-8″?>
<faces-config>
<managed-bean>
<managed-bean-name>dataBean</managed-bean-name>
<managed-bean-class>com.wordpress.quintessens.ConfigBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>

<managed-property>
<property-name>dataSource</property-name>
<value>dev1.quintessens.com</value>
<property-class>java.lang.String</property-class>
</managed-property>

</managed-bean>
</faces-config>

which I can use then in my java code:

package com.wordpress.quintessens;
import java.io.Serializable;
public class ConfigBean implements Serializable {
private String dataSource;
//… more variable declarations

public JsonJavaObject loadBackEndConfig(String Key) throws NotesException {
JsonJavaObject json = null;
NotesContext nct = NotesContext.getCurrent();
Session session = nct.getCurrentSession();
String DatabaseName = session.getCurrentDatabase().getFilePath();
String ViewName = “(LookUpBackEndConfig)”;
try {
json = loadJSONObject(this.dataSource, DatabaseName, ViewName, Key, 1);
} catch (NotesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}

public void setDataSource(String dataSource{
this.dataSource = dataSource
}
public String getDataSource() {
return dataSource
}

}

You can check if the value is passed correctly e.g. via Expression Language:

<xp:text escape=”true” id=”computedField1″
value=”#{ConfigBean.dataSource}”>
</xp:text>

I am curious how you prefer to configure your applications? In some cases I find it perhaps an overkill to store the configuration in Notes documents and publish the values via a managed bean.

Happy development =)

 

prettytime for your XPages

Introduction

I guess most of us believe that not all users are robots, and especially in social applications where you try to approach humans as human friendly as possible the display of date and time in such format can be off added value.

Timeago

There are many scripts to display date and time in a human friendly format. For a project we are using timeago, a jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. “4 minutes ago” or “about 1 day ago”).

However, in combination with an infinite scroll feature to navigate through document collections we notice that the script not always return instantly the transformed date/time.

That is why I looked at a server-side transformation.

PrettyTime

PrettyTime is an OpenSource time formatting library. Completely customizable, it creates human readable, relative timestamps like those seen on Digg, Twitter, and Facebook.

It turned out the implementation of PrettyTime was quiet simple. I will describe the steps for you.

Install the jar & call the Java class

Download the project jar file and place it in the WebContent \ WEB-INF \ lib folder.  For a computed field on a custom control in a repeat control I have as SSJS code to call the Java class:

<xp:text>
<xp:this.value><![CDATA[#{javascript:var theDate = compositeData.Date;
p = new org.ocpsoft.pretty.time.PrettyTime();
p.format(new Date(theDate))}]]></xp:this.value>
</xp:text>

As a result I get to date displayed as:

prettytime

Pro’s & Con’s

In comparison with client-side solutions I have detect some con’s and pro’s for a server side solution:

  • Static; the client side solutions are capably of updating the date/time value on the fly.
  • Speed; the server side generated human friendly date is there when a document row is presented.
  • Extensibility; the number of display languages is more numerous for most client-side solutions. Also you can often “configure” the text format when desired.
  • Consistency; having a human friendly date in a local language may be in conflict with internationalization of your XPages app since that might require more work.

Anyway: I happy to hear how you have solved the human friendly date issue.

Happy development!