This will be a very short post, and comes from rage against Windows Server and the Windows update system. Because there were outstanding Windows Updates requiring a reboot, a particular build script of ours was falling over without suitable information as to why exactly.

The cryptic error was:

Creating an instance of the COM component with CLSID {0002DF01-0000-0000-C000-000000000046} from the IClassFactory failed due to the following error: 800704a6.

The answer (at least for us):

Reboot!

There are windows updates getting in the way of instantiating new COM objects.

You’ll see a lot of people having a similar problem, not sure if reboot is the answer for them all, but make it your first step, and memorise the error code 800704a6. Unable to verify this but it looks to relate to the text code of ERROR_SHUTDOWN_IS_SCHEDULED.

The ServerFault post that helped most:
serverfault.com/q/ie8-script-error-800704a6

Stackoverflow Questions

stackoverflow.com/watin-nunit-and-cruisecontrol-net-error-message-800704a6
stackoverflow.com/tests-fail-sporadically-using-cruisecontrol-net-with-nunit-error-800704a6
stackoverflow.com/setup-method-failed-while-running-tests-from-teamcity
stackoverflow.com/tests-fail-sporadically-using-cruisecontrol-net-with-nunit-error-800704a6
stackoverflow.com/failed-due-to-the-following-error-800704a6-while-trying-to-read-data-from-a-text-file

Objective

Unit test a JavaScript method which contains a $.ajax() call. Using QUnit.

Details

This was supposed to be a simple task, and if I didn’t have a few (now) obvious faults in my JavaScript code, it would have been completed more quickly. I have gone through several answering my own StackOverflow questions on the next day here’s the one in question for the curious ones.

I will hide behind the excuse of it being the early days of the new year and still finding my coding groove after almost two weeks on holiday…

So in this post I’ll summarise the two approaches I came out with in the end. It’s two because neither worked for me first time, and in my attempt to solve the first discovered the second. In the end resolving both. I won’t bother going into much detail about QUnit, as there are many posts out there about it; here, and here and here and official documentation here, and other interesting things to do with it.

As a quick aside we use the NuGet package NQUnit.NUnit to help us integrate QUnit into our Visual Studio projects.

Basic Approach

Solution 1 – basic way as is shown on this StackOverflow answer

// Arrange
    var options,
        jsonText = '{"id": "123", "fieldName": "fbs", "data": "fbs-text"}',

// Set up to 'capture' the ajax call (this forms the mock)
$.ajax = function (param) {
    options = param;
};

// Act - call the method which is 'under test'
/* ... */

// Call the success (or failure) method to complete the mock of handling of the 'response'
options.success(expectedData);

// Assert - verify state of system is as expected
/* ... */

Alternate Approach MockJax

Solution 2 – using the MockJax library with a great walk-through on how to use it here.

There are several advantages in using MockJax, that can be summarised as just having more control over mocking the ajax portion of the method under test, including but not limited to; timeouts, introducing latency, returning HTTP status codes.

After having included MockJax in your project, the solution 1 code gets replaced with 1 method call to $.mockjax() and looks like this.


// Arrange 
    var jsonText = '{"id": "123", "fieldName": "fbs", "data": "fbs-text"}';

// The call to mockjax replaces the need to overwrite the jQuery ajax() method
$.mockjax({
    url: '/Your/Regular/Action',
    dataType: 'json',
    contentType: 'application/json',
    responseText: jsonText
    }
});

// Act - call the method which is 'under test'
/* ... */

//perform test assert state of system is as expected
/* ... */

Demonstration

Full QUnit test code is up as a Gist.

Find a working copy of the code here in it’s simplest form: jsfiddle.net/NickJosevski/9ZZmc/4/

We’ve gone to some lengths at work to automate, and have a continuous delivery style pipeline for all things build and deployment related. It’s well on its way, but not ‘perfect’ yet. Maybe perfection isn’t attainable, or maybe when you have a red button on the desk that when pushed does *everything*. None-the-less aiming for perfection will continue to drive us to improve.

So here I wanted to discuss what steps I took to get a nice JSLint Visual Studio plugin to form part of our build process. It was a bit of fussing about getting it to work, and it’s an example of still being imperfect, but for now it serves the build pipeline well enough.

If you don’t use JSLint for your JavaScript code, you probably should. It’s a static analysis tool to analyse and report on broken coding rules for JavaScript. Try it out on the creator (Douglas Crockford’s) site JSLint.com.

There is an easily accessible Visual Studio plugin called exactly what you would expect “JSLint for Visual Studio 2010” and here is the direct link for it on the VS Gallery for your installation pleasure.

If you do anything and stop reading here you’ve done well, install it and happy JavaScripting.

JSLint for Visual Studio 2010 Extension

But what about continuous integration?

For us it wasn’t enough, we wanted our build process which runs as psake scripts to fail if JSLint rules were broken.

Just for a bit more completeness on the psake digression and how the command line tool will execute under MSBuild, here’s a snippet of the ‘targets’ code that is referenced by the .csproj files that contain JavaScript. The input parameter on the executable being the directory containing the script files relative to .csproj file.

<Target Name="AfterBuild"> 
    <Message Text="Running jslint..." Importance="Normal" /> 
    <Exec Command="&quot;..\jslint\JSLint.CLI.exe&quot; .\Scripts\ " /> 
</Target>

So the search for command lines tools began. I found some existing command line tools, some which had more complex dependencies, others which seemed to be more ‘primitive’, i.e. did not report on errors the IDE based JSLint plugin was reporting.

There were 2 main objectives driving the choice of the tool

  1. Similarity and accuracy to JSLint.com and the Visual Studio extension
  2. Ease of setup

There was some discussion happening on StackOverflow, here and here but nothing I tried digging deeper into seemed suitable.

I then had an idea…

Take the core logic of the Visual Studio extension and wrap it in a very simple console application to execute as part of the build process.

With the approach I took, it seems even option 2 was difficult to achieve (consumed some time), but at least it had the least external dependencies to the other options out there.

The very first step was to obtain and install the VS2010 SDK, as this was an project which referenced many interop assemblies for interacting with the IDE. It needs to be the Service Pack 1 SDK in fact, and here’s a direct link. Once I was able to compile the extension it was then a matter of understanding how it operates and how to access a method to perform the ‘linting‘.

There were 2 major hacks to get access to some inner workings of the extension to operate:

  1. Making some ‘protected/internal’ methods and properties public
  2. Modifying where the JSLint logic obtained the settings file from (JSLintOptions.xml).

Locating JSLintOptions.xml proved somewhat difficult at first, as it was tucked away hiding in the Roaming section of my user folder on Windows (\Users\*\AppData\Roaming\). These hacks could greatly benefit from some re-factoring effort if I have ever have the time, or someone else is so inclined. But after an initial attempt to refactor out the most core of logic things fell apart in the land of SDK dependencies, so I rolled back and opted for a less elegant approach which was the 2 hacks listed above.

The logic for the console application is then trivially simple:

  1. Read .js files.
  2. Using the JSLinter class method Lint() supply the .js file content/
  3. Write errors to console
  4. Return error code, 0 (Success), 1 (JavaScript warnings), etc.

Show me the code!

If you want to see the hacks I had to make to get this to work head on over to this git repository on BitBucket. I offer no warranty it may be fragile so manipulate with caution.

If you just want the command line executable, then it’s built and stored in the repository in the /output folder, if I make any updates to the executable, I’ll also update that executable.

Areas for improvement in the console app:

  • Taking path locations as input parameters/external file of locations
  • Taking alternate settings files for rules to ignore/include
  • General tidyup

Outstanding issue

The final hiccup is not directly related to the use of the command line tool itself, but building the command line tool from source as part of a more comprehensive-all-inclusive build process. Adding commands in the .csproj file post-build settings was not sufficient. The build and copy of the executable needs run as a directive in the targets ‘afterbuild’ section of the .csproj file.

CSProject Settings Dialog - Post Build Events

Not suitable to place actions in 'post build' section

This led to a conflict between MSBuild and the VS2010 SDK, which was very frustrating and currently isn’t solved yet. The question is up on StackOverflow.

I rarely rant on my blog, but when a friend of mine brought up that he had to take a personality test as part of the interview process (a step prior to being given an offer), it just frustrated me so much. So at this point dear reader you may move along if this isn’t of interest as this is all my opinion on personality tests for software engineers.

Summary and Disclaimer
Unless your organisation has thought long and hard about designing a personality test specific to software engineers, don’t subject candidates to a generic personality tests. It reflects poorly on your understanding of software engineers.

If you use a generic personality test…

Q: Do you care about hiring and retaining the best software engineers?
A: test A resounding – No.

Q: Do you understand what it takes to be a good software engineers?
A: A clear – No.

Q: Does your organisation care about the previous two questions?
A: If no, then fair enough. Continue using the test, and move along.

Otherwise:

You have to be kidding me. When a professional organisation subjects any reasonably qualified software engineer to the same type of tests they subject potential employees in their specific field to then they are not concerned about hiring and retaining the best, or they have been ill-informed on how to recruit top software engineers. What got me fired up about this information was that the type of questions he described. They were so broad and irrelevant to what it would take to do his job. This frustration was further compounded when it was apparent that this test carried some significant weight in the recruitment process. They didn’t even bother to undertake more suitable programming/problem solving exercises that an Engineer would actually do in day to day activities in this job role.

At this point you may counter my argument with, a general statement such as “why not just use any and all tools available to help make a decision“. To this I answer: such questions are not relevant enough to accurately judge a good software engineer, and do more harm than good.

Here are some categories we derived from the discussion after he sat the test, and we analysed the questions that invoked the anger that’s feeding this post.

  1. Questioning the norm.
  2. Long standing ideas.
  3. Repetitive routines.
  4. Breaking rules.
  5. Data analysis.
  6. Being creative.

Here we are both speculating a bit, but the type of questions that represented the first 4 categories seemed to attempt to discover candidates that would be deemed as rebellious. As a software developer answering these questions you have to completely put aside what makes you a good software developer. I would give credit if the organisation was actively seeking ‘rebellious’ software developers ready to challenge the norm and bring improvements. But based on their sector, and other information this seems highly unlikely. The questions that matched the last 2 categories seemed reasonable.

A very brief search uncovered this reasearch paper; very SDLC and waterfall focused analysis of personalities (pdf), there didn’t seem to be any concept of applying Computer Science knowledge/research into this personality test. In fact several questions were difficult even to interpret for your typical software engineer.

If I was subjected to such a test as part of an application where the test wasn’t clearly justified as relevant to engineers, it would be safe to say right there an then to avoid stress I would decline and withdraw my candidacy.

Take away: treat your engineers with a bit more respect.

Over the last few months at least in the streams of information I typically consume, direct issues: Security Now topic of Password Haystacks, xkcs’s comic, Coding Horror, and indirect: Scott Hanselman one and two. Have all commented on the issue around passwords and strength and the need for better passwords.

In this post I am putting forward a novel approach: which as an homage to GRC’s Perfect Paper Passwords and accordingly have titled my approach:

When high entropy 16, 32, 64 or even 128 character passwords are just not secure enough!

Let’s jump right in with a sample, here I’ve mocked up the very familiar facebook interface with a nice large textbox to put in your Perfect Password Paragraphs™.

Perfect Password Paragraphs facebook log in modified

Disclaimer: if you’ve gotten this far and haven’t begun to appreciate the humour I’m so sorry, please don’t send me hate mail.

Features:

  • A big text area where with probable difficulty you have to type 100+ words to authenticate.
  • Typographical errors are ok as long as they are consistent for you.
  • A flow of sentences following a theme/style just needs to sound like the individual attempting to gain access.
  • “Sound Like” is a trademark (patent indefinitely pending) of Josevski Research Corp, is the flux capacitor grade specialty of this authentication system.

Comparison metrics:

  • Writing style
  • Choice of punctuation, frequency of commas, periods, ect.
  • Grammar choice.
  • spelling (American vs British English).
  • Consistency of spelling errors.
  • Choice of tense (present, past, and future)

Future Features based on demand:

  • International support.
  • 1337 sp34k.
  • Baby talk.
  • Obscure localised slang.
  • Pig Latin.
  • iOS, Windows Phone 7 and Android Support.

Alpha product coming online in 6-8 weeks ;)

Back in September of 2009 after a fair few months of thinking about what to put in to a new PC, the stars aligned and along with some friends of mine decided to take on a small project of building our own PCs. At that point I had never done the activity on my own, as in assembling everything from scratch, but was well across how the hardware did connect, and what the steps were.

The systems back there were Core i7 920s @ 2.6 Ghz, with 12Gb of RAM (6x2gb), 2x 1TB drives, 2x NVidia GTX 275s 892MB. At this point it’s obvious these machines were to be gaming rigs with some nice SLI action in the GFX department. These machines are CPU overclocked to run at 3.5Ghz and have been running well for just over 2 years now.

Fast forward to August 2011. Almost 2 years on, and I’m at it again, but this time to build our primary software development machines at work.

This system consists of Core i7 980 @ 3.2Ghz, with 24Gb of RAM (6x4gb), OCZ Vertex 3 SSD, 1x NVidia GTX 560 1Gb.

The following is just a summary of my experience, and those who took part in the builds with me, your millage may vary and in no way is this a definitive guide, there may be some useful tips and insights, either way this is to be an entertainment post, full of hardware pictures.

Choice of parts
“Bang for buck” is obviously your best bet, which translates into purchase what is important in your budget. This being 2011 very much the year of the SSD, this is where your first bit of attention should be.

In 2009, an SSD was well out of our price range, in particular with 32Gb models being the most popular and still not very affordable or even reliable yet. In 2011 this is not the case, and with budgeting to ensure a great SSD we ended up with 240Gb OCZ Vertex 3 Max IOPS drives. These were of the top end of the SSD spectrum, the only thing typically more expensive was larger capacity 500+Gb which had just come out, and some other specialised SSDs.

ocz vertex box and on case tray

Ensuring part capability
This just takes research as there isn’t much that can go wrong. The main concerns typically revolve around the capabilities of the motherboard, after you clearly select the motherboard that’s appropriate for your CPU chipset. Also of concern to double check on is physical space inside the chosen system case. This did bite us when early 2010 we decided to build a similar spec’d machine as the 2009 machine, but chose a newer and physically larger GFX card which did not fit the 2009 cases.

2009 Case -> Cooler Master CMStorm Scout
2011 Case -> Corsair Graphite 600 (black)

I found just searching for reviews and combinations people are bench-marking online make a good guide to compatible choices.

motherboard Gigabyte G1.Guerrilla

Purchasing
Shop around for any discounts if buying a larger quantity, combined order. We went as far as to choose to shop at multiple locations to obtain the best prices, and to ensure all the parts we wanted could be acquired exactly when build time came around. This may be a negative as if there are issues with multiple parts then you have to deal with 2 or more business for parts exchange. Luckily in both the 2009 build and the recent build there were no issues requiring travelling back to the store.

graphics card gtx 560 1gb

The Build
A quick checklist of the order of configuration, in both times, even trying both combinations, I found that at least for our cases, it was easier to assemble almost everything on the motherboard with it on the build table, and not in the case. This is the order that worked well for us.

  1. Install the RAM onto the motherboard.
  2. Lock in CPU with thermal paste.
  3. Add your CPU heat sink, plus any rear of motherboard mounts.
  4. Wire up CPU fans into motherboard.
  5. Clip on RAM cooling fans (wasn’t a feature on my 2009 machine).
  6. Screw-in feet for motherboard into case.
  7. Bolt motherboard down into case.
  8. Insert GFX card.
  9. Run SATA cables for SSD/HDDs, BluRay/DVD roms
  10. Link up any case based connections (HDD lights, fans, power button, etc)
  11. Tidy up cables now and as you go.

Cable Management
I’m of the opinion you should attempt to get all the internal cables tucked away as neatly as possible to help with airflow, and general appearance, in my machines a strong touch of OCD helped get them in a near perfect state of “out of the way”. Zip ties, twisty ties and making use of the case are your best friends here.

Cooling
Fans, fans and more fans. Here I don’t believe it’s necessary to go that overboard with advanced alternate tech cooling. But to each his own.

In both the 2009 and 2011 systems, we chose to go with an aftermarket heat sink for the CPU, this was clearly the right choice in 2009, but when we saw the stock fan that came with the Core i7 980 it looked like it would do a good job. None-the-less dual fans and larger grill section on the Noctua NH-U12P is what’s cooling the overclocked 920s and 980s.

noctual cpu fan, and corsair ram fan

Testing the configuration
Double check nothing is out of place, and turn it on. Good luck! ;)

case assembly complete

Play
Start using the system. After you have your Operating System installed that is.

monitors

In my last post “A trivial message loop using RabbitMQ in C#.NET” I demonstrated a simple concept of a circular message queue using RabbitMQ. I chose not to complicate the post with explaining some fundamentals of RabbitMQ leaving that for this post.

As of writing the version of RabbitMQ I am using is 2.4.1.

Some of the concepts I introduced in the last post were, and I’ll break them down in a hopefully a logical flow as steps to take.

  1. IConnection
  2. IModel
  3. ExchangeDeclare()
  4. QueueHelper.EnsureQueue()
  5. Subscription
  6. SimpleRpcClient
  7. SimpleRpcClient.Cast()
  8. Your own SimpleRpcServer
  9. HandleSimpleCast

First if you’re looking to get setup on Windows head on over to the RabbitMQ official documentation and follow the steps.

Also before you continue reading I urge you to go have a look at Mike Hadlow’s EasyNeqQ API and accompanying blog posts.

Some other good blog posts I have stumbled upon after starting to write my version of this come from Simon Dixon, at the time of me writing this he had 1, 2, 3 part series

On to my take, I’ll be explaining RabbitMQ along the lines of how my simple demonstration application functions, as a reminder it’s available on BitBucket – https://bitbucket.org/NickJosevski/rabbitloop

Step 1 – The Connection

I am using ConnectionFactory with a local machine address to create the connection the client and server will use to build the next required component.

IConnection connection = new ConnectionFactory
  { 
      Address = "127.0.0.1" //localhost
  }.CreateConnection();

Step 2 – The Model

Using the connection create a model this is used to configure the rest of details on how communication will take place between the client and server.

IModel model = connection.CreateModel();

Step 3 – ExchangeDeclare()

Declaring an exchange is the concept of setting up a named path for communication, the second parameter offers options on how messages are to be delivered, in this example I’m sticking with a simple choice of ‘Direct’

var exchange = "my.exchange";
model.ExchangeDeclare(exchange, ExchangeType.Direct);

Step 4 – QueueHelper.EnsureQueue()

This is my own helper extension method to help perform a few tasks; creating a queueId, using that queueId to declare a queue on the model, and then bind the queue and exchange together, finally returning the newly created queueName.

public static class QueueHelper
{
    public static string EnsureQueue(this IModel ch, String exchangeName)
    {
        var queueId = String.Format("{0}.reply", exchangeName);
        var queueName = ch.QueueDeclare(queueId, false, false, false, null);
        ch.QueueBind(queueName, exchangeName, "", null);
        return queueName;
    }
}

Step 5 – Subscription

The subscription is supplied to the server logic and is created using the model and the queueName

var sub = Subscription(model, queueName);

Step 6 – SimpleRpcClient
Creating the client is just as simple, and we’re ready to send a message.

var client = new SimpleRpcClient(model, queueName);

Step 7 – SimpleRpcClient.Cast()

The Cast() method on the SimpleRpcClient is the asynchronous way to send a message, I want to keep this post more straight forward so I am excluding the message class and how to serialize it but those steps are very basic.

var myMsg = new SerializableClassYouHaveCreated().Serialize();

rpcClient.Cast(new BasicProperties(), myMsg);

Step 8 – NicksSimpleRpcServer

This is where things start to get a little more involved, but it’s relatively straight forward. In this approach I create my own RpcServer that extends SimpleRpcServer.

public class NicksSimpleRpcServer : SimpleRpcServer
{
    private readonly SimpleRpcClient rpcClient;

    public NicksSimpleRpcServer(Subscription subscription, SimpleRpcClient client)
    : base(subscription)
    {
        rpcClient = client;
    }

}

Step 9 – HandleSimpleCast

All I do now is override the method that handles asynchronous messages (it also needs to de-serialize the content form byte[] body). Just to follow along from my sample application the server also has a client private member so it can continue to forward a modified message on wards.

//as an override method inside NicksSimpleRpcServer:
public override void HandleSimpleCast(Boolean isRedelivered, IBasicProperties requestProperties, byte[] body)
{
    //deal with incoming message, create new message to forward
     rpcClient.Cast(new BasicProperties(), msgToForward);
}

This is where our story comes to an end… As a final step we need to get our server running…

Using the Task Parallel Library create a Task that kicks off another method of the RpcServer – MainLoop(). MainLoop simply sits there (blocks) and accepts incoming messages, each time an asynchronous arrives HandleSimpleCast will fire and the message will be processed.

var server = new NicksSimpleRpcServer(sub, client);

new Task(server.MainLoop).Start();

Hope this is easy to follow.

During the May 2011 meeting of the Melbourne ALT.NET group, 3 presenters each with their chosen functional language tackled a basic problem of transmitting a message along a chain, with the objective of all nodes contributing to a final output. Here’s some of their code in the the languages of; Erlang, Scala and F#.

As an introductory post to RabbitMQ for my blog I thought I would cover how you go about setting up a simple RabbitMQ server-client in an asynchronous fashion. In this post I’m only going to cover the abstract concept and introduce some terms, I’ll go into more specific detail in another post as to the technical details of using RabbitMQ. I presented this concept as a very quick 10 minute lightning talk at DDD Melbourne 2011.

So stay tuned for more RabbitMQ based posts (links will appear here when they’re complete).

The objective:

  1. Start with a message that contains a letter ‘A’
  2. Send this message off to a node (N)
  3. Have that node increment the letter, e.g. first node makes it ‘B’
  4. Then that node sends it off, and so on looping for M number of messages.

A Node:

Node Structure

The Algorithm:
My RabbitMQ and C# based solution (simplest version), this list will contain some RabbitMQ specific concepts that I’ll describe later in the post. This is the algorithm to create, wire up and kick off processing.

  1. Create the N clients SimpleRpcClient.
  2. Keep a reference to the 1st client, this is what we use to begin messaging.
  3. Create N Subscription elements.
  4. Create N SimpleRpcServer elements these are the actual nodes.
  5. Supply the second client onwards and subscibtion to the node
  6. Create a new Threading.Tasks.Task() for each node.
  7. To complete the loop, wire up the first client, to the last node.

Node Communication (click for larger view):
Each node, houses a client to continue on sending the message.

Node Communication

The Code:

IConnection connection;
IModel model;

char[] letters; //A-Z, repeating
for (x = 0; x < totalToCreate; x++)
{
    var nextLetter = letters[x];
    //this builds up a string in the format of comm.0.a, comm.0.b, etc
    var exchange = String.Format("comm.{0}.{1}", x, nextLetter); 
    model.ExchangeDeclare(exchange, ExchangeType.Direct);
    var queueName = model.EnsureQueue(exchange);
    subscriptions.Add(new Subscription(model, queueName));

    clients.Add(new SimpleRpcClient(model, queueName));
}

for (x = 0; x < totalToCreate; x++)
{
    //note the use of [x+1] on the clients, 
    server = new SimpleRpcServer(subscriptions[x], clients[x-1]);

    new Task(server.MainLoop).Start(); //MainLoop is a RabbitMQ concept
}

//Inside RpcServer
public override void HandleSimpleCast(bool isRedelivered, IBasicProperties requestProperties, byte[] body)
{
    var messageToSend = body.Deserialize().IncrementLetter();

    rpcClient.Cast(new BasicProperties(), messageToSend);
}

The code above had been simplified a bit more just to demonstrate the concept, please review the project code for further intricacies in it how it needs to operate.

Working demo code on BitBucket – https://bitbucket.org/NickJosevski/rabbitloop

*Note: you’ll have to excuse some of the roughness of the code as it stands at 29th of May, I haven’t had a chance to refactor it to be more elegant.

There is a long list of RabbitMQ concepts that are beyond the scope of this blog post, a new one will follow soon with my explanations of how they work:

  • IConnection
  • IModel
  • QueueHelper.EnsureQueue()
  • HandleSimpleCast
  • rpcClient.Cast()
  • Subscription
  • ExchangeDeclare()

Also check back I may have completed a Prezi on the subject.

In my preivous post, I introduced “self submitting forms” with the help of some jQuery functions. I had 2 out-standing (todo) items from that post (and work). The first was to have some tracking around the input elements and when they’ve been re-modified before a delayed post has occurred.

Item 1 – Tracking Recently Modified

Problem Definition:
There are 2 input fields: “Deadline” and “Task Name”, the user modifies “Task Name” then “Deadline” then “Task Name” again. Under the previous approach, the first delayed processing of “Task Name” would end up sending 2 pieces of data in the form submit as separate actions. This is not optimal.

Solution Description:
Track when the input elements were modified, and if they’re modified in some “reasonable amount of time” again, then don’t send the previous value. This is for now is simply achieved by tracking the input element name with a “modified times” count value. Every time a change is made to an input element, we “push” the details onto a central collection, when it’s time to attempt to send the data we “pop” off that central collection.

Solution Steps:

1. Have somewhere to store the entries in a central collection, a simple dictionary style variable is fine for now.

var activeInputs;
//initialised later
activeInputs = {};

2. When an input element is modified, we simply store it’s ‘id’ and increment it’s modified counter in the ‘activeInputs’ dictionary:

var elemId = c.attr('id');
//c here is the input element that is associated with the handling event.

if(activeInputs[elemId] == null)
    activeInputs[elemId] = 1; //initialise
else
    activeInputs[elemId] = activeInputs[elemId] + 1; //increment

This method is the “push on to stack” approach, and does not need to supply feedback.

3. We next will need a method to decrement this, along with returning the modified count value:

var elemId = c.attr('id');
if(activeInputs[elemId] == null)
    return -1; //erorr state

if(activeInputs[elemId] > 1)
{
    countVal = activeInputs[elemId];
    activeInputs[elemId] = activeInputs[elemId] - 1;
}
else 
{
    countVal = activeInputs[elemId];
    activeInputs[elemId] = 0; //reset it
}

This method is the “pop from stack” approach; we need it to inform us if the input data was in fact ready to be “sent off”

So now if you recall the ‘startCountDownAndSendData’ function from the preivous post it had line to submit the form, this can now be wrapped by a check via the “pop” method to see if it should send. If there’s been a recent edit (i.e. the ‘activeInputs’ value is greater than 1), then it will not send.

I didn’t name the methods earlier, and only showed their internal workings, as naming these functions was tricky, but in the next code snippet, I give the pop method a name, to see them in action as a whole check it out on jsFiddle.

if(popProcessedControlFromStack(c) == 1)
{
    //if value "1" - active control then submit, otherwise it was editted recently                
    $('form#MyFormId').trigger('submit');
}

Item 2 – User Feedback on Progress

The second out-standing issue from the preivous post was the user feedback. For now I’m just going to borrow the one from WordPress when you save a post/draft.

Once you actually submit the data, you just need to handle the success response, this will either replace the above section or be a link. But for a bit of a wrap up on this post with the jQuery focus here’s a skeleton function to show some feedback.

function showSuccess(data) {
   $('#someDiv').html('<img id="checkmark" src="/Content/check.png" />');
}

The third (and coming soon) post, will cover the MVC side of this.

I have been prototyping some general approaches, some new functionality, and other various concepts, all part of how a larger system will work. After seeing some interesting and nostalgic things being done with jQuery, it gave me an idea for an approach that may be suitable to achieve some delayed asynchronous actions. Thanks to Aaron Powell for those neat walk-throughs.

My Idea is probably even simpler but focussed more around having elements of a form “submit themselves” in a way making use of new features of jQuery 1.5. I have not yet completed the polished version of this functionality, where it will handle errors and other complexities to be a robust solution. I do believe this approach does align with the progressive enhancement objectives of good websites, if a clients browser does not support this functionality there is still a standard submission of the form data available. But none-the-less would like to share/document my approach and direction.

Basic Flow

  1. User types-in/modifies an input field.
  2. jQuery code detects this.
  3. Asynchronously sends this piece of data.
  4. Provide elegant feedback when this is complete.

Improved flow (a future exercise)

  • Step 2 above, should count down and reset counting if that same field is changed before the data is sent. Still a “to do” item.
  • Step 4 isn’t exactly elegant at the moment; a confirmation message or icon shows up, which is rather crude.

Demo

Again thanks to Aaron for reminding me of the awesome site: jsFiddle, I used it to speed up my jQuery experiments without relying on Visual Studio and running an MVC application to create and test the jQuery logic.

$(':input').change(function() {
    var c = $(this);
    $.when(
    c.focusout()).then(function() {
        $('#last-action').append(c.attr('name') + ' = ' + c.val() + '<br />');
    });
});

Here is the jsFiddle demo of this functionality, simply type in any of the input boxes, and tab away and see the results be “submitted”. Of course no submit code is firing yet, we’ll look at that now.

Let’s refactor a little to support some more important functionality to get ready to submit our form. The line in particular about just appending the data can be replaced with a function to handle submitting the form, and just for the demo it will also still output the data in the little debug div. This is where I make use of Aaron’s demonstration of the recursive setTimeout pattern.

$(':input').change(function() {
    var c = $(this);
    $.when(
    c.focusout()).then(function() {
        startCountDownAndSendData(c, 5) //delay by 5 seconds
    });
});

With this function, we’re going to supply the html element (c) and an integer (waitDuration) representing how many seconds to wait before “submitting”.

function startCountDownAndSendData(c, waitDuration) {
    function go(){
        if(waitDuration <= 0) //count down from a supplied duration value (in seconds)
        {
            $('#last-action').append(c.attr('name') + ' = ' + c.val() + '<br />');
            $('form#MyFormId').trigger('submit');
            return;
        }
        waitDuration--;
        setTimeout(go, 1000);
    }
    go();
}

You can see this refactoring in operation here, but it won’t submit anywhere, that’s what we will handle next time in a post about Asynchronous MVC controllers. So steps from 3 and 4 are still to demonstrate to you dear reader, stay tuned… part two is here.