Flash hyperlink - changing var name in url - actionscript-3

I have trouble with hyperlink in flash on site. As site is in CMS, with different
stages of approval I do not know exact url, so
function piClick(e:MouseEvent):void
{
var url:String = "/cms__Main?name=Target_name";
var request:URLRequest = new URLRequest(url);
try {
navigateToURL(request, '_self');
} catch (e:Error) {
trace("Error occurred!");
}
}
does not work, as cms_Main changes according to stage of site. What I probably need to do is:
grab url (or part after last "/" if that is even possible)
change "name" variable inside String
f.e
https://domain_name/.../status?name=Name_I_need_to_swap&sname=Country_name&..

stage.loaderInfo.url will get you the address of the swf itself so it won't get you the full address, the query or the hash tag. You can, however, grab all this information using Javascript.
import flash.external.ExternalInterface;
function getFullAddress():String {
if (ExternalInterface.available) {
var href:String = ExternalInterface.call('function(){return window.location.href}');
if (href) return href.toString();
}
throw new Error('Make sure JS is enabled.');
}
var fullAddr:String = getFullAddress();
EDIT: Here's how you can get and modify all that you're asking.
import flash.external.ExternalInterface;
import flash.net.URLVariables;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.navigateToURL;
function getFullAddress():String {
if (ExternalInterface.available) {
var href:String = ExternalInterface.call('function(){return window.location.href}');
if (href) return href.toString();
}
throw new Error('Make sure JS is enabled.');
}
function getQuery(fullAddr:String):URLVariables {
if (!fullAddr.match(/\?[^#]/)) return new URLVariables();
var q:String = fullAddr.replace(/^.*?\?([^#]+)(#.*)?$/,'$1');
return new URLVariables(q);
}
function getAddress(fullAddr:String):String {
return fullAddr.replace(/\?.*/,'').replace(/#.*/,'');
}
function getRequest(url:String,query:URLVariables=null,method:String='GET'):URLRequest {
method = URLRequestMethod[method] || 'GET';
var req:URLRequest = new URLRequest(url);
req.method = method;
if (method == 'GET' && query != null) {
req.url += '?' + query.toString().replace(/%5f/gi,'_').replace(/%2d/gi,'-');
// this is because dash and underscore chars are also
// encoded by URLVariables. we want to omit this.
return req;
}
req.data = query;
return req;
}
var fullAddr:String = getFullAddress();
var addr:String = getAddress(fullAddr);
var query:URLVariables = getQuery(fullAddr);
query.name = 'Name_I_need_to_swap';
query.sname = 'Country_name';
// add as many variable-value pairs as you like
// and don't worry, they will be automatically
// encoded by the function called below
var req:URLRequest = getRequest(addr,query);
//navigateToURL(req);
// check the console to see the changed address
ExternalInterface.call('console.log',req);

you can get URL with this.loaderInfo.url

Related

Error in Apple's TVML documentation? pushPage function doesn't work

UPDATED 6/1/17 with the correct code pasted at the bottom.
I'm working through Apple's TVML guide, section 2: Navigating Between Pages. (https://developer.apple.com/library/content/documentation/TVMLKitJS/Conceptual/TVMLProgrammingGuide/NavigatingBetweenPages.html#//apple_ref/doc/uid/TP40016718-CH9-SW1)
Everything is fine until the last bit (Listing 4-4), which allow you to use the menu button on the remote to return to the previous page. Whenever I try it, my sample app simply won't load:
var baseURL;
function loadingTemplate() {
var template = '<document><loadingTemplate><activityIndicator><text>Loading</text></activityIndicator></loadingTemplate></document>';
var templateParser = new DOMParser();
var parsedTemplate = templateParser.parseFromString(template, "application/xml");
return parsedTemplate;
}
function getDocument(extension) {
var templateXHR = new XMLHttpRequest();
var url = baseURL + extension;
var loadingScreen = loadingTemplate();
templateXHR.responseType = "document";
templateXHR.addEventListener("load", function() {pushPage(templateXHR.responseXML, loadingScreen);}, false);
templateXHR.open("GET", url, true);
templateXHR.send();
}
function pushPage(page, loading) {
var currentDoc = getActiveDocument();
navigationDocument.replaceDocument(page, loading);
}
App.onLaunch = function(options) {
baseURL = options.BASEURL;
var extension = "templates/InitialPage.xml";
getDocument(extension);
}
What am I missing?
This works:
var baseURL;
function loadingTemplate() {
var template = '<document><loadingTemplate><activityIndicator><text>Loading</text></activityIndicator></loadingTemplate></document>';
var templateParser = new DOMParser();
var parsedTemplate = templateParser.parseFromString(template, "application/xml");
navigationDocument.pushDocument(parsedTemplate);
return parsedTemplate;
}
function getDocument(extension) {
var templateXHR = new XMLHttpRequest();
var url = baseURL + extension;
var loadingScreen = loadingTemplate();
templateXHR.responseType = "document";
templateXHR.addEventListener("load", function() {pushPage(templateXHR.responseXML, loadingScreen);}, false);
templateXHR.open("GET", url, true);
templateXHR.send();
}
function pushPage(page, loading) {
navigationDocument.replaceDocument(page, loading);
}
App.onLaunch = function(options) {
baseURL = options.BASEURL;
var extension = "templates/InitialPage.xml";
getDocument(extension);
}
Yes, I believe there is a mistake. They should have kept the line
navigationDocument.pushDocument(parsedTemplate);
at the end of the loadingTemplate method.
The idea is to push the loading page, then replace it with the new page.
On a side note, the line
var currentDoc = getActiveDocument();
has no business here. This code was obviously not tested or reviewed.

gulp-replace if content of files match regex

I have a folder of HTML files that contain a comment at the top with metadata. I would like to run one gulp-replace operation if the metadata matches one regex, and another gulp-replace operation if it doesn't match, then continue on with the rest of the tasks pipeline. If tried various iterations using gulp-if but it always results in "TypeError: undefined is not a function" errors
import gulp from 'gulp';
import plugins from 'gulp-load-plugins';
const $ = plugins();
function preprocess() {
var template_data = new RegExp('<!-- template_language:(\\w+)? -->\n', 'i');
var handlebars = new RegExp('<!-- template_language:handlebars -->', 'i');
var primaryColor = new RegExp('#dc002d', 'gi');
var mailchimpColorTag = '*|PRIMARY_COLOR|*';
var handlebarsColorTag = '{{PRIMARY_COLOR}}';
var replaceCondition = function (file) {
return file.contents.toString().match(handlebars);
}
return gulp.src('dist/**/*.html')
.pipe($.if(
replaceCondition,
$.replace(primaryColor, handlebarsColorTag),
$.replace(primaryColor, mailchimpColorTag)
))
.pipe($.replace, template_data, '')
.pipe(gulp.dest('dist'));
}
What's the most efficient way to go about this?
gulp-filter was the answer. Whereas gulp-if can be used to decide whether a particular operation should be applied to the whole stream, gulp-filter can be used to decide which files in a stream an operation should be applied to.
import gulp from 'gulp';
import plugins from 'gulp-load-plugins';
const $ = plugins();
function preprocess() {
var template_language = new RegExp('<!-- template_language:(\\w+)? -->\n', 'i');
var handlebars = 'handlebars';
var primaryColor = new RegExp('#dc002d', 'gi');
var handlebarsColorTag = '{{PRIMARY_COLOR}}';
var handlebarsCondition = function (file) {
var match = file.contents.toString().match(template_language);
return (match && match[1] == handlebars);
}
var handlebarsFilter = $.filter(handlebarsCondition, {restore: true});
var mailchimpColorTag = '*|PRIMARY_COLOR|*';
var mailchimpCondition = function (file) {
return !handlebarsCondition(file);
}
var mailchimpFilter = $.filter(mailchimpCondition, {restore: true});
return gulp.src('dist/**/*.html')
.pipe(handlebarsFilter)
.pipe($.replace(primaryColor, handlebarsColorTag))
.pipe($.debug({title: 'Applying ' + handlebarsColorTag}))
.pipe(handlebarsFilter.restore)
.pipe(mailchimpFilter)
.pipe($.replace(primaryColor, mailchimpColorTag))
.pipe($.debug({title: 'Applying ' + mailchimpColorTag}))
.pipe(mailchimpFilter.restore)
.pipe($.replace(template_language, ''))
.pipe(gulp.dest('dist'));
}

How to make a RESTFUL PUT call angulajrs

Im confused on how to make a RESTFUL API call with 'PUT'. I'm basically trying to save an edited profile but I'm confused on how to make the API call for it. This is what I have so far ...
var edit = angular.module('edit', ['ui.bootstrap','ngResource'])
.factory('editable', function($resource) {
return {
// get JSON helper function
getJSON : function(apicall) {
if(sessionStorage["EditUserId"] == undefined) {
// get the user id
var userid = sessionStorage["cerestiuserid"];
}
else {
var userid = sessionStorage["EditUserId"];
}
// json we get from server
var apicall = sessionStorage["cerestihome"];
// new api
return $resource(apicall + "/api/profiles/", {Userid:userid}, {'PUT': {method: 'Put'}});
}
};
});
This is the controller ...
//editable object
var object = editable.getJSON();
var edit = new object();
edit.UserName = "Hello World";
edit.$save();
Use restagular to invoke put service.
For example
admin.factory('AdminService', ['Restangular', 'AppConstants', 'AdminRestangular', 'WorkFlowRestangular', 'localStorageService',
function(Restangular, AppConstants, AdminRestangular, WorkFlowRestangular, localStorageService) {
var service = {}
service.updateAgency = function(data) {
return AdminRestangular.all(AppConstants.serviceUrls.agency).doPUT(data);
};
return service
}]);

How do I use this URLRequest script?

I started learning ActionScript 3 a week ago and have stumbled across a huge learning curve. I found this script on the internet:
var _loader:URLLoader;
var _request:URLRequest;
function loadData():void {
_loader = new URLLoader();
_request = new URLRequest("http://www.travoid.com/game/Purchase.php?gid=1");
_request.method = URLRequestMethod.POST;
_loader.addEventListener(Event.COMPLETE, onLoadData);
_loader.addEventListener(IOErrorEvent.IO_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.NETWORK_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.VERIFY_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.DISK_ERROR, onDataFailedToLoad);
_loader.load(_request);
}
function onLoadData(e:Event):void {
trace("onLoadData",e.target.data);
}
function onDataFailedToLoad(e:IOErrorEvent):void {
trace("onDataFailedToLoad:",e.text);
}
This all seems to work and is generating no errors or output, however my issue comes about when I use this next part of code (which I made)
function vpBuy(e:MouseEvent):void{
loadData();
if (e.target.data == "false") {
inf_a.visible = true;
inf_b.visible = true;
inf_c.visible = true;
inf_d.visible = true;
btn_ok.visible = true;
}
}
I get this error:
ReferenceError: Error #1069: Property data not found on
flash.display.SimpleButton and there is no default value. at
travoid_fla::MainTimeline/vpBuy() onLoadData
The part that is probably throwing this is:
if (e.target.data == "false") {
I was hoping e.target.data was what stored the value on the web page (which displays as false) but apparently not. With the code I found on the internet, what stores the information on the web page?
Thanks,
Ethan Webster.
The URLLoader load method is asynchronous, you have to wait the server response before triyng to get the result.
The functions onLoadData and onDataFailedToLoad are there to do that. When the response is well received the function onLoadData is called and you can get the data in e.target.data or _loader.data
The error in your function vpBuy is you try to access the data property on the object that triggered the MouseEvent (maybe a Button) and that object don't have such variable.
Try the following:
/** button clicked load the datas from the server **/
function vpBuy(e:MouseEvent):void
{
// load the datas from the server
loadData();
}
/** the datas are well loaded i can access them **/
function onLoadData(e:Event):void
{
trace("onLoadData",e.target.data);
if( e.target.data == "false" )
{
inf_a.visible = true;
inf_b.visible = true;
inf_c.visible = true;
inf_d.visible = true;
btn_ok.visible = true;
}
}
Hope this could help you :)

Assign a request timeout for adobe air URLRequest and get the response without using eventListner

Below code is used to read a file in the disk and upload as 1MB chunks to a php server via adobe AIR application. It iterates the do/while loop till the end of the file and uploading part is handled by function getConnection. The servers returns an XML as the response. With the eventListeners currently it goes to function onRequestComplete when it receives the response. Because of that issue current code exits the loop when it receives the response from the server. Is there any way that I can get the response of the request send by the function getConnection when it calling inside function startUpload ? also how can I define the request timeout for this single requests?
private function startUpload():void {
var localFilePath:String =localFilesToUpload[currentUploadedVideoIndex].file.nativePath;
var filePathArray = localFilePath.split("/");
var uploadedFile:File = new File(localFilePath);
var fileSize:Number = uploadedFile.size;
var fileName:String = filePathArray[filePathArray.length-1];
var fileId:String = "10";
var index:Number=0;
var chunkSize:Number=1024*1204;
var size:Number=chunkSize;
var serverPath:String = "http://myurl/rests";
//encode username and password
var userName:String="myusername";
var password:String="mypassword";
var encoder:Base64Encoder = new Base64Encoder();
encoder.insertNewLines=false;
encoder.encode(userName+":"+password);
var urlLoader:URLLoader=new URLLoader();
urlLoader.dataFormat=URLLoaderDataFormat.TEXT;
urlLoader.addEventListener(Event.COMPLETE,onRequestComplete);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR,onResponceFail);
var urlRequest:URLRequest = new URLRequest(serverPath);
urlRequest.method=URLRequestMethod.POST;
do{
//if this is true file must be uploaded as a chunk
if(fileSize>chunkSize){
if((index+size)>fileSize){ // if true this is the final chunk of the file.
size = fileSize-index; // take the remaining size of the file
}
}else{
size = fileSize; //this file can be uploaded directly
}
//read the bytes from the file in the specified location
var buff:ByteArray = new ByteArray();
var uploadedFileStream:FileStream = new FileStream();
uploadedFileStream.open(uploadedFile,FileMode.READ);
uploadedFileStream.readBytes(buff);
uploadedFileStream.close();
urlRequest.data=buff;
//add the http headers to the file part and send
this.getConnection(urlRequest, urlLoader,encoder.toString(),fileSize,index,chunkSize,fileName,fileId,buff);
}while(index<fileSize)
}
}
private function getConnection(urlRequest:URLRequest, urlLoader:URLLoader ,authString:String, fileSize:Number, index:Number, chunkSize:Number, fileName:String, fileId:String, requestBody:ByteArray):void{
//creates the relevent HTTP heaaders and assigned to parameters
try{
urlRequest.requestHeaders = parameters;
urlLoader.load(urlRequest);
}catch(error:Error){
Alert.show(error.message);
}
}
private function onRequestComplete(event:Event):String{
var loader:URLLoader = URLLoader(event.target);
Alert.show(loader.data,"Result");
}
private function onResponceFail(event:FaultEvent):void{
Alert.show(event.message.toString(),"Fault");
}
In order to achieve this, you should check if operation is finished in onRequestComplete instead:
Pseudo code just to get you going:
function startUpload()
{
// prepare big file
...
// then start the uploading
sendNextChunk();
}
function sendNextChunk()
{
// grab the next chunk
...
// and send it
getConnection(...);
}
function onRequestComplete()
{
// is there more chunks ?
if (...more chunks?)
sendNextChunk();
else
trace("All chunks uploaded");
}
Hope that helps,
Adnan