NotificationType.CRITICAL needs only to only fire when file loaded is a new file - actionscript-3

I have an Adobe Air desktop message board App built in Flash cs5, it loads an external ".txt" file in a dynamic text field and checks for a new file every 2 minutes. I need it to notify user with (NotificationType.CRITICAL) only if the file is new not just everytime it loads it. is it possible?
all the code in the app:
NativeApplication.nativeApplication.startAtLogin=true
stage.nativeWindow.alwaysInFront=true;
//external text file load and recheck every 2 minutes
var myInterval:uint = setInterval (loadUrl, 120000);
var loader:URLLoader = new URLLoader(new URLRequest("https://my_text_file.txt"));
loader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void {
var loadedText:URLLoader = URLLoader(event.target);
if(myText_txt.htmlText!=loadedText.data){
myText_txt.htmlText = loadedText.data;
stage.nativeWindow.notifyUser(NotificationType.CRITICAL)
}else {
//do nothing
}
}
function loadUrl():void {
loader = new URLLoader(new URLRequest("https:///my_text_file.txt"));
loader.addEventListener(Event.COMPLETE, completeHandler);
}
// button control
Minimize_BTN.addEventListener(MouseEvent.CLICK, minimize);
function minimize(e:MouseEvent){
stage.nativeWindow.minimize();
}
drag_BTN.addEventListener(MouseEvent.MOUSE_DOWN, drag);
function drag(e:MouseEvent){
stage.nativeWindow.startMove();
}
stop(); //Stop on the frame you want

Your code might not work if the myText_txt field is modifying the loaded text (e.g., if myText_txt's condenseWhite property is set to true). A more accurate way to determine if the text has changed would be to store it in a String variable named, for example, oldText and then comparing oldText with the newly loaded text.
Here's part of your code re-written to include the oldText variable. This code is also more efficient because it instantiates some variables only once and it avoids duplicating some code:
import flash.net.URLRequest;
function completeHandler(event:Event):void
{
var newText:String = loader.data;
if(newText != oldText)
{
myText_txt.htmlText = newText;
stage.nativeWindow.notifyUser(NotificationType.CRITICAL);
oldText = newText;
}
}
function loadUrl():void
{
loader.load(req);
}
// Initialize your variables and event handlers only one time
var req:URLRequest = new URLRequest("https:///my_text_file.txt");
// Set cacheResponse to false to prevent a successful response
// from being cached.
req.cacheResponse = false;
// And don't bother checking the cache, either.
// Not necessary, but the request will execute a little faster.
req.useCache = false;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
// Use oldText inside completeHandler() to determine
// whether the file's text has changed
var oldText:String = "";
var myInterval:uint = setInterval(loadUrl, 120000);
// Start loading the text right away
loadUrl();

Why don't you use FileReference object to find out about some properties like modificationDate and based on this verify if file is different you can also test it's size.

Related

AS3 Load Image Using Path From Text File

i use txt file that contain paths.
after loaded txt file and split to path array
then load img file from array path
but i get err in loading img
please help me
sample code:
var imglst:Array=new Array();
var lodimg:Loader=new Loader();
var lodtxt:URLLoader=new URLLoader();
lodtxt.load(new URLRequest("imglst.txt"));
lodtxt.addEventListener(Event.COMPLETE,onL_C);
function onL_C(e:Event)
{
var t:Array=new Array();
t=e.target.data.split(/\n/);
var s:URLRequest=new URLRequest(t[0].toString());
trace(t[0]);
lodimg.load(s);
}
lodimg.contentLoaderInfo.addEventListener(Event.COMPLETE,onL_Cimg);
function onL_Cimg(e:Event)
{
var i:Bitmap=new Bitmap();
i=Bitmap(lodimg.content);
i.width=100;
i.height=100;
addChild(i);
trace("OK");
}
Are you loading images from a different website from your own? Does the other website(s) have a crossdomain.xml to allow permissions of loading their content? Usually Flash will give you a "security error" as an event but your code isn't listening for such an event so your program is not aware of any such problems... look on google how to handle AS3 errors.
Anyways a workaround is to just load the bytes of file using URLloader and on completion you then only use Loader to decode the bytes into pixel colours.
import flash.utils.ByteArray;
var imglst : Array;
var lodimg : Loader;
//var lodtxt : URLLoader = new URLLoader();
var lodURL:URLLoader = new URLLoader();
var img_bytes : ByteArray = new ByteArray();
lodURL.load(new URLRequest("http://yoursite/imglst.txt"));
lodURL.addEventListener(Event.COMPLETE,onL_C);
function onL_C (e:Event)
{
//# Since load complete no need to keep listening for that
lodURL.removeEventListener(Event.COMPLETE,onL_C);
var t:Array=new Array();
t=e.target.data.split(/\n/);
var s:URLRequest=new URLRequest(t[0].toString());
trace(t[0]);
//lodimg.contentLoaderInfo.addEventListener(Event.COMPLETE,onL_Cimg);
//lodimg.load(s);
//# Now we know path so we load those file bytes
lodURL.dataFormat = URLLoaderDataFormat.BINARY;
lodURL.load(s); lodURL.addEventListener(Event.COMPLETE, onBytes_C);
}
function onBytes_C (e:Event)
{
//# on complete load of bytes...
trace("got bytes");
img_bytes = lodURL.data;
//trace("Image bytes total : " + img_bytes.length);
img_bytes.position = 0; //avoid "end of file" error
lodimg = new Loader();
lodimg.contentLoaderInfo.addEventListener(Event.COMPLETE,onL_Cimg);
lodimg.loadBytes(img_bytes); //we already have data so this will be fast
}
function onL_Cimg (e:Event)
{
var i:Bitmap = new Bitmap();
i = lodimg.content as Bitmap;
i.width=100;
i.height=100;
addChild(i);
trace("OK");
}

Refreshing every XX seconds

I am new to actionscript and flash, but i managed to make code that gets data from php file and refresh result every 30 seconds:
var timerRefreshRate:Number = 30000;
var fatherTime:Timer = new Timer(timerRefreshRate, 0);
fatherTime.addEventListener(TimerEvent.TIMER, testaa);
fatherTime.start();
function testaa(event:Event):void{
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE,varsLoaded);
loader.load(new URLRequest("data.php"));
function varsLoaded (event:Event):void {
this.opaqueBackground = loader.data.color;
title.text=loader.data.title;
banner_text.text=loader.data.text;
}
}
But now i am facing 2 problems:
1.) User must wait 30 seconds for movie to load first time
2.) Setting background color does not work any more.
What am i doing wrong?
You can call your function once to load immediately without waiting 30 seconds. Just change the parameters of the function to default to a null event:
function testaa(event:Event = null):void{
//...
}
Now you can call the function like so:
//...
fatherTime.start();
testaa();
So you start the timer but immediately run the function once.
For your second problem, the issue is most likely that you are using a nested function, so this does not refer to your class but rather the testaa function. Nested functions are bad practice in general and you should avoid them if possible. Move the function and loader reference outside and it should work. Final result should be something like this:
var loader:URLLoader;
var timerRefreshRate:Number = 30000;
var fatherTime:Timer = new Timer(timerRefreshRate, 0);
fatherTime.addEventListener(TimerEvent.TIMER, testaa);
fatherTime.start();
testaa();
function testaa(event:Event = null):void{
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE,varsLoaded);
loader.load(new URLRequest("data.php"));
}
function varsLoaded (event:Event):void {
this.opaqueBackground = loader.data.color;
title.text=loader.data.title;
banner_text.text=loader.data.text;
}

URLRequest load ownly when file is new, then fire NotificationType.CRITICAL

using AS3 and Flash CS5
I have a messageboard Adobe Air desktop App with a URLLoader making a URLRequest for a ".txt" file every 2 minutes. or however long I set the time to look. The App loads the txt file into a dynamic text field.
var loader:URLLoader = new URLLoader(new URLRequest("https://my_text_file.txt"));
loader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void {
var loadedText:URLLoader = URLLoader(event.target);
myText_txt.htmlText = loadedText.data;
}
Is it possible to have the URLRequest load the file only if its new? not every time?
then when the "new" file has been loaded fire
mainWindow.notifyUser(NotificationType.CRITICAL)
so the user knows there is a new message?
thanks in advance!!
var loader:URLLoader = new URLLoader(new URLRequest("https://my_text_file.txt"));
loader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void {
var loadedText:URLLoader = URLLoader(event.target);
if(myText_txt.htmlText!=loadedText.data){
myText_txt.htmlText = loadedText.data;
mainWindow.notifyUser(NotificationType.CRITICAL)
}else {
//do nothing
}
}
Since the application will still be running you should just compare the old text file to the new one to see if there have been any changes made.

AS3 - READ text from external .txt and CHANGE color of an object IF there is MATCH

I am working on a project that uses a batch script to check availability (ping) of the computers in a specific Network. It also changes the color of an object in Flash-based UI when there's an exact match from the script's results.
EXAMPLE:
1) Script runs checks and outputs into results.txt:
192.168.0.1=UP
192.168.0.2=DOWN
192.168.0.3=UP
2) Using AS3, I would like to read this file and search for a string like "192.168.0.1=UP". If there is a match it would change the object's color to GREEN. Otherwise, it would set as RED.
So far, I have managed to import the output file from the script inside Flash, using:
var textLoader:URLLoader = new URLLoader();
textLoader.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(e:Event):void {
trace(e.target.data);
}
textLoader.load(new URLRequest("Path:/To/result.txt"));
I understand I cannot just make AS3 search the file only for "192.168.0.1=UP" and change color if there is match.
How I can make use of the imported text? Do I have to make a string, that uses only the parts of the text I need and then make an IF statement to color the object if there is match?
Thanks in advance.
UPDATE:
Thanks to Gunther Fox, I was able to put the whole code together:
import flash.geom.ColorTransform;
var textLoader:URLLoader = new URLLoader();
textLoader.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(e:Event):void {
trace(e.target.data);
if (e.target.data.indexOf("192.168.0.1=UP") != -1) {
var colorGREEN:ColorTransform = <instance_name>.transform.colorTransform;
colorGREEN.color = 0x00FF00;
<instance_name>.transform.colorTransform = colorGREEN;
}
else {
var colorRED:ColorTransform = <instance_name>.transform.colorTransform;
colorRED.color = 0xFF0000;
<instance_name>.transform.colorTransform = colorRED;
}
}
textLoader.load(new URLRequest("Path:/To/result.txt"));
Now my AS3 changes color of a specific object, based on the batch script output.
UPDATE 2
I solved the problem with reloading of the text file:
var timer:Timer = new Timer(10000);
timer.addEventListener(TimerEvent.TIMER, onTimer);
timer.start();
function onTimer(evt:TimerEvent):void {
var textLoader:URLLoader = new URLLoader();
textLoader.addEventListener(Event.COMPLETE, onLoaded);
textLoader.load(new URLRequest("C:/Folder/output/result.txt"));
}
If you're looking for something very specific like the string "192.168.0.1=UP" you can use indexOf() and check if the result is -1 or not:
function onLoaded(e:Event):void {
trace(e.target.data);
if (e.target.data.indexOf("192.168.0.1=UP") != -1) {
// Change to green
}
else {
// Change to red
}
}

Flash AS3 - DisplayObject Argument Error - Trying to Remove and Add Loaded Content

I am working with flash and as3 to try and get a photo loader/viewer/upload tool built. I am using file reference to handle the browse/load/upload functions. My current stage has 2 loader boxes that i load the user selected image into. I need to be able to remove the image though and re-select another if the user decides.
So on the file loaded event i have this code:
// Load Image into Editor Function.
function onMovieClipLoaderComplete(event:Event):void {
var loadedContent:DisplayObject=event.target.content;
currentLoader =event.target.loader as Loader;
currentLoader.x=currentX;
currentLoader.y=currentY;
currentContent.buttonMode=true;
currentContent.addChild(currentLoader);
addChild(currentContent);
currentLoader.mask = currentMask;
addChild(replace_btn);
}
And on my replace button i have:
replace_btn.addEventListener(MouseEvent.CLICK, replaceImage);
function replaceImage(event:Event):void {
currentContent.removeChild(currentLoader);
removeChild(currentContent);
}
On pressing the replace button once it works fine but when i load another image into the loader - the next time i press the replace button (or any subsequent time) i get the following argument error in my flash as3 file:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at MethodInfo-13()
Does anyone know what this means? It's odd that it only happens on the second time onwards not at first. I thought that if i have:
currentContent.addChild(currentLoader); addChild(currentContent);
on load and then just
currentContent.removeChild(currentLoader); removeChild(currentContent);
on the replace function it would work?
Full as3 code is shown below if that also helps
I have only been learning flash for 3-4 months so please go easy on me and i apologise if my code is not done in the best way! :)
Lauren
// Set Start Up Values.
var image1_loader:Loader = new Loader();
var image1_content:Sprite = new Sprite();
var image1_mask:Sprite = new Sprite(); image1_mask.graphics.beginFill(0x000000,1); image1_mask.graphics.drawRect(54, 59, 330, 330); image1_mask.graphics.endFill();
var image2_loader:Loader = new Loader();
var image2_content:Sprite = new Sprite();
var image2_mask:Sprite = new Sprite(); image2_mask.graphics.beginFill(0x000000,1); image2_mask.graphics.drawRect(384, 59, 330, 165); image2_mask.graphics.endFill();
var currentBtn;
var currentLoader;
var currentContent;
var currentMask;
var currentX;
var currentY;
replace_btn.visible=false;
// Define FileReference.
var canvasImage:FileReference;
// Image Buttons Function.
image1_btn.addEventListener(MouseEvent.CLICK, start_fileRef);
image2_btn.addEventListener(MouseEvent.CLICK, start_fileRef);
image1_content.addEventListener(MouseEvent.MOUSE_DOWN, setCurrentSelection);
image2_content.addEventListener(MouseEvent.MOUSE_DOWN, setCurrentSelection);
function setCurrentSelection(e:MouseEvent):void {
if (e.currentTarget===image1_content){currentContent=image1_content;}
if (e.currentTarget===image2_content){currentContent=image2_content;}
}
// Browse File Function.
function start_fileRef(e:MouseEvent):void {
trace("onBrowse");
if (e.target===image1_btn){currentBtn=image1_btn; currentLoader=image1_loader; currentContent=image1_content; currentMask=image1_mask; currentX=54; currentY=59;}
if (e.target===image2_btn){currentBtn=image2_btn; currentLoader=image2_loader; currentContent=image2_content; currentMask=image2_mask; currentX=384; currentY=59;}
canvasImage=new FileReference();
canvasImage.addEventListener(Event.SELECT, onFileSelected);
var imageTypeFilter:FileFilter = new FileFilter("JPG/PNG Files","*.jpeg; *.jpg;*.gif;*.png");
canvasImage.browse([imageTypeFilter]);
}
// Selected File Function.
function onFileSelected(event:Event):void {
trace("onFileSelected");
canvasImage.addEventListener(Event.COMPLETE, onFileLoaded);
canvasImage.addEventListener(ProgressEvent.PROGRESS, onProgress);
var canvasImageName = canvasImage.name;
canvasImage.load();
}
// File Progress Function.
function onProgress(event:ProgressEvent):void {
var percentLoaded:Number=event.bytesLoaded/event.bytesTotal*100;
trace("loaded: "+percentLoaded+"%");
}
// File Loaded Function.
function onFileLoaded(event:Event):void {
var fileReference:FileReference=event.target as FileReference;
var data:ByteArray=fileReference["data"];
trace("File loaded");
var movieClipLoader:Loader=new Loader();
movieClipLoader.loadBytes(data);
movieClipLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onMovieClipLoaderComplete);
canvasImage.removeEventListener(Event.COMPLETE, onFileLoaded);
}
// Load Image into Editor Function.
function onMovieClipLoaderComplete(event:Event):void {
var loadedContent:DisplayObject=event.target.content;
currentLoader =event.target.loader as Loader;
currentLoader.x=currentX;
currentLoader.y=currentY;
currentContent.buttonMode=true;
currentContent.addChild(currentLoader);
addChild(currentContent);
currentLoader.mask = currentMask;
addChild(replace_btn);
// Reveal Retry Button over Hover Function //
currentContent.addEventListener(MouseEvent.ROLL_OVER, hover);
replace_btn.addEventListener(MouseEvent.ROLL_OVER, hover);
currentContent.addEventListener(MouseEvent.ROLL_OUT, unhover);
replace_btn.addEventListener(MouseEvent.ROLL_OUT, unhover);
function hover(event:Event):void {
replace_btn.visible=true;
}
function unhover(event:Event):void {
replace_btn.visible=false;
}
replace_btn.addEventListener(MouseEvent.CLICK, replaceImage);
function replaceImage(event:Event):void {
currentContent.removeChild(currentLoader);
removeChild(currentContent);
}
}
This currentContent.removeChild(currentLoader); should be fine, but this removeChild(currentContent); is most likely the problem source. Because you added it as currentContent.addChild(currentLoader), you must remove the container var (currentContent) with it as well.