Adobe AIR Mobile on iOS - processing text very slow - ios

I am writing an iOS app in Flash Builder 4.6 that will need to process a large text file. So far, I am just trying to get the version information from the file, a simple task that runs very fast in the simulator but takes a very long time (on the order of 10 seconds) on my iPad 2.
As the file is large (about 11MB), I am trying to only read far enough into the file to get the version data. Is it possible that the filestream loads the whole file into memory anyway? If so, how do I avoid that?
Note that the code works correctly, and displays the correct version info.
Any advice on how to speed it up would be greatly appreciated.
The file being processed can be found here: http://oanda.sca.org:80/oanda.db
The code is as follows:
Calling code:
protected function view1_viewActivateHandler(event:ViewNavigatorEvent):void
{
var DT:DatabaseTools = new DatabaseTools();
var version:String;
//Get version information from local file:
version = DT.GetLocalVer("oanda.db");
lblLclVer.text=version;
}
Actual function:
public function GetLocalVer(fileName:String):String
{
var out:ByteArray = new ByteArray();
var line_Out:String;
var char:int;
var line:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
var file:File = File.documentsDirectory.resolvePath(fileName);
var lineString:String;
var result:String = "Error";
stream.open(file,FileMode.READ);
var found:Boolean=false;
while((stream.bytesAvailable > 0) && !found)
{
char=stream.readByte();
if(String.fromCharCode(char) == "\n")
{
//reset the line
out=line;
line = new ByteArray();
//process the line to see if its the version info.
lineString=out.toString(); //since the version line never has UTF characters, convert it to a regular string
if(lineString.length > 25) //Any line shorter than this can't be the version line
{
var startOfLine:String = lineString.substr(0,17);
if(startOfLine == " ||C|Last update:")
{
result = lineString.substr(19,6);
found = true;
}
}
}
else
{
line.writeByte(char);
}
}
stream.close();
return result;
}
Thanks.

Related

HiQPdf Evaluation tag added when printing

I have a c# dll that uses HiQPdf to print a PDF from file. The issue is the printed PDF has a string added to the top left saying "HiQPdf Evaluation". The marigins are also greatly increased making the image smaller.
When I open the pdf and print from there it is fine. I couldn't find anything on the string being added so hoping someone here might have some insight :)
code:
public void PrintFromFile(string fileName, System.Drawing.Printing.PrinterSettings printerSettings)
{
var imagePrinter = new PdfPrinter();
imagePrinter.PrinterSettings.Copies = printerSettings.Copies;
imagePrinter.PrinterSettings.Duplex = printerSettings.Duplex;
imagePrinter.PrinterSettings.FromPage = printerSettings.FromPage;
imagePrinter.PrinterSettings.MaximumPage = printerSettings.MaximumPage;
imagePrinter.PrinterSettings.MinimumPage = printerSettings.MinimumPage;
imagePrinter.PrinterSettings.PrinterName = printerSettings.PrinterName;
imagePrinter.PrinterSettings.PrintFileName = printerSettings.PrintFileName;
imagePrinter.PrinterSettings.PrintRange = printerSettings.PrintRange;
imagePrinter.PrinterSettings.PrintToFile = printerSettings.PrintToFile;
imagePrinter.PrinterSettings.ToPage = printerSettings.ToPage;
imagePrinter.PrinterSettings.Collate = printerSettings.Collate;
var pdf = new MemoryStream(System.IO.File.ReadAllBytes("V:\\AccW2\\" + fileName));
pdf.Position = 0;
imagePrinter.PrintPdf(pdf);
}
If you have an HtmlToPdf element in you PrintPdf function you should set your SerialNumber
private void PrintPdf(string htmlbody, string pdfname)
{
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
// set a demo serial number
htmlToPdfConverter.SerialNumber = "-- HiQPdf Serial Number --";
}

Use OS.File to test if path is locked?

With OS.File I am able to open a file with lock on it:
let options = {
winShare: 0 // Exclusive lock on Windows
};
if (OS.Constants.libc.O_EXLOCK) {
// Exclusive lock on *nix
options.unixFlags = OS.Constants.libc.O_EXLOCK;
}
let file = yield OS.File.open(..., options);
Is it possible to test if the path is locked though. I'm looking for alternative to nsiToolkitProfile.lockProfile
This is copy paste to scratchpad code. The top block uses nsitoolkitprofile to test if locked. And it works fine. The second part uses OS.File.open and it always throws error.
Cu.import('resource://gre/modules/osfile.jsm');
Cu.import('resource://gre/modules/FileUtils.jsm');
var tps = Cc['#mozilla.org/toolkit/profile-service;1'].createInstance(Ci.nsIToolkitProfileService); //toolkitProfileService
var folderOfProfile = 'k46wtieb.clean'; //folder names of relative profiles found here: %APPDATA%\Mozilla\Firefox\Profiles
var rootPathDefault = FileUtils.getFile('DefProfRt', []).path;
var localPathDefault = FileUtils.getFile('DefProfLRt', []).path;
var aDirect = new FileUtils.File(OS.Path.join(rootPathDefault, folderOfProfile));
var aTemp = new FileUtils.File(OS.Path.join(localPathDefault, folderOfProfile));
try {
var locker = tps.lockProfilePath(aDirect, aTemp)
Services.ww.activeWindow.alert('NOT open');
locker.unlock();
} catch (ex) {
if (ex.result == Cr.NS_ERROR_FILE_ACCESS_DENIED) {
Services.ww.activeWindow.alert('its in use');
} else {
throw ex;
}
}
var promise = OS.File.open(aDirect.path)
promise.then(
function(aVal) {
Services.ww.activeWindow.alert('promise success, aVal = ' + aVal);
aVal.close();
},
function(aReason) {
Services.ww.activeWindow.alert('promise rejected, aReason = ' + uneval(aReason));
}
)
The promise is always rejected with aReason.becauseAccessDenied every time :(
Just try to open it... If you cannot because of permissions, then the file is probably locked in another location.

AS3 - How to load and read XML file on iOS

I'm working on simple iOS game where you have e.g. 10 levels and once you completed one the next level will unlock. I create the xml file here:
private function SaveProgress()
{
addChild(myTextField);
var GameSaveXML:XML =
<LEVEL>
<LEVEL_01>false</LEVEL_01>
<LEVEL_02>false</LEVEL_02>
<LEVEL_03>false</LEVEL_03>
<LEVEL_04>false</LEVEL_04>
<LEVEL_05>false</LEVEL_05>
<LEVEL_06>false</LEVEL_06>
<LEVEL_07>false</LEVEL_07>
<LEVEL_08>false</LEVEL_08>
<LEVEL_09>false</LEVEL_09>
<LEVEL_10>false</LEVEL_10>
</LEVEL>;;
//file.deleteFile();
var file:File = File.documentsDirectory.resolvePath("LevelsSaved.xml");
if (file.exists)
{
trace("EXISTS");
trace(GameSaveXML);
}
else
{
var fileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
var outputString:String = '<?xml version="1.0" encoding="utf-8"?>\n';
outputString += GameSaveXML.toXMLString();
fileStream.writeUTFBytes(outputString);
//GameSaveXML.replace(2,<LEVEL_03>true</LEVEL_03>);
trace(GameSaveXML);
fileStream.close();
trace("File Was Created");
}
}
I'm really struggling with loading the file and checking what levels are unlocked (true) and what levels are still locked (false). Can you please help? Thanks a lot!
If you know how to write xml, can't you read it the same way?
var content:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
var xml:XML = new XML(content);
if (xml.LEVEL_01 == 'true') trace('unlocked');
else trace('locked');
or you can use URLLoader to load xml as string
I'm 99% sure I did not undestand the question - sorry then :p

how to create .txt in local file system using Firefox extension

I am currently working on ffsniff extension code. In that I have to save data containing password information into a file in my local system. I have written my code but it is not even creating the file in my local system. (working in mozilla firefox)
Here is my code please help me out.
//// here data variable contains all the information
var fso = new ActiveXObject("Scripting.FileSystemObject");
varFileObject = fso.OpenTextFile("C:\\logs.txt", 2, true,0);
varFileObject.write(data);
varFileObject.close();
after this i tried different code:
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
var file = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("Desk", Components.interfaces.nsIFile);
file.append("logs.txt");
var ostream = FileUtils.openSafeFileOutputStream(file)
var converter = Components.classes["#mozilla.org/intl/scriptableunicodeconverter"].
createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(data);
}
});
but none of them is working..
Here's a working snippet that creates the destination directory if necessary and writes (overwrites) to file (in this case d:\temp-directory\temp-file.txt):
var {Cc,Ci,Cu}=require("chrome"); //for jetpack sdk.
Cu.import("resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");
var localFile = Cc["#mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
var data="test file content";
//localFile.initWithPath("D:\\temp-directory\\temp-file.txt"); //full path is okay if directory exists
localFile.initWithPath("D:\\temp-directory\\"); //otherwise specifiy directory, create it if necessary, and append leaf.
if(!localFile.exists()){
localFile.create(localFile.DIRECTORY_TYPE,FileUtils.PERMS_DIRECTORY);
}
localFile.append("temp-file.txt");
//localFile.createUnique(localFile.NORMAL_FILE_TYPE,FileUtils.PERMS_FILE); //optional: create a new unique file.
asyncSave(localFile,data,onDone);
function asyncSave(file,data,callbackDone){
// file is nsIFile, data is a string, optional: callbackDone(path,leafName,statusCode)
// default flags: FileUtils.openSafeFileOutputStream(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE);
var ostream = FileUtils.openSafeFileOutputStream(file);
var converter = Cc["#mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(data);
// optional: callbackSaved(status).
NetUtil.asyncCopy(istream, ostream, callbackSaved);
function callbackSaved (status) {
if(callbackDone){
if(status===0)callbackDone( file.path, file.leafName, status); //sucess.
else callbackDone( null, null, status); //failure.
};
}
}
function onDone(path,leafName,statusCode){
console.log([statusCode===0?"OK":"error",path,leafName].join("\n"));
}
More information:
https://developer.mozilla.org/en-US/docs/Code_snippets/File_I_O
https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/FileUtils.jsm
https://developer.mozilla.org/en-US/docs/PR_Open
https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/NetUtil.jsm
https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIFile
https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsILocalFile
A simple example of how to read/write a file from the filesystem in windows, using Firefox Extension:
// Write File to filesystem
Components.utils.import("resource://gre/modules/osfile.jsm"); // load the OS module
var encoder = new TextEncoder(); // This encoder can be reused for several writes
var array = encoder.encode("just some text"); // Convert the text to an array
var promise = OS.File.writeAtomic("C:\\foo.txt", array,{tmpPath: "foo.txt.tmp"}); // Write the array atomically to "file.txt", using as temporary
alert("URL HOST has been saved");
//Read File from filesystem
var decoder = new TextDecoder(); // This decoder can be reused for several reads
var promise = OS.File.read("C:\\foo.txt"); // Read the complete file as an array
promise = promise.then(
function onSuccess(array) {
alert(decoder.decode(array)); // Convert this array to a text
}
);
This solution is for making file in ubuntu, hope this helps others:
var file = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("ProfD", Components.interfaces.nsIFile);
file.append("trick_new");
if( !file.exists() || !file.isDirectory() ) { // if it doesn't exist, create
file.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
}
this.log_file = file.path + "/newlog.html";
You can also use text-stream to write to a local file.
function writeTextToFile(text, filename) {
var fileIO = require("sdk/io/file");
var TextWriter = fileIO.open(filename, "w");
if (!TextWriter.closed) {
TextWriter.write(text);
TextWriter.close();
}
}

save bmpData as jpg using adobe flex in air application

i use the following code:
protected function videoDisplay_playheadUpdateHandler(event:mx.events.VideoEvent):void
{
if(!captured && videoDisplay.playheadTime>=0){
capture();
}
}
private function capture():void
{
var bmpData:BitmapData = new BitmapData(videoDisplay.width, videoDisplay.height);
bmpData.draw(videoDisplay);
captured = true;
store(...); //????????
}
in order to capture a frame from a videoDisplay object
1) is it correct or am i doing something wrong?
2) what can i do to store the bmpData as .jpg at my computer?
i am using flex4.5 and it is an air app...
any ideas??
Thanks in advance!!
The following code should help you
var jpegEncoder:JPEGEncoder = new JPEGEncoder(90);
var jpgSource:BitmapData = new BitmapData(videoDisplay.width,videoDisplay.height);
jpgSource.draw(this);
var fileReference:FileReference = new FileReference();
fileReference.save(jpegEncoder.encode(jpgSource),"videoImage.jpg");
To use jpeg encode you need to have to import
import mx.graphics.codec.JPEGEncoder;
The above changes should be enough to allow the user to take a snapshot of a running video.
Please note, that with this the user will be prompted to select the location of the file.
Incase you want a silent save, let me know, I will put up the required code.
Somewhere in your application keep an image tag as follows.Most apt place should be just below the video.
<mx:Image scaleContent="true" width="150" height="120" maintainAspectRatio="false" id="myScaledSnapshot"/>
Now with this done, do the following changes in your code:
private function capture(filename:String):void
{
var bitmapData:BitmapData = new BitmapData(videoDisplay.width, videoDisplay.height);
bitmapData.draw(videoDisplay,new Matrix());
var bitmap : Bitmap = new Bitmap(bitmapData);
var jpg:JPEGEncoder = new JPEGEncoder();
var ba:ByteArray = jpg.encode(bitmapData);
myImageSnapshot.source=ba;
var jpegEncoder:JPEGEncoder = new JPEGEncoder(50);
var imageSnapshot:ImageSnapshot = ImageSnapshot.captureImage(this.myImageSnapshot,90,jpegEncoder);
var imageByteArray:ByteArray = imageSnapshot.data;
var newImage:File = File.desktopDirectory.resolvePath("KioskThumbs/"+filename+".jpg");
fileStream = new FileStream();
fileStream.open(newImage, FileMode.UPDATE);
fileStream.writeBytes(imageByteArray);
fileStream.close();
captured = true;
}
The above code really doesnt do anything special.
Its just using an image 'component' from flex, making it do the work for scaling the Video image, then taking the snapshot of this resized image component, and then writing it into a file.
My capture at last is:
private function capture(filename:String):void
{
var bitmapData:BitmapData = new BitmapData(videoDisplay.width, videoDisplay.height);
bitmapData.draw(videoDisplay,new Matrix());
var bitmap : Bitmap = new Bitmap(bitmapData);
var jpg:JPEGEncoder = new JPEGEncoder();
var ba:ByteArray = jpg.encode(bitmapData);
var newImage:File = File.desktopDirectory.resolvePath("KioskThumbs/"+filename+".jpg");
fileStream = new FileStream();
fileStream.open(newImage, FileMode.UPDATE);
fileStream.writeBytes(ba);
fileStream.close();
captured = true;
}
it works fine except the fact that i want to scale the photo lets say to 150 width 120height and not BitmapData(videoDisplay.width,videoDisplay.height); what can i do to solve that?
Thanks a lot all of you!

Resources