April 1, 2015

Faking PhantomJS's userAgent in Nightwatch.js

While working on some odd behavior with a PhantomJS driven Nightwatch.js test I had a need to change the userAgent that PhantomJS was reporting. Turns out there is a simple way to do this in the configuration file:

"desiredCapabilities": {
    "browserName": "phantomjs",
    "javascriptEnabled": true,
    "acceptSslCerts": true,
    "phantomjs.page.settings.userAgent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36"
}

I suspect a similar technique can be used for many of the PhantomJS settings.

Tags: nightwatch phantomjs programming testing

September 30, 2012

Sharing Code Between Node.js Applications

Last night my colleague Tim Walling and I gave a a talk the Node.js in the wild Meetup on Sharing Code Between Node.js Applications. This was based on our experiences growing a code base to support the backend for RumbleTV Baseball and RumbleTV Football. I've posted the slides with notes. Happy to answer any questions.

Tags: javascript nodejs programming

August 28, 2011

JavaScript: The Good Parts

JavaScript: The Good PartsJavaScript: The Good Parts by Douglas Crockford

My rating: 4 of 5 stars


An appropriately opinionated exploration of JavaScript. The exhaustive diagraming of the language syntax and common methods can be skipped by those who have used the language before. The observations in the chapters on Functions (4), Inheritance (5), Style (9), and lists of gotchas in appendices Awful Parts (A) and Bad Parts (B) make this a must read for anyone developing with JavaScript. The author has a very strong point of view that is presented throughout the book, but I found warranted given the number of ways on can unintentionally harm yourself in JavaScript.



View all my reviews

Tags: books javascript programming

March 30, 2010

Programming Language Trends

One idea that "The Passionate Programmer" recommends that I've always been intrigued by is the idea of mapping hot technologies along an early, middle and late adoption trend and seeing where the technologies you work with fall. It is a subjective exercise but does help you think about what is out there. Turns out for programming languages (not frameworks or toolkits) TIOBE Software has for some time now been producing a Programming Community Index that ranks programming languages. They have a methodology that I'm inclined to call good enough for most cases.

Tags: data programming

August 31, 2006

Fail Fast in Eclipse?

Is there a way to make Eclipse abort the build process as soon as the first compilation bug occurs? I've been working with Flex Builder 2 for some time and one of the things that bugs me is that if a base project has an error, Eclipse still tries to compile all of the other projects which depend on it. While sometimes this helps show all of the possible errors that might appear, more often then not, I don't want to waste the time waiting for the failed build to finish. This has become especially true since adding some external Ant tasks to handle other build features that Eclipse isn't doing out of the box. I've been over the preferences but didn't see anything that made sense so if you happen to know, please pass along this nugget. Keep in mind I'm running Eclipse 3.1.2 and can't upgrade to 3.2.

Tags: eclipse programming

July 30, 2006

Flex 2 Runtime Error 1065

Today while working on some code I started getting this error and stack trace:

ReferenceError: Error #1065: Variable LoadTest is not defined.
	at global/flash.utils::getDefinitionByName()
        at ... (rest of stack trace deleted)

Looking the error up in the documentation didn't help point the way to what might be going on since this had nothing to do with a "variable":

1065 Variable _ is not defined. You are using an undefined lexical reference. For example, in the following statements, the statement trace(x) generates an error because x is undefined. However, the statement trace(y) doesn't generate an error because y is defined: trace("hello world") trace(x) // x is undefined var y trace(y) // No error, y is defined.

In this case I was trying to dynamically instantiate a class by first finding the definition of that class and then newing it. Something like this:

public function createInstance(className:String):Object {
    var instance:Class = Class(getDefinitionByName(className));
    new instance();
}

It turns out the reason why the error was being thrown was that in my Flex Application I didn't have anything which "used" the class. In other words the compiler thought that the class was left over junk and didn't include it in the compiled swf. By adding in a use of it, everything started working. As example use would be something like:

private static const loadTestRef:LoadTest = null;

If there is another way to get this same behavior, please let me know.

Tags: actionscript as3 flex programming

July 30, 2006

Flex 2 Runtime Error 1009 and Runtime Modules

While the following error is most often encountered when trying to access a property or function through a null object reference, it can also rear its head when working with runtime modules.

TypeError: Error #1009: Cannot access a property or method of a null object reference.
	at mx.containers::Panel/mx.containers:Panel::layoutChrome()
	at mx.core::Container/mx.core:Container::updateDisplayList()[C:\dev\GMC\sdk\frameworks\mx\core\Container.as:2910]
	at mx.containers::Panel/mx.containers:Panel::updateDisplayList()
	at mx.core::UIComponent/validateDisplayList()[C:\dev\GMC\sdk\frameworks\mx\core\UIComponent.as:5672]
	at mx.core::Container/validateDisplayList()[C:\dev\GMC\sdk\frameworks\mx\core\Container.as:2731]
	at mx.managers::LayoutManager/mx.managers:LayoutManager::validateDisplayList()[C:\dev\GMC\sdk\frameworks\mx\managers\LayoutManager.as:594]
	at mx.managers::LayoutManager/mx.managers:LayoutManager::doPhasedInstantiation()[C:\dev\GMC\sdk\frameworks\mx\managers\LayoutManager.as:646]
	at Function/http://adobe.com/AS3/2006/builtin::apply()
	at mx.core::UIComponent/mx.core:UIComponent::callLaterDispatcher2()[C:\dev\GMC\sdk\frameworks\mx\core\UIComponent.as:7789]
	at mx.core::UIComponent/mx.core:UIComponent::callLaterDispatcher()[C:\dev\GMC\sdk\frameworks\mx\core\UIComponent.as:7732]

The problem seems to be that if the runtime module makes a side-effect reference to a component, which is not included in the main application, it never really gets included in the SWF and as such causes problems when accessed. That's a jumble of words so I think an example is needed.

Create a Flex Application with two files in it. The first one is called com.example.PanelComp.mxml:

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" width="400" height="300">
    <mx:Text text="Hi"/>
</mx:Panel>

The second one is the main application, call it LoadTest.as:

package {
    import com.example.PanelComp;
    import mx.core.SimpleApplication;

    public class LoadTest extends SimpleApplication {
        private static var panelComp:PanelComp;
    }
}

For more information on that SimpleApplication business check out Roger Gonzalez's blog.

Now in a different Flex Application we want to load the first application and then create an instance of PanelComp.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
    <mx:Script>
        <![CDATA[
            import mx.containers.Panel;
            import flash.utils.getDefinitionByName;

            // must uncomment for "Add Panel" to work
            // TypeError: Error #1009:
            // private static const panel:Panel = null;

            private var _loader:Loader;

            private function loadSwf(location:String):void {
                _loader = new Loader();
                var ctx:LoaderContext = new LoaderContext();
            	ctx.applicationDomain = ApplicationDomain.currentDomain;
            	_loader.contentLoaderInfo.addEventListener(Event.INIT, swfInit);
                _loader.load(new URLRequest(location), ctx);
            }

            private function swfInit(e:Event):void {
                _loader.content.addEventListener("ready", swfLoaded);
            }

            private function swfLoaded(e:Event):void {
                trace("Loaded");
            }

            private function createPanel():void {
                var clazz:Class = Class(getDefinitionByName("com.example.PanelComp"));
                // see note above about TypeError: Error #1009:
                addChild(new clazz());
            }
        ]]>
    </mx:Script>
    <mx:Button label="Load" click="loadSwf('../../LoadTest/bin/LoadTest.swf');"/>
    <mx:Button label="Add Panel" click="createPanel();"/>
</mx:Application>

As noted in the comments, until you uncomment the static reference to Panel in the wrapper application, you will get the stack trace. Something to keep in mind if you are using runtime modules.

Tags: actionscript as3 flex programming

June 30, 2006

Dynamic Interface

I would like a way in AS3 to define an interface as being dynamic. In some cases I want all classes that implement an interface to also have to be dynamic. Why might this be useful? I find the chained property accessors much nicer to deal with. I'm not as concerned about adding new methods to the interface and some of the other stuff that you can do with a dynamic class, I just want easy access to unspecified attributes. The fact that you can still use the associative array style lookup on an interface to get the same result only strengthens my belief that you should be able to mark an interface as dynamic.

Since you can't apply the dynamic keyword to an interface and there doesn't seem to be a system interface that endows dynamicness on an interface, you are forced to either use looser typing or use the alternative syntax. I think this calls for an example.

Say I have this interface defined:


package com.example {
public interface ISample {}
}

In another class I have a method that uses that interface:


package com.example {
public class UseSample {
public function displayProp(sample:ISample):void {
trace(sample.prop);
}
}
}

That generates the lovely compiler error:
1119: Access of possibly undefined property prop through a reference with static type com.example:ISample.

If you change the code to use array syntax it will compile:


package com.example {
public class UseSample {
public function displayProp(sample:ISample):void {
trace(sample["prop"]);
}
}
}

In my mind the array syntax is much more obtuse. Oh well, I can always hope :)

Tags: actionscript as3 flex programming

June 30, 2006

Events in Flex 2

Today I got a familiar error while working with some event code:

TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event@35f04c1 to com.neophi.events.CustomEvent.

The short answer is that this error results from failing to implement a clone() method on a custom event class. The long answer is that most of the time not implementing a clone() method won't hurt you, based on how you use your custom events, but you really should create one. In fact the Actionscript 3 (AS3) documentation is pretty clear about this:

When creating your own custom Event class, you must override the inherited Event.clone() method in order for it to duplicate the properties of your custom class.

This is a time that I wish AS3 had abstract methods.

Why I say you don't really need a clone() method is that it only becomes an issue if you relay an event. The follow code is an example of event relaying:

private function relay(customEvent:CustomEvent):void
{
    dispatchEvent(customEvent);
}

In this case an event listener redispatches the event that it got. When this happens the event framework behind the scenes calls the clone() method to create a new instance of the event. If you don't have a clone() method and the next listener in the chain is expecting an instance of CustomEvent, the error from above happens. If instead that same listener was only expecting an instance of the Event class, it would work, but any additional information contained in CustomEvent class would be lost, including the ability to cast it to an instance of CustomEvent.

In most cases the clone() method is simple to implement; just transfer any constructor arguments to a new instance of the class. Something like:

override public function clone():Event
{
    return new CustomEvent(_message);
}

Based on the type of event you will probably have more arguments including the all important type and often the other standard event variables for bubbling and cancelability.

While I'm on the subject of events I'll also talk about Event metadata or annotations that you can apply to classes. Often if you have an AS3 class that can emit custom events you will add metadata like this at the top:

package com.neophi {
    import com.neophi.events.CustomEvent;

    import flash.events.EventDispatcher;

    [Event(name="customChange", type="com.neophi.events.CustomEvent")]

    public class EventSource extends EventDispatcher {
        // class code removed 
    }
}

The thing to keep in mind is that depending on how this class will be used you probably don't need that metadata. If this AS3 class isn't used in MXML you can skip the metadata. The metadata is only used to inform the compiler how to translate an MXML event attribute into the appropriate code.

For example with the above class and metadata you could use it in MXML like this:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:neophi="com.neophi.*">
<mx:Script>
<![CDATA[
import com.neophi.events.CustomEvent;

private function customChanged(customEvent:CustomEvent):void
{
    output.text += "EventTest: " + customEvent + "\n";
}
]]>
</mx:Script>
<neophi:EventSource id="eventSource" customChange="customChanged(event);" />
<mx:Button label="Go" click="eventSource.source();"/>
<mx:TextArea id="output" width="100%" height="400"/>
</mx:Application>

Because cutomChange is defined in the metadata for the EventSource class, in MXML you can now assign a handler to that event. In this case the method customChanged will be called whenever our instance of EventSource dispatches that event.

The method the button is calling to cause eventSource to fire the event is:

public function source():void
{
    var customEvent:CustomEvent = new CustomEvent("Event Message");
    dispatchEvent(customEvent);
}

This code is part of the EventSource class listed above. A new instance of CustomEvent is created and then dispatched. At this point all listeners will get called.

If you tried instead to assign the customChange handler in MXML without the metadata in EventSource you would get a compile error like this:

Cannot resolve attribute 'customChange' for component type com.neophi.events.EventSource.

For events then the two rules of thumb are:

  1. always create a clone() method in any custom event class
  2. add event metadata if you will need to setup handlers for that event in MXML

Tags: actionscript3 as3 events flex programming

June 30, 2006

Regular Expressions

I've been playing around with Flex 2 for some time at work. One of the neat things that Actionscript 3 adds is native regular expressions. As part of an ongoing effort to share knowledge I volunteered to give an informal talk about regular expressions. To help with the talk I created this visual regular expression viewer. It helps show you what matched along with any groupings and other standard stuff. Additionally it can also perform a regular expression replace operation or a simple split operation.

You will need the Flash 9 in order to run the application.

Launch RegExp Tester!

If you find any bugs, have comments, etc. please leave me a comment.

Tags: actionscript as3 programming regexp regularexpression

May 31, 2006

Hacking Movable Type

While playing with the new tags feature I started with adding it to the main page of my site. The problem is that my older posts don't have any tags associated with them. The naive approach would just attach an empty "Tags: " line to each of those old posts. But even for my unskilled UI hacking skills that would be lame. There doesn't seem to be any kind of way to get the count of the number of tags associated with an entry in the Tags.app API. Doing some digging I did run across the MTIfNonEmpty template tag. I figured I could use that along with the MTTagsList widget to determine if a post had any tags.

Alas, it didn't work. Looking at the generated HTML there was a lot of excess whitespace. Thankfully I stumbled onto the trim filter. The documentation seems to indicate that the trim filter applied to the MTIfNonEmpty template tag would solve my problem.

Alas, it didn't work. After adding some debugging output to the MTIfNonEmpty template tag and the trim filter it looks to evaluate the value returned by the tag before applying the filters to the value. As a result the whitespace isn't getting trimmed correctly. Instead of trying to figure out why the call order looks to be out of order, I decided to take the easier approach and modify the definition of the MTIfNonEmpty test. The diff is below:

*** ./lib/MT/Template/ContextHandlers.pm~ Wed Aug 17 17:50:11 2005 --- ./lib/MT/Template/ContextHandlers.pm Thu May 4 23:54:42 2006 *************** *** 493,499 **** my $handler = $ctx->handler_for($args->{tag}); if (defined($handler)) { my $value = $handler->($ctx, { %$args }); ! if (defined($value) && $value ne '') # want to include "0" here { _hdlr_pass_tokens($ctx, $args, $cond); } else { --- 493,499 ---- my $handler = $ctx->handler_for($args->{tag}); if (defined($handler)) { my $value = $handler->($ctx, { %$args }); ! if (defined($value) && $value !~ /^\s*$/) # want to include "0" here { _hdlr_pass_tokens($ctx, $args, $cond); } else {

In short the template tag now considers any value that is only whitespace as being empty. I think given the nature of HTML (or XHTML) and optional whitespace, that this is a reasonable interpretation. Now to add the tags to other pages on the site, tag some of my older posts, and then see what my tag cloud starts to look like.

Tags: movabletype mt programming tags

May 31, 2006

Flex Beta 3

For anyone following Flex, beta 3 is now available.
From my experience, Flex Builder is much improved but there are still many quirks with it. There were quite a few Actionscript 3 language changes, but the documentation on them is good. My biggest complaint so far is that many MXML files in a Flex library project are not being handled properly by the MXML Editor which results in a complete lack of code assist. The same MXML file in a Flex Application works fine. I've not completely figured out why some of the files are so broken, especially when they seem to work fine on another user's system.

Tags: actionscript as3 flex programming

May 31, 2006

BFPUG Patterns Meeting

Tonight I attended the BFPUG Patterns Meeting. It was a small group of about a dozen people. The topic was the Factory pattern. An overview of the pattern and a few conceptual examples were given. Another participant and I then each gave an example of the pattern in code we are currently working on. When I got home I realized that my old roommate actually owned the copy of the Design Patterns book that I've referenced in the past. I wanted to reread the differences between the Abstract Factory Pattern and the Factory Method Pattern. Time to pick that up. Next month's pattern is tentatively the Decorator Pattern.

Tags: bfpug patterns programming

April 30, 2006

Actionscript 3 Class.forName

I'm sure this would be obvious for anyone that has been programming in Actionscript 3 for awhile, but coming in from the Java world I'm still trying to find the matching idioms. In particular I wanted a way to dynamically load a class based on its name. In Java this is the Class.forName() construct. Luckily AS3 also has a similar mechanism:

// return the class as a Class object
var temp:Class = flash.utils.getDefinitionByName("com.example.Sample") as Class;
// you can now call new it to create an instance along with passing constructor args
var instance:Object = new temp(arg1, arg2, ...);

If when doing this you get an "Runtime Error 1065" see this post.

Note: Update Nov 6, 2007
It looks like flash.util.getClassByName() has gone away. The example above has been updated to use the new mechanism called flash.utils.getDefinitionByName().

Tags: actionscript as3 programming

April 30, 2006

Flex 2, Actionscript 3, and E4X

I've found a feature of Actionscript 3 (AS3) that I've not seen in other languages that I think is pretty cool. It's taken me awhile to come to terms with it, but now that I've getting more comfortable with it I'm really starting to appreciate it. That feature is what is known as E4X or more officially Standard ECMA-357 ECMAScript for XML (E4X) Specification. At its core is the ability to work with and manipulate XML data in AS3 using standard language syntax instead of having to do everything through an API.

For example to create a variable that contains some hard coded XML you could just write:


var xml:XML =
<componentPackage>
<component id="MyButton" class="package1.MyButton"/>
<component id="MyOtherButton" class="package2.MyOtherButton"/>
</componentPackage>;

Notice the lack of any "new XML("")" or other traditional methods one might use to create an XML document. Pretty cool stuff. You can also do variable substitution when creating XML:


var attributeName:String = "class";
var xml:XML =
<componentPackage>
<component id="MyButton" {attributeName}="package1.MyButton"/>
<component id="MyOtherButton" {attributeName}="package2.MyOtherButton"/>
</componentPackage>;

That creates an XML document that looks exactly like the first XML example. Not the most convincing example, but you get the idea. You can substitute element names, attribute names, or whole attribute values. Besides being able to do inline XML document creation you can also do DOM style navigation to get at elements and attributes within the XML (these return XML or XMLList objects). Going back to the first XML example:


xml.component[0]; // <component id="MyButton" class="com.example.ui.MyButton"/>
xml.component[0].@id; // MyButton

Where things get really cool is the XPath like operations, technically called filters since it isn't as expressive as XPath:


xml.component.(@id == "MyButton"); // <component id="MyButton" class="com.example.ui.MyButton"/>

That searches for all component elements under the root that have an id of MyButton. There are a bunch more. In fact the Working with XML (doc link subject to change) section of the Flex 2 documentation has many good examples. It's at this point that I want to offer a hard learned lesson about what doesn't work with E4X (at present anyway, I can only hope that it will be solved in a future Flex 2 release).

The following line of code doesn't compile (again using the first XML example from above):


xml.component[0].@class; // Error: Expecting identifier before class

The reason is that "class" is a reserved keyword. Thankfully E4X provides alternative attribute access syntax, an example is:


xml.component[0].@["class"]; // package1.MyButton

A little clunky, but still reasonable. What I haven't been able to get working is any of the alternative syntaxes when trying to do a filter using the same attribute:


xml.component[0].(@class == "package1.MyButton"); // Error: Expecting identifier before class

I've tried all four listed variations: element.@attrName, element.attribute("attrName"), element["@attrName"], and element.@["attrName"]. None of them work in the above example, adjusted of course to account for the () filtering operation. This afternoon I finally stumbled upon a solution. This is even more clunky then the alternative attribute accessors, but it does eliminate the need to write custom loops to handle filters like the one above:


xml.component.(@\u0063lass == "package1.MyButton"); // <component id="MyButton" class="com.example.ui.MyButton"/>

In this case I'm using the Unicode value for the letter c (0063) which to my surprise worked. As I said earlier I hope this keyword issue is just a beta issue and it will be resolved. If not, consider using this approach to construct E4X filters that might reference AS3 keywords.

Tags: actionscript as3 e4x flex programmin xml

April 30, 2006

Actionscript 3 FAQ

Mike Chambers is asking for input on improving the Actionscript 3 FAQ.

Tags: actionscript as3 faq programming

April 30, 2006

Private or Helper Classes in Actionscript 3

I didn't find this well documented when I was looking it up so I thought I'd post a sample. While Actionscript 3 (AS3) doesn't support protected and private classes like Java does, you can have helper classes that are only visible within the file that they are defined. The syntax for them is a little weird but the Flex 2 Beta 2 compiler seems to like it. The syntax is that after the package you define the helper class:

package com.example {
     public class Sample {
          private var _helperClass:HelperClass = new HelperClass();
     }
}
// imports for the helper class go here
import com.example.xml.SaxHandler;
class HelperClass {
     private var _saxHandler:SaxHandler;
}

Tags: actionscript as3 programming

April 30, 2006

Life is Good

Life is good right now. At work this week we managed to get enough plumbing put together to have a first front-to-back communication of the application. It's always nice to have something that is starting to hang together even if some pieces of it are stubbed out. After work today Gilman Manor had the third consecutive week of grilling. Yummy chicken this time. I also attempted some grilled potatoes, but my foil wasn't quite heavy duty enough so a few of the potatoes got a little burned. I also made a batch of corn bread that was good. Not 100%, but this was my first attempt at corn bread from scratch and it turned out much better than the potatoes (which was my second attempt). At least this time the potatoes were somewhat edible, unlike my first attempt. My grill is a little too hot sometimes. Gilman Manor residents also played a bunch of poker tonight which was cool. Lastly, I've got more Tour of Duty to watch :)

Tags: bbq food gilmanmanor life programming

April 30, 2006

Pair Programming

Most of today and the later half of yesterday afternoon I spent pair programming. While I've collaborated for short periods of time with other coworkers, this is by far the first concentrated time I've spent doing it. Overall I'm inclined to believe most of what the advocates claim about pair programming. We created a lot of code and most of it worked on the first run. We didn't practice a TDD approach, but did make sure that good unit tests existed. Some of the simple issues that still came up even with two sets of eyes on the code were simple compile time errors like missing imports and changed method signatures on system APIs (the downside of working with a beta of Flex 2).

Unlike a "true" paired programming session, I didn't do much typing. I think this stemmed mostly from the fact that our development systems are laptops. It isn't as easy to slide the keyboard and mouse over to your partner in this case. Even though I wasn't doing the typing, I contributed to the code by helping spot potential issues (syntactic and strategic) while duplicating knowledge on some of the more potentially error prone plumbing of the system.

Tags: pair programming tdd work