Stay on Target

June 24th, 2010 1 comment

After I was accepted into the novitiate, the Vocation Director offered a warning that the time before entrance day could be very difficult. He was right on the nose with that one. Despite my best efforts to stay on task, my prayer life has been slipping. I need to refocus what I’m doing and get back on track.

Stay on Target

There are a number of books I should be reading right now that could help me prepare, but instead I’ve been bingeing the Dresden series. It’s really started getting good and I’m just tearing through them so fast that it’s really satisfying, but I think it has contributed to my present situation. Normally I institute a very strict policy for myself that I can read only one fantasy novel between my non-fiction books. This keeps me from going off the deep end and losing myself into rich series, like I did with the Wheel of Time back at Rowan. I’ve let myself become lax, and that will have to change.

As soon as I finish reading the 9th book in the series, I’ll be jumping back into The First Jesuits, which is incredibly interesting, but reads like an encyclopedia. Still, it is one of the books I’m supposed to be reading in preparation for entrance day, and I’ve let it slide now for too long.

What about you folks out there? Is there something going on that you’ve lost sight of, something you need to refocus, to stay on target?

Indivisible

May 2nd, 2010 1 comment

St. Augustine probably did more good than bad with his writing, but it doesn’t help me be any less frustrated. City of God, City of Man, two worlds which collide at an invisible line between the real and the unreal. The concept wasn’t his, but I still blame him for the popularity in common thought. Without Augustine, would we really have this all-pervasive gnostic sense about our own selves? Would we really see the spirit and the body as two separate entities? How different would our actions be if we never turned over the idea, if instead we knew ourselves as a whole, indivisible and inseparable from the here and now.

That’s the biggest problem I have with gnostic ideas. It’s not that there isn’t anything to be learned by classifying and delineating, but when we attribute individual value and stop seeing our bodies as part of our souls and vice versa, we stop seeing the entire person. More than that, we stop seeing each other.

There is no path to God through the soul alone. You can’t shed this flesh and ride your spirit alone up to the heavens. The body is not an anchor weighing you down. It is not a prison. All these ideas, they make us see ourselves in such a dark way, as if the only thing of worth were buried beneath a dirty mask. It’s a wonder how people survived with those thoughts at all!

Theology is a little beyond me tonight. It’s late and I’m only up because of an ill-advised nap this afternoon. In a few minutes I’ll be back in bed letting my slumbering mind take me on silly journeys where my cat is the conductor of an illegal space-train. I guess I just needed to get that thought out of my head.

AS3 Duplicate Loaded SWF

April 20th, 2010 4 comments

A really common problem that shows up in a lot of the Flash apps I build is the need to load external files and use them in multiple places. For Bitmaps, that’s not such a big deal. Copying the bitmap data and generating a new bitmap is a one line task. Things get more complex when you try to do the same thing with SWFs, though.

You can’t clone a SWF because you can’t clone a MovieClip in AS3. The problem is actually due to the Shape class. Unlike most of the other core display classes, Shape does not have a clone method. With a bit of recursion, you can duplicate most complex objects, but without Shape things hit a brick wall.

Depending on the type of SWF I’m loading, I’ve found a few silly ways around the problem. If the SWF is just a still image, you can do a bitmap clone in much the same way as you’d handle a normal Bitmap. You lose the ability to scale the vector information smoothly, but sometimes that’s okay. If you have more control of the source SWFs, you can build your assets into Library symbols with some linkage information, then instantiate as you need them. This has been my preferred method in the past as it allows you to perform only one external load, and you can control each instance as a fully vector, fully functional MovieClip object. Sometimes, though, you just don’t have the access and control needed to pull off that method. That’s where this other solution comes in.

Enter DuplicateLoader, another handy utility class from yours truly. This class loads your external SWF as a ByteArray, keeps a reference to it, and then as you need an instance, it processes that ByteArray through a Loader and voila, presto-chango, MovieClip! Simple right? Lets take a look.

package com.tomasino.display
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.SecurityErrorEvent;

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.ErrorEvent;
	import flash.events.IOErrorEvent;
	
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;

	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	import flash.utils.ByteArray;

	public class DuplicateLoader extends EventDispatcher
	{
		private var _byteLoader:URLLoader;
		private var _request:URLRequest;
		private var _instances:Array;
		private var _application:ApplicationDomain = new ApplicationDomain ();
		private var _context:LoaderContext = new LoaderContext ( false, _application );

		public function DuplicateLoader ( url:String = null )
		{
			if (url) load (url);
		}

		public function load ( url:String ):void
		{
			// Cleanup
			destroy ();
			
			// New Instances
			_instances = new Array();
			_byteLoader = new URLLoader ();
			_byteLoader.dataFormat = URLLoaderDataFormat.BINARY;

			// Listeners
			_byteLoader.addEventListener ( Event.COMPLETE, onBytesLoaded );
			_byteLoader.addEventListener ( SecurityErrorEvent.SECURITY_ERROR, onError );
			_byteLoader.addEventListener ( IOErrorEvent.IO_ERROR, onError );

			try
			{
				_request = new URLRequest ( url );
				_byteLoader.load ( _request );
			}
			catch (e:Error)
			{
				trace (e);
			}
		}
		
		public function convert ():void
		{
			if (_byteLoader && _byteLoader.data)
			{
				var converter:Loader = new Loader ();
				converter.contentLoaderInfo.addEventListener (Event.COMPLETE, onConvert, false, 0, true);
				
				try
				{
					converter.loadBytes ( _byteLoader.data , _context);
				}
				catch (e:Error)
				{
					trace (e);
				}
			}
			else
			{
				var e:ErrorEvent = new ErrorEvent ( ErrorEvent.ERROR, false, false, 'No data available to convert');
				dispatchEvent (e);
			}
		}
		
		public function getInstance ():DisplayObject
		{
			var returnInst:DisplayObject;
			if (_instances && _instances.length)
			{
				returnInst = _instances.shift();
			}
			return returnInst;
		}
		
		public function destroy ():void
		{
			// Remove any orphaned instances before loading a new byte-array
			if (_instances && _instances.length)
			{
				while (_instances.length)
				{
					_instances[0] = null;
					_instances.shift ();
				}
			}
			_instances = null;
			_byteLoader = null;
			_request = null;
		}
		
		/*
		 * Event Handling
		 */
		private function onError (event:ErrorEvent):void
		{
			_byteLoader.removeEventListener ( Event.COMPLETE, onBytesLoaded );
			_byteLoader.removeEventListener ( SecurityErrorEvent.SECURITY_ERROR, onError );
			_byteLoader.removeEventListener ( IOErrorEvent.IO_ERROR, onError );
			
			var e:ErrorEvent = new ErrorEvent ( ErrorEvent.ERROR, false, false, event.text);
			dispatchEvent (e);
		}
		
		private function onBytesLoaded (event:Event)
		{
			_byteLoader.removeEventListener ( Event.COMPLETE, onBytesLoaded );
			_byteLoader.removeEventListener ( SecurityErrorEvent.SECURITY_ERROR, onError );
			_byteLoader.removeEventListener ( IOErrorEvent.IO_ERROR, onError );
			
			var e:Event = new Event ( Event.COMPLETE );
			dispatchEvent ( e );
		}
		
		private function onConvert (event:Event)
		{
			var loaderInfo:LoaderInfo = event.target as LoaderInfo;
			var converter:Loader = loaderInfo.loader as Loader;
			converter.removeEventListener ( Event.COMPLETE, onConvert, false );
			_instances.push ( converter.content );
			converter = null;
			
			var e:Event = new Event ( Event.CHANGE );
			dispatchEvent ( e );
		}
	}
}

There are two main segments to the class. The first is the load() method that grabs your external content and loads it up into the ByteArray using a URLLoader. It’s pretty self-explanatory. Following that process, we need to convert the ByteArray into a usable Flash DisplayObject. This type of decode operation is best left to the folks at Adobe. They’ve written some wonderful magic into the Loader class that lets us pass in just about anything to a loadBytes() method and get back a useful object.

Calling the convert() method tells the class that you’d like a new instance of your SWF to be made available. You might be asking, “Why can’t I just use a getter and grab an instance right away?” If you were asking that, kudos. I was asking the same thing myself. The short answer is, Adobe sucks. The long answer is, the Loader class loadBytes() method is asynchronous only. Stupid, right? Right.

If that’s something that annoys you as much as it annoys me, please feel free to vote for change on the Flash Bug Tracker. Maybe we’ll start getting methods with the option to perform the operation synchronously or asynchronously. A simple change like that would allow me to stop making wordy blog posts like this.

Back to the class at hand. We were talking about the convert() method and how it will tell the class to make a new instance available. You can call this guy over and over and over to your heart’s content. Each time you do so, it preps a new instance and stores it. Once the instance is ready, DuplicateLoader fires off a CHANGE event to let you know things have been converted. Finally, you can hit the getInstance() method and get back the handy instance you’ve always wanted.

Now, a few internal notes. DuplicateLoader loads all SWFs into their own LoaderContext to avoid collisions and avoid a nasty security hole left by loadBytes. Also, as soon as you getInstance(), the class gets rid of its reference to that instance. The idea behind this was, when you are done with the SWF, you should be able to just delete it yourself. If I were maintaining a reference in my class as well, poor ol’ garbage collector would never know it was okay to delete it. Also, if there’s an error anywhere in the class, I grab the messages and dispatch them to a nice generic ErrorEvent to simplify event handling. Too many listeners make my head hurt.

If you’d like to see the class in action, here is a sample project that shows it in action. As always, the class is free to use, rip apart, call names, drunk-dial, or whatever floats your boat. I’m always happy to hear your comments and see projects where you’ve found my code useful. Enjoy!

Special thanks to Kristine McDermott for pointing my head in the right direction on this one. She’s such a smarty.

Categories: Computers, Flash

AS3 Synchronous URL (XML) Loading

April 1st, 2010 2 comments

Yes, you read that right, synchronous. After years and years of Flash programming, I finally came across a situation where I needed a synchronous solution over the normal asynchronous alternative. Here’s the quick rundown…

I am building a holiday card creator where little kids can place stamps and words and things to build cards for their friends and family. Once they’re done, they can share the cards via e-mail or Facebook. To send the data, I’m using a multi-part form post via a library written by a real awesome Flash dude. Lets call the service I’m using to send the data, “Service #1″. So far, so good.

Next, the client wanted us to add a profanity filter into the form so keep naughty little kids from spreading their potty-mouths across the interwebz. This filter will be called, “Service #2″.

Here’s where the problem came in. Now, when the users click “send”, I have to submit data to Service #2 first, wait for the asynchronous response, then, if it is valid, submit the data to Service #1. It’s not nuclear physics or anything. And I’d know, cause I learned that stuff back in the day. Unfortunately, this is where Adobe stepped in and ruined my party.

SecurityError: Error #2176: Certain actions, such as those that display a pop-up window, may only be invoked upon user interaction, for example by a mouse click or button press.

Now that I am calling Service #1 in the event handler of Service #2, it is disconnected from the original mouse click action. The result is this really nasty Flash security error. Boo!

I was left with a nasty problem and only a few possible solutions.

  1. Get Service #1 and #2 to execute inside the mouse event handler
  2. Fake a mouse event for Service #1
  3. Combine the services (this one was totally valid and probably the way to go, but I didn’t do it for reasons explained below)
  4. Change the internal operation of the Multi-Part URLLoader class to send a property other than “filetype” and thus bypass Flash Security
  5. Cry
I ended up choosing option #1 since the only challenge was getting Service #2 to execute synchronously. It should be the easiest thing in the world!

Surprise, surprise, getting AS3 to hit a service synchronously is stupidly annoying. My options quickly degraded to choosing between writing my own socket connection and handling everything manually, or figuring out a way to do it in JavaScript, and do it with ExternalInterface. My JavaScript chops, while not great, are better than my experience with socket connections. Thus the following utility class was born:

package com.tomasino.net
{
	import flash.external.ExternalInterface;
	import com.tomasino.external.Availability;
	
	public class SynchronousLoader
	{
		private static var _availability:Boolean = Availability.available;
		private static const LOAD_JS:String = 'function com_tomasino_net_SynchronousLoader_load ( url, params ) { RequestType = function () { try { return new XMLHttpRequest (); } catch (e0) {} try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} return false; }; var xhttp = RequestType (); if (xhttp) { xhttp.open("POST", url, false); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.setRequestHeader("Content-length", params.length); xhttp.setRequestHeader("Connection", "close"); xhttp.send(params); return xhttp.responseText; } else return false; }' ;
		public static function load (url:String, params:String):XML
		{
			var returnObj:String;
			var xmlReturn:XML;
			if (_availability)
			{
				try
				{
					returnObj = ExternalInterface.call (LOAD_JS, url, params);
				}
				catch (e:Error)
				{
					trace ('Could not call XMLHttpRequest via ExternalInterface:', e.message);
				}

				try
				{
					xmlReturn = new XML (returnObj);
				}
				catch (e:Error)
				{
					trace ('Could not parse XML response');
				}
			}
			return xmlReturn;
		}
	}
}

That big mass of javascript that is all condensed to one line does all the hard work. Here it is expanded for your reading pleasure.

function com_tomasino_net_SynchronousLoader_load ( url, params )
{
	RequestType = function ()
	{
		try { return new XMLHttpRequest (); } catch (e0) {}
		try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
		try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
		try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
		return false;
	};
	
	var xhttp = RequestType ();
	if (xhttp)
	{
		xhttp.open("POST", url, false);
		xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xhttp.setRequestHeader("Content-length", params.length);
		xhttp.setRequestHeader("Connection", "close");
		xhttp.send(params);
		return xhttp.responseText;
	}
	else
	{
		return false;
	}
}

Lets take a closer look at what I’m doing here. First, I’m utilizing ExternalInterface to call a JavaScript function that I have hard-coded into my class as a constant. I know that ExternalInterface performs its calls synchronously, so that’s perfect for my needs right away. Second, I learned that the JavaScript object XMLHttpRequest can perform its load operations synchronously or asynchronously depending on a boolean. (One could argue that building Flash’s URLLoader the same way would have made a little more sense than forcing developers to have only one option. Developers without options = angry developers.)

Now XMLHttpRequest is a newer class and some IE versions don’t have it, so I needed to use their weird ActiveXObject versions. You’ll notice that weird little block of try..catches doing the heavy lifting. That’s pulled almost directly from the wiki page for the class. Finally, I need to perform my request. I pass in the URL and the parameters as, well, parameters, then format everything and make my call.

There’s a few things to note. First, without the request headers, the service doesn’t understand what type of data it’s getting, so those are a must. That took some time to figure out. Second, the “params” should be a string of url-encoded name/value pairs, separated by ampersands. At the end, we return back the string of the server response to our flash method. We’ll let Flash try to parse that string into a native XML element. If it works, everyone is happy and you have your results, synchronously. Hooray!!!

Now the caveat: XMLHttpRequest can’t operate across domains. There might be some sneaky ways around that, but it’s out of scope for this solution. If you know a good way, let me know in the comments!

Also, you’ll notice I’m using my Availability class in here. For those that are unfamiliar, all it does is test to see if we are in an environment where ExternalInterface is available. You can make that work your own way, or grab the class from my server… whatever floats your boat.

Finally, and I really mean it this time, I promised I’d explain why I used this solution instead of just combining the services and making one call. To put it simply, AS3 forums pissed me off. I searched around for 15 minutes looking to see if someone had already solved my problem for me (like you are likely doing right now), only to find a frustrating number of post replies saying things like, “Why are you trying to do it synchronously?! That’s NEVER a good solution. Whine-whine-whine…” Sometimes I just wish people would answer the questions asked instead of going off on nerd-rants. Oh well!

Enjoy, comment, share, modify, whatever. Have a blast.

(Comments on this post disabled due to horrible spam-pocalypse)
Categories: Computers, Flash

Acceptance

March 13th, 2010 1 comment

And He began telling this parable: “A man had a fig tree which had been planted in his vineyard; and he came looking for fruit on it and did not find any.

“And he said to the vineyard-keeper, ‘Behold, for three years I have come looking for fruit on this fig tree without finding any. Cut it down! Why does it even use up the ground?’

“And he answered and said to him, ‘Let it alone, sir, for this year too, until I dig around it and put in fertilizer; and if it bears fruit next year, fine; but if not, cut it down.’”
    - Luke 13:6-9 (The Parable of the Fig Tree)

Some of the people I’ve met recently can point to one or two parables or passages in the Bible and say, “Look at that! That is where I found God’s purpose for me!” I’m not sure I ever saw a message so personal or clear in any particular thing. I identify with a lot of different biblical stories. As most of you know, I like to make a lot of analogies and find metaphor in just about everything that crosses my path. Maybe that has kept me from developing a special bond with any one thing; there’s too much to choose from.

The parable of the fig tree, though, has long managed to fall into a special category, or perhaps I should say a lack of category. It’s not that I don’t understand it, and it’s not that I can’t place its meaning in my life. The fig tree has some other element to it, an element of the numinous, ineffable sacred. I suppose, if you allow me to personify it a bit, the parable is like a man facing away from me. I know he is a man. I see what he is about and what he is doing, but his face is hidden.

A few minutes ago, I experienced a totally cheesy, totally predictable twist. At least, that’s how I’d describe it if my life were a movie. As I read the passage again that person/parable turned around to face me and there I was, staring back at myself. I told you it was predictable!

I’ve been learning to pray by placing myself in the scenes, becoming the actors, becoming onlookers, really being there. I have no idea why I never put myself into the position of that tree before, but the moment I realized it things woke up inside me.

How do I see myself? Am I worthy of being saved? How much longer can I go on “bearing no fruit”? If I am tended to, if I make the right decisions and respond to what my vineyard-keeper is trying to sow in my life, will I have a real worth? What is my fruit? It is love (caritas), obviously! Charity is the fruit that becomes the seed, that grows and spreads and falls again and again… The questions, the metaphors, they go on and on until I catch myself shaking my head back and forth in wonder at the blindness of a moment ago, of a lifetime ago.

This is what contemplative prayer is. It is waking up. It is suddenly having words stop being words in such a profound way that you shake your head at your former self, wondering how you could have ever been that person. It is waking up in a moment and knowing, just knowing, that you are making the right decision.

On that note, I received word that I have been accepted to enter the tri-state novitiate for the Maryland, New York, and New England Provinces of the Society of Jesus this summer.

Acceptance Letter

The letter represents a culmination of a decade of discernment, countless hours of writing, of reading, and prayer; and yet this is just another beginning. It is a milestone, a thing to be celebrated with joy and excitement, but I can’t fool myself into thinking I have really accomplished anything yet. I still stare at my branches and see no fruit. Maybe this represents buds?

I try more and more every day to live my life like I am fully in bloom, to share the love and faith and my sense of joy in the Lord. Soon I will have more support in that respect than I’ve ever known. I will also have people pushing me (and pulling me, I’m sure) to do more, to be more, to grow in that relationship of faith. The idea is so amazing, I can’t even come up with a pretty metaphor!

New things are on the horizon. I love new things.

To those of you who have been praying for me, thank you so much for absolutely everything. If you have a moment, join me in praying for the other (currently anonymous) souls who are still in the long discernment/application process. God bless!