Image manipulation in VBScript

I am back on Windows development. It is not what I prefer but still, it is development so I am right here! 😉

My task was to upload an image from a website (nothing difficult there) but the application has to resize and crop the uploaded image before saving it on the hard drive in order to save space.
Oh, and I forgot to mention that the website is built in VBScript (it would have been too easy if it has been built in ASP.Net…). 🙄

I went across a lot of image management libraries which work with VBScript during my search:

But I must admit that the most difficult part of this task was to find a good and FREE library.
The one I finally picked is ImageMagick.

Once the library is installed (click here to go to the download page), you can use the following code to resize the image to a maximum of 800 pixels and crop the white space around it:

Dim imageMagick
Set imageMagick = CreateObject("ImageMagickObject.MagickImage.1")

imageMagick.Convert "C:/testimage.jpg", "-fuzz", "10%", "-trim", "-resize", "800x800>", "C:/thumb-testimage.jpg"

Obviously, this tool can do much more than that, but this will be subject of another topic.
Or you can simply read the documentation: http://www.imagemagick.org/Usage/

, ,

1 Comment

Using the ‘date’ command in your crontab

Crontab, as most people know, enables users to schedule commands or shell scripts to run periodically at certain times or dates.

The other day, this very useful Linux tool gave me a hard time! 🙁
Indeed, one of my commands wasn’t working in cron but was working perfectly fine when written in a shell console.

The faulty command looked like this:

0 5 * * 3 /data/script.sh > /data/script_`date +%y%m%d`.log 2>&1

If I run this command in a shell console, everything works fine and I get a log file containing today’s date in its filename. However, if I set this command line in my crontab, it doesn’t work and no log file is even created!

Reading the documentation of cron, I discovered the following statement:

Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.

Well, this is good to know, isn’t it? 😉
We need to escape the percent-signs on our command line.

So in order to get our ‘faulty’ command to run in cron, it needs to look like the following:

0 5 * * 3 /data/script.sh > /data/script_`date +\%y\%m\%d`.log 2>&1

, , , ,

6 Comments

Validate your EAN barcode

On one of the applications I am working on, I had to validate an EAN (European Article Number) barcode.
This application is mostly using JavaScript validation so I asked my friend Google to find me a JavaScript method which would check my EAN barcode.
It found validators in different languages but none in JavaScript. 🙁

Because one is never better served than by oneself, I decided to write it myself and share it with you. 😉

function checkEan(eanCode) {
	// Check if only digits
	var ValidChars = "0123456789";
	for (i = 0; i < eanCode.length; i++) { 
		digit = eanCode.charAt(i); 
		if (ValidChars.indexOf(digit) == -1) {
			return false;
		}
	}
	
	// Add five 0 if the code has only 8 digits
	if (eanCode.length == 8 ) {
		eanCode = "00000" + eanCode;
	}
	// Check for 13 digits otherwise
	else if (eanCode.length != 13) {
		return false;
	}
	
	// Get the check number
	originalCheck = eanCode.substring(eanCode.length - 1);
	eanCode = eanCode.substring(0, eanCode.length - 1);
	
	// Add even numbers together
	even = Number(eanCode.charAt(1)) + 
	       Number(eanCode.charAt(3)) + 
	       Number(eanCode.charAt(5)) + 
	       Number(eanCode.charAt(7)) + 
	       Number(eanCode.charAt(9)) + 
	       Number(eanCode.charAt(11));
	// Multiply this result by 3
	even *= 3;
	
	// Add odd numbers together
	odd = Number(eanCode.charAt(0)) + 
	      Number(eanCode.charAt(2)) + 
	      Number(eanCode.charAt(4)) + 
	      Number(eanCode.charAt(6)) + 
	      Number(eanCode.charAt(8)) + 
	      Number(eanCode.charAt(10));
	
	// Add two totals together
	total = even + odd;
	
	// Calculate the checksum
    // Divide total by 10 and store the remainder
    checksum = total % 10;
    // If result is not 0 then take away 10
    if (checksum != 0) {
        checksum = 10 - checksum;
    }

	// Return the result
	if (checksum != originalCheck) {
		return false;
	}
	
    return true;
}

Note that this code can validate EAN-8 and EAN-13 barcodes.

,

8 Comments

The message tags of MyFaces and RichFaces

Working on an application using MyFaces and RichFaces, I had no choice but understand what is the difference between the message tag provided by Myfaces (h:message) and the message tag overridden by RichFaces (rich:message).

These tags allow to display information about the first FacesMessage that is assigned to the component referenced by the “for” attribute. The difference is that the RichFaces tag has some extra functionalities such as Ajax rendering, error markers and predefined css class names.
Have a look at the following page for more details: http://livedemo.exadel.com/richfaces-demo/richfaces/message.jsf

This is all nice and well but it is not the only difference. Indeed, the HTML code generated by both these frameworks will also be different!

First of all, let’s see how the tag <h:message styleClass="errormsg" for="element"/> will be transformed. If there is no message to display, nothing will be generated (which is a good behaviour). However, if a message is present, the tag will be replaced by the following HTML code:

<span class="errormsg">Required.</span>

So far, so good!

But now let’s check what code RichFaces is generating for the tag <rich:message styleClass="errormsg" for="element"/>.
The following is the code created if there is NO message to render:

<span class="rich-message errormsg" id="form:j_id255">
    <span class="rich-message-label"></span>
</span>

And here is the code which will replace the RichFaces tag if there is a message to display:

<span class="rich-message errormsg" id="form:j_id255">
    <span class="rich-message-label">Required.</span>
</span>

As you can see, the main difference is that RichFaces is wrapping the original span tag into another span tag. But, it is also generating some code even if there is no message to display! You would ask why is it doing that? The response is simple. The wrapper span element is necessary for RichFaces to Ajax-render the message tag if an error message has to be displayed for the targeting element.

So make sure you don’t put any padding or margin style in your custom CSS class which I called ‘errormsg’ in my example. Otherwise, you might have a gap when you were expecting nothing… (this happened to me) 😉

, , , , , ,

1 Comment

How to personalise the URLs with Faces Navigation?

This is an important question if you want to have search engine friendly URLs on your website!
But unfortunately, the solution is not straightforward with JavaServer Faces (JSF). 🙁

First of all, for security reason JSF doesn’t allow you to use the GET method for your forms. I didn’t really understand why but this is very (too) restrictive!
Can you imagine Google doing the same thing? We would have the same URL for every search terms http://www.google.co.uk/search instead of something like http://www.google.co.uk/search?hl=en&safe=off&esrch=FT1&q=test&meta=&aq=f&aqi=g10&aql=&oq=&gs_rfai=.
It wouldn’t be very easy to share a search page with a friend if Google was using the POST method. 😉

So the question is how to get around this JSF limitation?

Let’s take a look at how would look our faces-navigation.xml file for a search page:

<navigation-case>
    <from-action>#{searchBean.searchAction}</from-action>
    <from-outcome>success</from-outcome>
    <to-view-id>/search.xhtml</to-view-id>
    <redirect />
</navigation-case>

In this example, all the JSF elements calling the action searchBean.searchAction will be redirected to the search.xhtml page.
But, how are we going to get the search parameters into the URL?

Ideally, it would be great to be able to do something like the following:

<navigation-case>
    <from-action>#{searchBean.searchAction}</from-action>
    <from-outcome>success</from-outcome>
    <to-view-id>/search.xhtml?q=#{param.q}</to-view-id>
    <redirect />
</navigation-case>

This solution would allow us to inject EL expressions into the URL before the page is redirected to the destination page.
In order to do this, we need to create our own view handler and register it to our application. 😎

The code below is the view handler class which also includes some comments:

package com.logikdev.gui.handler;

import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.ViewHandler;
import javax.faces.context.FacesContext;

import com.sun.facelets.FaceletViewHandler;

/**
 * Overrides the Facelet view handler to support EL expressions in URLs.
 * @author Stéphane Moreau
 */
public class DynamicViewHandler extends FaceletViewHandler {

	public DynamicViewHandler(ViewHandler parent) {
		super(parent);
	}
	
	/* (non-Javadoc)
	 * @see com.sun.facelets.FaceletViewHandler#getActionURL(javax.faces.context.FacesContext, java.lang.String)
	 */
	@Override
	public String getActionURL(FacesContext context, String viewId) {
		String queryString = null;

		// Replace the EL expressions in the URL
		ExpressionFactory expressionFactory = context.getApplication().getExpressionFactory();
		ValueExpression valueExpression = expressionFactory.createValueExpression(context.getELContext(), viewId, String.class);
		String result = (String) valueExpression.getValue(context.getELContext());
		
		// Separate the query string from the URL
		int dotIndex = result.lastIndexOf('.');
		int questionMarkIndex = result.indexOf('?');
		if (questionMarkIndex != -1) {
			queryString = result.substring(questionMarkIndex, dotIndex);
			viewId = result.substring(0, questionMarkIndex) + result.substring(dotIndex);
		}
		
		// Call the parent without the query string
		result = super.getActionURL(context, viewId);
		
		// Put back the query string at the end of the URL
		if (queryString != null) {
			result += queryString;
		}
	        
		return result;
	}

}

And the following is the code to put in the faces-config.xml file in order to register the newly created view handler to the application:

<application>
	<variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>
	<view-handler>com.logikdev.gui.handler.DynamicViewHandler</view-handler>
</application>

One last thing!
This view handler also has a limitation which I wasn’t able to fix. 🙁 The file extension has to ALWAYS be placed at the end of the to-view-id URL! The view handler will then put it back before the question mark.
For example:

<navigation-case>
	<from-action>#{searchBean.searchAction}</from-action>
	<from-outcome>success</from-outcome>
	<!-- The extension has to be at the end -->
	<to-view-id>/search?q=#{param.q}.xhtml</to-view-id>
	<redirect />
</navigation-case>

If you perform a search on ‘jsf’ with the above navigation rule, the user will be redirected to the page /search.xhtml?q=jsf.

, , , , ,

2 Comments