How to catch Stream Error in ActionScript - actionscript-3

I have the following piece of code, which attempts to GET a publicly hosted (AWS S3) file.
private function ShowS3Message():void
{
// Attempt to download file from AWS
var descriptor:XML = NativeApplication.nativeApplication.applicationDescriptor;
var ns:Namespace = descriptor.namespaceDeclarations()[0];
var url:String = "https://s3.amazonaws.com/some-url/file-" + descriptor.ns::versionLabel.split(".").join("-") + ".txt";
var urlRequest:URLRequest = new URLRequest(url);
// Set up callback function
try{
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, awsFetchCallback);
loader.load(urlRequest);
}catch(error:Error){}
}
This is the callback function:
/**
* Callback function for AWS message file
*/
private function awsFetchCallback(event:Event):void
{
var data = event.target.data;
// show dialog
var msb:InformationMessageBox = new InformationMessageBox();
msb.mText = data;
msb.open(this, true);
}
When the file exists, there is no problem, and the code runs fine.
When the file doesn't exist, this throws a StreamError, despite the catch block.
what am I missing?

You should capture the IO error event, there is not exception thrown when the file does not exist.
loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
and then create your own error handler function.
more details in the doc here :
https://help.adobe.com/fr_FR/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html
If you just want to drown the error (because you seem to know the file may not exist sometimes) it is sufficient to create an empty error event handler.

Related

getting POST using URLRequest + if statement syntax issue

I'm trying to get the reply from the address specified in var url:String, which is either 0 or 1. If the reply is 1 then it must set currentState = CallFailed (as seen below). The client compiles without error (using Adobe Flash Builder 4.6) and seems to successfully reach var url:String, but doesn't seem to be getting the response\and or my if statement is incorrect.
Actionscript:
// check to see if block.php replies 0 or 1
var url:String = "https://domain.com/block.php?postid=" + calleeInput.text + "";
var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
request.data = variables;
request.method = URLRequestMethod.POST;
navigateToURL(request);
if (request.data == 1)
{
// if reply is 1 then cancel the call
currentState = CallFailed;
return;
}
PHP:
PHP will echo 0 or 1 when block.php is loaded. It's not encoded in any format such as JSON\AJAX.
It seems you want data from the server. Perhaps the URLLoader class would be better?
var url:String = "https://domain.com/block.php?postid=" + calleeInput.text + "";
var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
request.data = variables;
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener( Event.COMPLETE,
function( e:Event ) : void
{
// your response data will be here
// you'll have to verify the format
trace( e.target.data );
}
)
loader.load( request );
Put a breakpoint at the trace statement and check out the contents of e.target.data, and go from there
The purpose of navigateToURL() is to open the webbrowser, as stated in its documentation:
Opens or replaces a window in the application that contains the Flash Player container (usually a browser). In Adobe AIR, the function opens a URL in the default system web browser
In order to perform an request (without opening a browser, just the HTTP communication) you should use URLLoader.
The URLLoader class downloads data from a URL as text, binary data, or URL-encoded variables.
On a related note: your logic is not valid. The call to a server is asynchronous. You have to wait for the response to be returned before reasoning about the result.
The URLLoader class dispatches a number of Events that help you decide when the result of a request is returned or if there's a problem with it.

Deal connection lost in ActionScript 3

I have this code:
public function Json2Me(_urlJSON:String) {
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest();
request.url = _urlJSON;
loader.addEventListener(Event.COMPLETE, onLoaderComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR,informadorIO);
loader.load(request);
}
private function onLoaderComplete(e:Event):void{
var loader:URLLoader = URLLoader(e.target);
JSONEnviado = com.adobe.serialization.json.JSON.decode(loader.data);
dispatchEvent(new Event("LanzaJSON"));
}
public function informadorIO(e:Event):void{
trace(e);
}
I need to protect my code against connection lost, so what I have to do to keep my project running?
You can catch the IO errors on url loader:
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
private function ioErrorHandler(event:IOErrorEvent):void {
// URLLoader io failed
trace("ioErrorHandler: " + event);
// retry Json2Me maybe? How many times before you fail completely? Notify user?
Json2Me("https://someurl.com/xxxxx")
}
Also the uncaughtErrorEvents on the Loader/LoaderInfo can catch things like not even having a network connection.
LoaderInfo.uncaughtErrorEvents: to detect uncaught errors in code
defined in the same SWF. Loader.uncaughtErrorEvents: to detect
uncaught errors in code defined in the SWF loaded by a Loader object.
Example:
loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);
private function onUncaughtError(e:UncaughtErrorEvent):void {
e.preventDefault();
trace("onUncaughtError!!! - " + e.toString());
// Notify user of failure?...
}
You can also use a HTTPStatusEvent which can give use the returned HTTP status ( or even the returned HTTP response headers for an AIR app ) :
var url_loader:URLLoader = new URLLoader()
url_loader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, on_http_status); // works only for AIR
url_loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, on_http_status);
url_loader.load(new URLRequest('http://www.example.com'))
function on_http_status(e:HTTPStatusEvent): void
{
trace(e.type); // gives, for example : httpStatus
trace(e.status); // gives, for example : 200
}
Hope that can help.

Running-order of nested function-calls delayed/altered due to URLloader in AS3?

First of all: English is not my first language. ;-)
I am compiling the following code:
var sqldata:String;
function sql(saveorload,sqlstring) {
var sqlloader = new URLLoader();
var sqlrequest = new URLRequest("http://***/sql.php");
sqlrequest.method = URLRequestMethod.POST;
sqlloader.addEventListener(Event.COMPLETE, sqldonetrace);
var variables:URLVariables = new URLVariables();
variables.sqlm = saveorload;
variables.sqlq = sqlstring;
sqlrequest.data = variables;
sqlloader.load(sqlrequest);
}
function sqldonetrace(e:Event) {
sqldata = e.target.data;
}
sql("1","SELECT * FROM songs WHERE `flag2` LIKE '0'");
trace (sqldata);
So, here comes the problem:
"sqldata" is traced as "null". AS3 seems to run "sql", then "trace" and then "sqldone", but i would need sql -> sqldone -> trace...
I can't put the trace-command in the sqldone-function because it is stored as *.as and loaded at different points in my .swf and not always followed by only a trace-command.
Any Ideas/hints/flaws in script?
Actionscript is, by design, an event driven language. It also guarantees that the code executes in a single thread i.e. if a function call starts, no other(new call) actionscript code would execute until the first call finishes.
That being said, what you should have is to pass a complete handler to sql(...).
function sql(saveorload:String, sqlstring:String, completeHandler:Function):void
{
var sqlloader = new URLLoader();
var sqlrequest = new URLRequest("http://***/sql.php");
sqlrequest.method = URLRequestMethod.POST;
sqlloader.addEventListener(Event.COMPLETE, completeHandler);//tell urlloader to use the complete handler passed in parameters
var variables:URLVariables = new URLVariables();
variables.sqlm = saveorload;
variables.sqlq = sqlstring;
sqlrequest.data = variables;
sqlloader.load(sqlrequest);
}
And then use it from some other place like:
sql("1","SELECT * FROM songs WHERE `flag2` LIKE '0'", sqldonetrace);
function sqldonetrace(e:Event)
{
var sqldata:String = e.target.data;
trace (sqldata);
}
Also, I think you should check for error events from urlloader. Pass another parameter to sql as errorHandler

How to upload a background image using actionscript 3.0 code?

Need your help. I am trying it first time.
I have used following code.
But i get this in my console:
started loading file
SecurityError: Error #2000: No active security context.
and my image url is in same folder as my script file.
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, fileLoaded);
loader.load(new URLRequest("C:\Documents and Settings\Owner\Desktop\23Aug\demo1\mic.jpg"), context);
var context:LoaderContext = new LoaderContext();
context.applicationDomain = ApplicationDomain.currentDomain;
trace("started loading file");
addChild(loader);
function fileLoaded(event:Event):void
{
trace("file loaded");
}
Reasons to throw securityError exception.
Invalid path,
Trying to access a URL, that not permitted by the security sandbox,
Trying a socket connection, that exceeding the port limit, and
Trying to access a device, that has been denied by the user(Ex., camera, microphone.)
try this
private var _loader:Loader = new Loader();
private var _context:LoaderContext = new LoaderContext();
private var _url:URLRequest = new URLRequest("demo1/mic.jpg");
_context.checkPolicyFile = false;
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageloaded);
//_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
_loader.load(_url, _context);
private function onImageloaded(e:Event):void{
addChild(e.target.content);
}
Use slashes instead of back slashes :
loader.load(new URLRequest("C:/Documents and Settings/Owner/Desktop/23Aug/demo1\mic.jpg"), context);
But the best way is to use relative path like "./mic.jpg" and do not use absolute path.

URLLoader handler in child movie not being called

Hi I am writing a flex application that has a MainMovie that loads flex programs (ChildMovie) depending on what the user selects in the MainMovie. below is some pseudocode to help me describe my problem hopefully.
class MainMovie{
private var request:URLRequest = new URLRequest();
public function callPHPfile(param:String, loader:URLLoader,
handlerFunction:Function):void {
var parameter:URLVariables=new URLVariables();
parameter.param = param;
request.method = URLRequestMethod.POST;
request.data = parameter;
request.url = php file on server;
loader.addEventListener(Event.COMPLETE, handlerFunction);
loader.load(request);
}
}
Class ChildMovie {
private var loaderInChild:URLLoader = new URLLoader();
public function handlerInChild(e:Event):void {
process data....
loaderInChild.removeEventListerner(Event.COMPLETE, handlerInChild);
}
private function buttonClickHandler(e:Event):void{
Application.application.callPHPfile(param, loaderInChild, handlerInChild)
}
}
I can see that the callPHPfile function is being executed and received xml data from in httpFox, the problem is that the code in the handlerInChild function is not being executed. What am I doing wrong here?
It was a runtime error. I forgot that i uninstalled flash player debugger in firefox and it didn't show. in the handlerInChild function, there is a line
var data:XML = loader.data;
it should be
var data:XML = XML(loader.data);
and the code will run as expected.