How to separate strings in actionscripts 3 - actionscript-3

I need code sample to separate a string, i'm new developer please write sample code. thanks.
This is string:
username#gmail.com|3.705|18|0.90
I need to separate each part between "|":
username#gmail.com
3.705
18
0.90

var Sample_String: String = "username#gmail.com|3.705|18|0.90"
var VALUE1: String = Sample_String.split("|")[0];
var VALUE2: String = Sample_String.split("|")[1];
var VALUE3: String = Sample_String.split("|")[2];
var VALUE4: String = Sample_String.split("|")[3];
trace(VALUE1);
trace(VALUE2);
trace(VALUE3);
trace(VALUE4);
//---------------------------------------------------------------------------
Output:
username#gmail.com
3.705
18
0.90

You can use split function once to create an Array of split String as below:
private var myString:String = "username#gmail.com|3.705|18|0.90";
var splitStringArray: Array = myString.split("|");
for each (var splitString:String in splitStringArray)
{
trace(splitString);
}

Related

Converting XDocument to JSON with XHTML node using JSON.NET

Is there a simpler way to do this? I am sincerely concerned that this LinqPad doodle might be too verbose:
var xml = #"
<root attr1=""attribute one"" attr2=""attribute two"">
<title>this is the root</title>
<xhtml>
<div id=""wrapper"">
<p style=""first""><em>hello</em> world!</p>
</div>
</xhtml>
</root>
";
var xDoc = XDocument.Parse(xml);
Func<XNode, string> getXhtml = node =>
{
var s = string.Empty;
StringWriter wr = null;
try
{
wr = new StringWriter();
using(var jsonWriter = new JsonTextWriter(wr))
{
jsonWriter.StringEscapeHandling = StringEscapeHandling.EscapeHtml;
new JsonSerializer().Serialize(jsonWriter, node.ToString());
}
s = wr.ToString();
}
finally
{
if(wr != null) wr.Dispose();
}
return s;
};
var escaped_xhtml = getXhtml(xDoc.Root.Element("xhtml").Element("div"));
escaped_xhtml.Dump("escaped xhtml");
var placeholder = "#rx-xhtml";
xDoc.Root.Element("xhtml").Value = placeholder;
var json = JsonConvert.SerializeXNode(xDoc.Root, Newtonsoft.Json.Formatting.Indented);
var json_final =json
.Replace(string.Format(#"""{0}""",placeholder), escaped_xhtml);
json_final.Dump("json with escaped xhtml");
var jDoc = JObject.Parse(json_final);
escaped_xhtml = (string)jDoc["root"]["xhtml"];
escaped_xhtml.Dump("decoded xhtml");
It may be reasonable to assume that JSON.NET already has, say, the equivalent of my getXhtml() routine. JSON.NET has so many great features I am concerned that I might be missing out.
Is this what you want? It produces the same result for json_final:
// Parse the XML
var xDoc = XDocument.Parse(xml);
// Extract the "div" element.
var div = xDoc.Root.Element("xhtml").Element("div");
div.Remove();
// Convert the remainder to a JObject.
var jDoc = JObject.FromObject(xDoc.Root, JsonSerializer.CreateDefault(new JsonSerializerSettings { Converters = new[] { new XmlNodeConverter() } }));
// Store the Div element as a string literal.
jDoc["root"]["xhtml"] = div.ToString();
// Stringify the JSON using StringEscapeHandling = StringEscapeHandling.EscapeHtml
var json_final = JsonConvert.SerializeObject(jDoc, new JsonSerializerSettings { Formatting = Formatting.Indented, StringEscapeHandling = StringEscapeHandling.EscapeHtml });
It eliminates the string replacement and the getXhtml delegate. Note that StringEscapeHandling applies during the final conversion to string, not to intermediate conversions to Joken (where string literals are not escaped).
Even simpler still, replace the <Div> element with a corresponding XML string literal before converting to JSON:
// Parse the XML
var xDoc = XDocument.Parse(xml);
// Replace the DIV element with its XML string literal value
var div = xDoc.Root.Element("xhtml").Element("div");
div.Remove();
xDoc.Root.Element("xhtml").Value = div.ToString();
// Convert to JSON using StringEscapeHandling = StringEscapeHandling.EscapeHtml
var json_final = JsonConvert.SerializeObject(xDoc, new JsonSerializerSettings { Converters = new[] { new XmlNodeConverter() }, Formatting = Formatting.Indented, StringEscapeHandling = StringEscapeHandling.EscapeHtml });

How to get nested deep property value from JSON where key is in a variable?

I want to bind my ng-model with JSON object nested key where my key is in a variable.
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
Here I want to get value 5 from data JSON object.
I found the solution to convert "course.sections.chapter_index" to array notation like course['sections']['chapter_index'] this. but don't know how to extract value from data now
<script type="text/javascript">
var BRACKET_REGEXP = /^(.*)((?:\s*\[\s*\d+\s*\]\s*)|(?:\s*\[\s*"(?:[^"\\]|\\.)*"\s*\]\s*)|(?:\s*\[\s*'(?:[^'\\]|\\.)*'\s*\]\s*))(.*)$/;
var APOS_REGEXP = /'/g;
var DOT_REGEXP = /\./g;
var FUNC_REGEXP = /(\([^)]*\))?$/;
var preEval = function (path) {
var m = BRACKET_REGEXP.exec(path);
if (m) {
return (m[1] ? preEval(m[1]) : m[1]) + m[2] + (m[3] ? preEval(m[3]) : m[3]);
} else {
path = path.replace(APOS_REGEXP, '\\\'');
var parts = path.split(DOT_REGEXP);
var preparsed = [parts.shift()]; // first item must be var notation, thus skip
angular.forEach(parts, function (part) {
preparsed.push(part.replace(FUNC_REGEXP, '\']$1'));
});
return preparsed.join('[\'');
}
};
var data = {"course":{"sections":{"chapter_index":5}}};
var obj = preEval('course.sections.chapter_index');
console.log(obj);
</script>
Hope this also help others. I am near to close the solution,but don't know how can I get nested value from JSON.
This may be a good solution too
getDeepnestedValue(object: any, keys: string[]) {
keys.forEach((key: string) => {
object = object[key];
});
return object;
}
var jsonObject = {"address": {"line": {"line1": "","line2": ""}}};
var modelName = "address.line.line1";
var result = getDescendantPropValue(jsonObject, modelName);
function getDescendantPropValue(obj, modelName) {
console.log("modelName " + modelName);
var arr = modelName.split(".");
var val = obj;
for (var i = 0; i < arr.length; i++) {
val = val[arr[i]];
}
console.log("Val values final : " + JSON.stringify(val));
return val;
}
You are trying to combine 'dot notation' and 'bracket notation' to access properties in an object, which is generally not a good idea.
Source: "The Secret Life of Objects"
Here is an alternative.
var stringInput = 'course.sections.chapter_index'
var splitInput = stringInput.split(".")
data[splitInput[1]]][splitInput[2]][splitInput[3]] //5
//OR: Note that if you can construct the right string, you can also do this:
eval("data[splitInput[1]]][splitInput[2]][splitInput[3]]")
Essentially, if you use eval on a string, it'll evaluate a statement.
Now you just need to create the right string! You could use the above method, or tweak your current implementation and simply go
eval("data.course.sections.chapter_index") //5
Source MDN Eval docs.
var data = {
"course": {
"sections": {
"chapter_index": 5
}
}
};
var key = "course['sections']['chapter_index']";
var keys = key.replace(/'|]/g, '').split('[');
for (var i = 0; i < keys.length; i++) {
data = data[keys[i]];
}
console.log(data);
The simplest possible solution that will do what you want:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']";
with (data) {
var value = eval(key);
}
console.log(value);
//=> 5
Note that you should make sure key comes from a trusted source since it is eval'd.
Using with or eval is considered dangerous, and for a good reason, but this may be one of a few its legitimate use cases.
If you don't want to use eval you can do a one liner reduce:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
key.split(/"|'|\]|\.|\[/).reduce((s,c)=>c===""?s:s&&s[c], data)

Store User Control JSON object in DB

I have a JSON object that I want to store in a database. The JSON is generated by an User Control.
The JSON object:
var datatosend = {
isit: isitArray,
ec: ecArray,
bc: bcArray,
bb: bbArray,
io: ioArray
};
What is the best way to record a JSON object in the database using GeneXus?
Edit:
var isitArray = getObjectsRequest('isit', isitID);
var ecArray = getObjectsRequest('ec', ecID);
var bcArray = getObjectsRequest('bc', bcID);
var bbArray = getObjectsRequest('bb', bbID);
var ioArray = getObjectsRequest('io', ioID);
function getObjectsRequest(type, compId){
var array = [];
for (var i = 0; i<compId; i++) {
var comp = mainLayer.find('#'+ type + i)[0];
array.push({
xposition: comp.getX(),
yposition: comp.getY(),
titleid: comp.getId(),
description: comp.find('.textDescription')[0].getText(),
leftrelationsids: comp.leftCRelations,
rightrelationsids: comp.rightCRelations
});
};
return array;
}
var datatosend = {
isit: isitArray,
ec: ecArray,
bc: bcArray,
bb: bbArray,
io: ioArray
};
You can use a LongVarChar attribute to store the JSON, but you'll need to convert the JavaScript object to String first.

How to use AES-CBC 128-bit encryption in AS3?

I would like to encrypt a string in AS3 with AES-CBC 128-bit. How to do it?
Use AS3Crypto https://code.google.com/p/as3crypto/, here is the snippet:
//notice that decrKey and decrIV length must be 16 chars long! ex: 1234567890123456
private function encrypt(input:String,decrKey:String,decrIV:String):String
{
var inputBA:ByteArray=Hex.toArray(Hex.fromString(input));
var key:ByteArray = Hex.toArray(Hex.fromString(decrKey));
var pad:IPad = new NullPad();
var aes:ICipher = Crypto.getCipher("aes-cbc", key, pad);
var ivmode:IVMode = aes as IVMode;
ivmode.IV = Hex.toArray(Hex.fromString(decrIV));
aes.encrypt(inputBA);
return Base64.encodeByteArray( inputBA); //if not use Base64 encode, data would be just byteArray
}
Notice: this code is fully compatible ex: with PHP (or C#), here is decryption for it in PHP
//notice that $key and $iv length must be 16 chars long! ex: 1234567890123456
function decrypt($data,$key,$iv)
{
$decr= mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($data), MCRYPT_MODE_CBC, $iv);
return $decr;
}

Reverse engineering - Flash app

I have that code:
private function handleFlashVarsXmlLoaded(event:Event) : void
{
var secondsplit:String = null;
var item:Array = null;
var string:* = XML(String(event.target.data));
var notsplited:* = string.vars_CDATA; //what is .vars_CDATA?
var splitted:* = notsplitted.split("&");
var datacontainer:Object = {};
var index:Number = 0;
item = secondsplit.split("=");
datacontainer[item[0]] = item[1];
this.parseFlashVars(datacontainer); // go next
return;
}
That function is loaded when URLLoader is loaded.
I think that this function parse a XML file to string(fe. param1=arg1&param2=arg2), then split it by "&" and then by "=" and add data to datacontainer by
datacontainer["param1"] = "arg1"
But how should the XML file look like and what is string.vars_CDATA
I think, vars_CDATA is just a name of XML field, becourse variable named "string" is contains whole XML. So var "notsplited" contains a String-typed data of this field (I think so, becourse of the line "var splitted:* = notsplitted.split("&");", which splits String to Array).