Flex Console - How to use it? - apache-flex

I'm checking "Flex Console" --> here that looks really interesting.
It seems easy to use and light to integrate. But how? I've been looking around for some info about it but haven't been successful. I found this post but I don't understand how it is used...
If anyone have any idea on how to use it or have any recommendation about any other app that would do the same (save clear flex logs with filters and stuff) I'd be really appreciated.
Regards,
BS_C3

Flex Console has moved to a new location: http://code.google.com/p/flex-console/
In a nutshell, you create a MiniDebugTarget in your project and start logging using the Logging API.
import mx.logging.*;
import mx.logging.targets.*;
public class MyApp {
static private logger:ILogger = Log.getLogger("sample.MyApp");
public function MyApp() {
super();
// Add the MinuDebugTarget to channel
// all log messages to LocalConnection
// You only need to do this once!
var target:MiniDebugTarget = new MiniDebugTarget();
target.filters = ["*"];
target.includeDate = true;
target.includeTime = true;
target.includeCategory = true;
target.includeLevel = true;
Log.addTarget(target);
}
public function foo(bar:String):void {
logger.debug("foo({0})", bar);
try {
// do something
..
} catch(e:Error) {
logger.error("Error: ", e.message);
throw e;
}
}
}
Check out the Help page at the new site.

Related

How to test the method passed to subscribe method of the PubSubEvent in the Wpf Prism library?

I have two ViewModels, MainWindowShellViewModel(shellVm) and MainWindowContentViewModel(contentVm). The shellVm publishes an event and the contentVm subscribes to it.
The shell VM looks something like the following. I have omitted many details.
// ctor
public MainWindowShellViewModel(IEventAggregator eventAggregator)
{
_EventAggregator = eventAggregator ?? throw new ArgumentNullException(nameof(IEventAggregator) + " service injected is null!!!");
_AppStartingClosingEventToken = _EventAggregator.GetEvent<AppStartingClosingEvent>();
}
private void MainWindowShellLoaded()
{
var payload = new AppStartingClosingEventData();
payload.Data = "MainWindowStarting";
_AppStartingClosingEventToken.Publish(payload);
}
The AppStartingClosingEvent is a no brainer type as follows.
public class AppStartingClosingEvent : PubSubEvent<AppStartingClosingEventData>
{ }
public class AppStartingClosingEventData
{
public string Data { get; set; }
}
And finally, the contentVm looks as follows.
public MainWindowContentViewModel(IEventAggregator eventAggregator)
{
_AppClosingEventToken.Subscribe(AppStartingClosing);
}
private void AppStartingClosing(AppStartingClosingEventData appStartingClosingEventData)
{
if (appStartingClosingEventData.Data == "MainWindowStarting")
LoadState(appStartingClosingEventData);
if (appStartingClosingEventData.Data == "MainWindowClosing")
SaveState(appStartingClosingEventData);
}
I want to test the that the method AppStartingClosing inside of contentVm is called with proper data. I am using Moq
I am running out of ideas. Please suggest. Tried the following but so far no success.
How do I test Prism event aggregator subscriptions, on the UIThread?
Using Moq to verify a Prism event subscription fails
Unit testing with Moq, Prism 6, and Event Aggregation
Moq Event Aggregator Is it possible
// Verifying a delegate was called with Moq
EDIT
Here is what I have tried.
// Arrange
var mockingKernel = new MoqMockingKernel();
var eventAggregatorMock = mockingKernel.GetMock<IEventAggregator>();
var eventBeingListenedTo = new AppStartingClosingEvent();
eventAggregatorMock.Setup(e => e.GetEvent<AppStartingClosingEvent>()).Returns(eventBeingListenedTo);
var vm = mockingKernel.Get<MainWindowContentViewModel>();
var evData = new AppStartingClosingEventData();
evData.Data = "MainWindowStarting";
// Act
eventBeingListenedTo.Publish(evData);
Now, what should I do? I am not even clear if I have approached correctly.
Now what should I do?
After eventBeingListenedTo.Publish(evData); look whether whatever effect SaveState should have is actually happening.
I am not even clear if I have approached correctly.
You do not want to test whether one method in a class is called by another method of that class.
So instead of trying to do
subjectUnderTest.DoStuff();
MagicallyVerifyThatThisGotCalled( () => subjectUnderTest.SomeEffect() );
you should do
var subjectUnderTest = new SubjectUnderTest( serviceMock.Object );
subjectUnderTest.DoStuff();
serviceMock.Verify( x => x.SomeEffectOnTheService(), Times.Once );
Assert.That( subjectUnderTest.SomePropertyThatsChanged, Is.EqualTo( newValue ) );
Whatever SubjectUnderTest does internally to achieve the desired effect, is not in the scope of the test. It's private to SubjectUnderTest, you don't care how it is done as long as it is done at all. When testing, look at the externally visible state of your subject under test, and what it does to its dependencies.

Exporting a TypeScript module results in interfaces not getting picked up

I'm using TypeScript and SignalR together, and am trying to define static types for the generated SignalR classes. And if I do something like this, it works:
///<reference path="../Scripts/jquery-1.8.d.ts" />
///<reference path="../Scripts/signalr-1.0.d.ts" />
interface SignalR {
roomHub: Service.RoomHub;
}
module Service {
export var roomHub = $.connection.roomHub;
export interface RoomHub { }
}
And of course $.connection is of type SignalR, which is defined in the file "signalr-1.0.d.ts", and extended in the file above.
However, I need to be able to reference the Service module from other files, so I need to add the "export" keywords to both the module and the interface, i.e.:
///<reference path="../Scripts/jquery-1.8.d.ts" />
///<reference path="../Scripts/signalr-1.0.d.ts" />
export interface SignalR {
roomHub: Service.RoomHub;
}
export module Service {
// Error here: "The property 'roomHub' does not exist on type SignalR."
export var roomHub = $.connection.roomHub;
export interface RoomHub { }
}
However, when I do that, I get a little red squiggly line under $.connection.roomHub, and the compiler returns the error, "The property 'roomHub' does not exist on type SignalR."
I certainly don't understand everything about TypeScript, but that doesn't seem right to me. Have I run into a compiler bug? Or is there a different way to do this?
I was able to figure out a workaround. I pulled out the interfaces into a separate file:
// File: ISignalR.ts
interface SignalR {
roomHub: RoomHub;
}
interface RoomHub {
}
And then I referenced that file in my Service file
///<reference path="../Scripts/jquery-1.8.d.ts" />
///<reference path="../Scripts/signalr-1.0.d.ts" />
///<reference path="ISignalR.ts" />
export module Service {
export var roomHub = $.connection.roomHub;
}
And that works, oddly enough. I'm not sure if it's a compiler bug, or something I'm continuing to misunderstand, but it clearly has something to do with some subtle semantic changes related to the AMD module support. I'd love to hear more of an explanation from someone who groks TypeScript and/or RequireJS modules a little better than I do.
If the SignalR object has actual members, you want to use the declare module syntax instead. interface declarations only describe members on types (rather than describing extant objects).
///<reference path="../Scripts/jquery-1.8.d.ts" />
///<reference path="../Scripts/signalr-1.0.d.ts" />
declare module SignalR {
var roomHub: Service.RoomHub;
}
export module Service {
// Good now
export var roomHub = $.connection.roomHub;
export interface RoomHub { }
}
There is more than one way to wire SignalR up, and using createHubProxy and invoke are more TypeScript friendly:
export class FrameworkHub {
private connection: HubConnection;
private proxy: HubProxy;
Init(): void {
this.Connected = false;
this.connection = $.hubConnection();
this.connection.logging = true;
// Binding with createHubProxy means you can use a string name, so no need to add dynamic properties to the hub
this.proxy = this.connection.createHubProxy("MyHubName");
this.wireEventListeners();
this.initializeConnection();
}
// Binding with proxy.on means you can use a string name for the function, so no need to add dynamic properties to the hub.
wireEventListeners(): void {
this.proxy.on("HandleFrameworkMessage", (message: IFrameworkMessage) => {
console.log("HandleFrameworkMessage: " + message.AccountID + " - " + message.ArmID);
// Do something to handle the message here.
});
}
initializeConnection(): void {
//console.log("Framework Hub initializeConnection");
var that = this;
//Again, using invoke means passing a string argument.
this.connection.start().done(() => {
that.proxy.invoke("Connect", this.AccountID, this.ArmID).done((response:FrameworkHubResponse) => {
//console.log("FHR: " + response.Success + " - " + response.Message);
if (response.Success) {
// Do something.
}
else {
// Try again. Would be better with some kind of exponential back-off.
setTimeout(that.initializeConnection, 500);
}
});
});
}
}
That's a slightly rough example cut from real code, but I've found it the best TS way to use SignalR. Docs for this kind of connection are here: https://github.com/SignalR/SignalR/wiki/SignalR-JS-Client-Hubs-%28No-Proxy%29 - watch out because the Docs haven't always kept pace with the recent changes.

rso between flex and red5. I can create but cant read

so im still stuck on this that i can create remote shared object but cant read while im notified about changes. im using trunk version of red5, and flex 4.0 with flash builder. in debug i can see that changeLog has name of the changed value of rso, but object itself has undefined value.
Currently im working on local windows machine, but tried everything on ubuntu server 10.04 and got the same results. i can connect to the room, create a shared object and all client are notified about that, but only the user who changed the value of rso can read the value that one time, other just get undefined value.
Does anybody has any experience with this issue? I would really appreciate any help, because this is just driving me crazy, im for about three weeks, read all tutorials about rso and cant get any solution. I tried with persistent and non-persistent, initiated by server and by client, but all the time get the same results.
there is my code on the client side:
protected function application1_creationCompleteHandler(event:FlexEvent):void {
var room_id:Number = vars("room");
connection = new NetConnection();
connection.connect("rtmp://127.0.0.1/video/" + room_id);
connection.addEventListener(NetStatusEvent.NET_STATUS, onConnected);
connection.client = this;
}
private function onConnected(event:NetStatusEvent) : void {
if(event.info.code == "NetConnection.Connect.Success") {
so = SharedObject.getRemote("video", connection.uri, true);
so.addEventListener(SyncEvent.SYNC, onSync);
so.connect(connection);
} else {
Alert.show("Unsuccessful Connection", "Information");
}
private function onSync(event:SyncEvent):void {
if(so.data["video"] != undefined)
Alert.show(so.data["video"].toString(), "Information");
}
on the server side i have:
ISharedObject so;
IServiceCapableConnection iconn;
public static IScope iroom;
/** {#inheritDoc} */
#Override
public boolean connect(IConnection conn, IScope scope, Object[] params) {
iconn = (IServiceCapableConnection)conn;
if (!super.connect(conn, scope, params)) {
return false;
}
System.out.println("Connected True");
return true;
}
/** {#inheritDoc} */
#Override
public void disconnect(IConnection conn, IScope scope) {
super.disconnect(conn, scope);
}
#Override
public boolean roomStart(IScope room) {
if (!super.roomStart(room))
return false;
createSharedObject(room, "video", true);
so = getSharedObject(room, "video");
System.out.println("Room created succesfully");
ISharedObjectListener listener = new SOEventListener();
so.addSharedObjectListener(listener);
return true;
}
with listener on the client side i cant make output in console and see that rso is changed and what is current value, although im checking the persistence rso file on red5 server and the that look like everything is working and the only thing what is missing is opportunity to read value for all clients.
I will appreciate any help. Thanks
big problem appears not such a big. Problem was with encoding, which is AMF3 by default since AS3 and all i need to do, just change the encoding to AMF0.
connection = new NetConnection();
connection.objectEncoding = ObjectEncoding.AMF0;
connection.connect("rtmp://127.0.0.1/video/" + room_id);
Hope that helps for anybody, because somehow there is not a lot information about things like these on the net.

Flex ModuleManager unload module

I use ModuleManager load a module, like this Class:
public class LoadModule
{
private static var info:IModuleInfo;
private static var display:IVisualElement;
private static var downloadBar:ProgressBar;
private static var parent:Group;
public function LoadModule()
{
}
//load module
public static function load(url:String, parent:Group, bar:Boolean = true):void {
LoadModule.parent = parent;
info = ModuleManager.getModule(url);
info.addEventListener(ModuleEvent.READY, readyHandler);
info.addEventListener(ModuleEvent.SETUP, setupHandler);
info.addEventListener(ModuleEvent.ERROR, errorHandler);
info.load(null, null, null, parent.moduleFactory);
}
//add display object
private static function readyHandler(event:ModuleEvent):void {
LoadModule.display = event.currentTarget.factory.create() as IVisualElement;
parent.addElement(LoadModule.display);
}
private static function setupHandler(event:ModuleEvent):void {
}
//unload module
public static function unload():void {
if (LoadModule.info != null) {
LoadModule.info.addEventListener(ModuleEvent.UNLOAD, unloadHandler);
LoadModule.info.unload();
if (parent.getElementIndex(LoadModule.display) != -1) {
parent.removeAllElements();
LoadModule.display = null;
}
}
}
private static function unloadHandler(event:ModuleEvent):void {
LoadModule.info.removeEventListener(ModuleEvent.UNLOAD,unloadHandler);
trace("unloadModue");
}
//
private static function progresshandler(event:ModuleEvent):void {
downloadBar.label = "haved" + Math.round((event.bytesLoaded /event.bytesTotal) * 100) + "%";
}
private static function errorHandler(event:ModuleEvent):void {
throw Error(event.errorText);
}
public static function setDownloadbar(downloadBar:ProgressBar):void {
LoadModule.downloadBar = downloadBar;
}
}
Then i load a module and unload a module:
LoadModule.unload(); // 1
LodModule.load('..one.swf', parent);
LoadModule.unload(); //2
LodModule.load('...one.swf', parent);
In theory, It's only one module in my application, and I use "PopUpManager" pop a box, it shoud be one box. But, in fact, It's pop tow box.
I use Flash builder debug this code, and It does not notice me unloade swf..
I guess, It has tow module in appliction.
So, I need help. How to unload module in ModuleManager. I wish one module in application , not tow.
Thanks.
If I understand the question correctly, it sounds like you are having trouble unloading your module. There's a great Adobe resource that can help you solve these issues. A few considerations:
"If you have a module that does not unload, the steps to diagnose the problem are:
1) Make sure the module is being loaded into a child applicationDomain (use default parameters for the load() method in most cases)
2) Use the profiler to make sure there are no references to objects in the module."
If you reference any objects in the module, the module will not unload. You will want to check that the following areas make no reference to the module in question:
Styles
Resources
ExternalInterface.addCallback functions
Timers and Timer mechanisms
Listeners
Focus
Remote Objects
Loaded images

FlexUnit component testing patterns: use addAsync or manually initialize?

We've been using Flex for about 6 months here at work, and I found that my first batches of FlexUnit tests involving custom components would tend to follow this sort of pattern:
import mx.core.Application;
import mx.events.FlexEvent;
import flexunit.framework.TestCase;
public class CustomComponentTest extends TestCase {
private var component:CustomComponent;
public function testSomeAspect() : void {
component = new CustomComponent();
// set some properties...
component.addEventListener(FlexEvent.CREATION_COMPLETE,
addAsync(verifySomeAspect, 5000));
component.height = 0;
component.width = 0;
Application.application.addChild(component);
}
public function verifySomeAspect(event:FlexEvent) : void {
// Assert some things about component...
}
override public function tearDown() : void {
try {
if (component) {
Application.application.removeChild(component);
component = null;
}
} catch (e:Error) {
// ok to ignore
}
}
Basically, you need to make sure the component has been fully initialized before you can reliably verify anything about it, and in Flex this happens asynchronously after it has been added to the display list. So you need to setup a callback (using FlexUnit's addAsync function) to be notified when that's happened.
Lately i've been just manually calling the methods that the runtime would call for you in the necessary places, so now my tests tend to look more like this:
import flexunit.framework.TestCase;
public class CustomComponentTest extends TestCase {
public function testSomeAspect() : void {
var component:CustomComponent = new CustomComponent();
component.initialize();
// set some properties...
component.validateProperties();
// Assert some things about component...
}
This is much easier to follow, but it kinda feels like I'm cheating a little either way. The first case is slamming it into the current Application (which would be the unit test runner shell app), and the latter isn't a "real" environment.
I was wondering how other people would handle this sort of situation?
I see nothing wrong with using the async version. I can agree that the second version is shorter, but I'm not sure that I think it's easier to follow. The test does a lot of things that you wouldn't normally do, whereas the first example is more true to how you would use the component outside the test environment.
Also, in the second form you have to make sure that you do exactly what the framework would do, miss one step and your test isn't relevant, and each test must repeat this code. Seems to me it's better to test it in a situation that is as close to the real thing as possible.
You could have a look at dpUint's sequences, they made component testing a little more declarative:
public function testLogin():void {
var passThroughData:Object = new Object();
passThroughData.username = "myuser1";
passThroughData.password = "somepsswd";
var sequence:SequenceRunner = new SequenceRunner(this);
sequence.addStep(new SequenceSetter(form.usernameTI, {text:passThroughData.username}));
sequence.addStep(new SequenceWaiter(form.usernameTI, FlexEvent.VALUE_COMMIT, 100));
sequence.addStep(new SequenceSetter(form.passwordTI, {text:passThroughData.password}));
sequence.addStep(new SequenceWaiter(form.passwordTI, FlexEvent.VALUE_COMMIT, 100));
sequence.addStep(new SequenceEventDispatcher(form.loginBtn, new MouseEvent("click", true, false)));
sequence.addStep(new SequenceWaiter(form, "loginRequested", 100));
sequence.addAssertHandler(handleLoginEvent, passThroughData);
sequence.run();
}
(example from the dpUint wiki, see here for more info).

Resources