Async Public Events

Hi,
I'm building a component which serves as mediator between 3rd-party API and the rest of my app.
Basically, my problem is that I need to capture and handle some events sent by the API, do some work, and then trigger an event which will be used by my app. But, I must handle the API's event as fast as possible, and if I trigger a public event as part
of the handler procedure, I may get delayed by the event's consumers.
The code looks something like this
public class Mediator
private ExtApi extApi;
public event StatusChangedEventHandler StatusChanged;
public Mediator()
extApi = new ExtApi();
extApi.StatusChanged += extApi_StatusChanged;
private void extApi_StatusChanged(object sender, StatusChangedEventArgs e)
// do some work ...
// trigger a public event - consumed by the rest of the app
StatusChangedEventHandler handler = StatusChanged;
if (handler != null)
handler(this, e);
I was thinking about triggering my event "handler(this,e);" asynchronously, thus ensuring that my own handler (extApi_StatusChanged) won't be delayed.
How do I do that?
Are there better ways to solve the problem?

You are confusing me!!! Normally in .Net you have synchronous and asynchronous methods.  Synchronous methods are blocking which means they don't return until all the read/writing is completed. Asynchronous methods are non-blocking. they are part of
an event handler and return when the available data is processed. The event handler can be trigger by lots of ways like with timers or when data is available.
Your code below you are not using a public event
extApi.StatusChanged += extApi_StatusChanged;
You are using a standard build in method in the Net library to register an event and to specify the event handler to process the event.  All registered events are handled in the windows operating system.  there is no way of speeding up the event
handling.  Windows has a latency on the events that could be as much as 200msec.  The latency is pretty constant and should effect the performance of the application as long as the amount of data being processed doesn't overload the PC youi are using. 
Executive
client --------------------------|                       |                        |                              
API
client --------------------------|   Server           |      Client          |----------------------- Server
client --------------------------|                       |                        
|
Your architecture should look like the above.  You need an executive that funnels the messages to the API.  The executive will send one command to the API and wait for a response before sending a second command to the API.  The executive can
also periodically send a command to the API to get status.  The executive will have an input queue from the clients and process the messages as they are received from the clients.
jdweng

Similar Messages

  • Events - how to customize public events folder url

    I have customized each of my event landing and registration page urls.  I can't seem to customize the url for the public events folder.  How can I do this so people can have an easy to remember
    url to go to?
    Thank you,
    Leanne

    You can't. This URL is programmatically assigned when the folder is created by Connect. Folders don't have the option for custom URLS.
    You could always use a service that provides a shorter URL and re-directs to whatever you want. There are plenty of services like:
    Google: http://goo.gl
    Bitly: http://bitly.com
    TinyURL: http://tinyurl.com
    Short URL: http://shorturl.com

  • Calendar apps:  1. That my wife and I can share.  2. That shows some of the text in the full month view.  3.  That can have "public" events and "private" events.

    Hello All,
    I am looking for a calendar app that my wife and I can share on both of our iphones.  I am new to this and haven't found an app that will do what I want.
    1. I want the full month view to show some of the text of each event:  Like Pocket Informant and Monthly Calendar Mocha do (not just a dot).
    2. That both of us can post and see each other's events.
    3. That each of us can post "private" events that the other person won't see on their phone.  Things like, "Wife's surprise party."
    4. That sync's both calendars automatically.
    I know a lot of people use Fantastical, but I don't think that would give me the text in the full month view.
    Is there an app that can do all of the above?
    Thanks in advance.
    Rick

    Sharing and syncing is a feature of the calendar database; you can have multiple calendars, and each can be private, shared with specific other iCloud users, or public. If you have a Mac you can set that up in the Calendar app; for either Mac or Windows you can set it up by logging in to iCloud.com using your Apple ID.
    The other calendar apps all use the Apple calendar database; they just have different ways of presenting the content, and can also take advantage of "hidden" features of the Apple calendar database (such as adding icons to entries).

  • Public Event Calendar

    How can I make an Event Calendar publicly accessible (i.e. users can see the events posted without login) while having the remaining calendars accessible to REMOTE_USER (protected by SSO)?
    I don't want users to be able to add an Event Calendar with global agenda open to their favorites, I want to make it available via URL without login.
    Any suggestions?
    Thanks,
    r/ George

    Hi,
    It works here.
    Control-Click the event and select 'copy'. Click on the calendar you want to paste the event to, so it is highlighted with a grey background. Then select 'paste'.
    Best wishes
    John M

  • JDEV 10.1.3: Issue with Inherited public event handler methods in beans

    I have a bean validator method which it inherits from another base class.
    I am able to pick this method using the property inspector and it works fine.
    But in the jspx source view, i see a red wiggly line under the expression. Is this a bug or some bizzare way of enforcing some best practice (if using inherited event handler methods in beans is NOT a best practice)?
    The same is true for value change listeners.

    I started from scratch and the problem remains. Only one commandButton can fire an event which sets a variable that controls a af:switcher. The effect is similar to what the "blocking" attribute does but it is set to false on my components. Any ideas, time has already run out.

  • Using Async to wait for a specific event

    I've simplified the creation and deletion calls and used a generic item.  In my before method, I call Async.handleEvent to wait for PropertyChangeEvents, but this only waits for the first one.  My problem lies in the fact that ItemManager is an IEventDispatcher that sends multiple property change events, but I need to wait for the specific event with the property "item".  However, when I call Async inside the handler, it does not keep the Test method from running, Before assumes that it's Async responsibilities have been fulfilled and launches the next stage of tests.  How can I keep Before from moving on until an event with a specific property has been received?
    public class Test
            private static const TIME_OUT:int = 3000;
            [Before(async)]
            public function runBeforeEveryTest() : void
                // Create a new item
                item.create();  // This is an asynchronous creation that sends many Property Change events
                //Wait for the item to be created before continuing tests.
                Async.handleEvent( this, ItemManager.instance, PropertyChangeEvent.PROPERTY_CHANGE, handlePropertyChangeForItem, TIME_OUT);
            [After]
            public function runAfterEveryTest() : void
                // Delete the Item
                item.delete();
            [Test(async)]
            public function itemExists() : void
                      Assert.assertTrue( item.exists() );
           private function handlePropertyChangeForItem(evt:PropertyChangeEvent, eventObject:Object) : void
                 if (evt.property == "item")
                     // Now that the item has been created, we can start the tests.
                     return;
                 else
                     // Keep waiting.
                     Async.handleEvent( this, ItemManager.instance, PropertyChangeEvent.PROPERTY_CHANGE, handlePropertyChangeForItem, TIME_OUT);
    Thanks in advance, it's greatly appreciated!

    I can't reproduce this issue. All seems to be working fine with multiple deferred Async calls. I am pasting my code in. Since I did not have your manager, I tried to repiicate this with a timer. If you could look at my code and see if it differs from yours in a significant way, I can take another shot, but it seems to be working as expected.
    package  
    import flash.events.TimerEvent; 
    import flash.utils.Timer; 
    import mx.events.PropertyChangeEvent; 
    import org.flexunit.Assert; 
    import org.flexunit.async.Async; 
    public class NestedAsync { 
    private static const TIME_OUT:int = 3000; 
    private var timer:Timer; 
    Before(async)]
    public function runBeforeEveryTest() : void {   timer =
    new Timer( 1000, 5 ); 
      Async.handleEvent(this, timer, TimerEvent.TIMER, handleTimerTick, TIME_OUT);timer.start();}
    [After]
    public function runAfterEveryTest() : void {  timer.stop();
      timer =
    null;}
    Test(async)] 
    public function itemExists() : void {Assert.assertTrue(
    true );}
    private function handleTimerTick(evt:TimerEvent, eventObject:Object) : void {  
      if ( timer.currentCount == 5 ) { 
        // Now that the item has been created, we can start the tests. 
        return;  }
      else  { 
        // Keep waiting.    Async.handleEvent(
    this, timer, TimerEvent.TIMER, handlePropertyChangeForItem, TIME_OUT);
    suite.cases { 

  • HT4968 Is it possible to show events of some one's ical in my app publically?

    hello everyone,
    I am trying to develop an app in which i can show public events of my ical to everyone,
    Is it possible if yes then please share the solution.
    Any help will be deeply appriciated....

    Hi ShubhamGoswami!
    Here is an article that can tell you a little more about public calendar sharing with iCloud:
    iCloud: Calendar sharing overview
    http://support.apple.com/kb/PH2689
    More information on this can also be found in this link:
    iCloud: Share a calendar with others
    http://support.apple.com/kb/ph2690
    Thanks for coming to the Apple Support Communities!
    Regards,
    Braden

  • Async tcp client and server. How can I determine that the client or the server is no longer available?

    Hello. I would like to write async tcp client and server. I wrote this code but a have a problem, when I call the disconnect method on client or stop method on server. I can't identify that the client or the server is no longer connected.
    I thought I will get an exception if the client or the server is not available but this is not happening.
    private async void Process()
    try
    while (true)
    var data = await this.Receive();
    this.NewMessage.SafeInvoke(Encoding.ASCII.GetString(data));
    catch (Exception exception)
    How can I determine that the client or the server is no longer available?
    Server
    public class Server
    private readonly Dictionary<IPEndPoint, TcpClient> clients = new Dictionary<IPEndPoint, TcpClient>();
    private readonly List<CancellationTokenSource> cancellationTokens = new List<CancellationTokenSource>();
    private TcpListener tcpListener;
    private bool isStarted;
    public event Action<string> NewMessage;
    public async Task Start(int port)
    this.tcpListener = TcpListener.Create(port);
    this.tcpListener.Start();
    this.isStarted = true;
    while (this.isStarted)
    var tcpClient = await this.tcpListener.AcceptTcpClientAsync();
    var cts = new CancellationTokenSource();
    this.cancellationTokens.Add(cts);
    await Task.Factory.StartNew(() => this.Process(cts.Token, tcpClient), cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
    public void Stop()
    this.isStarted = false;
    foreach (var cancellationTokenSource in this.cancellationTokens)
    cancellationTokenSource.Cancel();
    foreach (var tcpClient in this.clients.Values)
    tcpClient.GetStream().Close();
    tcpClient.Close();
    this.clients.Clear();
    public async Task SendMessage(string message, IPEndPoint endPoint)
    try
    var tcpClient = this.clients[endPoint];
    await this.Send(tcpClient.GetStream(), Encoding.ASCII.GetBytes(message));
    catch (Exception exception)
    private async Task Process(CancellationToken cancellationToken, TcpClient tcpClient)
    try
    var stream = tcpClient.GetStream();
    this.clients.Add((IPEndPoint)tcpClient.Client.RemoteEndPoint, tcpClient);
    while (!cancellationToken.IsCancellationRequested)
    var data = await this.Receive(stream);
    this.NewMessage.SafeInvoke(Encoding.ASCII.GetString(data));
    catch (Exception exception)
    private async Task Send(NetworkStream stream, byte[] buf)
    await stream.WriteAsync(BitConverter.GetBytes(buf.Length), 0, 4);
    await stream.WriteAsync(buf, 0, buf.Length);
    private async Task<byte[]> Receive(NetworkStream stream)
    var lengthBytes = new byte[4];
    await stream.ReadAsync(lengthBytes, 0, 4);
    var length = BitConverter.ToInt32(lengthBytes, 0);
    var buf = new byte[length];
    await stream.ReadAsync(buf, 0, buf.Length);
    return buf;
    Client
    public class Client
    private TcpClient tcpClient;
    private NetworkStream stream;
    public event Action<string> NewMessage;
    public async void Connect(string host, int port)
    try
    this.tcpClient = new TcpClient();
    await this.tcpClient.ConnectAsync(host, port);
    this.stream = this.tcpClient.GetStream();
    this.Process();
    catch (Exception exception)
    public void Disconnect()
    try
    this.stream.Close();
    this.tcpClient.Close();
    catch (Exception exception)
    public async void SendMessage(string message)
    try
    await this.Send(Encoding.ASCII.GetBytes(message));
    catch (Exception exception)
    private async void Process()
    try
    while (true)
    var data = await this.Receive();
    this.NewMessage.SafeInvoke(Encoding.ASCII.GetString(data));
    catch (Exception exception)
    private async Task Send(byte[] buf)
    await this.stream.WriteAsync(BitConverter.GetBytes(buf.Length), 0, 4);
    await this.stream.WriteAsync(buf, 0, buf.Length);
    private async Task<byte[]> Receive()
    var lengthBytes = new byte[4];
    await this.stream.ReadAsync(lengthBytes, 0, 4);
    var length = BitConverter.ToInt32(lengthBytes, 0);
    var buf = new byte[length];
    await this.stream.ReadAsync(buf, 0, buf.Length);
    return buf;

    Hi,
    Have you debug these two applications? Does it go into the catch exception block when you close the client or the server?
    According to my test, it will throw an exception when the client or the server is closed, just log the exception message in the catch block and then you'll get it:
    private async void Process()
    try
    while (true)
    var data = await this.Receive();
    this.NewMessage.Invoke(Encoding.ASCII.GetString(data));
    catch (Exception exception)
    Console.WriteLine(exception.Message);
    Unable to read data from the transport connection: An existing   connection was forcibly closed by the remote host.
    By the way, I don't know what the SafeInvoke method is, it may be an extension method, right? I used Invoke instead to test it.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Using Async calls in a Util class

    I have a Utility class that I want to put code in that I'm reusing over and over again.  This includes Async.handleEvent calls.  If I call an instance of the Util class from a [Test(async)] method, can I use the Async call in that other event?
    When I tried this in my code, it said that it "Cannot add asynchronous functionality to methods defined by Test,Before or After that are not marked async" but my [Test] is marked as async. And when I was in the same class, I was able to have non-Test methods make Async calls.
    Thanks for the help!
    Mocked up Example (please note these are two separate files):
    // Test.as
    package
        import TimerUtil;
        public class Test
            [Test(async)]
            public function waitForTimer():void
                TimerUtil.newTimer();
    // TimerUtil.as
    package
        import flash.events.TimerEvent;
        import flash.utils.Timer;
        import org.flexunit.async.Async;
        public class TimerUtil
            private static var instance:TimerUtil;
            private var timer:Timer;
            private static const TIME_OUT:int = 1000;
            public static function newTimer() : void
                if (!instance) instance = new TimerUtil();
                instance.timer = new Timer(1000, 5);
                instance.timer.start();
                instance.waitForFifthTick();
            private function waitForFifthTick() : void
                Async.handleEvent(this, instance.timer, TimerEvent.TIMER, handleTimerTick, TIME_OUT);
            private function handleTimerTick ( evt:TimerEvent, eventObject:Object) : void
                if ( timer.currentCount == 5 )
                    // We are at the Fifth click, move on.
                else
                    Async.handleEvent(this, instance.timer, TimerEvent.TIMER, handleTimerTick, TIME_OUT);
    Message was edited by: zyellowman2
    I missed a comma.  And a few "instance"s

    Yes, you can put async calls in utility classes or wherever you want. That isn't the issue here though.
    In your test you call TimerUtil.newTimer()
    That code creates a timer and then returns. Then your test returns. At that moment, FlexUnit sees that your test has finished and that there are no outstanding registered asynchronous events so it declares the test a success. Then, a second later, your other method executes and tries to register an async call. FlexUnit has no idea what test this pertains to, or why this call is being made as it is no longer in the context of the original test, hence the message you are receiving that you can only using Async calls inside of a method marked with a Async... as, in FlexUnit's opion, the method that is executing this code no longer has anything to do with a test with an async param.
    The best way to think about this is a chain that cannot be broken. As soon as a method finishes executing with, FlexUnit will declare it a success unless we are waiting on something else (an async event of some sort) That is what the Async syntax really does, it tells the framework not to declare this method a success just yet, and that there is something else we need to account for to make that decision.
    So, right now, in your newTimer() you don't let the framework know that you will be waiting for an async event. Therefore, when that method and the test method is over, so is the test.
    Mike

  • Async problem when using FlexUnit4

    Hi all,
    I have a problem I could use a little help with. I'm trying to change a test to FlexUnit4 (first used FlexUnit 0.9), but when using the Async class I get a "Timeout Occurred before expected event" (from the ExpectAsync.handleAsyncTimeOut function (line 315)).
    The function looks like this:
    [Test(async)]
    public function GetApplicationMenuTest():void
    var event:GetApplicationMenuEvent=new GetApplicationMenuEvent(this.loader, applicationId);
    var asyncHandler:Function=Async.asyncHandler(this, resultHandler, 500);
    this.loader.fireEvent(event, asyncHandler);
    The loader.fireEvent(event:MVCEvent, callback:Function) method is a function that will set a busy indicator on the screen and that fires the event. When the event is fired a server call is eventually made, and we wait for a responds. When the responds is received the retrieved data is processed until finally the function this.event.loader.receiveData(resultObject) is called. Where the loader is the same as the function above and the resultObject is the processed responds data.
    This receivedata function removes the busy indicator from the screen and calls the the callback:Function as can be seen from the super class of the loader:
    public function receiveData(data:Object):void
       this.callBackFunction(data);
    The callBackFunction is the following function in our test:
    private function resultHandler(data:EibDataObject):void
    Assert.assertTrue("The session is not ok", data.sessionOK);
    Assert.assertTrue("Fault messages have been retrieved", data.messages.length <= 0);
    Using this setup described above I get a "Timeout Occurred before expected event". I never had a problem using the FlexUnit 0.9 setup that looked as follows:
    public function GetApplicationMenuTest():void
    var applicationId:String = "";
    var event:GetApplicationMenuEvent = new GetApplicationMenuEvent(this.loader, applicationId);
    this.loader.fireEvent(event, addAsync(resultHandler, Model.TIMEOUT));
    So the only difference in the test is the callback:Function that is set.
    I checked out the code of FlexUnit4 (http://opensource.adobe.com/svn/opensource/flexunit/branches/4.x/FlexUnit4) to debug the problem and I found that the method AsyncHandler.handleEvent(event:Event) would not be entered. When I changed this method to AsyncHandler.handleEvent(data:Object) I saw that the argument passed to this function was not an event but  the resultObject described above.
    This is offcourse pretty logical because AsyncHandler.handleEvent is the method that is returned as the Function from Async.asyncHandler(...).
    What do I need to do to change
    public function GetApplicationMenuTest():void
    var applicationId:String = "";
    var event:GetApplicationMenuEvent = new GetApplicationMenuEvent(this.loader, applicationId);
    this.loader.fireEvent(event, addAsync(resultHandler, Model.TIMEOUT));
    to FlexUnit 4 in the scenario described above? Hope you guys can help
    Greetz,
    Rick
    Also I have a small question, what is the 'timeout=xxx' statement for in the [Test] metadata when you also provide a timeout to the async method?

    A few things for you:
    1) The opensource.adobe.com address is always lagging behind. Our active website is www.flexunit.org and our active code development is at github. We just update the adobe site with major release versions.
    2) The timeout in the Test metadata: We support multiple simultaneous outstanding events in FlexUnit 4. In other words, you can say, you expect a given object to broadcast event1, followed by event2, followed by event3. The timeout in the Test is an overall timeout for all of the steps, so each is given their own timeout, but in total they should not exceed the number assigned in the Test metadata
    3) As you noted the async methods are expecting to handle an event and you are using them with a callback, which is the root of the problem. I clearly missed the fact that the .9 version would allow this use case, so, if you would, I would appreciate if you could file an enhancement request in our project at bugs.adobe.com and I can work on getting this resolved for the next version.
    In the meantime, you could use the responder functionality, which seems like it would work fine, albeit not as elegant as I would like. I can't test this out at my current location, but wanted to get you an answer asap, so post back with issues.
    [Test(async)]
    public function GetApplicationMenuTest():void
       var event:GetApplicationMenuEvent=new GetApplicationMenuEvent(this.loader, applicationId);
       var responder:Responder = new mx.rpc.Responder( resultHandler, null );
       var asyncResponder:IResponder=Async.asyncResponder(this, responder, 500);
       this.loader.fireEvent(event, asyncResponder.result );
    Mike

  • Async loading of test swf is never caught by listener

    Hi all,
    I'm really struggling getting a testing structure in place. I need to test a sub-swf which gets loaded into a range of main applications and its methods are then invoked. Therefore, I want to setup a test initially to load in that sub-swf (before calling its functions).
    However, despite Firebug revealing that the swf in question was called ok (200 return) the timeout function always eventually is invoked.
    Please can someone tell me what I'm doing wrong as I've been struggling with this for over a week.
    Code roughly copy-and-pasted (no errors when I run the original)...
    public class loadSWFTester
    import flash.display.Loader;
    import flash.display.LoaderInfo;
    import flash.events.*;
    import org.flexunit.asserts.*;
    import org.flexunit.async.Async;
    private var _loader:Loader;
    private var _request:URLRequest;
    [Before(async)]
    public function setUp():void
    _loader = new Loader();
    _request = new URLRequest("http://example.com/my.swf");
    [Test(async, description="Swf load example")]
    public function loadSwf():void
    _loader.addEventListener(Event.COMPLETE, Async.asyncHandler(this, verifySwfLoad, 10000, null, handleTimeout));
    _loader.load(_request);
    private function verifySwfLoad(event:Event, passThroughData:Object):void
    trace("[verifySwfLoad");
    private function handleTimeout(event:Event):void
    fail(" testLoad did not execute: "+event);

    If I specify a non-existant URL then I get this error:
    Error #2044: Unhandled IOErrorEvent:. text=Error #2035: URL Not Found.
    ...so the previous URLs I've been specifying must've been verified by the Flash player before failing in some respect somewhere else.
    No event listeners seem to pick up on anything. I've tried adding a few extra (not in the example link I supplied previously yet) but the timeout function is the one which is always hit.
    _loader.addEventListener(Event.INIT, Async.asyncHandler(this, initHandler, 10000, null, handleTimeout));
    _loader.addEventListener(IOErrorEvent.IO_ERROR, Async.asyncHandler(this, onIoError, 10000, null, handleTimeout));
    I've tried moving these listeners up in the [Before] block too with similar results.

  • Async tests and Assert throws exceptions

    Hi,
    In a regular non-async test, something like Assert.assertEquals( "apples", "oranges" ); gives a nice report that the strings didn't match.  The test fails and the suite continues and all is good.  If the test is asynchronous, though, you get an uncaught exception, and a timeout on the test rather than a nice report.  Worse, it will cause a command-line based test to freeze with a stack trace showing (if you have a debug version of Flash, of course), until you hit the dismiss button.
    Here's an example.  Without the Assert.assertEquals line, the test passes after two seconds as expected.  With the Assert.assertEquals in place, you get the behaviour I described.  So the question is, how do I use asserts in an asynchronous test?  I want the behaviour that you get with synchronous tests, i.e. a nice report and no pop-up dialog showing the stack.
            const TEST_COMPLETE:String = "testComplete";
            [Test(async)]
            public function myAsyncTest():void   
                Async.proceedOnEvent( this, this, TEST_COMPLETE, 5000 );
                var t:Timer = new Timer(2000, 1);
                t.addEventListener(TimerEvent.TIMER, timeout);
                t.start();
            private function timeout(e:Event):void
                Assert.assertEquals( "apples", "oranges" );
                dispatchEvent( new Event(TEST_COMPLETE) );
    Any help?
    Thanks!
    DB

    The code you have below doesn't do what you think it does.
    When you setup an async test in FlexUnit, it needs to know what code is related to a given test. When you use items like the asyncHandler() methods, it basically calls that code in a way that watches for assertions and can manage to track them when they occur.
    In your code, you are setting up a timer and that timer is calling another method which does an assertion. The timer calls that code directly from the top of the call stack... in other words, completely outside of FlexUnit. FlexUnit doesn't know your method is being called and cannot wrap the call in order to catch any information thrown from your assertion.
    Can you describe what you want to do and I can advise you on the right syntax? It isn't that assertions work differently in async tests, it is that FlexUnit has no idea that the timeout() method is being called, Flash Player is calling it directly, and hence there is no way for it to watch the assertion.
    I am guessing you want something more alogn the lines of this, but I am not sure:
    Test(async)] 
    public function myAsyncTest():void{
    var t:Timer = new Timer(2000, 1); 
    var handler:Function = Async.asyncHandler( this, timeout );t.addEventListener(TimerEvent.TIMER, handler );
    t.start();
    private function timeout(e:Event, passThroughData:Object ):void
    Assert.assertEquals(
    "apples", "oranges" );}

  • BeforeClass(async) handler assertion

    package
        import flash.events.TimerEvent;
        import flash.utils.Timer;
        import org.flexunit.Assert;
        import org.flexunit.async.Async;
        public class SomeTestCase
            [BeforeClass(async)]
            public static function startTimer():void
                const timer:Timer = new Timer(100, 1);
                Async.handleEvent(SomeTestCase, timer, TimerEvent.TIMER_COMPLETE, handleTimerComplete);
                timer.start();
            private static function handleTimerComplete():void
                Assert.assertTrue(false);
            [Test]
            public function someTest():void
    Assertion in handleTimerComplete will not fail. Is it a bug?
    flexunit-4.1.0-8-flex_4.1.0.16076

    Yes,
    take a look at the test classes
    TestBeforeAfterClassOrderAsync.as
    TestBeforeAfterOrderAsync.as
    Mike

  • Async testing question

    Hello,
    I would like to now how to proceed to test a delegate class that is taking an IResponder as method parameter.
    For exemple :
    LoginDelegate.as (simplified version) :
    public function login( responder : IResponder, username : String, password : String ) : void
    var s : SomeService = new SomeService();
    s.addEventListener( ResultEvent.RESULT, responder.result );
    s.addEventListener( FaultEvent.FAULT, responder.fault );
    s.login( username, password );
    As you can see, the delegate communicate with some backend service and then calls the provided responder methods.
    I tried to use Async.asyncResponder without luck:
    [Before(async)]
    public function runBeforeAsyncTest():void
    var d : LoginDelegate = new LoginDelegate();
    var responder : Responder = new Responder(result,fault);
    Async.asyncResponder(this, responder, 5000);
    d.login(responder, "someuser", "somepass");
    public function result(data:Object):void
    trace("result");
    public function fault(info:Object):void
    trace("fault");
    [Test]
    public function testLoginFail():void
    trace("testLoginFail")
    Assert.assertEquals("5", 5);
    It goes in result method, then It fails with :
    testLoginFail Error: Timeout Occurred before expected event
    Can someone please tell me how to test my delegate properly
    Thank you in advance

    Ok this seems to work, but I don't know if it is considered best practice :
    (I would still like to hear from someone used to test delegate)
    [Before(async)]
    public function runBeforeAsyncTest():void
    delegate = new LoginDelegate();
    user = null;
    [After(async)]
    public function runAfterAsyncTest():void
    delegate = null;
    [Test(async)]
    public function testLoginPass():void
    var responder : IResponder = Async.asyncResponder(this, new Responder(result,fault), 5000);
    delegate.login(responder, VALID_USER_ID, VALID_USER_PASS);
    public function result(data:Object):void
    user = data as UserDTO;
    Assert.assertTrue( user is UserDTO && user.id.toString() == VALID_USER_ID );
    public function fault(info:Object):void
    Assert.assertNull(user);

  • I am trying to raise event at UserControl, and catch it at Main program, But the event always return null

    I am trying to raise a event in one of classes of userControl, and Fire it in the Main class. I tried two different ways to fire this event, one of them works, But I still want to know why other way cannot work, and how to fix it.
    My userContol class:
    public partial class UserControl1 : UserControl
    public UserControl1()
    InitializeComponent();
    if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
    return;
    Class1 c = new Class1();
    Thread accept = new Thread(
    () =>
    c.connection();
    accept.Start();
    And the Class1:
    public class Class1
    public delegate void myhandler(object sender, EventArgs e);
    public event myhandler test;
    public Class1()
    public void connection()
    test(this, new EventArgs());
    In the Main, I just simply add into referent, and add
    xmlns:my="clr-namespace:WpfControlLibrary1;assembly=WpfControlLibrary1"
    then I try to subscribe this event in the main
    public partial class SurfaceWindow1 : SurfaceWindow
    /// <summary>
    /// Default constructor.
    /// </summary>
    public SurfaceWindow1()
    InitializeComponent();
    Class1 c = new Class1();
    c.test+=new Class1.myhandler(c_test);
    // Add handlers for window availability events
    AddWindowAvailabilityHandlers();
    public void c_test(object sender, EventArgs e)
    MessageBox.Show("fire");
    If I only raise this event not into thread, it works fine, but If I try to let it raise in this thread, this test event only return null, and shows:
    Object reference not set to an instance of an object.
    looks like I did not subscribe it ever. So How to fix it if I must use it in thread.

    Subscribing to events window to class is not a great approach.
    You have to then go un subscribe those handlers in order to allow your instance to be disposed.
    Forget that and you'll eventually notice you have memory leaks.
    The way I do this sort of thing is using mvvm light messenger.
    You can keep everything decoupled then.
    http://social.technet.microsoft.com/wiki/contents/articles/26070.aspx
    I just did a bit of code for someone else which shows how to do cross thread stuff with this approach.
    public partial class MainWindow : Window
    public MainWindow()
    InitializeComponent();
    Messenger.Default.Register<String>(this, (action) => ReceiveString(action));
    private void ReceiveString(string msg)
    MessageBox.Show(msg);
    Dispatcher.BeginInvoke((Action)delegate()
    tb.Text = msg;
    private void Button_Click(object sender, RoutedEventArgs e)
    Task.Factory.StartNew(() => {
    Messenger.Default.Send<String>("Hello World");
    Note that the message arrives on the thread it was sent from. That's not the ui thread because it was sent from that task.factory.startnew to deliberately put it on a different thread.
    In order to change UI controls, it uses dispatcher.begininvoke to run code on the UI thread.
    Although this is in one piece of code behind publisher and subscriber can be in two totally different classes which have no reference of knowledge of each other.
    Meaning you can send a message<t> from any class1 or whatever you like and your mainwindow can subscribe and act of receipt of a message<t>.
    It is the type which defines which message one is. You put data you want to send in t and use it in the subscriber.
    Hope that helps.
    Technet articles: Uneventful MVVM;
    All my Technet Articles

Maybe you are looking for