In AS3/AIR how can I execute the result method of a responder object? - actionscript-3

We are creating an extension for the NetConnection object. When we get an error we will retry “n” times. After “n” times we want to call the responder result method returning an error. The responder object contains two properties, both functions, however we cannot seem to see how to access those functions. Is it possible to execute the “result” function of Responder object?
An example might be;
_rspResponder:Responder = new Responder(someFunction);
// lots of code...
_rspResponder.result("Error: Connection timeout failure.\n A network connection error occurred, if needed please try to save work and restart the application.\n Otherwise just restart the application.\n");
Edit:
Based on comments below I created an extended responder like;
package com.fluorinefx
{
import flash.net.Responder;
public class PublicResponder extends Responder
{
/**
* result - Result handler function
*
* #return result
*/
private var _result:Function = null;
public function get result():Function
{
return this._result;
}
public function set result(value:Function):void
{
this._result = value;
}
/**
* status - Status (error) handler function
*
* #return status
*/
private var _status:Function = null;
public function get status():Function
{
return this._status;
}
public function set status(value:Function):void
{
this._status = value;
}
public function PublicResponder(result:Function, status:Function=null)
{
_result = _result;
_status = status;
super(result, status);
}
}
}
When I attempt to use it in my extended NetConnection like;
import com.fluorinefx.PublicResponder;
private var _rspResponder:PublicResponder;
public override function call(strCommand:String, rspResponder:Responder, ...parameters:Array):void
_rspResponder = rspResponder;
I get an implicit coercion error on the "_rspResponder = rspResponder;" line.

After “n” times we want to call the responder result method returning an error.
Is it possible to execute the result function of the Responder object?
Does something like this setup help you?
//# global vars
public var _rspResponder :Responder;
public var try_count :int = 0;
//# test it...
_rspResponder = new Responder( onResult, onError );
//# Since "result" param can be Object or String... using asterix to allow any data-type
private function onResult( result:* ) :void
{
trace( result ); try_count = 0;
}
//# no comment needed here...
private function onError( error:Object ) :void
{
try_count++;
_rspResponder = new Responder( onResult, onError ); //# retry again
//# after N retries, send custom error String to "onResult" function
if ( try_count == 5)
{
onResult( "Error: Connection timeout failure.\n A network connection error occurred, if needed please try to save work and restart the application.\n Otherwise just restart the application.\n" );
}
}

Related

Show usage of dynamic generated callable function name

Is there any posibility in PhpStorm to map usage of dynamic generated fucntion between it declaration an usage?
Assume I have next code:
<?php
class TestExample {
public function __construct($component) {
$component_parts = $this->get_dynamic_component_part_list($component);
$this->load_component_parts($component, $component_parts);
}
private function get_dynamic_component_part_list($component){
//Complex logic to get attached parts by $component
$component_parts = array('part1', 'part2');
return $component_parts;
}
private function load_component_parts(&$component, $component_parts) {
foreach ($component_parts as $component_part) {
$component[$component_part] = $this->{'load_' . $component_part}($component['id']);
}
}
private function load_part1($id) {
//Loading and prepare condition from one source
$part1 = new Part1($id);
// Complex algorithm
return $part1;
}
private function load_part2($id) {
//Loading and prepare condition from another source
$part2 = new Part2($id);
// Complex algorithm
return $part2;
}
}
class Part1 {
}
class Part2 {
}
I want to see usage of load_part1 and load_part2.
Is there any way to do it by usage phpDoc or in some other way?
At this moment PhpStorm notice me that this function doesn't have usage but realy it used in load_component_parts method.
You can use the phpDoc annotation #see.
For example:
$className = 'SomeClass';
$method = 'methodToCall';
$anArgument = 'bar';
/** #see SomeClass::someMethod() */
$foo = call_user_func([$className, $method], $anArgument);
This annotation will create at least a reference to this code, so that you know to come back here when you review SomeClass::someMethod() before throwing the "unused" method away.

Updating SharedObject Data Value in ActionScript

I want to update the value of _third.data["#ID"] in this code. What i want to do it to add something with _third.data["#ID"] when storing it in this.ID
What i want to do is:
this.ID = "myvalue" + _third.data["#ID"];
but in output i get myvalueundefined but if i remove "myvalue" from code thn it works fine and gives me the correct value please help me my knowledge of actionscript isn't that much i just learned some of it from internet.
Here is the coding:
public function main(_first:String, _second:Array, _third:SharedObject):Object{
this.ID = _third.data["#ID"];
};
What i want to do is:
public function main(_first:String, _second:Array, _third:SharedObject):Object{
this.ID = "myvalue" + _third.data["#ID"];
};
Using your code, I created the below test case. It's doing the same as your code, and is outputting the expected values.
package kazo
{
import flash.net.SharedObject;
/**
* ...
* #author KM
*/
public class TestCases
{
private var ID :String = null;
public function TestCases() { }
/**
* Start the test case
*/
public function start():void {
trace('Starting test case');
var SO:SharedObject = SharedObject.getLocal('TestCases');
if (!SO.data["#ID"]) {
trace('SO data not found, creating');
SO.data["#ID"] = '123';
SO.flush();
}
getID(SO);
}
/**
*
* #param _SO
*/
public function getID(_SO:SharedObject):void {
this.ID = "myvalue" + _SO.data["#ID"];
// trace = myvalue123
trace(this.ID);
}
}
}
trace:
(fcsh)Build succeeded
Done(0)
[Starting debug session with FDB]
Starting test case
myvalue123
If you're still having problems, I'd suggest trying to call toString() on the value you're pulling, so:
this.ID = "myvalue" + _SO.data["#ID"].toString();
Should that still not work, store it in two separate String variables and then combined them.

PHPUnit/DbUnit "Too many connections"

While running PHPUnit tests, a lot of connections are created but not closed.
I can see this in
mysql> show processlist;
In my database class I create a db connection by implementing PHPUnit_Extensions_Database_TestCase#getConnection().
I make sure that in the teardown the connection gets closed. See snippet:
<?php
abstract class My_Tests_DatabaseTestCase extends \PHPUnit_Extensions_Database_TestCase
{
static private $pdo = null;
private $conn = null;
/**
* #throws RuntimeException
* #return PHPUnit_Extensions_Database_DB_IDatabaseConnection
*/
final public function getConnection()
{
$iniFilePath = __DIR__ . '/../../../db-config.ini';
$iniFile = parse_ini_file($iniFilePath, true);
$dsn = "mysql:dbname=".$iniFile['phpunit']['dbname'].";host=".$iniFile['phpunit']['host'];
if ( $this->conn === null ) {
if ( self::$pdo == null ) {
self::$pdo = new \PDO($dsn, $iniFile['phpunit']['user'], $iniFile['phpunit']['password']);
}
$this->conn = $this->createDefaultDBConnection(self::$pdo, $iniFile['phpunit']['dbname']);
}
return $this->conn;
}
protected function getSetUpOperation()
{
return new \PHPUnit_Extensions_Database_Operation_Composite(array(
new \TestsExtensions\TruncateDatabaseOperation(),
\PHPUnit_Extensions_Database_Operation_Factory::INSERT()
));
}
protected function getTearDownOperation() {
return \PHPUnit_Extensions_Database_Operation_Factory::TRUNCATE();
}
protected function setUp()
{
parent::setUp();
$em = \ORM\Provider::getInstance()->getEntityManager(\ORM\Provider::DEFAULT_ID);
$em->clear();
}
protected function tearDown()
{
parent::tearDown();
$em = \ORM\Provider::getInstance()->getEntityManager(\ORM\Provider::DEFAULT_ID);
$em->getConnection()->close();
if ($this->conn) {
$this->conn->close();
}
}
}
Debugging showed that the connections were closed, but the processlist showed them with status "sleep".
The amount of connections rises until I get the "too many connections" error.
I do not want to increase the number of connections. I want to close the connection.
What can I modify to make this happen?
Snippet from PDO Connection management:
Upon successful connection to the database, an instance of the PDO
class is returned to your script. The connection remains active for
the lifetime of that PDO object. To close the connection, you need to
destroy the object by ensuring that all remaining references to it are
deleted--you do this by assigning NULL to the variable that holds the
object. If you don't do this explicitly, PHP will automatically close
the connection when your script ends.
Don't store the PDO or set it to null in the teardown:
Remove static private $pdo = null;
or
protected function tearDown()
{
parent::tearDown();
$em = \ORM\Provider::getInstance()->getEntityManager(\ORM\Provider::DEFAULT_ID);
$em->getConnection()->close();
if ($this->conn) {
$this->conn->close();
}
self::$pdo = null;
}
I don't think you need to store the PDO if you are going to pass it into the PHPUnit DB connection

win8 Frame delegate

I have a frame which has a function that updates the frame when an event in another class is raised.
I have the class 'IRCClient' and 'MainFrame'. The IRCClient class has an event 'OnMessageRecvd', the MainFrame has a function 'HandleNewMessageReceived'. In the MainFrame class I have the variables 'CurrentServer' and 'CurrentChannel' to indicate what channel on what server is currently shown to the user.
Now, when I set the 'CurrentServer' and 'CurrentChannel' in the callback of a button, they have a value and all is fine. However, when the 'HandleNewMessageReceived' function is called by the 'OnMessageRecvd' event of IRCClient, the CurrentServer and CurrentChannel are both equal to any value (null) stated in the constructor of MainFrame.
Does anyone have an idea what the source of this behavior is? Thanks a lot in advance.
EDIT:
Below is the code, I've only posted the code in question (any function that uses the CurrentChannel and CurrentServer properties) and snipped away unrelated code.
// Main page, shows chat history.
public sealed partial class MainPage : LIRC.Common.LayoutAwarePage
{
private uint maxMessages;
IRCClient ircc;
IRCHistory irch;
string CurrentServer, CurrentChannel;
// Does all the setup for this class.
public MainPage()
{
this.InitializeComponent();
ircc = App.ircc; // This is a global variable in the 'App' class.
ircc.OnMessage += NewMessageReceived;
irch = App.irch; // This is also a global variable in the 'App' class.
currentChannel = currentServer = null;
}
// Restores the previous state.
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
if (pageState != null)
{
if(pageState.ContainsKey("viewedChannel"))
{
// Retrieve required info.
string[] viewedChannelTokens = (pageState["viewedChannel"] as string).Split('.');
CurrentChannel = viewedChannelTokens[0];
CurrentServer = viewedChannelTokens[1];
// If the saved channel or server got corrupt
if (string.IsNullOrEmpty(CurrentChannel) || string.IsNullOrEmpty(CurrentServer))
{
// Check if a channel is open, if so, select it.
*snip* // Non-relevant code.
}
// Clear and load required history.
ClearHistory();
if(CurrentServer != null && CurrentChannel != null)
LoadHistory(CurrentServer, CurrentChannel);
}
}
// Create buttons that switch to a channel
*Snip* // Calls AddChannelButton
}
// Creates a button that, when clicked, causes the ChatHistoryView to display the ChannelHistory.
void AddChannelButton(string Server, string Channel)
{
Button btn = new Button();
btn.Content = Channel + "\n" + Server;
btn.Width = 150;
// A function to switch to another channel.
btn.Click += (e, s) =>
{
ClearHistory(); // Clears the ChatHistoryVi.ew field.
LoadHistory(Server, Channel); // Does the actual loading of the channel history
CurrentChannel = Channel;
CurrentServer = Server;
};
ChannelBar.Children.Add(btn);
}
// The function that is called by the IRCClient.OnMessageRecv event.
public void NewMessageReceived(ref DataWriter dw, IRCServerInfo ircsi, IRCClient.RecvMessage recvmsg)
{
if (ircsi.Name == CurrentServer && CurrentChannel == recvmsg.recipient)
{
AddMessage(DateTimeToTime(DateTime.UtcNow), recvmsg.author, recvmsg.message);
}
}
}
// Responsible for creating, managing and closing connections.
public class IRCClient
{
// A structure that describes a message.
public struct RecvMessage
{
public string author; // Nickname
public string realName;
public string ipAddress;
public string recipient; // Indicates in what channel or private converstion.
public string message; // The actual message
};
// Describes how a function that handles a message should be declared.
public delegate void MessageHandler(ref DataWriter dw, IRCServerInfo ircsi, RecvMessage msg);
// Gets raised/called whenever a message was received.
public event MessageHandler OnMessage;
}
It's not clear what is happening from what you said, but if the variables are set to the values you set in the constructor when you check them - it means that either you have not changed them yet by the time you are expecting them to be changed or you set the value of some other variables instead of the ones you thought you had.
These are only guesses though and you can't expect more than guesses without showing your code.

Trying to understand the AsyncToken in Flex/Actionscript

I am trying to understand the way the AsyncToken works in actionscript. How can I call a remote service and ensure that a specific parameter is available in the result or fault event functions? I think it is the async functionality I want to use.
The following code will hopefully explain what I am trying to do. Feel free to modify the code block as your explanation.
Thanks.
public function testSerivceCall(data:Object, callBackCommand:String):void
{
// Assume callBackCommand == "FOO";
// How can I pass in callBackCommand as a parameter to the result or fault events?
// How do I create an async token here?
var remoteObject:RemoteObject;
remoteObject = new RemoteObject();
remoteObject.destination = "zend";
remoteObject.source = "MyService";
remoteObject.endpoint = "http://example.com/service";
remoteObject.test.addEventListener(ResultEvent.RESULT, _handleTestResult);
remoteObject.test.addEventListener(FaultEvent.FAULT, _handleTestFault);
remoteObject.test(data);
}
private function _handleTestResult( event:ResultEvent ) : void
{
// How do I get the async token value?
// How can I get the value of callBackCommand in this code block?
if (callBackCommand == "FOO")
{
// do something related to "FOO"
}
else
{
// do something else with the result event
}
}
private function _handleTestFault( event:FaultEvent ) : void
{
// How do I get the async token value?
// How can I get the value of callBackCommand in this code block?
}
An edit to make this question more clear:
Assume I make the following method call somewhere in my code:
testSerivceCall(personObject, "LoginCommand");
How do I get access to the actual string "LoginCommand" inside the _handleTestResult function block?
The reason I want to do this is because I want to dynamically call back certain functions and hand off the result data to specific commands that I know ahead of time when I am making the service call.
I am just having a time grokking the AsyncToken syntax and functionality.
I did not even need closures. I added a class as below which I called externally.
The call was like this:
public class MyClass
{
...
var adminServerRO:AdminServerRO = new AdminServerRO();
adminServerRO.testSerivceCall("FOO",cptyId);
}
public class AdminServerRO
{
private function extResult( event:ResultEvent, token:Object ) : void
{
//the token is now accessed from the paremeter
var tmp:String = "in here";
}
private function extFault( event:FaultEvent ) : void
{
var tmp:String = "in here";
}
public function testSerivceCall(callBackCommand:String, cptyId:String):void
{
var remoteObject:RemoteObject = new RemoteObject();
remoteObject.destination = "adminServer";
var token:AsyncToken = remoteObject.getCounterpartyLimitMonitorItemNode(cptyId);
token.addResponder(new AsyncResponder(extResult,extFault,cptyId));
}
}
While the accepted answer will accomplish what the original submitter wants it does not actually answer the question which was asked. An AsyncToken is created as a result of a remote method call and is accessible from the ResultEvent. Since AsyncToken is a dynamic class you can add whatever property to it that you want. The code below should demonstrate this:
public function testSerivceCall(data:Object, callBackCommand:String):void
{
var remoteObject:RemoteObject;
remoteObject = new RemoteObject();
remoteObject.destination = "zend";
remoteObject.source = "MyService";
remoteObject.endpoint = "http://example.com/service";
remoteObject.test.addEventListener(ResultEvent.RESULT, _handleTestResult);
remoteObject.test.addEventListener(FaultEvent.FAULT, _handleTestFault);
var token:AsyncToken = remoteObject.test(data);
token.callBackCommand = callBackCommand;
}
private function _handleTestResult( event:ResultEvent ) : void
{
if (event.token.callBackCommand == "FOO")
{
// do something related to "FOO"
}
else
{
// do something else with the result event
}
}
private function _handleTestFault( event:FaultEvent ) : void
{
//event.token.callBackCommand should be populated here too
}
If you want to access the properties used during the remote call (parameters to the call and/or AsycToken), you can make use of closures. Just define the result event handler inside the calling method as a closure. It can then access any variable in the calling function.
public function testSerivceCall(data:Object, callBackCommand:String):void
{
var _handleTestResult:Function = function( event:ResultEvent ) : void
{
// token is visible here now
if (callBackCommand == "FOO")
{
// do something related to "FOO"
}
else
{
// do something else with the result event
}
}
var remoteObject:RemoteObject;
remoteObject = new RemoteObject();
remoteObject.destination = "zend";
remoteObject.source = "MyService";
remoteObject.endpoint = "http://example.com/service";
remoteObject.test.addEventListener(ResultEvent.RESULT, _handleTestResult);
remoteObject.test.addEventListener(FaultEvent.FAULT, _handleTestFault);
var token = remoteObject.test(data);
}
If I'm reading your question correctly, you're trying to figure out how to access the actual data returned by the ResultEvent ?
If so, assuming you've made the call correctly and you've gotten data back in a format you're expecting:
private function _handleTestResult( event:ResultEvent ) : void
{
// you get the result from the result property on the event object
// edit: assuming the class Person exists with a property called name
// which has the value "John"
var person : Person = event.result as Person;
if (person.name == "John")
{
Alert.show("John: " + person.name);
}
else
{
Alert.show("Not John: " + person.name);
}
}
private function _handleTestFault( event:FaultEvent ) : void
{
// Maybe you know the type of the returned fault
var expectedFault : Object = event.fault as MyPredefinedType
if (expectedFault.myPredefinedTypesPredefinedMethod() == "BAR")
{
// something here
}
}
The ResultEvent has a property called result which will hold an instance of the object returned by the result (it might be the output of an XML file if using a web service, or a serialized object if using AMF, for example). This is what you want to access. Similarly, FaultEvent has a fault property that returns the fault information.
Edit: Changed code in _handleTestResult() in response to Gordon Potter's comment.