As3 - LocalConnection between SWF and AIR desktop app - actionscript-3

I need to send a text from an embedded SWF (Web browser) to an AIR based desktop app.
I did everything like explained in the documentation but I can't establish a connection.
Does anybody see what I did wrong or can point me to a working example?
From the SWF:
function startConnection(e:Event=null):void
{
var localConnection:LocalConnection
localConnection = new LocalConnection();
localConnection.client = this;
localConnection.allowDomain("app#com.example.desktop");
var textToSend = "Hello world! Source: http://www.foobar.com";
localConnection.send("app#com.example.desktop:connectionName", "methodName",textToSend);
}
From the AIR desktop app:
function onBrowserInvoke (event:BrowserInvokeEvent):void{
var localConnection:LocalConnection
localConnection = new LocalConnection();
localConnection.client = this
localConnection.allowDomain("example.com");
localConnection.connect("connectionName");
}
Thank you.
Uli

The working code is:
AIR:
var localConnection:LocalConnection = new LocalConnection();
localConnection.send("_myConnection", "methodName", "Hello world! Source: http://www.foobar.com");
SWF:
var localConnection:LocalConnection = new LocalConnection();
localConnection.allowDomain("app#airtest"); //or use "*" wildcard to allow any domains and AIR applications
localConnection.client = this;
localConnection.connect("_myConne‌​ction");
Where airtest is the app id for AIR application. Use the _ symbol before local connection name for supporting unpredictable domain names (it'll work in debug mode and via http).

Related

Action script, NativeProcess , resolvePath and swf does not work

I will expose my problem but first I have to show you my configuration to give you all the details.
I have 2 Virtual Machines, 2 windows 7. The first one, it is where I developp all my Action Scripts, where there is my Development Environment(IDE) and second one there is nothing special installed. On both there is Adobe AIR and Adobe Flash Player.
Ok, here is my problem. I develop (on first one) a script that uses NativeProcess to run a CMD.exe that load in command line a dll.
And when I Build&Run the project everything is ok, I check and the dll is loaded. But the problem is when the second Windows connected into my localhost website (to the first windows that play as a server) and run the file "myProgram.swf" (the ActionScript program) that do not load my dll.
Now I print you all my code :
This is the script that loads the dll "myProgram.swf" :
public class NativeProcessExample extends Sprite
{
public var process:NativeProcess;
public function NativeProcessExample()
{
if(NativeProcess.isSupported)
{
setupAndLaunch();
}
else
{
trace("NativeProcess not supported.");
}
}
public function setupAndLaunch():void
{
var fmt:TextFormat = new TextFormat();
var txt:TextField = new TextField();
fmt.size = 32;
txt.text = 'Hello, world!' + '\n' +
'Width = ' + stage.fullScreenWidth + '\n' +
'Height = ' + stage.fullScreenHeight;
txt.setTextFormat(fmt);
txt.autoSize = TextFieldAutoSize.LEFT;
addChild(txt);
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = File.applicationDirectory.resolvePath("C:\\Windows\\System32\\regsvr32.exe");
nativeProcessStartupInfo.executable = file;
var args:Vector.<String> = new Vector.<String>();
args.push("C:\\Users\\myUser\\Downloads\\myDLL.dll");
nativeProcessStartupInfo.arguments = args;
var process:NativeProcess = new NativeProcess();
process.start(nativeProcessStartupInfo);
process.addEventListener(NativeProcessExitEvent.EXIT, exitHandler);
I cut (I deleted all includes and end part) the script cause its too long but here is the most interesting part.
Now I will show you my "index.php" where the 2nd Windows connected to recover and inject the dll. :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style type=\"text/css\">
body, html
{
width:100%;
height:100%;
overflow:hidden;
}
#SWFSquare
{
height: 200px;
width: 200px;
background-color: blue;
}
</style>
<script type="text/javascript" src="swfobject.js"></script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body bgcolor="#ffdfaf">
<div id="SWFSquare">
</div>
<input type="button" value="Download" id="buttonDownload" style="margin-left: auto; margin-right: auto; display: block;">
<script type="text/javascript">
$(function() {
$("#buttonDownload").click(function() {
window.open("myDLL.dll");
myFunction();
});
function myFunction() {
setTimeout(function(){
var element = document.getElementById("SWFSquare");
swfobject.embedSWF("myProgram.swf", element, 300, 120, 10);
},10000);
}
});
</script>
</body>
</html>
So I hope you have all needed information. Do not hesitate to ask me for more information.
So to remind. When I launch my script on 1st Windows under my Development Environment (IDE) everything works my DLL is loaded but when I try do load it with 2nd Windows by connected to index.php (=1st Windows as a server) the SWF works cause i get the message "HelloWorld" on the page but the dll is not loaded...
Can you help me ? I work on this for 2 weeks :-(.
First of all, Thank you guys for the quick response :-)
So, I will answer "Akmozo's question :
As you see on the description of my ActionScript it will use "NativeProcess" to run the cmd that will execute a command to load myDLL.dll
So, I just have to execute the swf to start all of this. That is the relation between AIR app and swf. I work on FlashDevelop environment and every script "myProgram.as" that you "Build&Runs" create a "myProgram.swf" file. Once I get this file (automatically created) I just have to run it through the web by my "index.php" and more precisely by this code :
var element = document.getElementById("SWFSquare");
swfobject.embedSWF("myProgram.swf", element, 300, 120, 10);
So, when 2nd windows connected to index.php that run the myProgram.swf and finally I have not dll loaded...
That's my problem. Did I answer you "Akzmozo" ?
Now, for your answer "VC.one" I think it should be possible to do it on the environment I especially prepared.
That is to say :
1st Windows with last update and patches
2nd Windows with no update and no last Flash Player (currently is 19.0.0.206)
I'm an IT security researcher (student) and that's why I'm working now on a breach in Adobe Flash Player 19. Normally, it possible to do it because there is already a CVE on this work, and I would (re) create this scenario. But I'm always stuck on this problem and I think I missed something but I don't know what it is...
But I'm always stuck on this problem and I think I missed something
but I don't know what it is...
#Akmozo is correct. Flash Player (browser) & AIR (OS app) are two different ways to run AS3 code as an application. They don't always work the same (an AS3 app rendered by browser Flash Player plugin is much more limited for security reasons, it cannot run programs on a computer otherwise hackers & virus creators would have found heaven with this power, spreading chaos via internet).
Also think about what happens if the SWF is run from a Mac or Linux browser? How do these OS load the dll (since it's a Windows-only file)? This breaks the rule that code in browser works same everywhere, regardless of platform.
Just to prove a point... update your textfield code to look like this below. In IDE testing it should say (NP) Support = true but when in browser you will get = false. Of course when its false then you cannot load the dll from a browser.
var fmt:TextFormat = new TextFormat();
var txt:TextField = new TextField();
fmt.size = 32;
txt.text = 'Hello, world!' + '\n' +
'Width = ' + stage.fullScreenWidth + '\n' +
'Height = ' + stage.fullScreenHeight + '\n' +
'(NP) Support = ' + String(NativeProcess.isSupported); //# check if available
txt.setTextFormat(fmt);
txt.autoSize = TextFieldAutoSize.LEFT;
addChild(txt);

Taking screenshot functionality in flex 3.5 was working but now it is not working

Taking screenshot functionality was working in my application but now it is not working. The code I am using for taking screen shot in flex is as below:
I am using flex 3.5 SDK
private function captureScreenShot():void
{
var jpgSource:BitmapData = new BitmapData (siteDisplayContainer.width, siteDisplayContainer.height); // siteDisplayContainer is the <mx:VBox> flex container
jpgSource.draw(siteDisplayContainer);
var jpgEncoder:JPGEncoder = new JPGEncoder(85);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
var myDate:Date = new Date();
var unixTime:Number = Math.round(myDate.getTime()/1000);
var reqURL:String = parentApplication.imageDownloadScriptURL+unixTime+".jpg"; // imageDownloadScriptURL is the php file absolute path
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest(reqURL);
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = jpgStream;
navigateToURL(jpgURLRequest, "_blank");
}
PHP file code for downloading flex screen shot:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// get bytearray
$jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
header('Content-Type: image/jpeg');
header("Content-Disposition: attachment; filename=".$_GET['name']);
echo $jpg;
echo '<script TYPE="text/javascript">window.close();</script>';
}
?>
Since the data is binary, I don't know how I can debug this code. I do not know where exactly is the code failing. There cannot be any major error since this exact code was working till about 6 months back.
How do I debug this code? What can be the reason for the code not working?
If it was working six months ago, have you checked your server settings for changes in the PHP version or security?
For testing the PHP, can you pass a binary into you it to verify that portion is working? For the flex side, I would setup the debugging version of flash player and then setup breakpoints and trace statements and just go through it and see if the flex debugging perspective and flash player give you any good debugging data to work with on narrowing down the culprit.

Loading files in Android Mobile using AIR and Actionscript 3.0

Im building a Test Maker App. I need some help on loading files in Android mobile. The type i want is the type where the user can look for his file from a file browser. This is the code i have so far but it wont work. My mobile always says "No files were found".
var file = File.applicationStorageDirectory.resolvePath("saved projects");//This is a folder
file.browseForOpen("Open Your File", [new FileFilter("Text Files", "*.txt")]);
file.addEventListener(Event.SELECT, onFileSelected);
public function onFileSelected(e:Event):void {
var stream:FileStream = new FileStream();
stream.open(e.target as File, FileMode.READ);
loadTxt.text = stream.readUTF();
}
Plus additional question: Where is the best location to save files in the ANdroid mobile?
You can write your file manager, it should not be difficult. Scan a directory with method "getDirectoryListing":
var file:File = File.applicationDirectory.resolvePath('myDirectory/');
var filesList:Array = file.getDirectoryListing();
and show a list of files.

Clearing StageWebView cache on Air Simulator

I use StageWebView for Facebook authentication in my mobile game. Everything works fine except that I can never reset StageWebView cache. I remain logged into Facebook and because of that I can't test authentication with another Facebook account.
I checked "Clear data on application launch" on debug settings to no avail.
Any ideas?
// use the token received for the logout:
// accessToken = getAccessTokenEvent.accessToken;
stageWebView = new StageWebView();
stageWebView.addEventListener(Event.COMPLETE,completa);
stageWebView.stage = FlexGlobals.topLevelApplication.stage;
stageWebView.viewPort= new Rectangle(0,0,FlexGlobals.topLevelApplication.stage.width-10,FlexGlobals.topLevelApplication.stage.height-10);
stageWebView.loadURL("https://m.facebook.com/logout.php?next=http://m.facebook.com&access_token="+ accessToken +"&confirm=1");
var loginRequest:URLRequest = new URLRequest();
loginRequest.method = URLRequestMethod.GET;

Is there a way generate a shortcut file with adobe air?

Good afternoon,
I would like create a application that can can create folders and short cuts to folders in the file system. The user will click a button and it will put a folder on there desktop that has short cuts to files like //server/folder1/folder2 Can you create a desktop shortcut with code in adobe air? How would you do that? How do you create a folder? I keep thinking this should be easy but i keep missing it.
Thank you for your help sorry for the trouble,
Justin
If your deployment profile is Extended Desktop, you may be able to use NativeProcess and some simple scripts that you could package with your app. This approach would entail handling the functionality on a per OS basis, which would take some work and extensive testing. However, I wanted to at least share a scenario that I verified does work. Below is a test case that I threw together:
Test Case: Windows 7
Even though the Adobe documentation says that it prevents execution of .bat files, apparently it doesn't prevent one from executing the Windows Scripting Host: wscript.exe. This means you can execute any JScript or VBScript files. And this is what you would use to write a command to create a shortcut in Windows (since Windows doesn't have a commandline command to create shortcuts otherwise).
Here's a simple script to create a shortcut command, which I found on giannistsakiris.com, (converted to JScript):
// File: mkshortcut.js
var WshShell = new ActiveXObject("WScript.Shell");
var oShellLink = WshShell.CreateShortcut(WScript.Arguments.Named("shortcut") + ".lnk");
oShellLink.TargetPath = WScript.Arguments.Named("target");
oShellLink.WindowStyle = 1;
oShellLink.Save();
If you package this in your application in a folder named utils, you could write a function to create a shortcut like so:
public function createShortcut(target:File, shortcut:File):void {
if (NativeProcess.isSupported) { // Note: this is only true under extendedDesktop profile
var shortcutInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
// Location of the Windows Scripting Host executable
shortcutInfo.executable = new File("C:/Windows/System32/wscript.exe");
// Argument 1: script to execute
shortcutInfo.arguments.push( File.applicationDirectory.resolvePath("utils/mkshortcut.js").nativePath);
// Argument 2: target
shortcutInfo.arguments.push("/target:" + target.nativePath);
// Argument 3: shortcut
shortcutInfo.arguments.push("/shortcut:" + shortcut.nativePath);
var mkShortcutProcess = new NativeProcess();
mkShortcutProcess.start(shortcutInfo);
}
}
If one wanted to create a shortcut to the Application Storage Directory on the Desktop, the following would suffice:
var targetLocation:File = File.applicationStorageDirectory;
var shortcutLocation:File = File.desktopDirectory.resolvePath("Shortcut to My AIR App Storage");
createShortcut(targetLocation, shortcutLocation);
Obviously there's a lot of work to be done to handle different OS environments, but this is at least a step.
As far as I know, File class does not allow the creation of symbolic links. But you can create directories with createDirectory(): http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/filesystem/File.html#createDirectory%28%29
Check if this can be useful: http://www.mikechambers.com/blog/2008/01/17/commandproxy-net-air-integration-proof-of-concept/
Air doesnt let you create shortcuts natively. Here's a workaround that works with Windows [may work on Mac but I don't have a machine to test].
Using Air, create a file that contains the following plain text
[InternetShortcut]
URL=C:\path-to-folder-or-file
Replace path-to-folder-or-file with your folder/file name
Save the file as test.url
Windows recognizes this file as a shortcut.
It is possible to coerce Adobe Air into creating symbolic links, other useful things, on a Mac. Here's how I did it:
You will need AIRAliases.js - Revision: 2.5
In the application.xml add:
<!-- Enables NativeProcess -->
<supportedProfiles>extendedDesktop desktop</supportedProfiles>
In the Air app JavaScript:
// A familiar console logger
var console = {
'log' : function(msg){air.Introspector.Console.log(msg)}
};
if (air.NativeProcess.isSupported) {
var cmdFile = air.File.documentsDirectory.resolvePath("/bin/ln");
if (cmdFile.exists) {
var nativeProcessStartupInfo = new air.NativeProcessStartupInfo();
var processArgs = new air.Vector["<String>"]();
nativeProcessStartupInfo.executable = cmdFile;
processArgs.push("-s");
processArgs.push("< source file path >");
processArgs.push("< link file path >");
nativeProcessStartupInfo.arguments = processArgs;
nativeProcess = new air.NativeProcess();
nativeProcess.addEventListener(air.NativeProcessExitEvent.EXIT, onProcessExit);
nativeProcess.addEventListener(air.ProgressEvent.STANDARD_OUTPUT_DATA, onProcessOutput);
nativeProcess.addEventListener(air.ProgressEvent.STANDARD_ERROR_DATA, onProcessError);
nativeProcess.start(nativeProcessStartupInfo);
} else {
console.log("Can't find cmdFile");
}
} else {
console.log("Not Supported");
}
function onProcessExit(event) {
var result = event.exitCode;
console.log("Exit Code: "+result);
};
function onProcessOutput() {
console.log("Output: "+nativeProcess.standardOutput.readUTFBytes(nativeProcess.standardOutput.bytesAvailable));
};
function onProcessError() {
console.log("Error: "+nativeProcess.standardError.readUTFBytes(nativeProcess.standardError.bytesAvailable));
};
Altering the syntax of the command and parameters passed to NativeProcess you should be able to get real shortcuts on Windows too.