Posts Tagged ‘programming’
Voodoo – A Todo list that demos the power of KnockoutJS
This small demo app will demonstrate the usage and power of JavaScript MVC frameworks and in particular KnockoutJS. You can learn more about the framework through the tutorials on the KO site. I will gloss over some of the details but you can learn more in framework documentation. My goal here is to give you a high-level sense of what’s possible. The picture along side shows what we’re building. You can find the demo here and the full sourcecode here.
The HTML
Strictly speaking jQuery is not required for KO to work but it is likely that you will often include it as a helper for the framework. As alway you need to start with the static resource inclusions.
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script> <script type="text/javascript" src="js/knockout-2.0.0.js"></script>
And you’ll need a form in order to create new todo items.
<form data-bind="submit: addTask" id="create-todo"> <input class="new-todo" data-bind="value: newTaskText" placeholder="What needs to be done?" /> </form>
For the first time you’ll notice the data-bind attribute. The framework recognises this attribute and parses the attribute value to determine what logic to apply. In this case the input element is bound to a JavaScript property called newTaskText.
Next up you need the markup that contains and displays each task. Some actions are available for each item too.
<div class="todos"> <ul data-bind="foreach: tasks, visible: tasks().length > 0" id="todo-list"> <li> <div class="todo" data-bind="css: { editing: isEditing }, event: { dblclick: startEdit }"> <div class="display" data-bind="css: { done: isDone }"> <input type="checkbox" class="check" data-bind="checked: isDone" /> <div class="todo-text" data-bind="text: title"></div> <a href="#" class="todo-destroy" data-bind="click: $parent.removeTask">×</a> </div> <div class="edit"> <form data-bind="submit: updateTask"> <input data-bind="value: title" /> </form> </div> </div> </li> </ul> </div>
Again you’ll notice that each element that is to be used in someway by KO has an attribute of data-bind. Below I’ve picked out a few lines to demonstrate key functionality. The following line is an instruction to run through a collection of tasks and only display the ul element if there’s anything in the collection.
<ul data-bind="foreach: tasks, visible: tasks().length > 0" id="todo-list">
The line below is used to conditionally apply a style class and ensures that the doubleclick event is bound to the appropriate handler.
<div class="todo" data-bind="css: { editing: isEditing }, event: { dblclick: startEdit }">
And here we have an example of an input element being bound to a JavaScript object field isDone – the object structure will be shown later.
<input class="check" type="checkbox" data-bind="checked: isDone" />
Now here’s some of the magic of KO. Below are the some stats based on the number of tasks in the list. If you were using jQuery or just JavaScript you would have to track the number of elements in the list and update the stats appropriately.
You have <b data-bind="text: incompleteTasks().length"> </b> incomplete task(s) <span data-bind="visible: incompleteTasks().length == 0"> - its beer time!</span>
With KO the view is driven by the underlying object data. If the number of items in the list changes all related information is automatically updated in the view! In KO this is facilitated through concepts known as observables and dependency-tracking.
The JavaScript
KO is the first time I’ve used OOP within JavaScript for some time, and it’s pleasure to work with the concepts in such a paradigm! In this small app there are only 2 classes, one for tasks (fairly obvious) and another for the ViewModel which you can consider the application class.
The Task class contains the properties and methods applicable to Tasks. You’ll notice how the properties are initialised using using the ko.observable() method. This is a touch more magic and it means that the values of these properties will be “watched”. If they are changed either through the user interface or via JavaScript then all dependent views elements and JavaScript values will be changed too.
function Task(data) { this.title = ko.observable(data.title); this.isDone = ko.observable(data.isDone); this.isEditing = ko.observable(data.isEditing); this.startEdit = function (event) { this.isEditing(true); } this.updateTask = function (task) { this.isEditing(false); } }
The ViewModel class exposes the Tasks in a meaningful way and provides methods on that data. Types of data exposed here are observable arrays of tasks and properties that return the number of complete and incomplete tasks. The operations are simple add and remove functions. Right at the end of the class I’ve used jQuery to load JSON objects into the todo list.
function TaskListViewModel() { // Data var self = this; self.tasks = ko.observableArray([]); self.newTaskText = ko.observable(); self.incompleteTasks = ko.computed(function() { return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() && !task._destroy; }); }); self.completeTasks = ko.computed(function(){ return ko.utils.arrayFilter(self.tasks(), function(task) { return task.isDone() && !task._destroy; }); }); // Operations self.addTask = function() { self.tasks.push(new Task({ title: this.newTaskText(), isEditing: false })); self.newTaskText(""); }; self.removeTask = function(task) { self.tasks.destroy(task) }; self.removeCompleted = function(){ self.tasks.destroyAll(self.completeTasks()); }; /* Load the data */ var mappedTasks = $.map(data, function(item){ return new Task(item); }); self.tasks(mappedTasks); }
The very last line in the JavaScript code tells KO to apply all it’s magic using the ViewModel and markup we’ve written.
Summary
To me it’s amazing how little code you need to write in order to build such a neat app. And you don’t even need to track the view state at all! Hopefully this gives you the confidence to start using JavaScript MVC/MVVM frameworks because in the end it helps save you heaps of time and effort.
The rise of JavaScript and it’s impact on software architecture
MVC and it’s siblings have been around for a while and developers are comfortable bathing in the warm light of their maturity and wide-spread advocation. However, a few years ago developers started doing more of their coding client-side and as a natural consequence the lines between M, V and C became blurred leaving many of us cold and uncomfortable when trying to explain where the architectural puzzle pieces belong.
I’m sure you’ve had a similar experience. Anyone who’s used jQuery, for example, has been in the uncomfortable situation where controller code now exists within view and even worse these two are tightly coupled by virtue of jQuery selectors. To make matters more complicated if you’ve ever used class-names for application state or .data() then you’re model, view and controller are now more tightly bound than the figures in a Kamasutra carving.
This is not a new problem but the solution(s) are quite new to me and so I thought I’d share my experiences.
jQuery is Great. But…
Ruby, Rails & RVM woes
I’ve had several issues over the past day pertaining to Ruby, Rails and RVM and all of them were caused by one silly thing.
Problem 1: You can’t swap between Ruby versions using RVM
If you can’t swap between Ruby versions that you know you’ve installed then you’ve probably installed something using “sudo”. It is highly recommended that you install & use RVM in the single user mode as this is easiest. If you do this then all the versions of Ruby etc. that you install will be installed in your home directory (usually ~/.rvm/) instead of system wide and this negates a whole bunch of complexities. Running this command will tell you which ruby executable you’re using:
which ruby
If the executable is not sitting in your home directory e.g. it’s in /usr/local/bin then you’re in a spot of bother. The easiest way I’ve found to fix this is to clear out all the RVM gemsets and start again. I’ve found that I needed to run:
rm -fr ~/.rvm rm -fr ~/.bin
Be careful with the second command. I’d have a look around that directory before deleting it to make sure it’s not being used by anything else.
Having wiped out these directory you can now using RVM to install fresh versions of Ruby.
Problem 2: Running “rails -v” or “rails” throws an error similar to “`report_activate_error’: Could not find RubyGem rails’
This is assuming you don’t have the first problem or that you’ve corrected it. It’s also most likely to occur if you’re using RVM. The cause here is that you’re using a local version of RVM to manage your Ruby versions but have installed Rails using “sudo” so that it’s been installed system wide. The solution is simple, remove the “sudo” so that rails is installed just for your currently active gemset.
gem install rails --version x.y.z
Across the Pond with Jason Venable aka TehNrd
Today I start a series of posts that’ll appear here and on the Tquila blog. The series will be in the format of Q&A with some of the finest Salesforce.com and Force.com evangelists, admins and developers. I’m starting with Jason Venable aka TehNrd and I’ll let him introduce himself.
Q: Tell me a bit about yourself. How long have you worked with the CRM vs the Force.com Platform? Were you always a developer?
A: My name is Jason Venable. I am 27 years old. I live in Seattle, Washington, USA. Oh, wait, you want something more interesting, got it. I’ve been working with salesforce.com CRM for a little over 4 years. Three of these years have also been working with force.com. All of this time has been administering and developing for a large enterprise salesforce.com deployment at F5 Networks. A lot of what I do is merging the two worlds of salesforce.com and force.com to meet business needs. This includes using all of the features force.com has to offer including, custom objects, validation rules, Apex code triggers, Visualforce pages, and web services to enhance and improve our companies use of salesforce.com.
Have I always been a developer? Heck no! If you told me I’d be doing coding and web app development 4 years ago I would have laughed at you. College classes that had me coding in notepad and some not so great experiences with the now dead s-controls left a bad taste in my mouth when it came to development. Then salesforce.com released Apex code and I saw how it could solve some of the problems we where facing. I taught myself the basics and the rest is history.
I also have a little blog related to all sorts of force.com goodness at tehnrd.com and some people follow around @TehNrd in Twitterland.
Q: What is your favourite type of development on the platform? What piece of work are you most proud of?
A: Databases design, triggers, and workflow are all cool but what I really like is building snazzy web apps. This has become even funner after jumping on the jQuery and jQueryUI bandwagon (disclaimer: I am a major jQuery fanboy). These JavaScript libraries allow you to make rich web apps with animations, drag & drop, and all sorts of other slick effects with minimal code. Pair this with Visualforce and the force.com database and you’ve got yourself a recipe for some great awesomesauce applications.
I think the coolest thing I’ve ever built on force.com was Gameforce. If anyone from salesforce.com reads this please don’t sue me for stealing your naming convention. Gameforce is a site built with force.com where you can play games. There is a single player black jack card game but what I think is even cooler is multiplayer Connect 4 and what I mean by multiplayer is two people on separate computers anywhere in the world. What I’m really proud of is this site is pure force.com. There is no flash, JavaScript, or any other tricks to handle the multiplayer game. You can check it out here.
Q: Where do you think “The Cloud” is headed?
A: I won’t even pretend to be the first person to say or think this, you talked about it here: http://tquilamockingbird.wordpress.com/2011/03/15/salesforce-com-crm-vs-oracle-ondemand/
But I really believe the younger generation will push adoption of the cloud to the next level. The CTOs and CEOs of today pick “the cloud” because it’s easy to manage, cheaper, and scalable. The CTOs and CEOs of tomorrow will choose cloud solutions for these same reasons but also because they know nothing else. Kids today use “the cloud” every day but don’t even realize it. Webmail, google docs, and mobile me to name a few. How many people under 20 use a local web client to check their personal mail, probably 3. How many people under 20 upload every picture they take to Flickr or Facebook and then don’t worry about the local copy, a lot. When it is time for these kids to choose solutions that solve business problems they will look to “the cloud” without even realizing “the cloud” is something new and useful. To them it will be their norm and the way things have always been.
Q: Which of the Spice Girls do you most closely identify with?
A: Of course the one living in UK has to work in a Spice Girls question. A secret fan you are perhaps? I’m not that scary and I’m not a baby. I don’t have red hair and I haven’t played organized sports in over 9 years. So in some strange way I think I just identified myself as relating the closest to Posh spice. Oh boy, I’m not going to be able to live this one down. I’m definitely not snobby or upscale but the other day someone said I had cool shoes so I guess that makes me stylish and poshy? Posh Dev!
Q: What advice do you have for beginners on the Force.com platform?
A: For beginners the Force.com Workbooks are a great resource. http://wiki.developerforce.com/index.php/Forcedotcomworkbook I am super jealous these didn’t exist when I first started. They are clear, concise, and walk you through the steps of building a full blown application. I also hear pretty good things about the Salesforce Handbook. apparently two guys that know a thing or two about salesforce.com and force.com development wrote it. The forums at developer.force.com are also a great place to hang out. When I first started doing force.com development the forums where the only resource available and the community helped me solve problems that ranged from the “simple face palm I can’t believe it was that easy” problems to the “holy smokes there is no way on earth I would have ever figured this out on my own” problems.
Q: Do you by any chance know of a better way to peel an orange?
A: Funny you ask because I actually do know the most superior method in the entire universe on how to consume an orange… http://www.tehnrd.com/the-best-way-to-eat-an-orange/
Cloud Computing – A Programmer’s Implementation of Hardware and Software Infrastructure?

Geeks - so efficient even lunch only takes half the time.
Yes, it’s a sweeping statement, and the comparison I’ll make probably doesn’t fill every nook and cranny but it’s just so darn tasty that I had to quickly knock something out. I think that the developer collective have a massive influence over the direction of software evolution, and therefore it’s underlying technologies. In times gone past the influence probably wasn’t so large (or was it Mr Turing?), but with the rise and rise of the Socially Networked era I think the effect has snowballed.
So where is my justification? Well it lies primarily in anecdote – yes yes I hear your nerdy cries you sons & daughters of empirical science, but hear me out m’kay. We, the developers, spend probably more time online than even an opposite-sex obsessed teen does on facebook (yes, I know it’s part of the internet). We search and we scrounge, getting easily bored and looking for the next interesting tidbit, that scrap of information that will make us better programmers or just entertain us. We take the weak, inefficient and uninteresting and toss it aside while rolling The Good Stuff ™ into our work thereby influencing something as small as the font-family used in the corporate intranet, to something as grand as your start-ups Next Big Idea.
I’ve waxed lyrical but I’d like to get down-right specific. Some large parallels can be drawn between the world of OOP and the advent of Cloud Computing, and it is primarily for this reason that I suspect that some developers somewhere (past or present) were key in architecting what we today call Cloud Computing. OOP is by no means the alpha-and-omega of programming philosophy but it was a fundamental and incredibly intelligent paradigm shift – as is Cloud Computing. My comparison is made by drawing parallels with 2 of the main tenets of OOP.
Encapsulation
Encapsulation can be defined as an information hiding mechanism – and I don’t mean in a Wikileaks expose kind of way. Broadly this is described as:
the internal representation of an object is generally hidden from view outside of the object’s definition. Typically, only the object’s own methods can directly inspect or manipulate its fields.
To those familiar with Cloud Computing the correlation is immediately apparent. As a customer of Cloud XYZ I expect the provider to deal with all of the infrastructure setup and maintenance while providing interfaces that let me create applications or host servers or whatever. For example, if I’m using GAE I don’t really need to know how many servers you have or the amount of RAM that each has installed, I just need to know that I can develop, build, deploy and run my application and that it will scale well.
Cloud Computing hides the implementation of the tools that you need in order to complete development whilst providing interfaces to these tools that make this possible.
Abstraction

Single Rainbow! WHAT DOES IT MEAN?!
For those unfamiliar with the concept it can be quite… abstract. Examples always help:
Abstraction is simplifying complex reality by modelling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.
For example, Lassie the Dog may be treated as a Dog much of the time, a Collie when necessary to access Collie-specific attributes or behaviors, and as an Animal (perhaps the parent class of Dog) when counting Timmy’s pets.
All of the clouds together i.e. all those platforms ending in “aaS” can be seen to form the highest level of abstraction. If you need a platform to host your Ruby applications then you’d starting shopping for a PaaS. Once your platform is chosen then you deal with the next layer of abstraction which might be concepts/requirements such as database space, CPU time and amount of RAM. The next layer might then be the application itself and so on and so forth.
Cloud Computing takes complex systems and breaks them into easy to digest chunks. By organising these into abstracted layers (imagine zoom-levels on a map) you can concentrate on, and understand, the level of information most applicable to your situation.
It is largely accepted that there are 2 more core principles of OOP namely Inheritance and Polymorphism. While parallels with Cloud Computing can be drawn for these two concepts I don’t think they’re as revolutionary as Encapsulation and Abstraction. Perhaps you disagree and if you do I’d love to hear your explanations.
So you’ve said some stuff and now I should believe you?
Of course not, but if you’re a developer I’m going to bet my bottom dollar (pound) that this makes sense to you; and not only does it make sense but you can see how big an improvement it really is. I have the utmost respect for those bigwigs in management as well as those well-dressed consultants, but for me I cannot see this type of vision being born anywhere else except in the mind of someone who’s gotten stuck into meaty application development and application architecture. Who ever it was, and where ever they may be, I salute them (live long and prosper).
Salesforce: Programmatically Populating Sample Data Post-Deployment
I’m not sure if this concept is obvious when reading my previous post, so I thought I’d run through it with a specific example.
Let’s say that you’ve created what can only be described as an exemplary application in the form of a Managed Package. Although your user interface is beyond compare, you’d also like to populate some of your core objects with example data. Some options that immediately spring to mind are:
- Get the person that installs the package to call you, and you can do it post-installation.
- Get the person that installs the package to create sample data manually post-installation.
- Give the user a “Start Here” page with a call-to-action – such as a commandButton – that fetches the data from some API and parses into object data.
Option 3 is pretty excellent, especially now that you can package Remote Site Settings but I think we can do one better. And when I say better I mean simpler and with fewer potential points of failure. Read the rest of this entry »
Salesforce: Enhanced Custom Settings
Okay book’s done, now where were we? Oh yes software development, right? Programming software engineering application development h4x0R-ing. Oh how I’ve missed getting my mitts dirty so without further ado…
Some time back Custom Settings were introduced on the Force.com Platform and we all star-jumped in the air, w00ting to anyone who would listen. Up till this point – if you’re anything like me – you were using custom objects to hold configuration data, whether this be lists of language-codes, or operational settings such at outbound web service endpoints, usernames, passwords etc. With Custom Settings you finally had a place to put this information – a home if you will – for your lonely, orphaned Control Data.
Quite quickly however I realised there was still a gaping hole that could be filled with Custom Settings but just didn’t feel right. Lists of data (such as currency codes and descriptions) fit really well into this structure but more serious Control Data that you only need to be listed once-off (such as important URLs, flags to active/deactive modules in your application, usernames and passwords) just don’t seem like they really belong with this other crowd. A quick list of reasons highlights this:
- Control Data is typically entered once off and creating an entire Custom Setting for a single line of data feels like a waste.
- Custom Settings are data so they can’t be deployed with code, they must be created after the fact. Control Data should be a little more important than regular data, it needs a smarter vehicle than plain-old data entry.
- If you’re creating packages you want as much autonomy for your clients as possible. If you use custom settings there will have to be that “Create data in Custom Setting X__c” step in each and every deployment. Read the rest of this entry »
Formatting – PageBlockSectionItem, InputField & OutPutField
There are a collection of forum posts asking why VisualForce formatting isn’t being applied correctly to PageBlockSectionItems and/or InputFields, and the answer isn’t immediately obvious so let’s see what we can throw together. Read the rest of this entry »
Salesforce Unit Tests & Code Coverage
Unit testing *sigh*. Oh how they vex me. If they weren’t so important (and required) I’d just skip the lot, but they are and so we – champions of software development – must press on in the face of dreary complexity; we will not back down, we will not surrender, we will look that CRT/LCD screen in the pixels and say, “Untested units, you will not defeat me!”.
Diving into the thick of things, the most common question seems to be, “Why can’t I get code coverage for my entire class?!”. The trick here is to think like a runtime engine, and consider how you might journey through all possible testing paths. Now I never said it’s easy, but with a bit of practice (and 8 truck loads of patience) you’ll get there. Let’s look at some common cases. Read the rest of this entry »