Adobe AIR. Local network error - apache-flex

For example, in local network, when Adobe Air is reading files from local server (\\Server\storage\) and network will be in down for a second, Air becomes eat a lot of memory and it is increasing up to 1GB (while normal memory use is 100 kb or less).
Just reading file with File('file path on local server'); from unstable network can cause this error.
Have anybody seen that in projects?
private function init() : void
{
file = new File("\\Server\dragracing\results.txt");
fileStream = new FileStream();
fileStream.addEventListener( Event.COMPLETE, fileComplete );
fileStream.openAsync( file, FileMode.READ );
}
private function fileComplete( event : Event ):void
{
fileContents = fileStream.readMultiByte( fileStream.bytesAvailable, ISO_CS );
.....
}
]]>

Have you tried closing the FileStream in the fileComplete method? Call the close method to make that happen.
private function fileComplete( event : Event ):void
{
fileContents = fileStream.readMultiByte( fileStream.bytesAvailable, ISO_CS );
fileStream.close();
.....
}
Also, based on your code it does not appear that you are ever actually reading information in from the file. from the file; so it is not clear the complete method will ever execute. There are plenty of methods used to read information in using the FileStream class.

Related

Telegram "API development tools" limits

I try to use my application (with TLSharp) but suddenly by using TelegramClient .SendCodeRequestAsync function, I get This Exception :
"Flood prevention. Telegram now requires your program to do requests
again only after 84894 seconds have passed (TimeToWait property). If
you think the culprit of this problem may lie in TLSharp's
implementation, open a Github issue "
after waiting for 84894 sec, It show this message again.
(I wait and try several times but messages doesn't differ:( )
Someone told me that its Telegram limits. Is it right?
Do you Have better idea to Send message/file to a telegram account?
It might be a late answer but can be used as a reference. the first problem is that Telegram APIs don't let each phone number to send code request more than 5 times a day. the second problem is shared session file that you use for TelegramClient by default. so you should create a custom session manager to separate each phone number session in a separate dat file.
public class CustomSessionStore : ISessionStore
{
public void Save(Session session)
{
var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Sessions");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var file = Path.Combine(dir, "{0}.dat");
using (FileStream fileStream = new FileStream(string.Format(file, (object)session.SessionUserId), FileMode.OpenOrCreate))
{
byte[] bytes = session.ToBytes();
fileStream.Write(bytes, 0, bytes.Length);
}
}
public Session Load(string sessionUserId)
{
var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Sessions");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var file = Path.Combine(dir, "{0}.dat");
string path = string.Format(file, (object)sessionUserId);
if (!File.Exists(path))
return (Session)null;
var buffer = File.ReadAllBytes(path);
return Session.FromBytes(buffer, this, sessionUserId);
}
}
then create your TelegramClient like this:
var client = new TelegramClient(apiId, apiHash, new CustomSessionStore(), phoneNumber);
I guess you are closing and starting your application many times or repeating this method. After 10 times the telegram API makes you wait for about 24 hours to prevent flood.
It's a Telegram limit, my advice: Wait 2-3 minutes between calling SendCodeRequestAsync()

flex FileReference load complete event never fired

I have an image which will be uploaded twice by flash. Besides, I'll do some resizing & compression stuff. So I have to load the data and create a BitmapData object.
_fileRef.addEventListener(Event.Complete, onLoadComplete);
_fileRef.load();
The problem is the complete event is never fired which could be checked from log message in console. What are the possibilities that such an event failed to be triggered?
my real code is shown as below:
private function prepareImage():void
{
_compressionFactor = 82;
if(as3_jpeg_wrapper==null)
{
as3_jpeg_wrapper = clibinit.init();
}
_fileRef.addEventListener(Event.COMPLETE, onImageComplete);
_fileRef.load();
}
private var tempLoader:Loader;
private var tempData:ByteArray;
private function onImageComplete(event:Event):void
{
Utils.log("loading data completed");
tempData = event.currentTarget.data;
_fileRef.removeEventListener(Event.COMPLETE,onImageComplete);
tempLoader = new Loader;
tempLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,onImageLoaded);
tempLoader.loadBytes(tempData);
}
The fact is that the log message "loading data completed" is never printed. I've traced the whole process, flash stucked here. The function prepareImage is called via:
Utils.log("We'll resize & compress the picture to be uploaded");
prepareImage();

Flex mobile : how to know it is the very first time running the application

I googled but didn't find a post for Flex mobile..
All I want for now is display an user agreement popup from TabbedViewNavigatorApplication when the user uses the app for the first time
var agreementView: UserAgreement = new UserAgreement();
PopUpManager.addPopUp(agreementView, this,true);
PopUpManager.centerPopUp(agreementView);
but maybe more later.
Please help..
What i did in my desktop air app;
I guess this will work at a mobile app also.
Make sure you have write access;
open yourproject-app.mxml scroll down to the end of the document. In the section, uncomment the following permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Now you can create files like for example an sqlite database.
At the applicationcomplete call the function checkFirstRun:
// functions to check if the application is run for the first time (also after updates)
// so important structural changes can be made here.
public var file:File;
public var currentVersion:Number;
private function checkFirstRun():void
{
//get the current application version.
currentVersion=getApplicationVersion();
//get versionfile
file = File.applicationStorageDirectory;
file= file.resolvePath("Preferences/version.txt");
if(file.exists)
{
checkVersion();
}
else
{
firstRun(); // create the version file.
}
}
public function getApplicationVersion():Number
{
var appXML:XML = NativeApplication.nativeApplication.applicationDescriptor;
var ns:Namespace = appXML.namespace();
var versionnumber:Number =Number(appXML.ns::versionNumber);
return versionnumber;
}
private function checkVersion():void
{
var stream:FileStream= new FileStream();
stream.open(file,FileMode.READ);
var prevVersion:String = stream.readUTFBytes(stream.bytesAvailable);
stream.close();
if(Number(prevVersion)<currentVersion)
{
// if the versionnumber inside the file is older than the current version we go and run important code.
// like alternating the structure of tables inside the sqlite database file.
runImportantCode();
//after running the important code, we set the version to the currentversion.
saveFile(currentVersion);
}
}
private function firstRun():void
{
// at the first time, we set the file version to 0, so the important code will be executed.
var firstVersion:Number=0;
saveFile(firstVersion);
// we also run the checkversion so important code is run right after installing an update
//(and the version file doesn't exist before the update).
checkFirstRun();
}
private function saveFile(currentVersion:Number):void
{
var stream:FileStream=new FileStream();
stream.open(file,FileMode.WRITE);
stream.writeUTFBytes(String(currentVersion));
stream.close();
}
private function runImportantCode():void
{
// here goes important code.
// make sure you check if the important change previously has been made or not, because this code is run after each update.
}
Hope this helps.
Greets, J.
Some you need to store whether the user has agreed to the agreement or not. IF they haven't agreed, then show it.
One way to do this would be to store a value in a shared object. Another way to do this would be to use a remote service and store such data in a central repository. I assume you'll want the second; so you can do some form of tracking against the number of users using your app.

application becomes unresponsive during directory listing in flex 3

I have designed an AIR application that displays a list with all txt files located in C:\ directory. I have used following code:
var videoListsArr:ArrayList = new ArrayList();
var folder:File = new File(driveName+":\\");
folder.getDirectoryListingAsync();
folder.addEventListener( FileListEvent.DIRECTORY_LISTING, handleDirectoryListing );
private function handleDirectoryListing( event:FileListEvent ):void
{
for each(var item:File in event.files)
{
var itemExtn:String = (item.extension != null) ? item.extension.toLocaleLowerCase() : null;
if(item.isDirectory)
{
item.getDirectoryListingAsync();
item.addEventListener( FileListEvent.DIRECTORY_LISTING, handleDirectoryListing );
}
else if(!item.isSymbolicLink && itemExtn != null)
{
if(itemExtn == "txt")
videoListsArr.addItem(txt);
}
}
}
This function works fine but it is being executed the application is hang and become unresponsive. Please tell me how to resolve this problem that it displays the list of txt file without making application unresponsive ?
from what i can see, you're getting a directory, looking at all the files in there, and if one of them is a directory, you look at all the files etc recursively, which could end up being very heavy depending on the start folder. remove the first if check and tell me if it's still unresponsive
I use a timer to break up the processing. My timer subclasses Timer to add a files:Array and a directories : Array.
The initial handler that processed the top-level directory (in my case, loadDirectoryHandler) loads the timer.files with all the files it cannot processes immediately as well as all the sub-directories,
On each cycle through the TIMER handler, it slices out a chunk of the files Array (e.g. 200 files), processes that, and then starts the timer if there are any left so they get processed on the next TIMER event.
For each directory, it takes the File object and
file.addEventListener( FileListEvent.DIRECTORY_LISTING, loadDirectoryHandler );
file.getDirectoryListingAsync();
Cheers

how to send byte array to server in flash builder (Flex 4)

I have a video file in my local system.I am using windows XP in my system. Now i want to send this video file byte array to server in Flash Builder (Flex 4). I am using PHP at server end.
How can i do this? Please guide
Thanks
Socket.writeBytes() will do what you need.
Via this link:
.
// serialization
var serializedSound:ByteArray;
serializedSound = serializeSound(sound);
serializedSound.position = 0;
// unserialization
var newSound:Sound = new Sound();
newSound.addEventListener(SampleDataEvent.SAMPLE_DATA, deserialize);
newSound.play();
function serializeSound(sound:Sound):ByteArray
{
var result:ByteArray = new ByteArray();
while( sound.extract(result, 8192) ){
result.position = result.length;
}
return result;
}
function deserialize(e:SampleDataEvent):void
{
for ( var c:int=0; c<8192; c++ ) {
if(serializedSound.bytesAvailable < 2) break;
e.data.writeFloat(serializedSound.readFloat());
e.data.writeFloat(serializedSound.readFloat());
}
}
Do you need just sending the bytearray to PHP or also getting the bytearray?
For sending the bytearray you can use Zend_AMF:
http://framework.zend.com/download/amf
It will handle all the conversion, and in php you will get the bytearray as a string through a variable (I use variable reference as: &$file to save some memory on calling of method)
Here is some code snippet it can help you:
Sending ByteArray to Zend_Amf
For getting the ByteArray you can use the FileReference load() method to get all the bytearray of a local file.
You do know that creating a ByteArray of the video in Flex is literally storing that video to memory right? Any kind of large or uncompressed video would use an enormous amount of client side memory which could cause errors if Flash hits its memory limit.
I don't think you're going about this the right way. What I recommend you do is instead just upload the video to the server which the server than then access the bytes within it. If you want to upload the video to the server, look at this tutorial here which shows how to upload the file from Flex and a PHP script to get and store the file: http://livedocs.adobe.com/flex/3/html/17_Networking_and_communications_7.html#118972
From here, PHP could then access the bytes if you are so inclined.
AS3 Code:
uploadURL = new URLRequest();
uploadURL.url = "upload.php?fileName=videotrack";
uploadURL.contentType = 'application/octet-stream';
uploadURL.method = URLRequestMethod.POST;
uploadURL.data = rawBytes;
urlLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
urlLoader.load(uploadURL);
rawBytes is the byte array that you want to upload to the server.
PHP Code
$fileName = $_REQUEST['fileName'] . ".mp3";
$fp = fopen( $fileName, 'wb' );
fwrite( $fp, $GLOBALS[ 'HTTP_RAW_POST_DATA' ] );
fclose( $fp );
I've used a .mp3 extension because my byte array was data from a mp3 file, but you can set the extension to whatever type of file your byte array represents.

Resources