I had an unusual request from one of the developers in my team today, so I thought I’d share the solution up here for anyone else who either finds it useful, or has a better approach?

Challenge

If I have a variable which contains a letter, how do I get the next letter in the Alphabet programatically?

Solution

Frustratingly, unlike many other languages such as a PHP/Java/.NET, there is no simple way to do this in Apex. So I created a simple class that should do the trick and thought that I’d share it here in case it’s useful.

If you need more character-based routines, there is a similar but more extensive character class available on the Apex-Lang project on Google Code.

Hopefully they’ll add more of these basic utility classes to the platform eventually.

global class Character {

	private static final Integer LOWER_ALPHA_INDEX = 65;
	private static final Integer UPPER_ALPHA_INDEX = 90;
	
	public static final Map charToAscii { get; private set; }
	public static final Map asciiToChar { get; private set; }

	static {
		charToAscii = new Map();
		charToAscii.put('A', 65);
		charToAscii.put('B', 66);
		charToAscii.put('C', 67);
		charToAscii.put('D', 68);
		charToAscii.put('E', 69);
		charToAscii.put('F', 70);
		charToAscii.put('G', 71);
		charToAscii.put('H', 72);
		charToAscii.put('I', 73);
		charToAscii.put('J', 74);
		charToAscii.put('K', 75);
		charToAscii.put('L', 76);
		charToAscii.put('M', 77);
		charToAscii.put('N', 78);
		charToAscii.put('O', 79);
		charToAscii.put('P', 80);
		charToAscii.put('Q', 81);
		charToAscii.put('R', 82);
		charToAscii.put('S', 83);
		charToAscii.put('T', 84);
		charToAscii.put('U', 85);
		charToAscii.put('V', 86);
		charToAscii.put('W', 87);
		charToAscii.put('X', 88);
		charToAscii.put('Y', 89);
		charToAscii.put('Z', 90);
		
		asciiToChar = new Map();
		for(String key : charToAscii.keySet()){
			asciiToChar.put(charToAscii.get(key), key);	
		}
	}

	public static String getNextLetterInAlphabet(String currentLetter) {
		// Find the current index by character
		Integer currentIndex = charToAscii.get(currentLetter);

		// Ensure Z index gets reset to A
		Integer newIndex = (currentIndex == UPPER_ALPHA_INDEX) ? LOWER_ALPHA_INDEX : currentIndex + 1; 

		// Get the next letter by index
		String nextLetter = asciiToChar.get(newIndex);

		System.debug('If current letter is ' + currentLetter + ', then next letter is: ' + nextLetter);
		return nextLetter;
	}
}

Functional Requirement

You have a field in your VisualForce page which you want to be automatically updated when the user changes the value of another field in the page.

This can obviously be done using VisualForce’s AJAX (Partial Page Rendering) implementation, but can often be quite slow when it’s done server-side instead of client-side.

Solution

Enter jQuery – the Swiss Army knife of client-side web development! All we need here is a very simple snippet of jQuery code in our VF page to bind the value of our target field to our source field, as shown in the steps below.

1. Add in the jQuery library as an external resource in your VF page (this example uses the Google CDN, but it could be saved as a static resource to your Salesforce Org and imported that way too). The noConflict() switch is explained in the code review below:

 

$.noConflict();

2. Add the following script to the bottom of your VF page:


jQuery('document').ready(function($) {
   var target = $('input[id*=INSERT-ID-OF-YOUR-FIELD-HERE]');
   var source = $('input[id*=INSERT-ID-OF-YOUR-FIELD-HERE]');
   source.blur(function(e) {
        target.val(source.val());
   });
});

So, let's take a more detailed look at what this code is doing.

Snippet 1, Line 3: Using jQuery.noConflict();

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. One such library also using $ as an alias is Prototype, which just happens to be used by certain Salesforce UI controls and the client-side elements of the VisualForce AJAX implementation.

As a result, it's generally good practice to include this noConflict mode switch so that any other JS frameworks/libraries that use the $ symbol as an alias will continue to work as they should.

You can continue to use the $ reference in your jQuery code by passing the $ object as a parameter to each delegate, as shown in Line 2 of the second code snippet.

Snippet 2, Line 2: Using the document 'ready' event

The $('document').ready(function() { .... }); is the way to say in jQuery, "execute this block of code when the page has finished loading".

This is one of the most commonly used events in the jQuery framework and one you'll probably find you'll use a lot, simply because this is a good point in the page execution life-cycle to instantiate your jQuery code, because you know the DOM of your page has fully loaded. You will also find that this is the event that most jQuery plugins use to instantiate their code as well.

Snippet 2, Lines 2 to 7: Passing our delegate function

jQuery uses a technique called delegation as a core principal that you'll find throughout the framework. In simple terms, you pass the function you want to execute as a parameter to the event handler that should execute it. In this example, we want our function to execute when the document ready event is fired, so we pass our function as a parameter to the document 'ready' event handler, referenced using $('document').ready()

Snippet 2, Lines 3 and 4: jQuery Selectors

jQuery uses the same approach found in CSS to provide a comprehensive range of selectors. Here, I have used the 'ends with' selector for Lines 3 and 4 to say "get me any field of type 'input' with an ID ending in the ID you have inserted in the code at the point it says INSERT-ID-OF-YOUR-FIELD-HERE.

VisualForce changes the IDs of every element, prefixing it with a series of IDs based on the DOM structure. So becomes in the rendered HTML. Using the 'ends with' selector is just one way to neatly sidestep this issue with jQuery. You could also use CSS class name selectors as well... I've just found this approach works best without getting in the way of anything else in my code.

Snippet 2, Line 5: Change vs. Blur as a reliable, cross-browser event

Obviously, as we want the target value to be updated when the source value changes, you'd assume we should use the 'change' event in jQuery right? Well, unfortunately, that planned is somewhat scuppered by our good old friend IE, which doesn't bubble the change event, so we can't use it in tandem with delegated functions.

As a result, it's easiest just to use the blur() event... although you could do some basic browser detection if you wanted, and only use the blur() event for IE and use change() for all other browsers.

Snippet 2, Lines 5-7: Binding the field values

So now we need to bind the actual value of the target field to the value of the source field. To do this, we send is a simple function delegate to the blur event handler: function(e) { target.val(source.val()); }

Whether you are new to jQuery or not, I hope you find this useful and please check out the extensive jQuery docs, as they are a great resource for learning about this fantastic framework.

Happy coding :-)

An inspirational talk by Software Architect and creator of the ‘Fighting Layout Bugs’ framework, Michael Tamm, in which he goes into great detail about how he has created an automated Java-based class library for automated unit testing of XHTML/CSS layout bugs.

http://www.infoq.com/presentations/Fighting-Layout-Bugs

You can download the open-source project from here:

http://code.google.com/p/fighting-layout-bugs/

Just look how simple it is to create a new front-end Unit Test using this Framework!

FirefoxDriver driver = new FirefoxDriver();
try {
    String testPageUrl = "http://www.test.de/";
    driver.get(testPageUrl);
    FightingLayoutBugs flb = new FightingLayoutBugs();
    flb.setScreenshotDir(new File("."));
    final Collection layoutBugs = flb.findLayoutBugsIn(driver);
    System.out.println("Found " + layoutBugs.size() + " layout bug(s)");
    for (LayoutBug bug : layoutBugs) {
        System.out.println(bug);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    driver.quit();
}

There are a few scenarios that it doesn't catch just yet, but this is a fantastic start on something that has so far just seemed to open-ended to be attempted in the past. But as Michael puts it... there is no 'impossible', just varying amounts of effort! ;-)

Great work Michael!

I’ve recently been working on a fairly straight forward WCF Web-Service using Castle ActiveRecord, which uses NHibernate under the hood.

So far, I’ve been really impressed with ActiveRecord as a well throught through abstraction of NHibernate’s key features, which does a great job of keeping you focussed on the important stuff, without getting bogged down in the config.

I don’t want to go into depth on this here, but just to give you a quick idea if you haven’t seen this before, you simply add the attributes to your entities to describe how you want them persisted:

[ActiveRecord]
public class UpdatePersonMessage : BaseObject
{
    [PrimaryKey(Generator=PrimaryKeyType.GuidComb)]
    public virtual Guid Id { get; set; }

    [Property(Length = 50)]
    public virtual string FirstName { get; set; }

    [Property(Length = 50)]
    public virtual string LastName { get; set; }
    ...
}

You can then get ActiveRecord to dynamically create your database on initialisation, with a single line of code:

ActiveRecordStarter.Initialize(typeof(UpdatePersonMessage));

OR, if you want to use a custom config location... (I've had to format a little strangley to prevent this scrolling)

IConfigurationSource config = 
      new XmlConfigurationSource("{pathto}/ActiveRecord.config");
ActiveRecordStarter.Initialize(config, 
      typeof(UpdatePersonMessage));

So, on the last coulpe of projects where I've used ActiveRecord, I've been thinking - when would I bother using NHibernate, having to create all the relevant XML mapping files either by hand, or via a tool such as MyGeneration, or by using the declarative API for configuration provided by Fluent NHibernate?

As far as my experience tells me, there are only just a few key questions you can ask that can help you decide whether or not:

Please note: this already assumes that a full ORM is the appropriate solution for your domain - see YAGNI principle if you are not sure

  1. How complex is your data model? (e.g. beyond 3NF/BCNF, or complex legacy)
  2. Is this is a sensitive legacy datasource, tightly coupled to other legacy applications?
  3. How many people will be making changes to the data model, and how often?

The more complex the requirement, the more you move away from a situation that would get the best out of ActiveRecord. The approach is deliberatly simple, and while the pattern can cope with most day-to-day projects, as soon as your data requirements become more bespoke, it could be worth reconsidering an approach using NHibernate nativley.

Mapping files, attributes or declarative C#

Almost treated as a secondary design decision is how to manage the mapping of your data model.

If you use XML configuration files with a large team who all have access and make frequent changes, it can be a nightmare to manage. and you'll quickly find yourself in the situation where you'll be wondering why a particular persistence routine isn't producing the expected behaviour anymore, and it's simply down to a change you were not aware of.

Obviously TDD can really help with this, as can limiting access to just a couple of key developers who take ownership of the data model (and lock the mappings section down in source control!). On most projects, a data architect or lead dev would already have been allocated this role anyway.

Managing the mapping using C# code (e.g. using Fluent NHibernate) is often the best alternative if you're not using ActiveRecord (or another configuration abstraction layer) for a number of reasons:

  1. No Type-Safety = runtime explosions
  2. No Intellisense
  3. Your code will always compile regardless of how present, or correct your mapping files are

Here's an example of Fluent NHibernate in action:

public class UpdateExhibitorMessage : BaseObject
{  
    public UpdatePersonMessage()  
    {  
        Id(x => x.Id);  
        Map(x => x.FirstName);  
        Map(x => x.LastName);
        ...
    }  
}  

then, using the Auto Persistence Model - you can create the schema in the much same way as ActiveRecord:

AutoPersistenceModel.MapEntitiesFromAssemblyOf().Configure(config);

Summary

I have to admit... this has been a rushed post and none of these ideas are particularly new, but my aim is really to make it clear that there are several different decisions involved in getting the right NHibernate implementation to suite your problem domain and your team that begin AFTER you've made the decision to use NHibernate, and each of these decisions need to be thought through carefuly, because - as with software development in general - there is never a one-size-fits-all approach.


Quick Post-Edit Note: Be weary of any developer suggesting you use a particular pattern or framework with being able to solidly defend the specific benefits to your current solution. I know it sounds obvious, but it's crazy how often you come across "CV++" or developers sticking to 'what they used on their last project' without choosing the approach that is the right fit for your current domain.

Casey @ Devlicio.us posted an interesting point the other day, discussing the lack of any real positive impact we software developers actually have on the world (other than lining already bulging blue-chip pockets), which led to an interesting discussion, which I’ve quoted here:

Job Satisfaction, And Making The World A Better Place

You know what we achieve with all our wonderful software patterns and practices? Not a lot on the whole.

We do fairly well financially out of it, and many of those who use our software do fairly well financially from it too. A select few of us write software that can have a small impact on the well being of others, but even then, it is in a totally detached way.

But how often can you say that your day at work has affected somebody else’s life for the better, or made a really positive change to the world? How often can you look in the mirror and say my whole day was spent helping other people?

So, what the hell am I doing in the software game? Well, like I suspect many of us, I fell into it by accident. It was my hobby at school, I wrote games software and made a fairly comfortable (for a schoolboy) living from doing it.

Although my choice of O Levels (equivalent to GCSEs these days) were picked around becoming a doctor, and even though my mother had to argue with the school for weeks to get them to allow me to do three sciences, home and family circumstances at that time meant I never actually took most of my school exams. So with nothing in the way of real qualifications, I drifted into what I was naturally good at – technical support and writing computer software. My hobby turned into
my career.

Twenty odd years later, and I am more than comfortable with my career, I like to think I am pretty good at it. I also still often think, I could have been adding much more value to other people’s lives if I had stuck with my original choice. Recently I met a lady who was a nurse, and I was totally inspired by her and how much satisfaction she clearly got from her work – she told me that I could still retrain even at this stage in life.

Now I expect you are waiting for some kind of development related conclusion here … but unfortunately there isn’t one. What there is, is a small realisation that I could probably be doing something more for the world.

So, I have started seriously investigating my options for a radical career change – and to retrain as a medical doctor. Now this isn’t quite my swansong from development just yet. Not only do I have some major considerations to make, but I also have to put enough money aside to finance this shift, and after all that I have to succeed in an application to medical school, which in the UK is a very difficult task indeed, as places at our universities are very sought after, and the universities can afford to be very selective. I could even do one or two years getting the entry requirements, only to fail to get a place at medical school.

But, I have started sending off enquiries to various universities asking for their advice on the best route in, and perhaps it will pay off. It will be time consuming, financially very hard in the short
term, but it could be the most rewarding thing I could possibly do.
Ultimately, Job Satisfaction is About More Than Financial Reward

Whatever I eventually do, I have made a decision to get out and start giving back something to the world, maybe that will be with 6 years of medical training, followed by years of excessively long hours for very little pay … or maybe it will be just finding ways to make people’s lives better while continuing my career in software.

I encourage you all to find something positive you can give back to the world – the development community has some incredibly smart and insightful people – let’s not waste all our efforts on arguing over whether we should invert our dependencies or not!

And if you want somewhere to start doing your small bit, can I suggest you take a read of The Girl Next Door by Bil Simser

Bloody hell that was DEEP!”

And my response:

Sid M wrote re: Job Satisfaction, And Making The World A Better Place on 04-02-2009 9:45 AM

Great post Casey! This is something I’ve often found myself pondering and I think it’s fantastic that you have the impetuous to go and do something dramatically different! I really admire that. Also, I share your distaste of people who would waste precious hours debating obscurity as if were somehow the key to the universe!

However, I do think there is real value to be found in software development (despite Scott’s post which missed the point somewhat). Lives have definitely been saved by software (keyhole surgery equipment requires software, as do dialysis machines, 4d radar scanners and many other types of equipment and domains critical to the medical profession).

It’s not just medical software either; Families have been brought closer as software has aided cheaper, more lucid communication (video conferencing, IP telephony, Messenger, Skype, etc) and children are being introduced to a greater wealth of information about the world around them than has ever been available before, aiding their education. The list definitely goes on…

I think the key problem is that most of us don’t find ourselves participating in that kind of life-impacting software development, but it doesn’t mean we can’t! If, like me, you really enjoy software development, but unlike Casey, you don’t wish to dramatically change direction (for whatever reason), then why not try moving closer to the part of your industry where you see value being added… and join in! If that’s not palatable either, then why not think of a way you could use software to impact people’s lives positively… build it and release it yourself!

Software definitely doesn’t have to be about making the rich richer, or building yet another meaningless, under-used application for a blue chip client. Software can (and should be) about pioneering new ways to use technology to make our lives better and more enjoyable and I believe that offers a very broad horizon of possibilities, many of which can add real value to people’s lives.

Looks like I’m starting again due to my WP database being the ONLY database I didn’t add to the backup schedule. Doh! The punishment for my school boy error? I have to start all over again. :-(

Follow

Get every new post delivered to your Inbox.