Sending Json Form from Flash AS3 - json

i am having one form accepting json post in Asp.net which i need to call from Flash As3...
i am using below code to do that. I have seen some post in which they say its working fine.
But i am encountering below Error
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Here is my code.
var messages:Array = new Array ();
messages.push({"From":fromemailTxt.text,"To": ToemailTxt.text,"Body": BodyText.text,"Subject":SubjectText.text});
var JsonObj:String = JSON.encode(messages);
trace(JsonObj);
var variables:URLVariables=new URLVariables(JsonObj);
RequestURL= srvStringURL;
var JSONLoader:URLLoader = new URLLoader();
JSONLoader.dataFormat=URLLoaderDataFormat.TEXT;
JSONLoader.addEventListener(IOErrorEvent.IO_ERROR, GetBookmarkURLError, false, 0, true);
JSONLoader.addEventListener(Event.COMPLETE, parseBookmarkURLResult, false, 0, true);
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var request:URLRequest = new URLRequest(RequestURL);
request.requestHeaders.push(hdr);
request.data=variables;
request.method = URLRequestMethod.POST;
try
{
JSONLoader.load(request);
}
catch (error:ArgumentError)
{
trace("An ArgumentError has occurred."+error.errorID.toString());
}
catch (error:SecurityError)
{
trace("A SecurityError has occurred.");
}
catch (error:Error)
{
trace("Unable to load requested document.");
}
Anybody have any idea on this??
Thanks

The error is, because you are passing incorrect string to URLVariables constructor. Do not use URLVariables. Instead pass data as string: request.data=JsonObj;

Below is the code I am using to consume REST Web service and pass json parameter to service it shows. Error #2032: Stream Error.
Andy idea what is going wrong
var ldr:URLLoader = new URLLoader();
ldr.dataFormat = URLLoaderDataFormat.TEXT;
var strData:String = "{\"gparam\": [ {\"productid\": \"" + productId + "\"},{\"message\": \"" + mesage + "\"},{\"googleappid\": \"" + googleappid + "\"},{\"senderid\": \"" + senderid + "\"},{\"appname\": \"" + appName + "\"},{\"userid\": \"" + userId + "\"},{\"receiverid\": \"" + receiverId + "\"} ]}";
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var req:URLRequest = new URLRequest("http://localhost/AndroidGCM/GCMNotification.svc/SendGCM");
req.requestHeaders.push(hdr);
req.method = URLRequestMethod.POST;
req.data = strData;
trace("data: " + req.data);
ldr.addEventListener(Event.COMPLETE,onComplete);
ldr.addEventListener(IOErrorEvent.IO_ERROR , onError);
ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR ,onSecurityErr);
ldr.load(req);
function onComplete(e:Event):void
{
trace("LOAD COMPLETE: " + ldr.data);
TextField(parMC.getChildByName("txtCheck")).appendText("\n LOAD COMPLETE: " + ldr.data);
}
function onSecurityErr(e:SecurityErrorEvent):void
{
trace("error: " + e.text );
}
function onError(e:IOErrorEvent):void
{
trace("error: " + e.toString());
}

Related

Extract data from JSON within Lambda so it's not undefined

Looking for advice / second opinion. I'm trying to pass JSON via HTTP API (api gateway) > Lambda. I'm receiving the data (pic of Cloudwatch), getting undefined when trying to extract values. The file is being written to S3, but undefined.
I included Lambda code, picture of Cloudwatch logs. I'm about there :) . Newbie here...
Logs
Lambda Code
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
exports.handler = async (event, context, callback) => {
var bucketName = process.env.bucketName;
var folder = process.env.folder;
var filename = getFileName();
console.log("Filename:" + filename);
var raw = JSON.stringify(event.body);
console.log("raw after stringify:" + raw);
var results = JSON.parse(raw);
console.log("results:" + results);
let firstname = results.firstName;
console.log("firstName:" + firstname);
let lastname = results.lastName;
console.log("lastName:" + lastname);
let message = results.Message;
console.log("Message:" + message);
var content = message + "," + firstname + "," + lastname;
console.log("content:" + content);
var keyName = getKeyName(folder, filename);
var params = { Bucket: bucketName, Key: keyName, Body: content };
s3.putObject(params, function (err, data) {
if (err)
console.log(err)
else
console.log("Successfully saved object to: " + bucketName + "/" + keyName);
});
function getKeyName(folder, filename) {
return folder + '/' + filename;
}
function getFileName() {
var _uuid = uuidv4();
var _date = Date.now();
return _uuid + "-" + _date;
}
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
var html = '<html><head><title>Prayer received result</title></head>' +
'<body><h1>Your Prayer has been received!</h1></body></html>';
//callback(null, res); - use this when using proxy model
callback(null, html);
};
Made the following changes.
//var raw = JSON.stringify(event.body);
//console.log("raw after stringify:" + raw);
var results = JSON.parse(event.body);
console.log("results:" + results);
Hope this helps others. I'm newer as of this post to Lambda, JSON.

Firebase "MD5" & BloddyCrytpo's dont match

I'm trying to do a check to see if the user has a local file. If the user does, I get bloodycrypto to make a md5 out of it. Then I compare the two values. One from the firebase file's metadata and the other from the byte array of the file digested. They never match. Does Firebase do something different when trying to generate the md5 of a file I upload?
private function handleMetaSuccess(e:StorageReferenceEvent):void
{
trace("Meta succes for reference:" + this.name);
storageMetaData = e.metadata;
trace("reading file.");
fileBA = new ByteArray();
var fs:FileStream = new FileStream();
fs.open(Definitions.CACHE_DIRECTORY.resolvePath(name + ".jpg"), FileMode.READ)
fs.readBytes(fileBA);
fs.close();
var byteHash:String = MD5.hashBytes(fileBA)
trace("Local hash = " + byteHash); //93b885adfe0da089cdf634904fd59f71
trace("Network hash = " + storageMetaData.md5Hash); //bo7XPotC+T5wmAcpagnXBw==
if (byteHash != storageMetaData.md5Hash)
{
trace("Not equal. Getting file."); //Always happens
getFile();
}
else
{
loadFile();
}
}
Upon closer inspetion (thanks to Organis) firebase doesn't return a proper MD5. What is it? In my storage consol I don't see an md5 property, so is this autogenerated? The files were uploaded through my rest API based off phantom's guide.
Update: Following Organis' comment about the way Firebase handle's MD5s
var byteHash:ByteArray = new ByteArray();
byteHash.writeUTFBytes(MD5.hashBytes(fileBA));
var byteHashWithLength:ByteArray = new ByteArray();
byteHashWithLength.writeUTF(MD5.hashBytes(fileBA));
trace("Bytehash with length = " + Base64.encode(byteHashWithLength)); //ACAyMTMzYTdmYjczYTEzZDQ3ZDkzMTEyY2I1OWQyYTBmMg==
trace("Plain = " + Base64.encode(byteHash)); //OTNiODg1YWRmZTBkYTA4OWNkZjYzNDkwNGZkNTlmNzE=
trace("Storage md5 = " + storageMetaData.md5Hash); //UsoNl5sL1+aLiAhTOTBXyQ==
Trying to take the md5 I get and turn it into base64 results in consistent mismatching results. Is there an argument I am missing or applying incorrectly when I try to decode everything?
...So I would do something like
var storageHash:String = Base64.decode(storageMetaData.md5Hash).toString();
to follow your example right?
Try this code below to get your storageMetaData.md5Hash correctly decoded from Base64 :
Let me know result of trace("storage hash : " + storageHash); to check if you're getting an (expected) sequence of 32 hex values.
private function handleMetaSuccess(e:StorageReferenceEvent):void
{
trace("Meta succes for reference:" + this.name);
storageMetaData = e.metadata;
trace("reading file.");
fileBA = new ByteArray();
var fs:FileStream = new FileStream();
fs.open(Definitions.CACHE_DIRECTORY.resolvePath(name + ".jpg"), FileMode.READ)
fs.readBytes(fileBA);
fs.close();
var byteHash:String = MD5.hashBytes(fileBA); //Local hash
var ba_storageHash:ByteArray = new ByteArray();
ba_storageHash = Base64.decode(storageMetaData.md5Hash); //update ByteArray
var storageHash:String = bytesToHexString(ba_storageHash); //Hex values of bytes shown as String
trace("Network hash : " + storageMetaData.md5Hash); //bo7XPotC+T5wmAcpagnXBw==
trace("Local hash : " + byteHash); //93b885adfe0da089cdf634904fd59f71
trace("storage hash : " + storageHash); //what is result??
if (byteHash != storageHash)
{
trace("Not equal. Getting file."); //Always happens
getFile();
}
else
{
loadFile();
}
}
// # Byte values (Hex) shown as (returned) String type
private function bytesToHexString(input:ByteArray) : String
{
var strOut:String = ""; var strRead:String = "";
input.position = 0;
var intBASize:uint = input.length;
for (var i:int = 0; i < intBASize; i++)
{
strRead = input.readUnsignedByte().toString(16);
if(strRead.length < 2) { strRead = "0" + strRead; } //# do padding
strOut += strRead ;
}
return strOut.toLowerCase(); //strOut.toUpperCase();
}

as3 converting video to byteArray

i am attempting to upload a video to facebook using the as3 api(FacebookMobile.uploadVideo) which accepts a video as either fieleReferance or byteArray. a followed the example # http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118666ade46-7d54.html for creating the byteArray i ma getting a 2058 error when uncompressing the byte array (this may be because i dident compress it but neither did adobe in the example).
if i comment this bit out i am getting an #353 You must select a video file to upload error from Facebook.
Byte Array Code:
public function UICompleteHandler(event:MediaEvent):void
{
trace("Welcome back from the camera");
var media:MediaPromise = event.data;
trace("file info "+media.file.url + " - " + media.relativePath + " - " + media.mediaType);
filePath = media.file.url;
trace("Object encoding is: " + inBytes.objectEncoding + "\n\n" + "order file: \n\n");
readFileIntoByteArray(filePath, inBytes);
trace("length 1: "+inBytes.length);
trace("position 1: "+inBytes.position);
inBytes.position = 0; // reset position to beginning
//inBytes.uncompress(CompressionAlgorithm.DEFLATE);
trace("position 2: "+inBytes.position);
inBytes.position = 0; //reset position to beginning
}
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = new File(fileName);
trace ("file to byte array "+ inFile.url);
trace ("file name var : "+fileName);
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
inStream.close();
}
Handle Upload Code:
public function handleUpload(ev:TouchEvent)
{
trace ("posting to facebook - FileName: "+ accessCamera.fileName + " - FilePath: " + accessCamera.filePath);
var params:Object ={
title:'test upload on FB api',
description:'test upload on FB api',
fileName: accessCamera.fileName,
video: accessCamera.inBytes
}
trace ("params.video = "+params.video);
FacebookMobile.uploadVideo('me/videos', onComplete, params);
}
private function onComplete( result:Object, fail:Object ):void {
trace("facebook post onComplete called" );
if (result)
{
//result.id is id of post that was just posted
trace ("great");
}
else if (fail)
{
trace("post Failed");
trace('code: '+fail.error.code);
trace('message: '+fail.error.message);
trace('type: '+fail.error.type);
}
}
when i trace out the params.video i get a load of random characters. the problem seems to be facebook dosnt appear to see the bytearray(if i even success fully created it) as a video.

FileLoadException when using CompileAssemblyFromDom

I believe this is a permissions issue but I don't know how to solve it, I receive the following exception:
System.IO.FileLoadException: LoadFrom(), LoadFile(), Load(byte[]) and LoadModule() have been disabled by the host.
at System.Reflection.RuntimeAssembly.nLoadImage(Byte[] rawAssembly, Byte[] rawSymbolStore, Evidence evidence, StackCrawlMark& stackMark, Boolean fIntrospection, SecurityContextSource securityContextSource)
at System.Reflection.Assembly.Load(Byte[] rawAssembly, Byte[] rawSymbolStore, Evidence securityEvidence)
at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)
at Microsoft.CSharp.CSharpCodeGenerator.FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea)
at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea)
at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit[] compilationUnits)
When executing the following code:
var engine = this.CreateRazorEngine();
var typeName = "view_" + Guid.NewGuid().ToString("N");
var results = engine.GenerateCode(new StringReader(content), typeName, "", typeName + ".cs");
if (!results.Success) { this.Fail("Unable to compile view '" + this.filename + "'."); return; }
using (var codeProvider = new CSharpCodeProvider()) {
var tempPath = Path.GetTempPath();
var outputFile = Path.Combine(tempPath, Guid.NewGuid().ToString("N") + ".dll");
var compilerParameter = new CompilerParameters(this.references, outputFile, true) { GenerateInMemory = true, CompilerOptions = "/optimize", TempFiles = new TempFileCollection(tempPath) };
var compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameter, results.GeneratedCode);
if (compilerResults.Errors.HasErrors) {
var compileExceptionMessage = string.Join(Environment.NewLine + Environment.NewLine, compilerResults.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning).Select(e => e.FileName + ":" + Environment.NewLine + e.ErrorText).ToArray());
this.Fail(compileExceptionMessage);
return;
}
this.view = Activator.CreateInstance(compilerResults.CompiledAssembly.GetType(typeName, true, false), true) as ViewBase;
}
For clarity the CreateRazorEngine code is:
private RazorTemplateEngine CreateRazorEngine() {
var host = new RazorEngineHost(new CSharpRazorCodeLanguage()) { DefaultBaseClass = typeof(ViewBase).FullName };
foreach(var name in this.usings) { host.NamespaceImports.Add(name); }
return new RazorTemplateEngine(host);
}
Can someone let me know what code and where I need to put it to increase the level of security so that the created assembly has permission enough to load the references it has been given please.

Multipart/form-data Flex HTTPService uploading a file

I am new to Flex and also new to writing a client for a web service.
My question is more about Flex (Flash Builder 4.5) APIs, what APIs to use.
I want to access a web service, and create a Flex / AIRwrapper for it,
which anyone can use.
Here is the spec of webservice.
I have to do a post on POST https://build.phonegap.com/api/v1/apps
content type has to be "multipart/form-data"
JSON bodies of requests are expected to have the name 'data' and will be something like this:
data={"title":"API V1 App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}
include a zip file in the multipart body of your post, with the parameter name 'file'.
I want to make a 'multipart/form-data' Post and send one string and one zip file.
My first question to self was if I send both string + binary data in the body,
how will server understand where string end and where zip file starts?
Then I read how text + binary data can be sent through "multipart/form-data" post request. There has to be some boundaries.
After this I read and example in flex and tried following it.
http://codeio.wordpress.com/2010/04/03/5-minutes-on-adobe-flex-mimic-file-upload-for-in-memory-contents/
but it doesn't seem to be working for me.
public function createNewApp(cb:Function , appFile : File):void
{
var service:HTTPService = new HTTPService();
service.url = ROOT+"apps";
service.showBusyCursor = true;
service.addEventListener(ResultEvent.RESULT, function(e:ResultEvent):void {
//translate JSON
trace(e.result);
var result:String = e.result.toString();
var data:Object = JSON.parse(result);
cb(data.link);
});
service.addEventListener(FaultEvent.FAULT, defaultFaultHandler); //todo : allow user to add his own as well
authAndUploadNewApp(service,appFile);
}
private function authAndUploadNewApp(service:HTTPService,appFile : File):void {
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(username + ":"+password);
service.headers = {Accept:"application/json", Authorization:"Basic " + encoder.toString()};
service.method ="POST";
var boundary:String = UIDUtil.createUID();
service.contentType = "multipart/form-data; boundary=—————————" + boundary;
var stream:FileStream = new FileStream();
stream.open(appFile, FileMode.READ);
var binaryData:ByteArray = new ByteArray();
var fileData : String = new String();
stream.readBytes(binaryData);
stream.close();
fileData = binaryData.readUTFBytes(binaryData.bytesAvailable); // I think this is where I have problem.... how do
//how do i converrt this bytearray/stream of data to string and send it in my post request's body - i guess if this step work rest should work..
var params: String = new String();
var content:String = "—————————" + boundary + "nr";
content += 'Content-Disposition: form-data; name="data";' + '{"title":"ELS test app 2","package":"com.elsapp.captivate","version":"12.3.09","create_method":"file"}' + "nr";
content += "—————————" + boundary + "nr";
content += 'Content-Disposition: form-data; name="file";' + fileData + "nr";
content += "—————————–" + boundary + "–nr";
service.request = content;
service.send();
}