Wednesday, December 24, 2014

JSF Hacks for Advent

1. Validator with error message in user selected languages

The trick is to set the language  preference selected by user in session map, then in the validator class get the value of language preference and return respective error message in respective language.

Download full sample here.



public class NameValidator implements Validator {

    public void validate(FacesContext context,UIComponent component,Object value)
            throws ValidatorException {
        if (component == null) {
        String valueToCheck = "";
        String label = (String) component.getAttributes().get("label");
        if (value instanceof String) {
            valueToCheck = (String) escapeHtmlTextFieldValue((String) value);
            Object submittedValue = ((UIInput) component).getSubmittedValue();
            if (submittedValue != null) {
                ((UIInput) component).setSubmittedValue(value);
            } else {
                ((UIInput) component).setValue(value);
        if (!valueToCheck.trim().matches("^[a-zA-Z]*$")) {
            ((UIInput) component).setValid(false);
            String lang = getAttributeByName(component, "language");
            if (lang != null && lang.equals("japanese")) {
                context.addMessage(component.getClientId(context), new FacesMessage(FacesMessage.SEVERITY_ERROR, "名前ルール間違っています、ご確認してください", "名前ルール間違っています、ご確認してください"));
            } else {
                context.addMessage(component.getClientId(context), new FacesMessage(FacesMessage.SEVERITY_ERROR, "name validation error", "Name rule is not considered, please check"));

2. Using placeholder and other data attributes in JSF 2.1.

Using placeholder in JSF 2.2

JSF 2.2 allows you to use placeholder attribute using p:passthrough under xmlns="" namespace.
Sample below.

 <html xmlns=""
        <h:inputText value="#{bean.value}" p:placeholder="Enter text"/>

Using placeholder in JSF 2.1

We need to tweak the textarea renderer a little to let this happen,
The steps are simple

1. Create a custom renderer extending the default TextareaRenderer

The following code allows placeholder and data-target attributes to be used with h:inputTextarea tag in JSF 2.1. More attributes can be allowed by adding them to string array "attributes".

package com.sample;

/* imports */

public class CustomTextareaRenderer extends TextareaRenderer {

    private static final String[] attributes = new String[]{

    protected void getEndTextToRender(FacesContext context, UIComponent component, String currentValue) throws IOException {
        final ResponseWriter originalResponseWriter = context.getResponseWriter();
        context.setResponseWriter(new ResponseWriterWrapper() {

            public ResponseWriter getWrapped() {
                return originalResponseWriter;

            public void startElement(String name, UIComponent component) throws IOException {
                super.startElement(name, component);
                if ("textarea".equalsIgnoreCase(name)) {
                    for (String attr : attributes) {
                        final String value = (String) component.getAttributes().get(attr);
                        if (value != null) {
                            super.writeAttribute(attr, value, attr);

        super.getEndTextToRender(context, component, currentValue);

2. Make sure the JSF renderer kit calls to custom renderer instead of default renderer.

<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.0"


3. Time to play: the tag
<h:inputTextarea id="myTextArea" cols="10" rows="2" value="#{bean.value}" placeholder="Enter Text !" data-target="I use this in my javascript to custom select textareas" />

3. Using maven to validate facelets (実行直前ビルド時Faceletを自動で有効にする)

Those who are using eclipse need not worry about this because eclipse xml validator does it for you automatically.
In the pom.xml < build > section add following code


Saturday, May 10, 2014

Hokkaido, the snow capital of Japan

Saturday, March 1, 2014

C# coding conventions

Naming Conventions

  • Always use Camel case (A word with the first letter lowercase, and the first letter of each subsequent word-part capitalised) while declaring variables.
  • Use Pascal (A word with the first letter capitalised, and the first letter of each subsequent word-part capitalised) naming format while declaring Properties.
  • Avoid all uppercase or lowercase names for properties, variables or method names. Use all uppercase when declaring const variables.
  • Never use a name that begins with a numeric character.
  • Always prefer meaningful names for your class, property, method, etc. This will be very useful for you to maintain the code in future. For example, “P” will not give proper meaning for a class. You will find it difficult to know about the class. But if you use “Person”, you will easily understand by it.
  • Never build a different name varied by capitalisation. It is a very bad practice. It will not be useful while developing code, as you will not know what is “person” class and what is “Person” class!!! But from the above scenario, it can be very easily understandable that “person” is an instance variable of “Person” class.
  • Don't use the same name used in .NET Framework. People who are new to your code have great difficulty to understand it easily.
  • Avoid adding prefixes or suffixes for your identifiers. Though in some guidelines, they use “m_” and in some other they use “_” as the prefix of variable declaration. I think it is not that much useful. But, it depends on your organisational coding practices. This point is contradictory based on various organisations and there is no strict guidance on it.
  • Always use “I” as prefix for Interfaces. This is a common practice for declaring interfaces.
  • Always add “Exception” as suffix for your custom exception class. It will give better visibility to your exception class.
  • Never prefix or suffix the class name to its property names. It will unnecessarily increase the property name. If “Firstname” is a property of “Person” class, you can easily identify it from that class directly. No need to write “PersonFirstname” or “FirstnameOfPerson”.
  • Prefix “is”, “has” or “can” for boolean properties like “isVisible”, “hasChildren”, “canExecute”. These give proper meaning to the properties.
  • Don't add prefix for your controls, instead write proper name to identify the control.

Commenting Conventions
  • Place the comment on a separate line, not at the end of a line of code.
  • Begin comment text with an uppercase letter.
  • End comment text with a period.
  • Insert one space between the comment delimiter (//) and the comment text, as shown in the following example.

Value types vs Reference types

  • If you want to store your data, use value types and when you want to create an instance of your type by defining the behavior, use reference types.

Value type

static void Main(string[] args)
int i = 5;
    // will print "Currently i = 5"
"Currently i = " + i);
static void SetValues(int x)
x +=

Reference type

static void Main(string[] args)
int i = 5;
ref i);
    // will print "Currently i = 15"
"Currently i = " + i);
static void SetValues(ref int x)
x +=

Need nullable data type ?

Simple data type

// simple declaration of int
int index = 0;

Nullable data type

// nullable data type declaration
int? index = null;

Runtime constants Vs Compile time constants

Runtime constants

// runtime constant
public readonly string CONFIG_FILE_NAME = "web.config";
  • must be initialised at the time of declaration and can’t be changed later.
  • limited to only numbers and strings.
  • it is a bit faster.

Compile time constants

// compile time constantpublic const string CONFIG_FILE_NAME = "web.config";
  • Runtime constants (readonly) are initialised in the constructor and can be changed at different initialisation time.
  • more reliable code.

Explicit casting Vs Implicit casting


// this line may throw Exception if it is unable to downcast from Person to Employeevar employee = (Employee) person;


It is better to use “is” and “as” operator while casting.
// check if the person is Employee typeif(person is Employee)
// convert person to Employee type employee = person as Employee;

Use string.Format() or StringBuilder for String Concatenation

Simple string concatenation

string str = "a";
str +=
str +=

Using string.Format()

string str = string.Format("{0}{1}{2}{3}{4}", "a", "r", "s");

Using StringBuilder

StringBuilder sb = new StringBuilder();
string str = sb.ToString();

Use IDisposable Interface wherever possible
class BaseClass : IDisposable

It will help free up the class resources when unused.

Using lambda expressions

  • If you are defining an event handler that you do not need to remove later, use a lambda expression.  
  • Use lambda expressions wherever you can remove boilerplate code.

public Form2()
// You can use a lambda expression to define an event handler.
this.Click += (s, e) =>

for() Vs foreach()

Prefer foreach over for, C# compiler generates the best iteration code for your particular collection.

Special Note

* Split your Logic in Several Small and Simple Methods

Further Secure Coding Guidelines