how to synchronize methods in actionscript? - actionscript

The question is how could I stop a method being called twice, where the first call has not "completed" because its handler is waiting for a url to load for example?
Here is the situation:
I have written a flash client which interfaces with a java server using a binary encrypted protocol (I would love to not have had to re-invent the whole client/server object communcation stack, but I had to encrypt the data in such a way that simple tools like tamper data and charles proxy could not pick them up if using SSL).
The API presents itself to flas as an actionscript swf file, and the API itself is a singleton.
the api exposes some simple methods, including:
login()
getBalance()
startGame()
endGame()
Each method will call my HttpCommunicator class.
HttpCommunicator.as (with error handling and stuff removed):
public class HttpCommunicator {
private var _externalHalder:function;
public function communicate(data:String, externalHandler:APIHandler):void {
// do encryption
// add message numbers etc to data.
this._externalHalder = externalHandler;
request.data = encrypt(addMessageNumers(data)));
loader.addEventListener(Event.COMPLETE, handleComplete);
loader.load(request);
}
private function handleComplete(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
String data = decrypt(loader.data);
// check message numbers match etc.
_externalHandler(data);
}
The problem with this is I cant protect the same HttpCommunicator object from being called twice before the first has handled the complete event, unless:
I create a new HttpCommunicator object every single time I want to send a message. I also want to avoid creating a URLLoader each time, but this is not my code so will be more problematic to know how it behaves).
I can do something like syncronize on communicate. This would effectivly block, but this is better than currupting the data transmission. In theory, the Flash client should not call the same api function twice in a row, but I but it will happen.
I implement a queue of messages. However, this also needs syncronization around the push and pop methods, which I cant find how to do.
Will option 1. even work? If I have a singleton with a method say getBalance, and the getBalance method has:
// class is instantiated through a factory as a singleton
public class API{
var balanceCommunicator:HttpCommunicator = new HttpCommunicator(); // create one for all future calls.
public funciton getBalance(playerId:uint, hander:Fuction):Number {
balanceCommunicator.communicate(...); // this doesnt block
// do other stuff
}
Will the second call trounce the first calls communicator variable? i.e. will it behave as if its static, as there is onlyone copy of the API object?
If say there was a button on the GUI which had "update balance", and the user kept clicking on it, at the same time as say a URLLoader complete event hander being called which also cals the apis getBalance() function (i.e. flash being multithreaded).

Well, first off, with the exception of the networking APIs, Flash is not multithreaded. All ActionScript runs in the same one thread.
You could fairly easily create a semaphore-like system where each call to communicate passed in a "key" as well as the arguments you already specified. That "key" would just be a string that represented the type of call you're doing (getBalance, login, etc). The "key" would be a property in a generic object (Object or Dictionary) and would reference an array (it would have to be created if it didn't exist).
If the array was empty then the call would happen as normal. If not then the information about the call would be placed into an object and pushed into the array. Your complete handler would then have to just check, after it finished a call, if there were more requests in the queue and if so dequeue one of them and run that request.
One thing about this system would be that it would still allow different types of requests to happen in parallel - but you would have to have a new URLLoader per request (which is perfectly reasonable as long as you clean it up after each request is done).

Related

How to test a private function inside an RxSwift observer?

observable.subscribe(onNext: { _ in
somePrivateFunction()
})
What is the RxSwift way to test that when observable receives an event the somePrivateFunction actually gets called or not? Since the subscription and the function are in the same class I can't mock it.
You need to check if any logic is placed in a subscription that can block call of this function. If there is - it may be worth to extract it to a parameter (eg. filter) so that logic can be a part of stream itself.
I assume that observable (source) is injected/redirected from another component (if it's not, most probably it should be). To mock that signal you can use TestableObservable, you can read more here: http://adamborek.com/rxtests-rxactionsheet/
Last but not least - you need to identify what kind of action somePrivateFunction() does. If it's setting some external values - then you can test that outgoing connection from that function. If it sets some internal flags - you can test if value of that flag has changed.

Handling a method that takes too long to execute and is not awaitable

We are building a custom way to process timesheets using eConnect. A method is exposed that allows out timesheets documents to be submitted to GP. This method is run synchronously, but can take a long time to complete. How can I handle this so that the user's client can make additional requests in the meantime?
I have attempted to use async/await on this method, but because the method isn't awaitable this will not work. The method depends on a windows service. I have researched potentially wrapping it in Task.Run but have hesitations since this sounds like a bad practice.
public bool SaveTimesheets(string ConnectionString, List<PATimeSheetsType> Timesheets)
{
string timesheetDocument = string.Empty;
//Creating timesheet document
bool result = false;
eConnectMethods eConnectMethods = new eConnectMethods();
//CreateEntity takes minutes to complete and return
result = eConnectMethods.CreateEntity(ConnectionString, timesheetDocument);
return result;
}
The behavior I currently get is that, if for instance I am doing an ajax calls on the client-side, the call doesn't seem to get there while the method above is executing. I would like it so that the method call executes in the background so that the client can still communicate with the server to execute other requests.
How can I handle this so that the user's client can make additional requests in the meantime?
The easiest solution is to change your session state to be None or Read-Only (for both this and the other requests). Then ASP.NET will allow multiple client requests for the same session.
If you're on pre-Core, the session state docs are here.

Add a property to an object (or at least similar outcome)

First, the context of what I'm doing. I am running an HttpServer which is handling HttpRequests.
HttpServer.bind(ADDRESS, PORT).then((HttpServer server) {
listenSubscription = server.listen(onRequest);
});
void onRequest(HttpRequest request) {
//handle request here
}
I'd like to add some logging to all this, and due to the asynchronous nature of it all, want to add some identifying marker to the requests (so I can match up the request receipts with the responses, fer example). The code inside of onRequest() calls a bunch of other functions to do different things (handle GET vs POST requests, etc.), so simply generating an id at the top is a cumbersome solution as I'd have to pass it around through all those other function calls. I am, however, already passing around the HttpRequest object, so I thought it would be nice to throw an id field on it, just like you would in Javascript, except that Dart doesn't work that way.
Thoughts then went to subclassing the HttpRequest class, but converting the HttpRequest object the onRequest() method receives seemed like much more trouble and overhead than my needs required.
So I ask, is there any idiomatic Dart way attach some data to an existing object? If there isn't something idiomatic, what is the simplest (both in code and runtime complexity) way you can think of to accomplish this?
Well, there's an Expando, but I don't know the performance implications.
Something like:
// somewhere top level. Create this once.
final loggingId = new Expando();
...
// inside of onRequest
loggingId[request] = generateId();
...
// later inside log()
print(loggingId[request]);
Expandos are like weak-reference maps, from my understanding.

OpenRasta: Uri seems to be irrelevant for handler selection

When registering two handlers for the same type, but with different URIs, the handler selection algorithm doesn't seem to check the uri when it determines which handler to use.
If you run the program below, you'll notice that only HandlerOne will be invoked (twice). It does not matter if I call for "/one" or "/two", the latter supposed to be handled by HandlerTwo.
Am I doing something wrong or is this something to be fixed in OpenRasta? (I'm using 2.0.3.0 btw)
class Program
{
static void Main(string[] args)
{
using (InMemoryHost host = new InMemoryHost(new Configuration()))
{
host.ProcessRequest(new InMemoryRequest
{
HttpMethod = "GET",
Uri = new Uri("http://x/one")
});
host.ProcessRequest(new InMemoryRequest
{
HttpMethod = "GET",
Uri = new Uri("http://x/two")
});
}
}
}
class Configuration : IConfigurationSource
{
public void Configure()
{
using (OpenRastaConfiguration.Manual)
{
ResourceSpace.Has.ResourcesOfType(typeof(object))
.AtUri("/one").HandledBy(typeof(HandlerOne));
ResourceSpace.Has.ResourcesOfType(typeof(object))
.AtUri("/two").HandledBy(typeof(HandlerTwo));
}
}
}
class HandlerOne
{
public object Get() { return "returned from HandlerOne.Get"; }
}
class HandlerTwo
{
public object Get() { return "returned from HandlerTwo.Get"; }
}
Update
I have a feeling that I could accomplish what I want similar using UriNameHandlerMethodSelector as described on http://trac.caffeine-it.com/openrasta/wiki/Doc/Handlers/MethodSelection, but then I'd have to annotate each handler methods and also do AtUri().Named(), which looks like boilerplate to me and I'd like to avoid that. Isn't AtUri(X).HandledBy(Y) making the connection between X and Y clear?
Eugene,
You should never have multiple registrations like that on the same resource type, and you probably never need to have ResourcesOfType<object> ever associated with URIs, that'll completely screw with the resolution algorithms used in OpenRasta.
If you're mapping two different things, create two resource classes. Handlers and URIs are only associate by resource class, and if you fail at designing your resources OpenRasta will not be able to match the two, and this is by design.
If you want to persist down that route, and I really don't think you should, then you can register various URIs to have a name, and hint on each of your methods that the name ought to be handled using HttpOperation(ForUriName=blah). That piece of functionality is only there for those very, very rare scenarios where you do need to opt-out of the automatic method resolution.
Finally, as OpenRasta is a compsable framework, you shouldnt have to go and hack around existing classes, you ought to plug yourself into the framework to ensure you override the components you don't want and replace them by things you code yourself. In this case, you could simply write a contributor that replaces the handler selection with your own moel if you don't like the defaults and want an MVC-style selection system. Alternatively, if you want certain methods to be selected rather than others, you can remove the existing operation selectors and replace them (or complement them with) your own. That way you will rely on published APIs to extend OpenRasta and your code won't be broken in the future. I can't give that guarantee if you forked and hacked existing code.
As Seb explained, when you register multiple handlers with the same resource type OpenRasta treats the handlers as one large concatenated class. It therefore guesses (best way to describe it) which potential GET (or other HTTP verb) method to execute, which ever it thinks is most appropriate. This isn't going to be acceptable from the developers prospective and must be resolved.
I have in my use of OpenRasta needed to be able to register the same resource type with multiple handlers. When retrieving data from a well normalised relational database you are bound to get the same type response from multiple requests. This happens when creating multiple queries (in Linq) to retrieve data from either side of the one-to-many relation, which of course is important to the whole structure of the database.
Taking advice from Seb, and hoping I've implemented his suggestion correctly, I have taken the database model class, and built a derived class from it in a resources namespace for each instance of when a duplicating resource type might have been introduced.
ResourceSpace.Has.ResourcesOfType<IList<Client>>()
.AtUri("/clients").And
.AtUri("/client/{clientid}").HandledBy<ClientsHandler>().AsJsonDataContract();
ResourceSpace.Has.ResourcesOfType<IList<AgencyClient>>()
.AtUri("/agencyclients").And
.AtUri("/agencyclients/{agencyid}").HandledBy<AgencyClientsHandler>().AsJsonDataContract();
Client is my Model class which I have then derived AgencyClient from.
namespace ProductName.Resources
{
public class AgencyClient: Client { }
}
You don't even need to cast the base class received from your Linq-SQL data access layer into your derived class. The Linq cast method isn't intended for that kind of thing anyway, and although this code will compile it is WRONG and you will receive a runtime exception 'LINQ to Entities only supports casting Entity Data Model primitive types.'
Context.Set<Client>().Cast<AgencyClient>().ToList(); //will receive a runtime error
More conventional casts like (AgencyClient) won't work as conversion to a SubClass isn't easily possible in C#. Convert base class to derived class
Using the AS operator will again compile and will even run, but will give a null value in the returned lists and therefore won't retrieve the data intended.
Context.Set<Client>().ToList() as IEnumerable<AgencyClient>; //will compile and run but will return null
I still don't understand how OpenRasta handles the differing return class from the handler to the ResourceType but it does, so let's take advantage of it. Perhaps Seb might be able to elaborate?
OpenRasta therefore treats these classes separately and the right handler methods are executed for the URIs.
I patched OpenRasta to make it work. These are the files I touched:
OpenRasta/Configuration/MetaModel/Handlers/HandlerMetaModelHandler.cs
OpenRasta/Handlers/HandlerRepository.cs
OpenRasta/Handlers/IHandlerRepository.cs
OpenRasta/Pipeline/Contributors/HandlerResolverContributor.cs
The main change is that now the handler repository gets the registered URIs in the initializing call to AddResourceHandler, so when GetHandlerTypesFor is called later on during handler selection, it can also check the URI. Interface-wise, I changed this:
public interface IHandlerRepository
{
void AddResourceHandler(object resourceKey, IType handlerType);
IEnumerable<IType> GetHandlerTypesFor(object resourceKey);
to that:
public interface IHandlerRepository
{
void AddResourceHandler(object resourceKey, IList<UriModel> resourceUris, IType handlerType);
IEnumerable<IType> GetHandlerTypesFor(object resourceKey, UriRegistration selectedResource);
I'll omit the implementation for brevity.
This change also means that OpenRasta won't waste time on further checking of handlers (their method signatures etc.) that are not relevant to the request at hand.
I'd still like to get other opinions on this issue, if possible. Maybe I just missed something.

Remoting (server side)

I´m relative new on remoting (2.0 C#). Is there any/someway to lock the server side object/instance to one client?
I have up to 10 clients that will connect to the server. The server will offer 3 different task/operations/classes and if one client does a request and if the server is not working on that, I´ll like to lock this operation to that client. The reason for this is that the requests works with HW that only can handle on task at the time. Hope you understand what I like too do.
EDIT:
I´ll try to explain my problem again...
I have 3 classes that will have X number of methods/operations (operations that will trigger a external hardware to do some measuring). When a client "connects" to one class (at the time) and request a measuring to be performed I want to lock that class to the client, hence, the client will own this class and it shall be able to execute all methods. No other client shall be able/allowed to access this class while the first client has control. The other tow classes should be open for requests from other clients, but the same principle/rules shall apply to these classes. As soon as a client request a lock it shall have it as long as it requires it. I´ll will have an intreface that all clients must follow. Call a method called Lock() to require the control over the class and Unlock() to release the control. I/We will develop all the clients and the server!
Thanks for all the help, so far!
Regards
/Anders
You have to lock the task by using semaphores in order to ensure only one thread at a time. Look into the Semaphore and Mutex classes.
Edit:
You can do many ways from locking to complex semaphores, here you have two samples:
This one only locks to ensure that one execution is being done at a time:
private static object lockObject=new object();
public void Test()
{
lock (lockObject)
{
//your code here
}
}
This one uses a Mutex to wait until it is released, but with a timeout that will return with some information to the client indicating that the method could not be executed.
private static Mutex mutex = new Mutex();
public bool Test2()
{
if (!mutex.WaitOne(500))
{
return false;
}
try
{
//your code here
}
finally
{
mutex.ReleaseMutex();
}
return true;
}
Ok, now I see the point.
You can use the CAO approach instead: create a factory (can be a singleton) that gives you a CAO (Client Activated Object) if nobody else owns an instance.
CAO is good for that because it will ensure that if the client dies the CAO would be released.
Explaining a CAO is too much for a simple answer, it is something like this: CAO is a class inherited from MarshalByRefObject that you will create from your factory and return the instance from one method (i.e.: your Lock method); the object lives in the server and the client receives only a proxy. The object will live into the server while it's lease is being refreshed by the client (done automatically while the object is referenced and client are alive).
You may take a look to the Ingo Rammer's articles and books on remoting.
jmservera, thanks for all your help.
I have now found a solution that will work for me...I´m using the proxy pattern combined with the factory pattern. I do use the WellKnownObjectMode.Singleton method so I can control how many active instances I have on my server.
And by doing it this way, i don´t need to share my code with the client, only the interface (as you said before).
Regards
/Anders

Resources