Show ActionScript console output in the actual GUI - actionscript-3

my question is simple, yet I couldn't find any answer of it in the net, maybe it's impossible to do...
The thing is that I have an ActionScript 3.0 application, and wanted to include a little one-line size textbox which showed all the trace() calls and such, which are shown in the console.
Has anyone got any idea of how can it be done? I would really appreciate it, as I have a full project with traces on it that I'd like to show, and it's now when I'm finishing that I'm realising I don't know how to do it :P
Of course not everything is lost, as I could just do my own class that showed there the messages, but it would be cleanier, and quicker not to have to replace all the trace() calls for my new class and method.
Regards and thanks in advance :)

I just did this last week.
There are logging frameworks for Flex out there. A shame, though, that Flex's logging only works in Debug mode. If you search SO for Flex logging you'll find various suggestions. None of them are amazing, IMO.
Finally I rolled my own by just creating a Log class with a static function that acts as a proxy for trace.
Something like:
public static myTrace(... args) : void { ... }
Then you just forward the args to trace but also to whatever other destination you want (e.g. an array of strings + dates) that you can then display in the log window.
Incidentally, I also used SwfAddress to trigger the log window whenever a certain parameter is added to the URL. Very handy.
Oh, what the heck.. here's the class. It just keeps the last 100 strings and there's also a "dump" function that you can invoke if you want to send the data to your server or just quickly print the entire history.
public class Log
{
public static var lines : ArrayList = new ArrayList();
public static const MAX_LINES : int = 100;
private static function logLine(line : String) : void
{
while (lines.length > MAX_LINES)
lines.removeItemAt(0);
lines.addItem({"line" : line, "time" : new Date()});
}
public static function logDump() : String
{
var ret : String = "";
for each (var entry : Object in lines.source)
{
ret = (entry.time as Date).toUTCString() + " " + entry.line + "\n" + ret;
}
return ret;
}
public static function debug(...args) : void
{
trace(args);
var line : String = "";
for (var i : int = 0; i < args.length; i++)
if (args[i] != null)
line += args[i].toString();
logLine(line);
}
}

Alternatively, you can use the ASDebugger
http://labs.flexperiments.nl/asdebugger-20-a-real-time-debugger-and-editor/
ASDebugger.debug( 'shallala' );
ASDebugger.debug_prop( variable );
Try to avoid using the debug display object option. The debugger can crash for complex objects (especially in flex)
You can probably do a simple replacement of 'trace(' to 'ASDebugger.debug('

Related

what to add to or remove from to change lines

i'm a beginner in learning actionscript and i'm seeing examples to learn from them. in the following lines, what should i add or remove so i can hide or not show system messages? and what are these lines actually say?
public function set showSystemMsgs(param1:Boolean) : void
{
var _loc:* = this.showSystemMsgs;
if (_loc !== param1)
{
this.showSystemMsgs = param1;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "showSystemMsgs", _loc, param1));
}
return;
}
public function get showSystemMsgs() : Boolean
{
return this.showSystemMsgs;
}
public function removeEventListener(param1:String, param2:Function, param3:Boolean = false) : void
{
_bindingEventDispatcher.removeEventListener(param1, param2, param3);
return;
}
If your goal is to understand code, stop reading decompiled code. This is not code meant to be read by humans opposed to what the code looked like before compilation.
There are plenty of resources on pretty much everything available by now, with explanations, comments and readable code.
object.showSystemMsgs = false;
Might work, where object is a reference to an object of the class which you partially posted.

RootFrame UriMapper for Caliburn Micro

I have been googling on how to actually implement this with no avail. Could not find a single resource on how to actually do it using Caliburn Micro.
Basically, I am trying this http://www.developer.nokia.com/Community/Wiki/OAuth_on_Windows_Phone
In the example, it used redirect_uri as normal link. I did it with Protocol/File Association (refer http://www.developer.nokia.com/Community/Wiki/URI_associations_for_Windows_Phone_8). Everything works fine. I got it to work without Caliburn Micro.
But based on that example, I would require to implement UriMapperBase and assigned it to RootFrame.UriMapper.
My question is how do I actually implement UriMapper with CaliburnMicro for WP8. For Win 8, it is different as I could override the OnActivate and check for the ActivationKind.Protocol and there is no need for UriMapper.
Ok. Finally managed to get it to work. So, will post it here because I'm pretty sure there will be a lost soul again like me who will appreciate the answer to this.
To use UriMapper in Caliburn, you will need to override the CreatePhoneApplicationFrame in the bootsrapper.
In Boostrapper.cs
protected override PhoneApplicationFrame CreatePhoneApplicationFrame()
{
// var frame = base.CreatePhoneApplicationFrame(); this doesnt work
var frame = new PhoneApplicationFrame(); // this works
frame.UriMapper = new AssociationUriMapper();
return frame;
}
AssociationUriMapper.cs - I just followed the example as per links above
public class AssociationUriMapper : UriMapperBase
{
private string tempUri;
public override Uri MapUri(Uri uri)
{
tempUri = System.Net.HttpUtility.UrlDecode(uri.ToString());
// URI association launch for contoso.
if (tempUri.Contains("pocketthis:MainPage"))
{
// Get the category ID (after "CategoryID=").
//int categoryIdIndex = tempUri.IndexOf("CategoryID=") + 11;
//string categoryId = tempUri.Substring(categoryIdIndex);
// Views/MainPage.xaml returns external exception,
// so remember the / before views
return new Uri("/Views/MainPage.xaml", UriKind.Relative);
}
// Otherwise perform normal launch.
return uri;
}
}
Hope this will help anyone trying to implement Uri/File Association in WP8 with Caliburn Micro.

Value Will Set properly, but Get receives Null

So, I have successfully grabbed a value out of an XML document and set it into a separate class called "AddCommas." The trace functions have shown me that it sets properly.
For more details, my objective is to take the language indicator ("fr" for french or "en" for english), set it inside the appropriate class and into a variable I will use. Now, I am using this variable to be used in an if statement; which will help me format a number properly (commas, decimals, spaces) per the clients request.
However, my problem is when I try to get the value to use it. It always comes back as Null. I have placed traces all over my program trying to pinpoint when this happens, but I cannot find it. Here's the code...
The pull from the XML file and into the set (this works fine, but I am adding it for your benefit in case I missed something)
public var commaHold = new AddCommas();
localLanguage = xmlObj.localLanguage;
trace("localLanguage + " + localLanguage);
commaHold.setLanguage(localLanguage); // Set Language
//More code follows...
This is the set function istelf...
public function setLanguage(localLanguage:String){
langHold = localLanguage;
trace("Set Language = " + langHold); //This always shows a successful set
}
Now am I wrong in thinking that in AS3, once langHold in my AddCommas class has been set I should be able to use it without calling a get within the function I am using the If Statement in, right? Such as this?
var language = langHold;
if (language == "en"){
trace("Language is = " + language); // More code follows afterwards and as of now, this shows NULL
Now, I have attempted plenty of Get functions to add the language variable in the call itself to this function and it's always the same. Am I missing some fundamentals here?
Thank you very much for your time.
If you expect a string comparison you need to use quotes, unless en is a String variable since langHold is a String, like:
if (language == "en"){
Consider modifying the set function to use the as3 keyword like:
private var _language:String;
public function set language(value:String):void {
_language = value;
//do other stuff here if necessary, put a breakpoint on the line above
}
public function get language():String{
return _language;
//put a breakpoint on the line above
}
You should be able to see when any instance of your class has the property changed. The only other issue I can think of is it is not the same instance of the class and therefore doesn't share the property value you set earlier. In the debugger you can check the "hashCode" or "address" it shows for this to see if it changes when it hits the breakpoints.
Here's a sample Singleton structure in AS3 (this all goes in one file):
package com.shaunhusain.singletonExample
{
public class SingletonExample
{
private static var instance:SingletonExample;
public static function getIntance():SingletonExample
{
if( instance == null ) instance = new SingletonExample( new SingletonEnforcer() );
return instance;
}
/**
*
* #param se Blocks creation of new managers instead use static method getInstance
*/
public function SingletonExample(se:SingletonEnforcer)
{
}
}
}
internal class SingletonEnforcer {public function SingletonEnforcer(){}}
using this single shared instance from any other class would look something like this:
private var singletonInstance:SingletonExample = SingletonExample.getInstance();
ShaunHusain's theory of using a Singleton was the perfect solution I needed. However, his code gave me a bizarre 1061 error and my format and code appeared to be error free. Regardless, I looked up another way to use a Singleton as follows that worked perfectly for me. Honestly, Shaun's code should work for anyone and I have no idea why it wasn't. I am perfectly willing to admit that it was probably a typo on my end that I just did not see.
I ended up embedding the Set and Get within the Singletons class and used it as an intermediary to hold the information I needed. It worked perfectly.
package chart {
import chart.*;
//
public class StaticInstance {
private static var instance:StaticInstance;
private static var allowInstantiation:Boolean;
private var language:String;
public static function getInstance():StaticInstance {
if (instance == null) {
allowInstantiation = true;
instance = new StaticInstance();
allowInstantiation = false;
}
return instance;
}
public function StaticInstance():void {
if (!allowInstantiation) {
throw new Error("Error: Instantiation failed: Use StaticInsance.getInstance() instead of new.");
}
}
public function setLanguage(_language:String):void{
language = _language;
trace("language set = " + language);
}
public function getLanguage():String{
return language;
}
}
}
This code allowed me to hold the data and call upon it again from two different classes. It's a very hack job instead of just being able to pass on the variable from function to function, but in my case we didn't create this file, we are modifying it and attempting to do things beyond the original scope of the project.
Thanks again for your help Shaun! I hope this helps other people!

When extending Array, problems accessing members

I am currently working with some code that my co-worker wrote. Here is a simplified look at it:
The People class:
package model{
public class People extends Array{ // NOTE: it is not dynamic
public function toXML():XML {
var out:XML = <people/>;
for each(var per:Person in this){
out.appendChild(per.toXML());
}
return out;
}
}
}
Which is basicly an Array of Persons:
package model{
public class Person {
public var name:String;
public var phoneNumber:String;
public function Person(name:String, phoneNumber:String){
this.name = name;
this.phoneNumber = phoneNumber;
}
public function toXML():XML {
var xml:XML = <person/>;
xml.#name = name;
xml.#phone = phoneNumber;
return xml;
}
}
}
This is basicly how my co-worker is using the code:
var people:People = new People();
people.push(new Person("Jake", "902 825-4444"));
people.push(new Person("Bob", "514 444-3333"));
return people.toXML().toXMLString();
Note: The he adds Person objects but he never looks at what is in the People Array except to print out the XML
Fast-forward (do people still know that this means?) to the present. I now need to look inside the People class and do something like this:
var people:People = ... init and fill with Person objects
for(var i:int=0; i<people.length(); i++){
doSomething(people[i]); // <-- Error thrown here.
}
Unfortionatly this throws this error:
ReferenceError: Error #1069: Property 0 not found on model.People and there is no default value.
at runner::Runner$/newUse()
at ExtendsArray/start()
at ExtendsArray/___ExtendsArray_Application1_initialize()
at flash.events::EventDispatcher/dispatchEventFunction()
What should I do?
Edit, Aside: Extending Array is not my doing this is part of our old model. We are moving away from the old model because it is full of garbage like this. I just need to grab this stuff from the old model to convert it into the new model. I would like to tear this code out of our product but the cost of doing that is probably not warranted.
What should I do?
Use only class methods to access and set items in your "array", don't use Array-specific syntax. And/or make the class dynamic.
EDIT I think you can leave everything as is and avoid making your class dynamic by defining only one additional method for item access (if it's not there for some reason). Something like:
public functon getItem(index:uint):*
{
if (index >= length) {
return null;
}
return this.slice(index, index+1)[0];
// this creates a redundant array on the fly, sorry.
}
// usage:
var people:People = ... init and fill with Person objects
for(var i:int=0; i<people.length(); i++){
doSomething(people.getItem(i));
}
And I know that is not the way it's meant to be answered on stackoverwlow, but... I can't hold it. ))
Anything extends Array -- is a heresy. If I see that in production code, I'll immediatelly proceed to initiating a "purge the unclean" sequence.
Just try googling for the subject a little bit, and you will see, that almost no one has got alive and well from an activitiy like that.
The main rational reason why this abomination is not meant to exist (aside form it being a heresy) is that you can not use array access [], you can not instantiate it like a normal array with items and you can not set items through array syntax [] and be notified of the changes somewhere in your class. But it is an Array by the right of birth, so any of your fellow developers not familiar with the subject may try to use it like a normal Array, because it's quite natural. And then they'll probably post another question on stackoverflow.
So, if you are still limited to just using class methods, what's the point in extending anyway? Whay not use neat aggregation/composition or proxy ways?
It's amazing, but there's even an article on extending Array on adobe.com. What they do not mention there is that you are likely to start burning in hell right away.
Array.length is a getter: it returns an int. people.length() is the same as calling 3(). I don't know how it worked when you tested that.
It looks like you'd be better off implementing something like IList and have addItem push into a Vector.<Person>. That will guarantee that you only have Person objects.
You should probably should not be extending Array. If you want to extend anything, extend Proxy (You can even use the ProxyArray class example with a Vector.<Person>). Extending top level classes (with the exception of Object) is often an invitation for confusion.
If you really, really want to extend Array, you have to make the class dynamic -- you are arbitrarily assigning and removing properties.
This looks like it works:
var s:String = "";
for each(var per:Person in people){
s += per.name + " ";
}
The People class has to be scripted as public dynamic class since it is extending the Array class.
From this Adobe help article: A subclass of Array should use the dynamic attribute, just as the Array class does. Otherwise, your subclass will not function properly.
You used the "push" function which apparently created an associative array.
Associative arrays can not be called by index. They can also not be reversed or have their order changed.
You need to access them by using the for..in loop
for (var key:String in people) {
trace("person : " + (people[key] as person).name);
}
// or as you found out the for each.. in
for each(var person:Person in people){
trace("person : " + person.name);
}
The arr.length() function of an associative array will always be 0 and you saw that with your error.
//Try this example you will see how an array can act like an array as we know it and an object.
var a:Array = [];
a[0] = true;
a.push(true);
a.push(true);
a["foo"] = true;
a.push(true);
a.push(true);
a.bar = true;
trace("for loop\n");
for(var i:int = 0, ilen:int = a.length ; i < ilen ; i++){
trace(i,a[int(i)]);
}
trace("\nfor...in loop\n");
for(var key:String in a){
trace(key,a[key]);
}

Can a Flex 3 method detect the calling object?

If I have a method such as:
private function testMethod(param:string):void
{
// Get the object that called this function
}
Inside the testMethod, can I work out what object called us? e.g.
class A
{
doSomething()
{
var b:B = new B();
b.fooBar();
}
}
class B
{
fooBar()
{
// Can I tell that the calling object is type of class A?
}
}
Sorry the answer is no (see edit below). Functions received a special property called arguments and in AS2 it used to have the property caller that would do roughly what you want. Although the arguments object is still available in AS3 the caller property was removed from AS3 (and therefore Flex 3) so there is no direct way you can do what you want. It is also recommeded that you use the [...rest parameter](http://livedocs.adobe.com/flex/3/langref/statements.html#..._(rest)_parameter) language feature instead of arguments.
Here is a reference on the matter (search for callee to find the relevant details).
Edit: Further investigation has shown that it is possible to get a stack trace for the current executing function so if you are lucky you can do something with that. See this blog entry and this forum post for more details.
The basic idea from the blog post is you throw an Error and then catch it immediately and then parse the stack trace. Ugly, but it may work for you.
code from the blog post:
var stackTrace:String;
try { throw new Error(); }
catch (e:Error) { stackTrace = e.getStackTrace(); }
var lines:Array = stackTrace.split("\n");
var isDebug:Boolean = (lines[1] as String).indexOf('[') != -1;
var path:String;
var line:int = -1;
if(isDebug)
{
var regex:RegExp = /at\x20(.+?)\[(.+?)\]/i;
var matches:Array = regex.exec(lines[2]);
path = matches[1];
//file:line = matches[2]
//windows == 2 because of drive:\
line = matches[2].split(':')[2];
}
else
{
path = (lines[2] as String).substring(4);
}
trace(path + (line != -1 ? '[' + line.toString() + ']' : ''));
Is important to know that stackTrace is only available on the debugger version of Flash Player. Sorry! :(
I'd second the idea of explicitly passing a "callingObject" parameter. Unless you're doing really tricky stuff, it should be better for the caller to be able to supply the target object, anyway. (Sorry if this seems obvious, I can't tell what you're trying to accomplish.)
To add to the somewhat ambiguous first paragraph of James: the arguments property is still available inside a Function object, but the caller property has been removed.
Here's a link to the docs: http://livedocs.adobe.com/flex/3/langref/arguments.html
This might help someone, I'm not sure... but if one is using an Event this is possible using the e.currentTarget as follows:
private function button_hover(e:Event):void
{
e.currentTarget.label="Hovering";
}