Javascript Arrays

Introductions

An array is simply a list of variables that are the same type. An example of an array would be an array of ages containing 0, 1, 2, 3 etc. The array doesn’t have to be integers, it can be an array of strings, objects or even arrays.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Create an array
var ages = new Array(1,2,4,99,54,23);
 
// Create another array
var names = new Array(“bill”, “bob”);
 
// Create a literal array
var games = [“minecraft”,”half life”,”freecell”];
 
// Add values to an empty array
var ages = new Array();
ages[0] = 1;
ages[1] = 2;
ages[2] = 9;

It is important to know that the array is actually an object that contains values. Because this type is actually an object there are properties that can be called to help handle the information inside of the array.

Helper Functions And Properties

In javascript, along with many other languages, there are functions built around arrays that will allow you, the developer, to better use them and be more efficient in your coding. The length property is one of the most commonly used properties when going through an array.

1
2
3
4
5
6
7
8
9
// Going through the items in an array.
// Create the array
var ages = new Array(1,2,3,5,7);
 
// Loop through using the length property
for(var x = 0; x < ages.length; x++) {
// Print out the items one by one with an alert.
<p dir="ltr">alert(ages[x]);</p>
}

Array push and pop are commonly used to add items to the array without having to get the position of where the item will be added yourself.

1
2
3
4
5
6
7
8
// Create an array with one item
var names = [“bob”];
 
// push an item onto the array.
names.push(“caleb”);
 
// the resulting array will now be the same as it would be if you created it like this.
var names = [“bob”,”caleb”];

Now we are going to pop an element off of the end of the array and return the item. This call not only returns the value but it will alter the array in memory changing the values within it.

1
2
3
4
5
// create a new array of names that we will play with
var names = [“chewbacca”,”yoda”,”skywalker”,”ben”];
var poppedValue = names.pop();
 
// As a result the names array will no longer have “ben” in it and the poppedValue will contain the string “ben”;

Two Dimensional Array

The concept of a 2D array can seem a little intimidating at first until you realize that you need to look at the data as columns and rows. Here is an example of what a 2D array would look like.

1
2
3
4
// Creating a 2D array
var x = new Array(0,1);
x[0] = new Array(0,0);
x[1] = new Array(0,0);

In order to access a property within the second array you will just need to fetch the value using the key.

1
2
// Display the item that is in the first column of the first row.
alert(x[0][0]);

Another way to create an array like this is to loop through the items upon creation.

1
2
3
4
5
6
7
8
9
10
11
//Create the array container
var names = new Array();
 
for(var x = 0; x &lt; 10; x++) {
names[x] = new Array();
// Go through the second dimension and set the values.
for(var y = 0; y &lt; 10; y++) {
// Assign the value of the item to bob.
names[x][y] = “bob”;
}
}

Google Drive API

Introduction

Google Drive is out! Yes that’s right, Google’s Drive project which allows users to store content onto a Google server and pull it from any device is now available. This product offers 5GB free to google users with additional packages for extra money.

This is a pretty cool thing and not just because Google is doing drop box properly but more so because they are doing drop box across the Google platforms and offering an API to those of us that are interested in developing for it.

My plans

My plan over the next couple of days is to create a way to store server logs and general statistics for my server to the Google Drive. This will allow me to easily check on how things are going from my mobile device.

Google Drive API

If you are interested in working with Google Drive than I suggest that you take a look at the API that Google has provided us. https://developers.google.com/drive/v1/reference/

If you are going to work with the API that is available you will have to register your own app. https://developers.google.com/drive/register

Performance

The API has some interesting features for performance. When performing an update you can receive a partial response. This response type will only return the specific fields that you ask for rather than the entire object. The API also supports a header type of gzip to allow for speedier and smaller sent and received packets of information.

For more information on Google Drive API performance: https://developers.google.com/drive/performance

Tags: , ,

Statistics – Simple Logging Design

Introduction

This article is the first in a series focussed on Statistics, Logging and Graphing web application events and information

When creating a web application it is important to keep track of everything a user does. Some people may think that this is a little over the top but the more information we can gather within a web application the better. It also allows simple and easy moderation practices for those that are moderators within the application.

Pre-Planning

This is by far the most important stage in development. During this stage you are going to need to create proper data structures that in theory will not have to be change (although this is extremely rare.) This means that you are going to create the general database that will handle most of the current up to date information and another section that will be used for logging.

Within the main database we are going to have simple things like a user table, a user settings table, a user profile table and a user information table. On tables that hold general information it is important to add a time stamp column that holds the value of last modified. The user should have a column that tells us when the users profile was created. These values aren’t going to really help us when gathering information for a single user simply because the sample of data that we can compare it to is so small. Fortunately these simple values are excellent when we need to pull up values quickly in our system to display user information.

Single User Sample

The logging database is going to help us create a large sample of a single user. This is where we are going to constantly insert information and never delete or modify the records. In one of these tables we can store required values that will tell us when a user has had one of their comments deleted by a moderator. Within this table we are going to log the moderator’s id, the user’s id, the time stamp that this action was performed on. and a numeric value that reflects on the reason that the comment was removed. With this data we can then count the comments that are still alive and well and count the comments that were deleted. With this information we can divide the comments that are still alive and well by the comments that were deleted thus giving us a ratio that we can work with.

Note: It is a good idea to keep track of numbers like this as well and when the ratio was calculated. This will allow us to track user behaviour.

Multiple User Sample

Given that we could have a ratio of how well the user follows rules when it comes to commenting on things and taking part in discussion we filter out the users that are not contributing to the community/application. We can also sort users by this ratio and from there bury into their statistics, activities and logs.

Because we have logged all of the individual comments from this user we can closely examine the user interactions by graphing comments, removed comment, comments removed for x

Password Recovery {Theory}

Password Recovery is a must have in any web application and you as a software engineer need to make sure that you handle this process properly. There are two methods that I like to use but in this article I will only be using one of them. Before you start programming it is a good idea to go through some of the larger web applications to see what they are doing. You may want to modify your process.

Before we begin I should probably make sure that you know just what you are in for before trying this. You are going to need to have knowledge of a server side language, the ability to send mail on your server, store Cookies and Sessions, along with having a running database with access to user emails as a unique field in the database.

Stage 1

The password recovery system is going to first require the user to input their email and submit it for checking. On this processing step we will do the following.
1. Check that the email follows proper formatting and there are no bad characters.
2. Check the email against the database to make sure that the user does exist and they have an active account.
3. Check the password recovery table to make sure that the user has not had their password reset in the last 15 minutes.

Now that we have checked and bypassed anything that will put a large hold on the password recovery process we can move on to actually storing the information and content that is required to reset the users password.

Because we are going to be resetting the users password we need to make sure that the user supplied us with a proper email. Even if they did not we are going to show a success screen saying that an email has been sent. This way a bot that is entering in randomness to get emails will not be able to find them this way since everything will return true.

Note: Brute Force should be check for on all forum submissions and thus a lock out system should be added but that is a whole other article.

We now need to generate the items that are going to be stored. Because we will be storing information in a cookie and inside of a session. I know guys that store two keys but I just store a time stamp in the database, break it up into segments, add alpahnumeric characters and hash the information. This way I can keep a time stamp in the database and keep the information secretly stored in a session specific to the user.

Note: When storing time only use the generating function once and store the value into a variable so we have the same time when committing to the database.

Now that we have the information set into the appropriate variables we can store the information via insert to a table that holds the user id, key and time stamp. This way we can track our two keys and a time stamp of when they tried to reset their password. If we wish to lock the user out of the system for a certain amount of time we can simply change the key to null and check for this. If the (current time – date stored) < (15 * 60) and there is no key then we can just display an error message.

When everything is properly stored into the database we can send the user an email. This email will contain a link to the password recovery page along with a key which will be the one saved in the cookie. This way we can pass two keys back and know that the only way for this user to be the wrong user is if they have the email account as well.

Stage 2

This page is going to check for a key that is alphanumeric and of a certain length. With this key we are going to check to make sure it is the same as the cookie and that it is in the database. If the user is in the database we can pull the rest of the information including their email from the other table to make sure that we are able to regenerate one of their keys assuming that we used it.

Finally we need to make sure that the generated key matches the one that is stored inside of the session and the date is within the allotted time. From here we need to first delete the record in the database, generate a random password, hash it and store it into the system, and send them a copy of this new password via email.

During this last portion you need to handle the case that the page was accessed with improper values or missing values. eg: if the user does not have the cookie set or the time is out of range we need to handle the case and remove the key from the database so we know that that user won’t be able to try and reset their password for another 15 minutes. You can also bump up the time that is stored in the database depending on what was missing in case of a bad attempt which will allow you to easily lock a user out.

Google’s Plus 1 Button Integration And Options

Google has recently changed it’s theme, search method, oh and it has created a social networking site that will rival that of Facebook. The software giant has also rolled out the +1 button (plus 1 button) which is in direct competition with the Facebook like button. The plus 1 button has not only already been integrated into a lot of personal sites and blogs but it has been put into Google’s search results which is going to change the way we find content on the web and how this content is shared with friends, family and co-workers.

The Plus 1 Button Code

The button is also just as simple as the Facebook option when it comes to developer integration. The button only requires two lines of code, one in the header or body and the other where you would like the button to be placed.

1
2
<script type="text/javascript" src="http://apis.google.com/js/plusone.js"></script>
<g:plusone></g:plusone>

Plus 1 Button Size Options

There some options as far as customization of the button goes. The first thing to take into consideration is the size and how it will appear. You can choose between small(height: 15px), medium(height: 20px), tall(height: 60px) and leaving it blank. If you leave it blank it will appear to look the same as the medium option but it will be 24px rather than the 20px that medium is.

1
2
<!-- example of a small plus 1 button -->
<g:plusone size="small"></g:plusone>

Force A URL Through The Plus 1 Button

You can also force a URL into the button that the plus one will be applied to. This is simply done with an href tag and then the url.

1
2
<!-- example of fixed url being set -->
<g:plusone href="http://codewithdesign.com"></g:plusone>

URL Authentication – A New Approach

It is time for web developers and software engineers to make a new approach when checking the validity of URLs and emails that are provided by users. Icann has decided that it is going to allow new suffix’ and the ability to host a website on a domain that has no suffix ie: ‘http://codewithdesign/index.php’. With this change in URLs means that all regular expressions are going to have to not force a suffix or that last decimal as a root URL.

How Will The New Domains Affect Me?

The new domain scheme is going to change how your website validates proper emails and URLs which can be a rather large change on websites that do not have formatting called from one place. Because of this change you will have to overhaul your website/blog/app to support new URLs and emails.

How Should I Go About Making The Change

If you haven’t done so already it is a good idea to make sure that your formatting and checking is coming from one place and will be able to handle the errors accordingly. The first thing that is required is either a functions file or a class file that will support multiple formats of input. This way when something like this changes you only need to update the code once.

Ways To Check URLs And Emails

When working with a URL you can change your regular expression to just check for proper characters and the presence of ‘http://’ or ‘https://’, but there is a much more fun way to check for the new format as well. You should still be using a filter or a regular expression but make sure that your version of PHP is high enough if you are going to use a filter.

Check For An Existing Email

Because of the new URL scheme we are going to need to handle the case that the user is from a website such as ‘http://bearattacksarenotgood/’ This will require us to check for an existing email without the checking of a proper suffix in the email since a user can have the email ‘calebjonasson@bearattacksarenotgood’.

We can easily check for an existing email by using a function called ‘checkdnsrr’ but first we need to split the email name from the URL which will give us ‘calebjonasson’ and ‘bearattacksarenotgood’ which we can accomplish by using the list function will will break apart a string by finding a character.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
//load a variable with an email.
$emailAddress = 'calebjonasson@bearattacksarenotgood';
//split the email by the user name and domain name
list($userName, $domainName) = split('@', $emailAddress);
//use checkdnsrr to validate the domain names existence.
if(checkdnsrr($domainName, 'MX'))
{
    //return value on success.
    return true;
}else{
    //return value on failure.
    return false;
}
 
?>

Pinging A Server

It is possible to ping a server through PHP and it is also possible to just use a cURL to request the page information and check and the response headers. The first thing I will show you is how to send a request which will allow you to check for ping of the data server in question.

My prefered method of doing so is to install net ping onto the server. This is the best solution that I have found on the web to this day and is very simple to use. Here is a tutorial from Code Diesel.

Flex Data Service Debugging Software

I wanted to share an exceptional piece of software that I was recommended to use at work as an excellent debugging tool. The software is called Charles and comes with an excellent demo version that closes every thirty minutes and will give you a little window telling you that you are using a demo from time to time but aside from those two draw backs they haven’t left a whole lot out.

I needed some software after being unable to figure out why we were unable to connect to a data service with Flex. This software upon launch quickly showed us the response that we were not being displayed through Flex and allowed us to quickly sort out our gateway issues. Even though we used this software to help debug flex we have also been using for a lot of http requests and all other browser based debugging that involves sending and retrieving data.

If you aren’t convinced as to download the free copy yet I should probably mention that the software only costs about $30 for a full license and comes in better packages based on how many copies of the software you purchase. It also comes with the ability to throttle your own bandwidth and latency to test in slow conditions which is great when testing against a local server.  The software also allows you to change and resend requests to test back end services which is a huge benefit as a server guy.

The software package comes available and fully supported for Linux, Mac, and of course Windows.

I’m not a software review nor am I paid to voice my opinions but I would advise that any company that wants to save some serious time on debugging should buy this software. It is great for everything web.