Friday, December 23, 2011

Creating Windows Shortcuts for Java Applications

I recently started reading about implementing Selenium Server into my testing process. I quickly downloaded the jar file from their website and opened up my cmd.exe application. While I used the following process for starting Selenium Server, some minor modifications can allow you to shortcut start your programs.

Problem:
I wanted to create a shortcut icon to start Selenium Server to save me a couple of steps.

Solution:
Windows allows easy creation of shortcuts by finding the application, right-clicking, choose Send To => Desktop (create shortcut).

To start, I used this step to create a shortcut to cmd.exe. I used the Start Menu Application Search to easily locate cmd.exe. Once listed, I right-clicked, and created a shortcut on the desktop.


Now I right-click the shortcut and choose Properties. This opens a window that allows me to customize what my shortcut is going to do.



Under the Shortcut Tab, I altered the Target field to read:

C:\Windows\System32\cmd.exe /k java -jar C:\dev\tools\selenium-server-standalone-2.15.0.jar

Now let's break this down. The first part is of course the cmd application that I want to run followed by /k an argument for cmd that tells it to keep the console window open after launching. This is important as our application may give important information to the console or cease to continue running altogether once closed.

Next, I call Java, in my case I have java in my Windows Classpath so that the term java is actually a shortcut to the Java application on my machine. You can read more about setting up java in your system classpath here.

The Java application accepts an argument of -jar which indicates that we are running a compiled jar application. Followed by the application location.

Apply and close any windows remaining, now double click the shortcut icon and hopefully you see something like the following.


Good luck.

Thursday, December 15, 2011

Yum Update Trixbox Issues Dependency Errors

After installing Trixbox on my VirtualBox to mess around with, I noticed that many packages were out of date so I went to update those packages.

Problem:
After typing yum update, yum did it's thing but halted before installing anything with the following message:

Missing Dependency: libcares.so.1 is needed by package sipsak-0.9.6-1.el5.i386 (installed)
Error: Missing Dependency: libcares.so.1 is needed by package sipsak-0.9.6-1.el5.i386 (installed)

Solution:
Your going to have to install these manually before yum will be able to handle them. Use the following commands to download and install these packages.

wget http://download.fedora.redhat.com/pub/epel/5/i386/sipsak-0.9.6-8.el5.i386.rpm
wget http://download.fedora.redhat.com/pub/epel/5/i386/c-ares-1.6.0-2.el5.i386.rpm
rpm -Uhv sipsak-0.9.6-8.el5.i386.rpm c-ares-1.6.0-2.el5.i386.rpm

Workaround:
If you don't have time to deal with these and would prefer to continue installing all other updates, you can tell yum to ignore broken dependencies by using the argument --skip-broken.

yum update --skip-broken

Trixbox 2.8 Adding Repo Addons Breaks GUI

After installing Trixbox 2.8 on my Oracle VirtualBox, I was playing around and enabled the Trixbox Addons repo under Settings > Repositories. Upon refresh my it was apparent that my GUI had been destroyed and I was seeing HTML and a little bit of JavaScript. I began searching for a clue.

Problem: 
Trixbox GUI disappeared upon adding the Addons Repository.

Solutions:
Thanks to some forums, the answer was simple enough.

Open the following file for editing:
/var/www/html/maint/includes/application_top.php

Go to line 137 and past the following line of code:

if(!isset($_SESSION['trixbox_template'])){ $_SESSION['trixbox_template'] = 'default';}

So the file reads as follows:

// Template Chooser
//include('includes/templateChooser.php');
if(!isset($_SESSION['trixbox_template'])){ $_SESSION['trixbox_template'] = 'default';}
//setSession('templateChoice', 'trixbox_template', $sessionFile);

Details:
It appears that updating the repos causes the theme to break by removing the theme currently set in the session. The errors listed by httpd involved missing a slue of css/skin files.

NET: Registered protocol family 2

Well installing Trixbox on my Oracle VirtualBox to play around, my install ran into a problem and halted. I've heard this has happened for other installations on VBox and this solution worked for them.

Problem: 
NET: Registered protocol family 2

Solution:
Luckily a quick search said I needed to enable IO APIC in VirtualBox. Looking around, I found it and my installed proceeded as expected.

Picture:

Under settings, check Enable IO APIC

Tuesday, November 1, 2011

T-Mobile G2 with Android Debug Bridge (ADB) and Flash Builder 4.5 on Windows 7 64 bit

Problem: 

I recently developed an application for the Android market and was excited to test it out on an actual Android device. I plugged in my T-Mobile G2 phone, set the USB Debugging and the Unknown Sources options (found in Settings -> Applications [USB Debugging is in the section Development]). Windows 7 said it found a new device but was unable to install drivers specifically for the G2.



First Attempted Solution - FAILED:

After reading many blogs and forums on how to fix this issue, I decided on one method and started downloading software (HTC Sync) and following the poor instructions given by the blogger. Once all was said and done, it didn't end up working right. ddm found a device but it was always offline.

Final Solution - SUCCESS:

 So I back tracked everything uninstalling software and uninstalling drivers for the device. I decided to follow some direction given in forums I was reading through and did the following. I went to where Flash Builder was installed, for me that is C:\Program Files (x86)\Adobe\Adobe Flash Builder 4.5\utilities\drivers\android. As the path shows continue to navigate to the android directory. In that directory you will see an android_winusb.inf. This file is a driver for many android devices (except the G2). Next, I added the two lines of code below into the android_winusb.inf file. One under under the sections [Google.NTx86] and [Google.NTamd64]. Then I used the Device Manager on my computer to find the Android Phone and then locate this file as the driver for that device.


Add the lines below to sections [Google.NTx86] and [Google.NTamd64] in the file:
C:\Program Files (x86)\Adobe\Adobe Flash Builder 4.5\utilities\drivers\android\android_winusb.inf

;T-Mobile G2 - Start of code
%SingleAdbInterface% = USB_Install, USB\VID_0BB4&PID_0C91
%CompositeAdbInterface% = USB_Install, USB\VID_0BB4&PID_0C91&MI_01
;End of Code


Good luck devs.

* The forum that assisted in helping me solve this problem is xda-developers.com.

Wednesday, September 21, 2011

ActionScript 3.0 Pad String Method

Problem: I use PHP a lot and am currently working on a project in ActionScript  (Flash Builder). I found myself needing a method similar to str_pad. I found a couple online, but nothing as powerful as the one provided in PHP.

Solution: Write my own... here it is. You will find it is very similar to PHP's str_pad method. Also note, there could be a couple improvements in padded string generation, but this will do for now.

/**
             * Add a number of padding in front or back of a string.
             * @param string:String - The string to pad
             * @param length:uint - The final length of the string
             * @param pad_string:String - The string to use as padding
             * @param pad_left:Boolean - padding front or back of string
             */   
            public function padString(input:String, pad_length:uint, pad_string:String, pad_left:Boolean = true):String
            {
                // return input if length greater than padded length
                if (input.length >= pad_length) return input;
               
                // generate padding
                var paddedString:String = "";
                for (var i:uint = 0; i < pad_length - input.length; i++)
                    paddedString += pad_string;
               
                // concatonate results
                var resultStr:String = pad_left ? (paddedString + input) : (input + paddedString);
               
                // account for overflow if any
                if (resultStr.length > pad_length){
                    // chop off extra from result based on pad_type
                    if (pad_left)
                        resultStr = resultStr.substr(resultStr.length - pad_length, resultStr.length);
                    else
                        resultStr = resultStr.substr(0, pad_length);
                }
                return resultStr;
            }

Thursday, July 14, 2011

How to find the Perfect Web Hosting

Problem:
As a developer, sometimes it is hard to know which hosting companies to trust. We are compelled to read reviews (which might be biased or bought) to try and figure out what people are thinking. It may sometimes only seem helpful to only look at the bad reviews. Obviously this has it's downfalls, so how do you do it?

How do you know which hosting company to trust?

Solution:
No hosting company can give you 100% up-time guarantee and some hosting companies will have more problems than others. Remember, I'm not a hosting expert, but the following is what I've found over time.

Things to consider:
  1. How much work am I willing / able to do for a web server?
    • You can choose to manage your server yourself or have someone else manage it although if you don't feel comfortable doing so, there is an in between option. VPS is a virtual private server. This means that you physically share the same box (and some resources) as someone else, but that you have full control of your operating system and the programs installed.
  2. Do I need a Dedicated, Collocated, Cloud, or VPS server?
    •  These server types will cost more than shared hosting. In all three cases, you will have to consider security.
      • Collocation [~$40 / month + server cost]: Your required to buy your own server and find a data center to host it. If something goes wrong that you can't fix remotely, you have to gain physical access to the box to service it.
      • Dedicated [~$70 / month starting]: This allows you to put the strain of physical hardware maintenance in someone else's care; for a price. 
      • VPS [~$20 / month starting]: This is similar to dedicated hosting except that you share some resources with other hosting clients. Now days you will be guaranteed a certain amount of RAM, CPU priority, and disk space, but generally you all share the same motherboard. This means if another user is writing/reading files a lot, you could see slow down with your service.
      • Cloud [~$100 / month]: Often used as a buzz word to charge more, this is similar to a VPS. The difference with real cloud hosting is that you generally have redundancy, high availability, and rapid scaling when you need more or less resources. Because of the distribution of redundancy It's also generally able to respond quicker than a single location web site because of the redundancy in different states/counties/etc. Redundancy can be applied in any of the above options with fail overs using load balancers.
    • If your starting out and you don't have big requirements, I strongly suggest you go with Shared Hosting. You can always change over later (and most likely will change no matter where you start). 
    • If your ready to move away from Shared Hosting and you don't need the extra benefits of cloud hosting, I would suggest VPS or Dedicated hosting solutions. This allows you to save on costs now. Remember, if you don't choose to add redundancy and your server has problems, your web site will be down. Dedicated is nice if you want to guarantee 100% of the machine's resources.
  3. Is shared hosting (or reseller hosting) too insecure?
    • Shared hosting provides a good sandbox environment that allows you to have control over your website, email, and domains (if you host your domains here). They generally provide a control panel which is great for those who don't feel comfortable with managing their web server themselves.
Web Hosting I Recommend:
  • Shared Hosting / Development: If your looking for inexpensive with the most options, and OK reliability, I would suggestion DreamHost, they do appear to have more down-time than other companies but they provide quick service, unlimited domains, databases, emails, and you can set up crons as well as have SSH access your web sites. I currently use DreamHost for several websites where 99.9% up time is not critical.
  • Shared Hosting / Production: If your needing near-constant up-time, I suggest HostGator, they have great service, reliable servers and quick staff. I have used them for both Business Hosting (shared hosting) and VPS. They have always been helpful and have been prompt to address issues, they even will help with tasks like auditing security and so on for free depending on the service you purchase. They also offer both dedicated and collocated options at much higher prices.
  • VPS: If your ready to make the move to VPS, I recently moved to Linode servers. They seem to be really reliable and I haven't had any problems yet. I did email support once with a simple question and they responded in about 20 minutes. I'm not sure how this response time would change had I had an emergency, but I assume only time will tell.
  • Dedicated: One of my clients has a need for dedicated hosting with some real power to it. After reviewing many dedicated hosting providers, we have decided to go with Limestone Networks. I don't know enough about them at this point to promote them or give feedback, but I will update this as time goes on.
  • Cloud: Finding a real cloud host is not easy, but one of the most popular is Amazon AWS. They provide rapid scaling, replication, fail over, etc. but you will be charges for every add-on. To give a price comparison, a similar setup to the Dedicated Server with Limestone Networks was a cost difference of about $350. AWS priced in at nearly $600 where Limestone Networks priced in at about $250. Note, because it is dedicated hosting, scaling is not an easy task nor does it have low latency through distributed data centers, but those aren't priorities for us.
Full Disclosure: While my primary concern of this post is to be completely honest about my experiences and educate, some of the links to hosts above have commission tracking codes attached. If you use the links posted above to sign-up with any of these companies, I may benefit from it (and Thank You if you do!)

Tuesday, June 21, 2011

NetBeans 7 - Deletes my files!

When I saw that NetBeans 7 was ready for download, I anxiously upgraded. At first it's new features appeared to be great until I suddenly realized that files on my server were being deleted...

Problem:
NetBeans would go to download my web site from the server to the local hard drive. After this process was complete, I found several files on my server had disappeared. I restored them via subversion (thank goodness, I am using versioning). I ran this test several more times to see if I could find correlations to what was deleted, however the problem seemed to select files at random.

Solution:

Returned to NetBeans 6.9.1 for now. I sure hope they fix these issues soon. I have really enjoyed the new features:

  • Introduction of JDK 7 support including editor enhancements (syntax, hints)
  • Revamped support for WebLogic Application Server and GlassFish 3.1
  • Oracle Database improvements
  • HTML5 editing support
  • Maven 3 is supported and bundled with the IDE
  • Improved support for CDI, REST services, Java Persistence, and Bean Validation
  • PHP Rename Refactoring
  • Line wrapping
  • Improved detection of external changes (native file system listening)
  • Updates to the C/C++ support (remote file system browsing, library projects running/debugging, enhanced templates/specializations)
  • Support for Git 1.7.х
  • Additional enhancements are listed at the NetBeans IDE 7.0 New and Noteworthy page
Featured from: netbeans.org

Wednesday, June 8, 2011

CodeIgniter 2.0+ is ajax check

Problem:
In some instances, you may want to know if your request in the controller was ajax.

Solution:
Turns out CodeIgniter has added an is_ajax_request method to the input class.

$this->input->is_ajax_request()

Monday, May 30, 2011

Issues while integrating PHP ActiveRecord with CodeIgniter 2.0.2

Intro
Being tired of having a trying to fully utilize CodeIgniter's built-in ActiveRecord (which is really  a loose interpretation of the ActiveRecord design pattern if you ask me), I decided to look for a standalone PHP ActiveRecord implementation. I followed Matt Machuga's tutorial for integrating PHP ActiveRecord with CodeIgniter (I had some issues with his newer revised tutorial).

First Issue: PHP ActiveRecord not loading values into class object.
PHP ActiveRecord appeared to be working except that it would not load the class values. The class structure were defined by the database table and were accessible. Creating and saving a model worked.

First Solution: Remove Constructors
PHP ActiveRecord wasn't loading object values from the database. After some searching, I found a forum on phpactiverecord.org specifing that your model classes can't use constructors (without respect to signature in PHP ActiveRecord). After removing the constructors, data would populate perfectly.

Second Issue: Storing in Session (or psudo-session)
So it appears that CodeIgniter uses cookies to store session data, not PHP's native session. Their implementation also did not support namespace classed (like our model that extends ActiveRecord/Model).

Second Solution: Go PHP Native Sessions
I decided to integrate the NativeSession library for CodeIgniter. This library claimed to allow you to use the session the same but it would integrate with PHP's native session. Be sure to follow the instructions and comments carefully for CI 2.0.*. So far it has been working without issues.

Third Issue: __PHP_Incomplete_Class Object
This happens when you are trying to access a class definition without it's presence. In other words, PHP wants to have access the actual class file for the class it is trying to instantiate.

Third Solution: Order of Loading Libraries
In CI libraries are loaded in the order they are specified. In our now reconfigured solution, we are autoloading session and activerecord (and anything else your using). In order for our new PHP Native Session to know which class definition an instance has, it needs access to our ActiveRecord library. This means changing the loading order to first load activerecord and then load session will fix out problem.
$autoload['libraries'] = array('ActiveRecord', 'session');
After all this, everything appears to be working properly. If any issues arise, I'll update my post with solutions I find.

Best of luck.

Thursday, February 24, 2011

Shuffling Object Properties in JavaScript

Problem:
If you are looking to reorder properties of a JavaScript object (because you may have had an associative array from PHP pass you a json encoded array), you may have found it difficult to do.

Note: I build on my previous method of ActionScript 3.0 Shuffle method. JavaScript and ActionScript are both ECMA languages and have a very similar syntax. The shuffle method I am using below if identical to the one I posted previously.

Solution:
The solution I came up with may not be the most elegant but it gets the job done. It uses a combination of three functions (including the Array shuffle prototype method).

First I started with the JavaScript object that I wanted to shuffle properties for:
var obj = {
        "red":"RED",
        "blue":"BLUE",
        "green":"GREEN",
        "yellow":"YELLOW",
        "purple":"PURPLE"
    };

Next I copied my Array prototype method into the top of the document (note that because it's a prototype method, we are required to define it before using it.
Array.prototype.shuffle = function(){
        for (var i = 0; i < this.length; i++){
            var a = this[i];
            var b = Math.floor(Math.random() * this.length);
            this[i] = this[b];
            this[b] = a;
        }
    }
Now I wrote two new methods to help get the job done. A function called getKeys() which takes an object and extracts the keys returning a simple array of keys for that object.
function getKeys(obj){
        var arr = new Array();
        for (var key in obj)
            arr.push(key);
        return arr;
    }
Last I wrote a method that would put it all together and returned a new object that has shuffled properties. The method first defined a new object that will hold my shuffled properties. Then we use our getKeys function to get all the keys from the object. Then we call the shuffle() method (accessible directly through class prototyping). We iterate through the keys (checking for the property shuffle -which now exists on our object) and by using the same key on both objects, we are able to transfer the key and value to the new object.
function shuffleProperties(obj) {
        var new_obj = {};
        var keys = getKeys(obj);
        keys.shuffle();
        for (var key in keys){
            if (key == "shuffle") continue; // skip our prototype method
            new_obj[keys[key]] = obj[keys[key]];
        }
        return new_obj;
    }
 Now to use this from your program, you can do it like this:
obj = shuffleProperties(obj); // run shuffle
With overwriting our original obj with the returned object from the shuffleProperties() method we can now use our obj as though we had just shuffled the properties around.

Here is the complete code:
var obj = {
        "red":"RED",
        "blue":"BLUE",
        "green":"GREEN",
        "yellow":"YELLOW",
        "purple":"PURPLE"
    };
   
    Array.prototype.shuffle = function(){
        for (var i = 0; i < this.length; i++){
            var a = this[i];
            var b = Math.floor(Math.random() * this.length);
            this[i] = this[b];
            this[b] = a;
        }
    }
   
    obj = shuffleProperties(obj); // run shuffle
   
    function shuffleProperties(obj) {
        var new_obj = {};
        var keys = getKeys(obj);
        keys.shuffle();
        for (var key in keys){
            if (key == "shuffle") continue; // skip our prototype method
            new_obj[keys[key]] = obj[keys[key]];
        }
        return new_obj;
    }
   
    function getKeys(obj){
        var arr = new Array();
        for (var key in obj)
            arr.push(key);
        return arr;
    }
If you have improvements or suggestions, please leave a comment. Thanks!

Thursday, February 3, 2011

Copy Vector in AS3

Problem: 
When dealing with complex datatypes, you will find the normal assignment doesn't work to make a copy as it does with simple datatypes like int, string, etc.
var vec:Vector. = oldVec; // returns the same object - not a copy!
In short, all this does is passes the reference to the complex datatype so that it now has two variables that point to the same data. Therefor manipulating the oldVec variable would reflect in vec and visa vera.
vec.push("hello"); // this is manipulating the object at the reference - in other words, vec and oldVec still contain the same thing including the new string "hello".

Solution:
With some complex objects (generally visual components), there is a 'clone' method available which allows deep copying of the complex datatype so that you have two separate datatypes. Others have written methods which will copy your data. If you are looking for a shallow copy, Vector provided a concat() method which when passed no parameters, returns a copy of your original vector.
var newVec:Vector. = oldVec.concat(); // returns a shallow copy
Note: Shallow copy means that if you have a vector of complex datatypes, only so many depths are copied to the returned vector object. This solution works well for shallow copies of vectors containing simple datatypes (i.e. int, uint, string, etc.).

Wednesday, February 2, 2011

CodeIgniter - Library class not found when upgrading to CI 2.0

Problem: 
If you have recently upgraded your CodeIgniter framework to their recent 2.0 release, you have have run into some issues, that were not covered in the upgrade guide or in the user manual. A specific error I ran into was a file not found when a controller was looking for it's parent class. The parent class happened to be a general Controller file that extended the CI native Controller class (now should be CI_Controller with 2.0). The class I had written called MY_Controller could not be found.

Solution:
After looking around online I finally found the solution. What was failed to be mentioned in the documentation was that your extending class files should be moved from the 'libraries' folder to the new 'core' folder. This solves the issue.

Thanks for this thread for revealing the solution.

Friday, January 21, 2011

MySQL Warning - Out of range value for DATETIME column 'expire' at row 1

Problem:
While writing a web site I found I needed to update a field in a table with the current date plus 3 days.

Query:
UPDATE `user` SET `expire` = 'DATE_ADD(NOW() + INTERVAL 3 DAY)' WHERE `email` = '[email protected]';

mySQL Warning:
Warning 1264: Out of range value for column 'expire' at row 1

Solution:
After reading some I found that the solution was to remove the quotation marks around the DATE_ADD() method. It make sense since the method is run by mySQL and the quotation marks mean for mySQL to interpret this as a string.

Note: You can also remove the DATE_ADD method altogether, mySQL understands how to do the math by the addition sign.