HttpService Error #2096 - actionscript-3

I've written a Httpservice to get data from server but when I tried to run the service it got me the error (#2096). Below is my code:
package
{
import flash.net.URLRequestHeader;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.messaging.AbstractConsumer;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
public class JSONDataLoader
{
private var httpService:HTTPService;
private var errVO:ErrVO;
[Bindable]
public var errAC:ArrayCollection = new ArrayCollection();
[Bindable]
public var errStr:String;
public function JSONDataLoader(url:String)
{
httpService = new HTTPService();
httpService.url = url;
httpService.method = "POST";
httpService.contentType = "application/json";
var headerParams:Object = new Object();
headerParams["Host"] = "192.168.11.59:3333";
headerParams["Content-Length"] = 347;
httpService.headers = headerParams;
var parameters:Object = new Object();
parameters["FromDate"] = "01-01-2013 18:30";
parameters["Location"] = "String content";
parameters["LocationId"] = 2147483647;
parameters["ReportId"] = 9223372036854775807;
parameters["ReportName"] = "String content";
parameters["Team"] = "17,22,30,1,40,53,55,69,70,73,77";
parameters["TeamId"] = 2147483647;
parameters["ToDate"] = "01-01-2013 18:30";
httpService.send(parameters);
httpService.addEventListener(ResultEvent.RESULT, resultHandler);
httpService.addEventListener(FaultEvent.FAULT, faultHandler);
}
private function resultHandler(event:ResultEvent):void
{
var rawData:String = String(event.result);
var obj:Object = JSON.parse(rawData);
Alert.show("Data: " + rawData);
}
private function faultHandler(event:FaultEvent):void
{
errStr = event.fault.faultString+" "+event.message;
Alert.show("Error!!!" + errStr);
}
}
}
What i am doing worng here. Is there problem with my headers or request body.
Please help me, as i am stuck with this from past 2 days.
Here is the full error message...
Error!!!Error #2096 (mx.messaging.messages::HTTPRequestMessage)#0
body = (Object)#1
FromDate = "01-01-2013 18:30"
Location = "String content"
LocationId = 2147483647
ReportId = 9223372036854776000
ReportName = "String content"
Team = "17,22,30,1,40,53,55,69,70,73,77"
TeamId = 2147483647
ToDate = "01-01-2013 18:30"
clientId = (null)
contentType = "application/json"
destination = "DefaultHTTP"
headers = (Object)#2
DSEndpoint = "direct_http_channel"
httpHeaders = (Object)#3
Content-Length = 347
Host = "192.168.11.59:3333"
messageId = "C130487E-0EBA-375E-E71D-A580EFE175EE"
method = "POST"
recordHeaders = false
timestamp = 0
timeToLive = 0
url = "my url"

You may need to check if the content of the parameters contains illegal characters like '<' or '>'. Replacing them with '& l t ;' or '& g t ;' (without spaces) may solve the problem.
Errors may occur when HttpService sends or receives strings including these two marks.
Using URLRequest would be a better choice since it would be free from this problem.

Related

Mongo Connection Exception handling

I am trying to make some exception handling on the following code. Basically I want a MessageBox.Show("ErrorMessage") to show if the connection to the server can't be established.
public List<MongoDBModel> MongoDBModel
{
get
{
string connectionString = "mongodb://127.0.0.1";
var mongoClient = new MongoClient(connectionString);
var mongoServer = mongoClient.GetServer();
var databaseName = "TestPointToPoint";
var db = mongoServer.GetDatabase(databaseName);
var mongodb = db.GetCollection<MongoDBModel>("OCS.MeterEntity");
var mongodbQuery = Query<MongoDBModel>.EQ(x => x._id, MeterUID);
List<MongoDBModel> Cursor = mongodb.FindAs<MongoDBModel>(mongodbQuery).ToList();
return Cursor;
}
}
I have already tryed with
if (mongoServer.State == MongoServerState.Connected)
{
var databaseName = "TestPointToPoint";
var db = mongoServer.GetDatabase(databaseName);
var mongodb = db.GetCollection<MongoDBModel>("OCS.MeterEntity");
var mongodbQuery = Query<MongoDBModel>.EQ(x => x._id, MeterUID);
List<MongoDBModel> Cursor = mongodb.FindAs<MongoDBModel>(mongodbQuery).ToList();
return Cursor;
}
else
{
MessageBox.Show("Connection to MongoDB lost");
return null;
}
but that did not work since the state of the mongoServer first changes to connected in the query.
What should I do to make it work?
I feel stupid now :P
Using a simple try-catch worked.
public List<MongoDBModel> MongoDBModel
{
get
{
string connectionString = "mongodb://127.0.0.1";
var mongoClient = new MongoClient(connectionString);
var mongoServer = mongoClient.GetServer();
var databaseName = "TestPointToPoint";
var db = mongoServer.GetDatabase(databaseName);
var mongodb = db.GetCollection<MongoDBModel>("OCS.MeterEntity");
try
{
var mongodbQuery = Query<MongoDBModel>.EQ(x => x._id, MeterUID);
List<MongoDBModel> Cursor = mongodb.FindAs<MongoDBModel>(mongodbQuery).ToList();
return Cursor;
}
catch (MongoConnectionException e)
{
MessageBox.Show(e.Message);
return null;
}
}
}
Sorry for your troubles.

upload file to box api v2 using as3

I'm trying to upload file to box using v2. The only result i get is the error while uploading. I'm able to authenticate, get the auth token but not able to upload, I have given the code which i'm using. If i'm wrong anyway just correct me. Any help will be appreciated!!
public function upload(argFile:flash.filesystem.File):void{
argFile.addEventListener(Event.COMPLETE,
function onComplete(event:Event):void
{
trace("complete:"+event.toString());
}
);
argFile.addEventListener(IOErrorEvent.IO_ERROR,
function onIOError(event:IOErrorEvent):void
{
trace("Error:"+event.toString());
}
);
var url:String = "https://api.box.com/2.0/files/data";
// Setup the custom header
var customHeader:String = "BoxAuth api_key=" + api_key + "&auth_token=" + auth_token;
var headers:Array = [
new URLRequestHeader("Authorization", customHeader)
];
// create the url-vars
var urlVars:URLVariables = new URLVariables();
urlVars.filename1 = '#'+argFile.name;
urlVars.folder_id = "0";
// create the url-reqeust
var request:URLRequest = new URLRequest();
request.contentType = "application/octet-stream";
request.method = URLRequestMethod.POST;
// set ther url
request.url = url;
// set the header
request.requestHeaders = headers;
// set the vars
request.data = urlVars;
try {
argFile.upload(request);
} catch (e:Error)
{
trace(e.toString(), "Error (catch all)");
}
}

how to test WCF JSON services - unit test

How can I test WCF JSON services. I want to create something like unit tests for this services. Is there any tutorial for something like this? I would b most interested to write the JSON object myself like
{somedata:abc,foo:boo}
Here is a link that might get you started.
http://www.entechsolutions.com/wcf-web-service-for-soap-json-and-xml-with-unit-tests
"-create a dynamic class that matches JSON datastructure
-Serialize it to JSON
-Send json to web service
-Deserilize response to a dynamic object
-Make sure that response has value that I expected"
POST
[Test]
public void Add_WhenMethodPost_And_ValidApiKey_ReturnsSum()
{
var addRequest = new
{
Value1 = 5,
Value2 = 11,
ApiKey = Const.ValidApiKey
};
var url = string.Format("{0}/json/add", Const.WebServiceUrl);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
var jsSerializer = new JavaScriptSerializer();
var jsonAddRequest = jsSerializer.Serialize(addRequest);
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(jsonAddRequest);
writer.Close();
var httpWebResponse = (HttpWebResponse)request.GetResponse();
string jsonString;
using (var sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
jsonString = sr.ReadToEnd();
}
var jsonAddResponse = jsSerializer.Deserialize<dynamic>(jsonString);
Assert.AreEqual(16, jsonAddResponse["Sum"]);
}
GET
[Test]
public void Add_WhenMethodGet_And_ValidApiKey_ReturnsSum()
{
var url = string.Format("{0}/json/add?value1={1}&value2={2}&apiKey={3}", Const.WebServiceUrl, 5, 11,
Const.ValidApiKey);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
string jsonString;
var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
jsonString = sr.ReadToEnd();
}
var jsSerializer = new JavaScriptSerializer();
var jsonAddResponse = jsSerializer.Deserialize<dynamic>(jsonString);
Assert.AreEqual(16, jsonAddResponse["Sum"]);
}

Multipass login to assistly.com with as3crypto

I'm trying to automatically login my users into assistly.com with their multipass login as described here: http://dev.assistly.com/docs/portal/multipass
I have tried to convert their code examples ( https://github.com/assistly/multipass-examples) to Actionscript using as3crypto, obviously without success.
Here's what I have:
package
{
import com.adobe.crypto.SHA1;
import com.adobe.serialization.json.JSON;
import com.hurlant.crypto.*
import com.hurlant.util.Base64;
import flash.utils.ByteArray;
public class AssistlySingleSignOn
{
protected static var API_SITE_KEY:String = "YOUR SITE KEY"
protected static var MULTIPASS_KEY:String = "YOUR MULTIPASS API KEY"
public function AssistlySingleSignOn()
{
}
public static function generateMultipass(uid:String, username:String, email:String):String
{
var o:Object = {};
o.uid = uid;
o.expires = "2012-12-29T10:25:28-08:00";
o.customer_email = email;
o.customer_name = username;
var salted:String = API_SITE_KEY + MULTIPASS_KEY;
var hash:String = SHA1.hash(salted);
var saltedHash:String = hash.substr(0, 16);
var iv:String = "OpenSSL for Ruby";
var ivByteArray:ByteArray = new ByteArray();
ivByteArray.writeUTFBytes(iv);
var key:ByteArray = new ByteArray();
key.writeUTFBytes(saltedHash);
key.position = 0;
var json:String = JSON.encode(o);
var jsonByteArray:ByteArray = new ByteArray();
jsonByteArray.writeUTFBytes(json);
var padding:IPad = new PKCS5(16);
ivByteArray.position = 0;
key.position = 0;
var cyphered:CBCMode = Crypto.getCipher("aes-128-cbc", key, padding) as CBCMode;
jsonByteArray.position = 0;
cyphered.IV = ivByteArray;
cyphered.encrypt(jsonByteArray);
jsonByteArray.position = 0;
var base64:String = Base64.encode(jsonByteArray.readUTFBytes(jsonByteArray.length));
/*Convert to a URL safe string by performing the following
Remove any newlines
Remove trailing equal (=) characters
Change any plus (+) characters to dashes (-)
Change any slashes (/) characters to underscores (_)*/
base64 = base64.replace(/\n/g, "");
base64 = base64.replace(/=/g, "");
base64 = base64.replace(/+/g, "-");
base64 = base64.replace(/\//g, "_");
return base64;
}
}
}
I'm assuming that I'm doing something wrong with the IV stuff or the padding, because I don't quite understand it ;-)
You might want to use a different crypto class, or modify the as3crypto one. I know there are inconsistencies in the SHA1 function vs. the PHP sha1 function. See this:
sha1 hash from as3crypto differs from the one made with PHP
This could be making your values invalid. My recommendation would be to trace out all your data as it's being calculated and run it against the same things in PHP or another of the examples in github. See where the data diverges. I'm betting it's going to be issues relating to AS3Crypto.

HTTPService: What is its send method doing?

I've got a JSON string:
query = {"action":"do","password":"c","name":"s"}
When using HTTPService's send method:
_service = new HTTPService();
_service.url = "http://localhost:8080";
_service.method = "POST";
_service.contentType = "application/json";
_service.resultFormat = "text";
_service.useProxy = false;
_service.makeObjectsBindable = true;
_service.addEventListener(FaultEvent.FAULT,faultRX);
_service.addEventListener(ResultEvent.RESULT,resultRX);
_service.showBusyCursor = true;
var _request:Object = new Object();
_request.query = query;
_service.request = _request;
_service.send();
I don't know what I am doing wrong but on my HTTP server I get:
{["object","Object"]}
Any clues please?
Thanks
You are declaring an object of an object.
Try:
_service.request = query;
_service.send();
you get
{["object","Object"]}
because of this
var _request:Object = new Object();
_request.query = query;
_service.request = _request;
do this
var jsonOBJ:Object = {};
jsonOBJ.action = "do";
jsonOBJ.password = "c";
jsonOBJ.name = "s";
var _service:HTTPService = new HTTPService();
_service.url = "http://localhost:8080";
_service.method = "POST";
_service.contentType = "application/json";
_service.resultFormat = "text";
_service.useProxy = false;
_service.makeObjectsBindable = true;
_service.addEventListener(FaultEvent.FAULT,faultRX);
_service.addEventListener(ResultEvent.RESULT,resultRX);
_service.showBusyCursor = true;
_service.send( JSON.encode( jsonOBJ ) );// encode the json object with AS3Corelib
Don't forget top JSON decode the string on the server side.