Migration from Flex 3 to Flex 4.5: problem with network format - apache-flex

I'm currently migrating a large project from Flex 3 to Flex 4.5. The problem I'm stuck on is network communication: we're using a custom protocol that we embed in AMF3, but it seems the messages sent by flash.net.NetConnection aren't readable.
Our Java back-end uses some BlazeDS classes to deserialize the message, namely flex.messaging.io.amf.AmfMessageDeserializer.AmfMessageDeserializer, and I can monitor the network traffic with Charles Web Proxy which decodes AMF3. The very simple code herebelow sends a message that can be decoded by Charles when compiled in Flex 3.5, but not in Flex 4.5 (I get "Failed to parse data (com.xk72.amf.AMFException: Unsupported AMF3 packet type 17 at 26").
import mx.controls.Alert;
private function init():void
{
var pdl : Dictionary = new Dictionary();
var connection : NetConnection = new NetConnection();
connection.connect("http://localhost");
var responder : Responder = new Responder(result);
connection.call("net", responder, pdl);
}
private function result(pdl : Object) : void {
Alert.show("coucou", "hello");
}
I've set up an apache server at localhost:80 to test this.
Has anyone used NetConnection in Flex 4.5 and encountered deserialization problems? How did you solve them?
Thanks,
Daniel

AMF3 has a bunch of different core types it can serialize. One of those core types is new to AMF3 in the past year or two, Dictionary, and it has a "packet type" of 17, thus the error message. I'm not sure why Flex 3 would serialize it as something other than a Dictionary and Flex 4.5 would serialize it as the new Dictionary type, but you're getting an error because your BlazeDS backend doesn't support the new Dictionary type.
The solution is to either figure out what it was sending as in Flex 3 and switch to that, or to upgrade BlazeDS (there seems to have been a patch added to BlazeDS last year for Dictionary http://forums.adobe.com/thread/684487).
edit: Didn't realize that the error was with Charles. Charles probably hasn't added support for Dictionary, as it's not part of the documented AMF3 specs. Have you tried the beta of Charles?

Since you're working with legacy code, you may need to set the NetConnection's objectEncoding property manually before you make the connection. You can set the connection's objectEncoding with the help of the ObjectEncoding class.
What version of Flash Player are you using?

Related

Is it possible to determine whether a Thrift TBaseClient is currently busy or available?

In our system, we have one C++ component acting as a Thrift Server, and one .netCore/C# component as a client.
So far, I was managing a single connection, so using a singleton to create my ThriftPushClientWrapper which implements TBaseClient. (via the generated object from the thrift interface)
.AddSingleton<IThriftPushClientWrapper>(sp =>
{
var localIpAddress = IPAddress.Parse(serverIp);
var transport = new TSocketTransport(localIpAddress, dataPort);
var protocol = new TBinaryProtocol(transport);
return new ThriftPushClientWrapper(protocol);
});
(so far using 0.13 version of the Thrift library, need to update to 0.14.1 soon, but wonder if the server part must be updated too/first).
This is working great.
Now, I want multiple clients that can connect to the server simultaneously, all on the same ip:port
So I am starting a ClientFactory, but wonder how to deal with the creation of the client.
To be more precise, the server part is configured for 5 threads, so I need 5 clients.
One simple approach would be to create a new client each time, but probably inefficient.
A better approach is to have a collection of 5 clients, and using the next available free one.
So I started with the following factory, where I should get the index from outside.
private readonly ConcurrentDictionary<int, IThriftPushClientWrapper> _clientDict;
public IThriftPushClientWrapper GetNextAvailablePushClient(int index)
{
IThriftPushClientWrapper client;
if (_clientDict.ContainsKey(index))
{
if (_clientDict.TryGetValue(index, out client) && client != null)
return client;
else // error handling
}
// add new client for the expecting index
client = CreateNewPushClient();
_clientDict.TryAdd(index, client);
return client;
}
private IThriftPushClientWrapper CreateNewPushClient()
{
var localIpAddress = IPAddress.Parse(serverIp);
var transport = new TSocketTransport(localIpAddress, dataPort);
var protocol = new TBinaryProtocol(transport);
return new ThriftPushClientWrapper(protocol);
}
My next issue it to determine how to set the index from outside.
I started with a SemaphoreSlim(5,5) using the semaphore.CurrentCount as index, but probably not the best idea. Also tried with a rolling index from 0 to 5. But apparently, a CancellationToken is used to cancel further procceesing. Not sure the root cause yet.
Is it possible to determine whether a TBaseClient is currently busy or available?
What is the recommended strategy to deal with a pool of clients?
The easiest solution to solve this is to do it right. If you are going to use some resource from a pool of resources, either get it off the pool, or mark it used in some suitable way for that time.
It's notable that the question has nothing to do with Thrift in particular. You are trying to solve a weak resource management approach by trying to leverage other peoples code that was never intended to work in such a context.
Regarding how to implement object pooling, this other question can provide further advice. Also keep in mind that especially on Windows platforms not all system resources can be shared freely across threads.

Read existing messages from a Subscription/Topic in Azure ServiceBus

I am trying to read all existing messages on an Azure ServiceBus Subscription, using the Microsoft.Azure.ServiceBus.dll (in .Net Core 2.1) but am struggling.
I've found many examples that the following should work, but it doesn't:
var client = new SubscriptionClient(ServiceBusConnectionString, topicName, subscription, ReceiveMode.PeekLock, null);
var totalRetrieved = 0;
while (totalRetrieved < count)
{
var messageEnumerable = subscriptionClient.PeekBatch(count);
//// ... code removed from this example as not relevant
}
My issue is that the .PeekBatch method isn't available, and I'm confused as to how I need to approach this.
I've downloaded the source for the ServiceBusExplorer from GitHub (https://github.com/paolosalvatori/ServiceBusExplorer) and the above code example is pretty much as it's doing it. But not in .Net Core / Microsoft.Azure.ServiceBus namespace.
For clarity though, I'm trying to read messages that are already on the queue - I've worked through other examples that create listeners that respond to new messages, but I need to work in this disconnected manner, after the message has already been placed on the queue.
ServiceBusExplorer uses WindowsAzure.ServiceBus Library, which is a .Net Framework Library and you cannot use it in .Net Core applications. You should use Microsoft.Azure.ServiceBus (.Net Standard Library) in .Net Core applications.
Check here for samples of Microsoft.Azure.ServiceBus
var client = new SubscriptionClient(ServiceBusConnectionString, topicName, subscription, ReceiveMode.PeekLock, null);
client .RegisterMessageHandler(
async (message, token) =>
{
await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
}
);
Try using RegisterMessageHandler. It will
receive messages continuously from the entity. It registers a message handler and
begins a new thread to receive messages. This handler is awaited
on every time a new message is received by the receiver.

Flash Builder Localhost works 100% Remote Host just shows title of Object for every entry

I have finally gotten my Flash Builder to look at my remote services but now I have a problem that my Remote information, which should be the same except for alot more entries, just displays each object with the title [object Object] I have had a look around and I see if I test the service out locally, it is working as it calls all the information under Response Name 'object and Response Value 'Object'
On my localhost configuration this shows the name which is inside my Object items. How can I fix this?
[object Object] is the result of the toString() method of Object. If you get this it probably means your custom object type is being returned as a generic object from the remote AMF service. A lot of things could be the cause of this. Here are a few to check:
1) Make sure that your custom object type is compiled into the app. IF the object is never used explicitly the Flex compiler will not put it in the final SWF. You can do this by creating a fake variable:
private var myUnusedObject : MyCustomObjectType;
Or, I believe, there is a compiler flag to force unused classes to be compiled into the SWF.
2) You may have to add a formal mapping on your server. This depends primarily on what server side tech you're using. In AS3 you add a RemoteAlias metadata to the class. In ColdFusion you use the alias tag on the cfcomponent tag. I believe in WerbORB.NET I had to add the mapping in an XML Config file [but it's been years since I've done that]. I assume alternate technologies use similar approaches.
3) Check case sensitivity on the path names for your server code and make sure that the aliases (mentioned in 2) match.
4) In ColdFusion AMF you have to make sure that your public properties and types match up. They must be in the same order in your AS3 class as they are in your remote CFC. The property types must match. String to String; Boolean to Boolean, etc... I assume other AMF implementations have similar restrictions.

concurrency issues with granite ds , flex

I use granite ds in my java server , but , when 100 user they're connected to flex application , granite return this error "Could not get channel id for message: flex.messaging.messages.RemotingMessage"
Thank for the help.
This is not an error but just a warning issued by the AMF3Serializer class. It can happen, for example, when the server is sending data without explicitly using a declared channel.
You can safely ignore this warning: channel identification is only used in order to handle legacy (ie: old-fashion) serialization options (legacyCollection / legacyXMLDocument), see Adobe documentation about them here (the "Configuring AMF serialization on a channel" section).
It is very unlikely that you need to use these very specific serialization options. So, again, just ignore or disable this warning.

Adobe AIR HTTP Connection Limit

I'm working on an Adobe AIR application which can upload files to a web server, which is running Apache and PHP. Several files can be uploaded at the same time and the application also calls the web server for various API requests.
The problem I'm having is that if I start two file uploads, while they are in progress any other HTTP requests will time out, which is causing a problem for the application and from a user point of view.
Are Adobe AIR applications limited to 2 HTTP connections, or is something else probably the issue?
From searching about this issue I've not found much but one article did indicated that it wasn't limited to just two connections.
The file uploads are performed by calling the File classes upload method, and the API calls are done using the HTTPService class. The development web server I am using is a WAMP server, however when the application is released it will be talking to a LAMP server.
Thanks,
Grant
Here is the code I'm using to upload the file:
protected function btnAddFile_clickHandler(event:MouseEvent):void
{
// Create a new File object and display the browse file dialog
var uploadFile:File = new File();
uploadFile.browseForOpen("Select File to Upload");
uploadFile.addEventListener(Event.SELECT, uploadFile_SelectedHandler);
}
private function uploadFile_SelectedHandler(event:Event):void
{
// Get the File object which was used to select the file
var uploadFile:File = event.target as File;
uploadFile.addEventListener(ProgressEvent.PROGRESS, file_progressHandler);
uploadFile.addEventListener(IOErrorEvent.IO_ERROR, file_ioErrorHandler);
uploadFile.addEventListener(Event.COMPLETE, file_completeHandler);
// Create the request URL based on the download URL
var requestURL:URLRequest = new URLRequest(AppEnvironment.instance.serverHostname + "upload.php");
requestURL.method = URLRequestMethod.POST;
// Set the post parameters
var params:URLVariables = new URLVariables();
params.name = "filename.ext";
requestURL.data = params;
// Start uploading the file to the server
uploadFile.upload(requestURL, "file");
}
Here is the code for the API calls:
private function sendHTTPPost(apiFile:String, postParams:Object, resultCallback:Function, initialCallerResultCallback:Function):void
{
var httpService:mx.rpc.http.HTTPService = new mx.rpc.http.HTTPService();
httpService.url = AppEnvironment.instance.serverHostname + apiFile;
httpService.method = "POST";
httpService.requestTimeout = 10;
httpService.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
httpService.addEventListener("result", resultCallback);
httpService.addEventListener("fault", httpFault);
var token:AsyncToken = httpService.send(postParams);
// Add the initial caller's result callback function to the token
token.initialCallerResultCallback = initialCallerResultCallback;
}
If you are on a windows system, Adobe AIR is using Microsofts WinINet library to access the web. This library by default limits the number of concurrent connections to a single server to 2:
WinInet limits the number of simultaneous connections that it makes to a single HTTP server. If you exceed this limit, the requests block until one of the current connections has completed. This is by design and is in agreement with the HTTP specification and industry standards.
... Connections to a single HTTP 1.1 server are limited to two simultaneous connections
There is an API to change the value of this limit but I don't know if it is accessible from AIR.
Since this limit also affects page loading speed for web sites, some sites are using multiple DNS names for artifacts such as images, javascripts and stylesheets to allow a browser to open more parallel connections.
So if you are controlling the server part, a workaround could be to create DNS aliases like www.example.com for uploads and api.example.com for API requests.
So as I was looking into this, I came across this info about using File.upload() in the documentation:
Starts the upload of the file to a remote server. Although Flash Player has no restriction on the size of files you can upload or download, the player officially supports uploads or downloads of up to 100 MB. You must call the FileReference.browse() or FileReferenceList.browse() method before you call this method.
Listeners receive events to indicate the progress, success, or failure of the upload. Although you can use the FileReferenceList object to let users select multiple files for upload, you must upload the files one by one; to do so, iterate through the FileReferenceList.fileList array of FileReference objects.
The FileReference.upload() and FileReference.download() functions are
nonblocking. These functions return after they are called, before the
file transmission is complete. In addition, if the FileReference
object goes out of scope, any upload or download that is not yet
completed on that object is canceled upon leaving the scope. Be sure
that your FileReference object remains in scope for as long as the
upload or download is expected to continue.
I wonder if something there could be giving you issues with uploading multiple files. I see that you are using browserForOpen() instead of browse(). It seems like the probably do the same thing... but maybe not.
I also saw this in the File class documentation
Note that because of new functionality added to the Flash Player, when publishing to Flash Player 10, you can have only one of the following operations active at one time: FileReference.browse(), FileReference.upload(), FileReference.download(), FileReference.load(), FileReference.save(). Otherwise, Flash Player throws a runtime error (code 2174). Use FileReference.cancel() to stop an operation in progress. This restriction applies only to Flash Player 10. Previous versions of Flash Player are unaffected by this restriction on simultaneous multiple operations.
When you say that you let users upload multiple files, do you mean subsequent calls to browse() and upload() or do you mean one call that includes multiple files? It seems that if you are trying to do multiple separate calls that that may be an issue.
Anyway, I don't know if this is much help. It definitely seems that what you are trying to do should be possible. I can only guess that what is going wrong is perhaps a problem with implementation. Good luck :)
Reference: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html#upload()
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html#browse()
Just because I was thinking about a very similar question because of an error in one of my actual apps, I decided to write down the answer I found.
I instantiated 11
HttpConnections
and was wondering why my Flex 4 Application stopped working and threw an HTTP-Error although it was working pretty good formerly with just 5 simultanious HttpConnections to the same server.
I tested this myself because I did not find anything regarding this in the Flex docs or on the internet.
I found that using more than 5 HTTPConnections was the reason for the Flex application to throw the runtime error.
I decided to instantiate the connections one after another as a temporally workaround: Load the next one after the other has received the data and so on.
Thats of course just temporally since one of the next steps will be to alter the responding server code in that way that it answers a request that contains the results of requests to more then one table in one respond. Of course the client application logic needs to be altered, too.

Resources