ActionScript 2: Event doesn't fire? - actionscript-2

So I have a soundHandler class that's supposed to play sounds and then point back to a function on the timeline when the sound has completed playing. But somehow, only one of the sounds plays when I try it out. EDIT: After that sound plays, nothing happens, even though I have EventHandlers set up that are supposed to do something.
Here's the code:
import mx.events.EventDispatcher;
class soundHandler {
private var dispatchEvent:Function;
public var addEventListener:Function;
public var removeEventListener:Function;
var soundToPlay;
var soundpath:String;
var soundtype:String;
var prefix:String;
var mcname:String;
public function soundHandler(soundpath:String, prefix:String, soundtype:String, mcname:String) {
EventDispatcher.initialize(this);
_root.createEmptyMovieClip(mcname, 1);
this.soundpath = soundpath;
this.soundtype = soundtype;
this.prefix = prefix;
this.mcname = mcname;
}
function playSound(file, callbackfunc) {
_root.soundToPlay = new Sound(_root.mcname);
_global.soundCallbackfunc = callbackfunc;
_root.soundToPlay.onLoad = function(success:Boolean) {
if (success) {
_root.soundToPlay.start();
}
};
_root.soundToPlay.onSoundComplete = function():Void {
trace("Sound Complete: "+this.soundtype+this.prefix+this.file+".mp3");
trace(arguments.caller);
dispatchEvent({type:_global.soundCallbackfunc});
trace(this.toString());
trace(this.callbackfunction);
};
_root.soundToPlay.loadSound("../sound/"+soundpath+"/"+soundtype+prefix+file+".mp3", true);
_root.soundToPlay.stop();
}
}
Here's the code from the .fla file:
var playSounds:soundHandler = new soundHandler("signup", "su", "s", "mcs1");
var file = "000";
playSounds.addEventListener("sixtyseconds", this);
playSounds.addEventListener("transition", this);
function sixtyseconds() {
trace("I am being called! Sixtyseconds");
var phase = 1;
var file = random(6);
if (file == 0) {
file = 1;
}
if (file<10) {
file = "0"+file;
}
file = phase+file;
playSounds.playSound(file, "transition");
}
function transition() {
trace("this works");
}
playSounds.playSound(file, "sixtyseconds");
I'm at a total loss for this one. Have been wasting hours to figure it out already.
Any help will be deeply appreciated.

Well, after using the Delegate class, I got it to work with this code:
import mx.events.EventDispatcher;
import mx.utils.Delegate;
class soundHandler{
public var addEventListener:Function;
public var removeEventListener:Function;
private var dispatchEvent:Function;
private var soundToPlay;
private var soundpath:String;
private var soundtype:String;
private var prefix:String;
private var mcname:String;
public function soundHandler(soundpath:String, prefix:String, soundtype:String, mcname:String) {
EventDispatcher.initialize(this);
_root.createEmptyMovieClip(mcname, 1);
this.soundpath = soundpath;
this.soundtype = soundtype;
this.prefix = prefix;
this.mcname = mcname;
}
private function playSoundCallback(file, callbackfunc) {
var soundname = "s"+file;
_root[soundname] = new Sound(_parent.mcname);
_root[soundname].onLoad = function(success:Boolean) {
if (success) {
_root[soundname].start();
}
};
trace("Play Sound: "+file+".mp3; Function To Call: "+callbackfunc);
_root[soundname].onSoundComplete = Delegate.create(this,function():Void {
trace("Sound Complete: "+this.soundtype+this.prefix+this.file+".mp3");
dispatchEvent({type:callbackfunc});
});
_root[soundname].loadSound("../sound/"+soundpath+"/"+soundtype+prefix+file+".mp3", true);
_root[soundname].stop();
}
private function playRandomSoundCallback(phase, scope, callbackfunc) {
var file = random(scope);
if (file == 0) {
file = 1;
}
if (file<10) {
file = "0"+file;
}
file = phase+file;
playSoundCallback(file, callbackfunc);
}
private function playSound(file) {
var soundname = "s"+file;
_root[soundname] = new Sound(_root.mcname);
_root[soundname].onLoad = function(success:Boolean) {
if (success) {
_root[soundname].start();
}
};
trace("Play Sound: "+file+".mp3");
_root[soundname].loadSound("../sound/"+soundpath+"/"+soundtype+prefix+file+".mp3", true);
_root[soundname].stop();
}
private function playSoundRandom(phase, scope) {
var file = random(scope);
if (file == 0) {
file = 1;
}
if (file<10) {
file = "0"+file;
}
file = phase+file;
playSound(file);
}
private function playSoundAS(identifier) {
var soundname = identifier;
_root[soundname] = new Sound(_root.mcname);;
trace("Play Sound AS: "+identifier+".mp3");
_root[soundname].attachSound("identifier");
_root[soundname].start();
}
}

Related

Flyweight pattern in this simple net core Api uses more memory ram

I'm trying to aplicate Flyweight method pattern in a simple .net core Api to see how much memory is saved compared to not using the pattern.
I have two methods, the first one creates 5000 objects without uses the pattern and the another creates 5000 object using the pattern. After each of them create the objects, then they call a method that returns the current memory used by the App.
public class MemoryService : IMemoryService
{
private readonly TreeFactory _treeFactory;
public MemoryService()
{
_treeFactory = new TreeFactory();
}
//create without pattern
public long SetObjectsMemory()
{
List<Tree> trees = new List<Tree>();
for (int i = 0; i < 5000; i++)
{
var tree = new Tree()
{
Id = new Random().Next(1, 9999999),
Part = new PartTree()
{
Name = "Nameany",
Bark = "Barkany",
Color = "Colorany"
}
};
trees.Add(tree);
};
return Utilities.GetCurrentMemoryUsed();
}
//crete with flyweight pattern
public long SetObjectsMemoryFactory()
{
List<Tree> trees = new List<Tree>();
for (int i = 0; i < 5000; i++)
{
var tree = new Tree()
{
Id = new Random().Next(1, 9999999),
Part = _treeFactory.GetPartTree("Nameany", "Barkany", "Colorany")
};
trees.Add(tree);
}
return Utilities.GetCurrentMemoryUsed();
}
}
I use the pattern like a class that uses a list of Parts and return a part object if exists.
public class TreeFactory
{
private static List<PartTree> _parts;
public TreeFactory() {
_parts = new List<PartTree>();
}
public PartTree GetPartTree(string name, string bark, string color)
{
if (_parts.Any(x => x.Name == name && x.Bark == bark && x.Color == color))
{
return _parts.Where(x => x.Name == name && x.Bark == bark && x.Color == color).FirstOrDefault();
}
else {
var newpart = new PartTree()
{
Name = name,
Bark = bark,
Color = color
};
_parts.Add(newpart);
return newpart;
}
}
}
The way to get the current memory used by the App is using Process of this way (in Utilities class):
public static long GetCurrentMemoryUsed() {
Int64 memory;
using (Process proc = Process.GetCurrentProcess())
{
memory = proc.PrivateMemorySize64 / (1024 * 1024);
}
return memory;
}
And in my Startup i inject the MemoryService like a Singleton. In the controller i use 3 methods for call the functions:
[HttpGet, Route(nameof(WeatherForecastController.GenerateMemory))]
public IActionResult GenerateMemory()
{
var total=_memoryService.SetObjectsMemory();
return Ok(total);
}
[HttpGet, Route(nameof(WeatherForecastController.GenerateLiftMemory))]
public IActionResult GenerateLiftMemory()
{
var total = _memoryService.SetObjectsMemoryFactory();
return Ok(total);
}
[HttpGet, Route(nameof(WeatherForecastController.GetMemory))]
public IActionResult GetMemory()
{
var total = Utilities.GetCurrentMemoryUsed();
return Ok(total);
}
The problem is: When i call in the navigator the method in controller without pattern (/weatherforecast/GenerateMemory), then this returns (current)+2mb, but when i call the method
with pattern (/weatherforecast/GenerateLiftMemory) this returns (current)+3mb.
Why the method with pattern flyweight returns more used MB (growing) than the methods without the pattern ??
The repository with the code for test it. Gitlab repository memory api
The code which uses TreeFactory consumes more memory because its GetPartTree method called many times in a loop so as Linq methods Any and Where inside it. Both of these methods create additional Iterator objects under the hood in order to iterate through the collection and it causes additional memory consumption.
I wrote simple benchmark using BenchmarkDotNet with more options to demonstrate the issue
Extended MemoryService
public class MemoryService : IMemoryService
{
private const int TreeCount = 50000;
private readonly TreeFactory _treeFactory;
public MemoryService()
{
_treeFactory = new TreeFactory();
}
//crea objetos en memoria sin patrones
public decimal SetObjectsMemory()
{
List<Tree> trees = new List<Tree>();
for (int i = 0; i < TreeCount; i++)
{
var tree = new Tree()
{
Id = 1,
Part = new PartTree()
{
Name = "Nameany",
Bark = "Barkany",
Color = "Colorany"
}
};
trees.Add(tree);
};
return Utilities.GetCurrentMemoryUsed();
}
//crea objetos en memoria usando patron flyweight
public decimal SetObjectsMemoryFactory()
{
List<Tree> trees = new List<Tree>();
for (int i = 0; i < TreeCount; i++)
{
var tree = new Tree()
{
Id = 1,
Part = _treeFactory.GetPartTree("Nameany", "Barkany", "Colorany")
};
trees.Add(tree);
}
return Utilities.GetCurrentMemoryUsed();
}
public decimal SetObjectsMemoryFactoryImproved()
{
List<Tree> trees = new List<Tree>();
for (int i = 0; i < TreeCount; i++)
{
var tree = new Tree()
{
Id = 1,
Part = _treeFactory.GetPartTreeImproved("Nameany", "Barkany", "Colorany")
};
trees.Add(tree);
}
return Utilities.GetCurrentMemoryUsed();
}
//crea objetos en memoria usando patron flyweight
public decimal SetObjectsMemoryFactoryWithoutLambda()
{
List<Tree> trees = new List<Tree>();
for (int i = 0; i < TreeCount; i++)
{
var tree = new Tree()
{
Id = 1,
Part = _treeFactory.GetPartTreeWithoutLambda("Nameany", "Barkany", "Colorany")
};
trees.Add(tree);
}
return Utilities.GetCurrentMemoryUsed();
}
}
Extended TreeFactory
public class TreeFactory
{
private static List<PartTree> _parts;
public TreeFactory()
{
_parts = new List<PartTree>();
}
public PartTree GetPartTree(string name, string bark, string color)
{
if (_parts.Any(x => x.Name == name && x.Bark == bark && x.Color == color))
{
return _parts.Where(x => x.Name == name && x.Bark == bark && x.Color == color).FirstOrDefault();
}
var newpart = new PartTree()
{
Name = name,
Bark = bark,
Color = color
};
_parts.Add(newpart);
return newpart;
}
public PartTree GetPartTreeImproved(string name, string bark, string color)
{
var existingPart = _parts.Where(x => x.Name == name && x.Bark == bark && x.Color == color).FirstOrDefault();
if (existingPart != null)
return existingPart;
var newpart = new PartTree()
{
Name = name,
Bark = bark,
Color = color
};
_parts.Add(newpart);
return newpart;
}
public PartTree GetPartTreeWithoutLambda(string name, string bark, string color)
{
for (int i = 0; i < _parts.Count; i++)
{
var x = _parts[i];
if (x.Name == name && x.Bark == bark && x.Color == color)
return x;
}
var newpart = new PartTree()
{
Name = name,
Bark = bark,
Color = color
};
_parts.Add(newpart);
return newpart;
}
}
Benchmark in a separate console project
class Program
{
static void Main(string[] args)
{
var result = BenchmarkRunner.Run<MemoryBenchmark>();
}
}
[MemoryDiagnoser]
public class MemoryBenchmark
{
private IMemoryService memoryService;
[GlobalSetup]
public void Setup()
{
memoryService = new MemoryService();
}
[Benchmark]
public object SimpleTrees()
{
var trees = memoryService.SetObjectsMemory();
return trees;
}
[Benchmark]
public object FlyTrees()
{
var trees = memoryService.SetObjectsMemoryFactory();
return trees;
}
[Benchmark]
public object FlyTreesImproved()
{
var trees = memoryService.SetObjectsMemoryFactoryImproved();
return trees;
}
[Benchmark]
public object FlyTreesWithoutLambda()
{
var trees = memoryService.SetObjectsMemoryFactoryWithoutLambda();
return trees;
}
}
And its results
Method
Mean
Error
StdDev
Gen 0
Gen 1
Gen 2
Allocated
SimpleTrees
9.040 ms
0.1804 ms
0.2346 ms
718.7500
453.1250
265.6250
4.44 MB
FlyTrees
19.701 ms
0.1716 ms
0.1521 ms
2500.0000
906.2500
437.5000
15.88 MB
FlyTreesImproved
18.075 ms
0.2869 ms
0.2684 ms
1781.2500
625.0000
312.5000
10.92 MB
FlyTreesWithoutLambda
4.919 ms
0.0273 ms
0.0242 ms
421.8750
281.2500
281.2500
2.53 MB

managed c++ classes crash in create_task

Basically, what is happening is when trying to change a variable of a Managed class (UWP), it crashes. Additionally, it seems to only crash if I try modifying a variable which is created with the app namespace. In other words, if I create a new namspace and managed class, I can modify variables just fine.
void ASynTaskCategories(void)
{
concurrency::task_completion_event<Platform::String^> taskDone;
MainPage^ rootPage = this;
UberSnip::HELPER::ASYNC_RESPONSE^ responseItem = ref new UberSnip::HELPER::ASYNC_RESPONSE();
create_task([taskDone, responseItem, rootPage]() -> Platform::String^
{
//UBERSNIP API 0.4
UberSnip::UBERSNIP_CLIENT* UberSnipAPI = new UberSnip::UBERSNIP_CLIENT();
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
UberSnipAPI->Http->request();
taskDone.set(UberSnipAPI->Client->BodyResponse);
responseItem->Body = UberSnipAPI->Client->BodyResponse;
return "(done)";
}).then([taskDone, responseItem, rootPage](Platform::String^ BodyResponse) {
Platform::String^ BR = responseItem->Body;
cJSON* cats = cJSON_Parse(_string(BR));
cats = cats->child;
int *cat_count = new int(cJSON_GetArraySize(cats));
rootPage->Categories->Clear();
GENERIC_ITEM^ all_item = ref new GENERIC_ITEM();
all_item->Title = "All";
rootPage->Categories->Append(all_item);
for (int i = 0; i < *cat_count; i++) {
cJSON* cat = new cJSON();
cat = cJSON_GetArrayItem(cats, i);
string *track_title = new string(cJSON_GetObjectItem(cat, "name")->valuestring);
GENERIC_ITEM gitem;
gitem.Title = "Hi";
GENERIC_ITEM^ ubersnipCategory = ref new GENERIC_ITEM();
ubersnipCategory->Title = _String(*track_title);
rootPage->Categories->Append(ubersnipCategory);
}
});
This does not crash
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
but this one does
all_item->Title = "All";
I am almost positive it has something to do with it being in the apps default namespace and it being accessed outside of the main thread ... At least that's what it seems like as that's really the only difference besides the actual class.
This is what GENERIC_ITEM looks like.
[Windows::UI::Xaml::Data::Bindable]
public ref class GENERIC_ITEM sealed {
private:
Platform::String^ _title = "";
Platform::String^ _description;
Windows::UI::Xaml::Media::ImageSource^ _Image;
event PropertyChangedEventHandler^ _PropertyChanged;
void OnPropertyChanged(Platform::String^ propertyName)
{
PropertyChangedEventArgs^ pcea = ref new PropertyChangedEventArgs(propertyName);
_PropertyChanged(this, pcea);
}
public:
GENERIC_ITEM() {
};
property Platform::String^ Title {
Platform::String^ get() {
return this->_title;
}
void set(Platform::String^ val) {
this->_title = val;
OnPropertyChanged("Title");
}
}
property Platform::String^ Description {
Platform::String^ get() {
return this->_description;
}
void set(Platform::String^ val) {
this->_description = val;
OnPropertyChanged("Description");
}
}
void SetImage(Platform::String^ path)
{
Windows::Foundation::Uri^ uri = ref new Windows::Foundation::Uri(path);
_Image = ref new Windows::UI::Xaml::Media::Imaging::BitmapImage(uri);
}
};
I know there is no issue with the class because it works perfectly fine if I run this exact same code on the initial thread.
Any suggestions? Thanks! :D
Figured it out after several hours! In case someone else is having this issue, all you must do is use the Dispatcher to run code on the UI that is not available outside of the UI thread.
void loadCats(UberSnip::HELPER::ASYNC_RESPONSE^ responseItem, MainPage^ rootPage) {
Platform::String^ BR = responseItem->Body;
cJSON* cats = cJSON_Parse(_string(BR));
cats = cats->child;
int *cat_count = new int(cJSON_GetArraySize(cats));
rootPage->Categories->Clear();
GENERIC_ITEM^ all_item = ref new GENERIC_ITEM();
all_item->Title = "All";
rootPage->Categories->Append(all_item);
for (int i = 0; i < *cat_count; i++) {
cJSON* cat = new cJSON();
cat = cJSON_GetArrayItem(cats, i);
string *track_title = new string(cJSON_GetObjectItem(cat, "name")->valuestring);
GENERIC_ITEM gitem;
gitem.Title = "Hi";
GENERIC_ITEM^ ubersnipCategory = ref new GENERIC_ITEM();
ubersnipCategory->Title = _String(*track_title);
rootPage->Categories->Append(ubersnipCategory);
}
}
void ASyncTaskCategories(void)
{
concurrency::task_completion_event<Platform::String^> taskDone;
MainPage^ rootPage = this;
UberSnip::HELPER::ASYNC_RESPONSE^ responseItem = ref new UberSnip::HELPER::ASYNC_RESPONSE();
auto dispatch = CoreWindow::GetForCurrentThread()->Dispatcher;
auto op2 = create_async([taskDone, responseItem, rootPage, dispatch] {
return create_task([taskDone, responseItem, rootPage, dispatch]() -> Platform::String^
{
//UBERSNIP API 0.4
UberSnip::UBERSNIP_CLIENT* UberSnipAPI = new UberSnip::UBERSNIP_CLIENT();
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
try{
UberSnipAPI->Http->request();
}
catch (...) {
printf("Error");
}
int err = UberSnip::UTILS::STRING::StringToAscIIChars(UberSnipAPI->Client->BodyResponse).find("__api_err");
if (err < 0) {
if (UberSnip::UTILS::STRING::StringToAscIIChars(UberSnipAPI->Client->BodyResponse).length() < 3) {
return;
}
}
taskDone.set(UberSnipAPI->Client->BodyResponse);
responseItem->Body = UberSnipAPI->Client->BodyResponse;
dispatch->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]()
{
rootPage->loadCats(responseItem, rootPage);
}));
for (int i = 0; i < 100;) {
}
return "(done)";
}).then([taskDone, responseItem, rootPage](Platform::String^ BodyResponse) {
});
});
//rootPage->loadCats(responseItem, rootPage);
}

Photo doesn't show in browser

I am making a web application in asp.net with MVC 4 and i'm trying to show the user twitter home feed. To get the user home feed i'm using twitterizer2. Everything work fine and i have the user home feed and the feed photo link but it doesn't display in the browser. If i open the picture link from the browser address bar it is displayed and also if i use another photo link not related with twitter everything works fine. So i'm guessing it has something to do with twitter.
My view is this:
<div class="NoBullets" style="font-size:#Model.TextSize">
<ul style="list-style-type:none">
#foreach (var status in Model.TStatusCollection)
{
<li>
<img src=#status.User.ProfileImageLocation style="float:left" width="48" height="48" align="bottom"> #status.Text<br />
#string.Format("{0:dd MMMM yyyy} {0:H:mm}", status.CreatedDate)
</li>
}
</ul>
</div>
And the model:
public class PortletMyTwitter : PortletBase
{
private int noOfTweets = 15;
private string textSize = "medium";
private string userExtAppID;
private TwitterStatusCollection tStatusCollection;
private IList<object> noOfTweetsList = new List<object>()
{
new {value = 5},
new {value = 10},
new {value = 15},
new {value = 20},
new {value = 25}
};
private IList<object> textSizeList = new List<object>()
{
new {value = "small"},
new {value = "medium"},
new {value = "large"}
};
public string UserExtAppID
{
get { return userExtAppID; }
set { userExtAppID = value; }
}
public IList<object> NoOfTweetsList
{
get { return noOfTweetsList; }
}
public int NoOfTweets
{
get { return noOfTweets; }
set { noOfTweets = value; }
}
public IList<object> TextSizeList
{
get { return textSizeList; }
}
public string TextSize
{
get { return textSize; }
set { textSize = value; }
}
public TwitterStatusCollection TStatusCollection
{
get { return tStatusCollection; }
}
public void GetSettings(XmlDocument xmlPortletState)
{
if (xmlPortletState.GetElementsByTagName("UserExtAppID").Count > 0)
{
if (xmlPortletState.GetElementsByTagName("UserExtAppID")[0].FirstChild != null)
UserExtAppID = ((System.Xml.XmlText)(xmlPortletState.GetElementsByTagName("UserExtAppID")[0]).FirstChild).Value;
}
if (xmlPortletState.GetElementsByTagName("HideHeader").Count > 0)
{
if (xmlPortletState.GetElementsByTagName("HideHeader")[0].FirstChild != null)
HideHeader = bool.Parse(((System.Xml.XmlText)(xmlPortletState.GetElementsByTagName("HideHeader")[0]).FirstChild).Value);
}
if (xmlPortletState.GetElementsByTagName("TextSize").Count > 0)
{
if (xmlPortletState.GetElementsByTagName("TextSize")[0].FirstChild != null)
try
{
TextSize = ((System.Xml.XmlText)(xmlPortletState.GetElementsByTagName("TextSize")[0]).FirstChild).Value;
}
catch
{
TextSize = "medium";
}
}
if (xmlPortletState.GetElementsByTagName("NoOfTweets").Count > 0)
{
if (xmlPortletState.GetElementsByTagName("NoOfTweets")[0].FirstChild != null)
try
{
NoOfTweets = Convert.ToInt32(((System.Xml.XmlText)(xmlPortletState.GetElementsByTagName("NoOfTweets")[0]).FirstChild).Value);
}
catch
{
NoOfTweets = 10;
}
}
UpdateFeed();
}
protected void UpdateFeed()
{
try
{
OAuthTokens oauthTokens = new OAuthTokens()
{
AccessToken = "",
AccessTokenSecret = "",
ConsumerKey = "",
ConsumerSecret = ""
};
TimelineOptions myOptions = new TimelineOptions();
myOptions.IncludeRetweets = false;
myOptions.UseSSL = true;
myOptions.APIBaseAddress = "https://api.twitter.com/1.1/";
myOptions.Count = NoOfTweets;
TwitterResponse<TwitterStatusCollection> twitterDataSource = TwitterTimeline.HomeTimeline(oauthTokens, myOptions);
tStatusCollection = twitterDataSource.ResponseObject;
}
catch (Exception)
{
}
}
}

How to download to an sd card in AIR

I have a download function that I got from Andy Matthews, and an sd Card function that I got from Christian Cantrell. Now I need to download to the sd Card.
Q: How do I specify that storage = e.storageVolume.rootDirectory.nativePath?
var remoteFile = 'http://www.CompanyName.com/ClientName.txt';
jQuery(function($){
air.StorageVolumeInfo.storageVolumeInfo.addEventListener(air.StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNT, onVolumeMount);
air.StorageVolumeInfo.storageVolumeInfo.addEventListener(air.StorageVolumeChangeEvent.STORAGE_VOLUME_UNMOUNT, onVolumeUnmount);
var PluggedIn = false;
var volumes = air.StorageVolumeInfo.storageVolumeInfo.getStorageVolumes();
for (var i = 0; i < volumes.length; i++) {
if (volumes[i].isRemovable) {
if (volumes[i].name == 'COMPANYNAME') {
PluggedIn = true;
$('#content').append('I see you already have CompanyName plugged in!');
var myNativePath = volumes[i].rootDirectory.nativePath;
var storage = 'desktopDirectory'; // myNativePath
downloadFile(remoteFile, storage);
} else {
$('#content').append('What you have plugged in is not CompanyName.');
}
}
}
if (!PluggedIn){
$('#content').append('<h1>Please insert your CompanyName card.</h1>');
}
})
function onVolumeMount(e) {
if (e.storageVolume.isRemovable) {
$('#content').html('<h1>Thank you</h1>');
if (e.storageVolume.name == 'COMPANYNAME') {
var myNativePath = e.storageVolume.rootDirectory.nativePath;
var storage = 'desktopDirectory'; // myNativePath
downloadFile(remoteFile, storage);
} else {
$('#content').append('<p>The card you just plugged in is not CompanyName.</p>');
}
} else {
$('#content').append('<p>This device is not removable</p>');
}
}
function onVolumeUnmount(e) {
$('#content').html('<h1>Goodbye!</h1>');
}
function downloadFile(remoteFile, storage){
var fn = remoteFile.match(/[a-z0-9-+\._]+?$/i);
var myFile = air.File[storage].resolvePath(fn);
var myURLStream = new air.URLStream();
myURLStream.addEventListener(air.Event.COMPLETE, function(e){
var myByteArray = new air.ByteArray();
myURLStream.readBytes(myByteArray, 0, myURLStream.bytesAvailable);
var myFileStream = new air.FileStream();
myFileStream.openAsync(myFile, air.FileMode.WRITE);
myFileStream.writeBytes(myByteArray, 0);
myFileStream.close();
});
myURLStream.load(new air.URLRequest(remoteFile));
}
var myFile = new air.File("file:///" + storage).resolvePath(fn);

air process adt flex

I have two air applications and installed them in desktop and executed them and two air processes are listed in taskbar manager.Now how can I execute some method of one air application from another air application?
Use LocalConnection.
You can Host a Connection in one AIR application and connect from the the other AIR guy... From there - you can call methods.
BEWARE: LocalConnection can be a little tricky and odd (for example, connections are global and the names can't overlap).
From the Example Doc listed above....
// Code in LocalConnectionSenderExample.as
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.LocalConnection;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.events.StatusEvent;
import flash.text.TextFieldAutoSize;
public class LocalConnectionSenderExample extends Sprite {
private var conn:LocalConnection;
// UI elements
private var messageLabel:TextField;
private var message:TextField;
private var sendBtn:Sprite;
public function LocalConnectionSenderExample() {
buildUI();
sendBtn.addEventListener(MouseEvent.CLICK, sendMessage);
conn = new LocalConnection();
conn.addEventListener(StatusEvent.STATUS, onStatus);
}
private function sendMessage(event:MouseEvent):void {
conn.send("myConnection", "lcHandler", message.text);
}
private function onStatus(event:StatusEvent):void {
switch (event.level) {
case "status":
trace("LocalConnection.send() succeeded");
break;
case "error":
trace("LocalConnection.send() failed");
break;
}
}
private function buildUI():void {
const hPadding:uint = 5;
// messageLabel
messageLabel = new TextField();
messageLabel.x = 10;
messageLabel.y = 10;
messageLabel.text = "Text to send:";
messageLabel.autoSize = TextFieldAutoSize.LEFT;
addChild(messageLabel);
// message
message = new TextField();
message.x = messageLabel.x + messageLabel.width + hPadding;
message.y = 10;
message.width = 120;
message.height = 20;
message.background = true;
message.border = true;
message.type = TextFieldType.INPUT;
addChild(message);
// sendBtn
sendBtn = new Sprite();
sendBtn.x = message.x + message.width + hPadding;
sendBtn.y = 10;
var sendLbl:TextField = new TextField();
sendLbl.x = 1 + hPadding;
sendLbl.y = 1;
sendLbl.selectable = false;
sendLbl.autoSize = TextFieldAutoSize.LEFT;
sendLbl.text = "Send";
sendBtn.addChild(sendLbl);
sendBtn.graphics.lineStyle(1);
sendBtn.graphics.beginFill(0xcccccc);
sendBtn.graphics.drawRoundRect(0, 0,
(sendLbl.width + 2 + hPadding + hPadding), (sendLbl.height + 2), 5, 5);
sendBtn.graphics.endFill();
addChild(sendBtn);
}
}
}
// Code in LocalConnectionReceiverExample.as
package {
import flash.display.Sprite;
import flash.net.LocalConnection;
import flash.text.TextField;
public class LocalConnectionReceiverExample extends Sprite {
private var conn:LocalConnection;
private var output:TextField;
public function LocalConnectionReceiverExample() {
buildUI();
conn = new LocalConnection();
conn.client = this;
try {
conn.connect("myConnection");
} catch (error:ArgumentError) {
trace("Can't connect...the connection name is already
being used by another SWF");
}
}
public function lcHandler(msg:String):void {
output.appendText(msg + "\n");
}
private function buildUI():void {
output = new TextField();
output.background = true;
output.border = true;
output.wordWrap = true;
addChild(output);
}
}
}