Tuesday, 22 December 2015

Generate random test data for your requirements

Hi guys,

This post is about a tool that I have made which will help to make your life easier. I have made a web based tool to generate random data based on your provided specification. You can use this data in a variety of places: like for software testing purposes, development purposes or even just for some sample data for your spreadsheet.
The tool can be found here: http://apps.chatterjeebusinesses.com/

Let us say, we have a requirement, where you implement a method to validate whether a user name is unique or already exists for @ginger.com (hypothetical). So you need user names of the form
abcdef@ginger.com
qwe322@ginger.com,
etc. as an input

You basically need data where the first 6 digits are a combination of small English alphabets and digits and then it is followed by a constant value of @ginger.com.

We shall be specifying the above in the tool using the interactive UI.

1. You need to first specify these placeholder sequences (like small English alphabets and the digits). You need to specify your placeholder sequences, which will be part of the final sequences.
Here we specify two such sequences:

Digits which we define as 0123456789
and small-Alphabets which we define as abcdefghijklmnopqrstuvwxyz

Here is a screenshot that captures the same:


2. You would then require to define the sequence itself. As we can see our sequence will consist of two parts, a variable part consisting of 6 places of small letters or digits and then a constant value of @ginger.com.

We click the add button below the table to define our "sequence elements" and select both the small-alphabets and digits from the multi-select and specify 6 as the number of positions in the "Positions to replace" column. Next we define a constant sequence by checking the check box for "Is Constant Sequence" and then specifying the constant sequence as "@ginger.com"

Here is what it will look after putting the above values:

3. You are then presented with the option to specify whether you want random values for the placeholder sequences or you want sequential values. Finally you need to specify the number of sequences to be generated.

Here is a screenshot from the application with values filled in:


4. Finally, click the "generate" button to generate the data based on the above specifications, separated by comma, that you can copy to your input vector o a CSV file and start using.

Here is the snapshot:

The details that you enter will be tracked anonymously for quality improvement purposes. 
Hope you enjoy using the tool as much as I enjoyed building it. Please feel free to post your feedback on the tool or on my blog in the comments section here. I will be happy to be of any help!

Cheers!

Sunday, 20 December 2015

Integrating your web application with REST web services

Hi everyone,

In today's post I will walk you through the steps by which you can integrate your application to a web service. I will consider a web application and we will be using JQuery/JavaScript to achieve the same. However, most modern languages have libraries using which you can make HTTP requests.

For today's scenario I will be considering integrating our application with the OMDB API. It is a publicly available API which can be found here: http://omdbapi.com/ . It is developed by Brian Fritz and licensed under CC-BY 4.0. From the website, the OMDb API is a free web service to obtain movie information, all content and images on the site are contributed and maintained by our users.
The idea of our application is very simple; the user will enter the title of a movie, presses the search button and in case the movie exists, we shall populate the details of the movie on the page.
To achieve this we shall use HTML and JQuery.

Setting up the request

Firstly, we need to determine how we need to pass the request to the web service. In our case we need to pass our parameters in the URL itself. In some cases it might be needed to pass the necessary details in the request body. We can see the example in "Usage" section followed by the parameters section where the parameters are mentioned that needs to be populated while constructing the URL for the request. We can even try some interactive examples and see how we can search by title and how to specify the values the parameters. Here is a snapshot:

The encircled region shows the URL that needs to be generated. If you observe closely, you will see that the dynamics parts of the URL is where you specify the title of the movie, year of release, plot and response. Based on the documentation of the web service it is clear that only the title part is required in our case and everything else can be left as they will take the default values.
So in our case to construct the URL we will use this code:

var urlWithParameters = "http://www.omdbapi.com/?t=" + encodeURI(movieTitle) + "&y=&plot=short&r=json";

where movieTitle variables value comes from the search box input.

With the URL to hit now known, we can form the AJAX call as below:

var urlWithParameters = "http://www.omdbapi.com/?t=" + encodeURI(movieTitle) + "&y=&plot=short&r=json";
        $.ajax({
            url: urlWithParameters,
            method: "GET",
            dataType: "json",
            success: function (response) {
                populateUIWithResults(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert("An error occurred: " + textStatus);
            }
        });


Working with the response

Once we know how to set up the request, the next step is to utilize the web service response and showing it in our UI. First we need to note in what format the response is received and how is the response formatted. We can observe it while we were setting up the request itself as to what is the format of the JSON response. I am attaching the same snapshot as the before one but highlighting the response region.

Most web-services will have documentation that will document the response format. In our case as we can see above the response is a plain JSON object.
We do not need to parse the JSON response as the framework will automatically convert the JSON response to a JavaScript object and we need to just read the properties of this JavaScript object and populate the values on the UI based on them. Here is the body of the populateUIWithResults(response) method that handles the response:


function populateUIWithResults(movieResponse) {
    if (movieResponse) {
        console.log("A response is received from the web service");
        if (movieResponse.Response) {
            $("#title").html(movieResponse.Title);
            $("#year").html(movieResponse.Year);
            $("#genre").html(movieResponse.Genre);
            $("#actors").html(movieResponse.Actors);
            $("#plot").html(movieResponse.Plot);
            $("#language").html(movieResponse.Language);
            $("#imdbRating").html(movieResponse.imdbRating);
            $("#duration").html(movieResponse.Runtime);
            $("#poster").attr("src",movieResponse.Poster);
        } else {
            alert(movieResponse.Error);
        }
    } else {
        console.log("No response is received from the web service");
        alert("No response is received from the web service")

    }

where all the identifiers marked with # are the IDs of the HTML span elements where the respective values will be stored. As you can see the respective properties of the JavaScript object are set as the inner HTML of the span tag in the HTML page.

The complete code for the implementation can be found here: http://webservicesintegration.codeplex.com

Here is a screen shot of the running application:

Thanks for reading my blog post. In case you have any questions or comments, please feel free to reach out to me in the comments section.

Cheers!

Friday, 4 December 2015

Hard to detect bugs and how to avoid them

Hi guys,

Today while resolving some issues I discovered some one of a kind bugs that some folks had introduced. Interestingly these bugs were introduced only because they had the best of intentions in their mind and had made the changes in their code so that it was more resilient. The language is JavaScript although most languages can be included as these were some very basic programming errors.


Here is the code snippet that was failing due to a null exception at times:

if(response != null && response.data == 1 || response.data == 3 || response.data == 5)
{
  // some logic
}

The above code looks pretty harmless at the first glance. There is a null check at the beginning on the response object and thereafter there is a check  on the value in the data property of the same response object.
Unfortunately, this code fails in case the response object is null. This is because the logical operators being used associate from left to right and the operator does not short-circuit on false. So if we break the operands for the or (||) operator:

Operand 1: response != null && response.data == 1
Operand 2: response.data == 3
Operand 3: response.data == 5

When the response object is null, the first operand evaluates to false (as the first operand of the and operator is false), since the OR operator does not short circuit on false, the second operand is evaluated and it throws a null exception as response object is null and we are trying to access the "data" property of a null object.

The proper way to implement the check will be
if(response != null && (response.data == 1 || response.data == 3 || response.data == 5))
{
  // some logic
}

This will work as the and operator will short-circuit on false, so once response object is null, the first operand evaluates to false, the result of the "and" operation will also be false.

The most readable option will be:
if(response != null)
{
   if(response.data == 1 || response.data == 3 || response.data == 5)
     {
        // some logic
     }
}

You might want to add logging here to verify as part of the else clauses that there are no "silent failures".

if(response != null)
{
   if(response.data == 1 || response.data == 3 || response.data == 5)
     {
        // some logic
     }
   else{
       console.log(" The value of response.data is not 1, 3 or 5. It is: " + response.data);
  }
}
else
{
    console.log("The response object is null.");
}

Thursday, 3 December 2015

Debugging JavaScript using proactive logging

Hi guys,

JavaScript is a language which is quite flexible and this can both be a boon as well as a curse if not used correctly. Since we use JavaScript while developing our applications I wanted to share a tip that would make the debugging process much less cumbersome. Always insist on logging to the console the branch that your code is taking using the console.log method that comes out of the box with JavaScript. This helps you to log output on the special console window that all major browsers possess.
Pressing F12 in Firefox, Chrome and IE opens the "Dev tools" window in these browsers and you can see a tab that will be titled as console. Here are a few examples:


Internet Explorer




Chrome

You can thus use the console.log(""); method and use it in your code and observe the output in the log output window of the browser. Logging should be for each of the branch that your program can take. This makes it clear once your script executes as to what path the program took and it will help you visualize the same. Here is an example:

var userName = $("#txtBox").val();
if(userName)
{
 console.log("The user name is: " + userName);
  // other logic goes here
}else
{
console.log("There is no value in the user name text box");
}

You can see in the above that all the details of the execution are being logged which includes the values that are being used (in the if clause) and also in case there are no values in the else clause. This really helps when the script has grown in size and there is a need to obtain what is going on in your script.
This also prevents the "silent failing" of your code. Imagine a scenario where the user name is a mandatory field on a form and due to some reason the client side logic to check the requirement level for the field has not fired. Since the user does not enter any data, the else part of the above code would run and without logging you would never realize that there is something wrong unless you have some explicit unexpected functional behavior.

So logging is the way to go and a glance at the log output will tell you exactly what had happened and why your program executed the way it did!

Hope this article makes developing and debugging your JavaScript applications a little easier and helps you save some time!

Please post your comments in case you have any.

Cheers,
Anurag