SQL Server Quick Tip: Restoring A Database Backup

Posted: May 1st, 2012 | Author: | Filed under: SQL | No Comments »

Restoring your SQL Server database using the GUI can leave your database stuck in the “restoring” state. One quick solution is to restore your database by using this simple SQL script.

RESTORE DATABASE your-database-name FROM DISK='c:\your\backup\file\and\path\backup.bak' WITH REPLACE

Feed The Google Black Bar’s Google Play Link A Plate Of Death, Greasemonkey Style

Posted: March 27th, 2012 | Author: | Filed under: JavaScript | No Comments »

Here’s a Greasemonkey script that I whipped up in 30 seconds that banishes the Google Black Bar’s new Google Play link back to the hell from whence it came. You may want to remove line 13.

1
2
3
4
5
6
7
8
9
10
11
12
13
// ==UserScript==
// @name 	Oi Vei, Google Play
// @namespace  	http://code.christophervigliotti.com
// @include    	http://*.google.*
// @include     http://google.*
// @include     https://*.google.*
// @include     https://google.*
// @include     https://accounts.google.*
// @description Fixes Google's Black Bar
// ==/UserScript==
 
document.getElementById('gb_78').parentNode.style.display = 'none';
alert('YOU SHALL NOT PASS');

SCJA Chapter 2, Exercise 2-1

Posted: March 21st, 2012 | Author: | Filed under: Java | No Comments »

I’ve decided to become a Sun Certified Java Associate and am studying for the exam. I’m sharing my answer to Exercise 2.1, as it took a bit of work to grok the answer. The goals of Exercise 2.1 are to create an ArrayList of floats, iterate through the list and printing out the values when they meet a certain condition. I know that this is Java 101 stuff here, but the key for me to complete this exercise was to realize that I could declare floats to numeric values that contained decimals easily by adding an f immediately after the number.

float requiredFishLength = 28.0;

This code throws an error

float requiredFishLength = 28.0f;

Just add f-bomb!

Lastly, here’s my solution for Exercise 2-1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
float requiredFishLength = 28.0f;
ArrayList<Float> fishLengthList = new ArrayList<Float>();
 
fishLengthList.add(10.0f);
fishLengthList.add(15.5f);
fishLengthList.add(18.0f);
fishLengthList.add(29.5f);
fishLengthList.add(45.5f);
 
for(float fishLength: fishLengthList){
	if(fishLength > requiredFishLength){
		System.out.println(fishLength);
	}
}

Firebug JavaScript Logging Gotcha

Posted: March 13th, 2012 | Author: | Filed under: JavaScript, jQuery | 2 Comments »

I’ve been doing a lot of Javascript / jQuery work over the last week and have been using Firebug’s handy-dandy console.log() debugging method. Thanks to the awesomeness that is Firebug the era of debugging one’s JavaScript code with irritating alert() messages is over. One gotcha that I’ve fallen for more than once this past week is that leaving console.log() calls in your code when you aren’t running Firebug will cause JavaScript errors. A simple work-around for this problem is to have JavaScript test for the existence of console before attempting to log the message. I’m doing this in the code sample below in a function that I’ve named consoleLog().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
function booya(){
 
    // this will make IE cry like a sad, sad baby when Firebug is not present
    console.log('booya');
 
    // this will appease the demon child
    consoleLog('method booya() in the house');
}
 
function consoleLog(message){
    if(window.console){
        console.log(message);
    }
}

Ideally one should not be leaving debug code in their completed work, but I make an exception in cases where the debugging code serves as a code comment that may be helpful to other developers.

You can read more about Firebug and Logging here.


jQuery Add ‘Em Up

Posted: March 6th, 2012 | Author: | Filed under: JavaScript, jQuery | No Comments »

Here’s a bit of code that calculates the sum of the values found in a group of form fields. Dollar signs, decimals and commas are added to each form field as-needed, non-numeric characters are brought to the user’s attention. I chose not to leverage the jQuery Calculation Plug-in because I wanted small/light code that targeted the following requirements:

  1. calculate the sum of a group of form fields
  2. add dollar signs, decimals and commas as-needed
  3. ignore non-numeric form field values during calculation, but alert the user

You can check out a working example here and check out the code below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<script>
jQuery(document).ready(function(){
 
	// call doTotals() once when the page loads
	doTotals('calc','total','error_');						
	doTotals('morecalc','anothertotal','error_');						
 
	// call doTotals() each time one of the 'calc' fields or 'morecalc' fields change
	jQuery('.calc').change(function(){
		doTotals('calc', 'total','error_');
	});
	jQuery('.morecalc').change(function(){
		doTotals('morecalc','anothertotal','error_');	
	});
});
 
// spiffy function that adds commas to a number
function addCommas(nStr) {
 
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
	    x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
 
/*
 this function...
	1. adds a group of form fields
	2. formats the form fields
	3. writes the total
	4. highlights any errors
 
usage...
 
	doTotals('calc','total','error_');
	where
		'calc' is a the class name that is present in each form field that you want to add
		and
		'total' is the id of the span/div that you wish to display the total in
		and
		'error_'
		is the name of the span that accompanies each form field.  an error message will be displayed in this span
*/
function doTotals(valuesClassName, totalIdName, errorIdPrefix){
 
 
	var doWriteDollarSignsToFormFields = true;
	var total = 0;
	jQuery('.' + valuesClassName).each(function(){
 
	value = jQuery(this).val();
 
	// remove all whitespace
	while(value.indexOf(' ') != -1){
		value = value.replace(' ', '');	
	}
 
	// remove all dollar signs
	while(value.indexOf('$') != -1){
		value = value.replace('$', '');		
	}
 
	// remove all commas
	while(value.indexOf(',') != -1){
		value = value.replace(',', '');			
	}
 
	// if at this point value is blank, change it to 0
	if(value == ''){
		value = '0';
	}
 
	// if at this point the value is not blank and is a number...				
	errorFieldName = '#' + errorIdPrefix + jQuery(this).attr('id');
	if(value != '' && ! isNaN(value)){
 
		// write the cleaned value (with commas) to the form field
		if(doWriteDollarSignsToFormFields == true){
			jQuery(this).val('$' + addCommas(parseFloat(value).toFixed(2)));
		}else{
			jQuery(this).val(addCommas(parseFloat(value).toFixed(2)));
		}
 
		// convert the value and add it to the total
		valueParsed = parseFloat(value);
 
		total = total + valueParsed;
		// console.log('remove error from span id ' + errorFieldName);
		jQuery(errorFieldName).html("");
	}else{
		// console.log('write error to span id ' + errorFieldName);
		jQuery(errorFieldName).html("<< please enter a numeric value");
	}
 
	});
 
	// update the total
	if(doWriteDollarSignsToFormFields == true){
		jQuery('#' + totalIdName).html('$' + addCommas(parseFloat(total).toFixed(2)));
	}else{
		jQuery('#' + totalIdName).html(addCommas(parseFloat(total).toFixed(2)));
	}
}
</script>

…and here’s an HTML table…

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<h1>add em' up!</h1>
<table style="width:800px;">
<tr>
	<td style="width:400px;vertical-align:top;">
		<h2>group a</h2>
		<input type="text" class="calc" id="calc1" value="$55.50" />
		<span id="error_calc1">error_calc1</span><br />
		<input type="text" class="calc" id="calc2" value="19.99" />
		<span id="error_calc2">error_calc2</span><br />
		<input type="text" class="calc" id="calc3" value="" />
		<span id="error_calc3">error_calc3</span><br />
		<input type="text" class="calc" id="calc4" value="" />
		<span id="error_calc4">error_calc4</span><br />
		<input type="text" class="calc" id="calc5" value="cheese" />
		<span id="error_calc5">error_calc5</span><br />
	</td>
	<td style="width:400px;vertical-align:top;">
		<h2>group b</h2>
		<input type="text" class="morecalc" id="calc6" value="" />
		<span id="error_calc6">error_calc6</span><br />
		<input type="text" class="morecalc" id="calc7" value="" />
		<span id="error_calc7">error_calc7</span><br />
		<input type="text" class="morecalc" id="calc8" value="" />
		<span id="error_calc8">error_calc8</span><br />
	</td>
</tr>
<tr>
	<td>
		<h2>total a</h2>
		<span id="total">0.00</span>
	</td>
	<td>
		<h2>total b</h2>
		<span id="anothertotal">0.00</span>
	</td>
</tr>
</table>

The power of jQuery compels me!


Java-licious Java Primer: Properties

Posted: February 16th, 2012 | Author: | Filed under: Java, O-O | No Comments »

In this second installment of the Java-licious Java Primer series we are going to focus on “properties”.

Arguments

Methods may require arguments in order to function. Arguments are the values that you pass into a method. Lets compare these two examples…

1
2
3
public static void displayYourName(){
	System.out.println("John Jacob Jingleheimer-Schmidt");
}

Example 1a – a method that does not require any arguments

We can determine that the above method does not require any arguments because the arguments are not defined in the parenthesis “()” on line 1.

1
2
3
public static void displayYourName(String yourName){
	System.out.println(yourName);
}

Example 1b – a method that requires one argument

Check out the code inside of the parenthesis “()” on line 1. “String yourName” means that the method expects you to pass in a string when calling this method. The method will refer to this string as “yourName”.

Remember that methods may (or may not) require arguments.

Returned Values

Additionally methods may return values. Lets compare these two examples…

1
2
3
public static void displayYourName(){
	System.out.println("John Jacob Jingleheimer-Schmidt");
}

Example 2a – a method that does not return a value

1
2
3
public static String getYourName(){
	return "John Jacob Jingleheimer-Schmidt");
}

Example 2b – a method that returns a string

Remember that methods may (or may not) return values.

Methods And Properties

A class is made up of methods and properties. Methods (covered in the previous post) define the behavior of classes. Properties on the other hand define the non-behavioral aspects of a class. For example, if we were to think of a Person as a class, breathing, running and jumping would be considered methods. Name, hair color, height, weight and gender would be some of the properties of the Person class.

Lets create a class called “RegularDrip.java” into a package named “coffee”. Your code should look like the example in Figure 1.

1
2
3
4
5
6
7
8
9
10
package coffee;
 
public class RegularDrip {
 
	private static String whoAreYou = "I am a cup of regular drip coffee";
 
	public static String getWhoAreYou(){
		return whoAreYou;
	}
}

Figure 3a – Class RegularDrip.java

Two items of note here. The first is the code on line 5. This is the classes only property. It’s name is “whoAreYou” and it’s type is a “String”.

5
private static String whoAreYou = "I am a cup of regular drip coffee";

Figure 3b – the whoAreYou property of class RegularDrip.java

Data Types

All properties have a data type. Data types are just that…one of the many different type of data. Our whoAreYou property on line 5 is the “string” datatype. Let’s add another property to our object. Add the code below after line 5.

private static int ouncesRemaining = 8;

Figure 4a – the ouncesRemaining property of class RegularDrip.java

Our RegularDrip class now has two properties! There are a few differences between the two properties that we should look into.

5
6
private static String whoAreYou = "I am a cup of regular drip coffee";
private static int ouncesRemaining = 8;

Figure 4b – the properties of class RegularDrip.java

The second one has a type of “int”. That’s Java-speak for “integer”, which is math speak for “number”. The other difference is on the right side of the equals sign. The whoAreYou property is a string, which means that we have to wrap it’s value in quotes. The ouncesRemaining property however, is an int…which means that we need to declare it’s value without quotes.

Lets Make Coffee

Using MrJava5000.java from the previous lesson lets add a few additional lines of code. After the package declaration add the following code:

import coffee.RegularDrip;

Figure 5a – an import statement

This code is an import statement. It allows us to access the RegularDrip class.

And after the sayHello() method call in the main() method add this code:

RegularDrip myMorningCup = new RegularDrip(); // new
System.out.println(myMorningCup.getWhoAreYou());

Figure 5b – make a new cup of coffee, then tell us about it

This code creates a new instance of RegularDrip named ‘myMorningCup’, then sends the returned value of the RegularDrip instance’s getWhoAreYou() method to the console window.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package coffeemakers;
 
import coffee.RegularDrip; // new
 
public class MrJava5000 {
 
	public static void main(String[] args) {
		sayHello();
		RegularDrip myMorningCup = new RegularDrip(); // new
		System.out.println(myMorningCup.getWhoAreYou());
	}
 
	public static void sayHello(){
		System.out.println("hello world");
	}	
}

Figure 5c – MrJava5000.java

Run the MrJava5000.java class now and prepare to be amazed as your creation actually produces a (fake) cup of coffee!

Many Ways To Say Hello

Lets take a look at the println() method. We know that

Here are a In all three examples we output the word “hello” to the console window. In each of the three examples we pass a string into the println() method. In the first example we create a string on-the-fly simply by wrapping some text in quotes.

1
2
3
4
public static void main(String[] args) {
	// say hello
	System.out.println("hello...is it me you're looking for");
}

Example 6a – Hello

Check out the println() method call. Note that “hello” is wrapped in quotes because println() expects a string.

1
2
3
4
5
public static void main(String[] args) {
	// say hello again
	String greeting = "hello...is it me you're looking for";
	System.out.println(greeting); 
}

Example 6b – Hello

Again focusing on println(), note that “greeting” is not wrapped in quotes. This is because “greeting” is a variable of type “string”.

1
2
3
4
5
6
7
8
// say hello a third time
public static string getHello(){
	return "hello...is it me you're looking for";
}
 
public static void main(String[] args) {
	System.out.println(getHello());
}

Example 6c – Hello

This time we pass the returned value from the getHello() method into the println() method.

Next Time

Next time we’ll dig deeper into what an “instance” of a class is.


Java-licious Java Primer: Methods

Posted: February 13th, 2012 | Author: | Filed under: Java, O-O | No Comments »

Welcome to the first of the “Java-licious Java Primer” series. The series was created for folks that are new to software development (experienced code-heads and vulcans may want to skip this one). In this post we’ll be covering how to create a class, how to add a method to the class, and how to “call” the method.

Start Here

In order to follow along you will need to download and install the Eclipse IDE. IDE is fancy-talk for “interactive development environment”…which is fancy talk for “the program that we will edit and run java files in”. Download the zip file, and unzip the contents to to c:\Eclipse. To open Eclipse simply browse to c:\Eclipse and double-click eclipse.exe.

Create A New Project

In Eclipse follow these two simple steps to create a new project…

  1. Click on “File” > “New” > “New Java Project”
  2. Name your project “Javalicious” and click “Finish”

Create Your First Class

  1. In the Package Explorer pane, right click on the Javalicious project, select “New” > “Class”
  2. Name your class “MrJava5000″ and give it a package name of “coffeemakers”
  3. Under “Which method stubs would you like to create” make sure that “public static void main(String[] args)” is checked.
  4. Click “Finish”

Your new class is now created and should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
package coffeemakers;
 
public class MrJava5000 {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
 
	}
 
}

Figure 1 – MrJava5000.java

What Does It All Mean?

Before we proceed with attempting to understand all the strange letters, squiggles and assorted shapes in Figure 1 lets take a step back and talk about code comments. Here is how code comments are written in Java.

// I am a single-line code comment.
/**
* I am a multi-line 
* code comment.
*/
/*
 I am also a multi-line 
 code comment.
*/

Code comments are the ideal place to leave notes for yourself, and to explain what a given section/line of code does to other developers. I’ve modified the code in Figure 1, adding comments and removing a few things.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// this is the package declaration
package coffeemakers;
 
/* 
this is the class declaration.  it's "public" which means that it can be used by other classes.
note the curly brace '{' after the class name.  it's matching curly brace is on line 14
*/
public class MrJava5000 {
 
	// this is a method named 'main'.  this method begins on line 11 and ends on line 13.
	public static void main(String[] args) {
 
	}
}

Figure 2 – MrJava5000.java with lots of code comments

Package Declaration

So the code on line 2 is the package declaration. It basically says “the MrJava5000 class is found in the folder named ‘coffeemakers’. Think of packages as folders. If we were to change the name to from “coffeemakers” to “coffeemakers.mrjava” Eclipse would simply move the file from [project root]\src\coffeemakers\ to [project root]\src\coffeemakers\mrjava\.

Class Declaration

You may notice several occurrences of the left and right curly braces “{” and “}”. The class declaration on line 8 has a left curly brace. It’s matching right curly brace is found on line 14. Everything between these two symbols is a part of class body.

The “Main” Method

Lines 11 through 13 contain the a method. This is a special method named ‘main’. It is special in that it will run whenever you run the class.

11
12
13
public static void main(String[] args) {
 
}

Figure 3 – The “main” Method

Lets Add Another Method

Below the closing curly brace for the main method(and before the closing curly brace for the class) add the following code.

public static void sayHello(){
  System.out.println("Hello world");
}

Figure 3a – The “sayHello” Method

This is a new method named “sayHello”. It calls a method named “println”. This method displays whatever text is contained within the parenthesis and quotes.

Your code should look like this…

1
2
3
4
5
6
7
8
9
10
11
12
package coffeemakers;
 
public class MrJava5000 {
 
	public static void main(String[] args) {
 
	}
 
	public static void sayHello(){
		System.out.println("hello world");
	}	
}

Figure 3b – MrJava5000.java, including our new “sayHello” method

Now let’s run this Java class and see what happens. Highlight MrJava5000.java in the Package Explorer window and press the green play button. Observe the results. Actually that’s a joke, as there are no results to observe. The reason why we didn’t see the “hello world” text that we wanted to is due to the fact that we aren’t “calling” the helloWorld() method from our main() method. Let’s do that now by adding the following code to the main method.

sayHello();

Figure 4a – calling the “sayHello” method

OK, now we have added code inside of the main() method that calls the helloWorld() method. Your code should now look like this…

1
2
3
4
5
6
7
8
9
10
11
12
package coffeemakers;
 
public class MrJava5000 {
 
	public static void main(String[] args) {
		sayHello();
	}
 
	public static void sayHello(){
		System.out.println("hello world");
	}	
}

Figure 4b – MrJava5000.java, ready to say hello

Run the code again and you should see the following text in the Console panel.

hello world

You’ve just created your first Java class. When run, this classes main method runs. The main method calls the sayHello method, which in turn outputs the text “hello world” to the console panel. This of course means that you are one step closer to becoming a Java legend!


New To Java? Read This Book

Posted: February 2nd, 2012 | Author: | Filed under: Java, O-O | 2 Comments »

If you are new to the strange and wonderful world of Java development, Head First Java is the essential primer.

Do you have a favorite “Intro to Java” or “Intro to Object Oriented Development” resource? Please share in the comments :)


“Zeus, There It Is” or “Don’t Bring Me Down…Zeus”

Posted: January 18th, 2012 | Author: | Filed under: ColdFusion | 2 Comments »

I’ll be participating on a preview of ColdFusion Zeus tomorrow at noon. See you there.


Selenium Conditional Statements And Assertions

Posted: January 18th, 2012 | Author: | Filed under: Selenium | No Comments »

This post is a part of my Learn Selenium series.

Here’s a test case that demonstrates the use of conditional statements and assertions in Selenium RC. This code uses the parent class BigDaddyKane, which is explored in detail in a previous post.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// package declaration, imports, etc.
package awesomeTests;
import java.security.SecureRandom;
import java.math.BigInteger;
@SuppressWarnings("deprecation")
 
// class decaration
public class FancyTests extends BigDaddyKane {
 
	// This is a method for generating a random string.  
	// You can disregard it for now, just note that we'll be using this later.
	public String getRandomString(){
		SecureRandom random = new SecureRandom();
		return new BigInteger(130, random).toString(32);
	}
 
	// Here is our first test case.  It verifies that the text 
	// "Repeated Overflows" appears in the h1 of the main page.
	public void testIsBlogTitleCorrect() throws Exception {
 
		// open the root page of the site
		selenium.open("/");
 
		// Lastly we use assertEquals().  This test will fail if the text 
		// "Repeated Overflows" is not present in an h1 element
		assertEquals("Repeated Overflows", selenium.getText("css=h1"));		
	}
 
	/* Here is our second test case.  This example demonstrates the use of conditional logic in conjunction with 
	 * the Selenium function isElementPresent().  
	 */
	public void testAddCommentToBlog() throws Exception {
 
		// open the root page of the site
		selenium.open("/");
 
		// click on the top-most post and wait for the page to load
		selenium.click("xpath=//div[2]/div/h1/a");
		selenium.waitForPageToLoad(pageReloadTime);	
 
		// using this variable to determine the user's logged in state
		boolean userIsLoggedIn = false;
 
		/* since Wordpress will now allow duplicate comments we need to make the comment text unique each time this test is run.  
		 * Note the use of the + symbol when declaring the string.  This means that the text to the left of the plus in quotes will be 
		 * appended by the results of the getRandomString() function call.
		 */
		String comment = "the chicken says: " + getRandomString();
		System.out.println(comment);
 
		// are these elements present?
		boolean nameFieldExists = selenium.isElementPresent("id=author");
		boolean mailFieldExists = selenium.isElementPresent("id=email");
		boolean urlFieldExists = selenium.isElementPresent("id=url");
 
		// displays the above boolean values in the console screen (so you can see what's going on)
		/*
		System.out.println(nameFieldExists);
		System.out.println(mailFieldExists);
		System.out.println(urlFieldExists);
		*/
 
		// note: in cases where the author, email and url fields are not present the user is already logged in
 
		// if the name, email and url fields do not exist, then the user is logged in
		if(nameFieldExists == false && mailFieldExists == false && urlFieldExists == false){
			userIsLoggedIn = true;
		}
 
		// if the user is not logged in, fill in the name, mail and url fields
		if(userIsLoggedIn == false){
			System.out.println("user is logged in");
			selenium.type("id=author", "Paul McCartney");
			selenium.type("id=email", "billgates@microsoft.com");
			selenium.type("id=url", "http://wikipedia.org");
 
		}else{
			System.out.println("user is not logged in");
		}
 
		// fill in the comment field and click the submit button
		selenium.type("id=comment", comment);
		selenium.click("id=submit");
		selenium.waitForPageToLoad(pageReloadTime);
 
		// if the comment was added either the text "Your comment is awaiting moderation." or the value of the String 'comment' should be present
		boolean expectedResult = false;
		if(selenium.isTextPresent("Your comment is awaiting moderation") || selenium.isTextPresent(comment)){
			expectedResult = true;
		}
 
		// lets display the expected result
		System.out.println(expectedResult);
 
		// use assertEquals to conclude this test case.  note that we could also use assertTrue(expectedResult) here...
		assertEquals(expectedResult, true);
 
	}
}