Check user entered text aginst xml - actionscript-3

i am trying to check user entered text in a dynamic text box against a XML file, so if the user enters the it traces jackpot and the array no its stored at is stored, this is what i have so far but cant get it to work, anyone have any ideas ? all that is on the stage is a dynamic text box called userID and a button called idBtn to check, thanks
EDIT : i changed it around, what i cant get to work is the comparison between the user entered text and what is in the xml, the if loop always runs through even when true,
import flash.display.MovieClip;
import flash.text.TextField;
var xmlloader:URLLoader = new URLLoader();
var xmlreq:URLRequest = new URLRequest("users.xml");
xmlloader.load(xmlreq);
xmlloader.addEventListener(Event.COMPLETE, convertdata);
function convertdata(event:Event)
{
var xmlinfo:XML = new XML(event.target.data);
var postedlist:XMLList = xmlinfo.user;
var totallist:Number = postedlist.length();
trace(totallist);
for(var i:int=0 ; i < totallist ; i++)
{
trace("id_no[i] before lowered " + xmlinfo.user.id_no[i])
xmlinfo.user.id_no[i] = xmlinfo.user.id_no[i].toLowerCase();
trace("id_no[i] after lowered " + xmlinfo.user.id_no[i])
}
function checkUser(event:MouseEvent):void
{
for(var i:int=0 ; i < totallist ; i++)
{
var enteredID:String = userId.text
enteredID = enteredID.toLowerCase();
trace("before if "+ xmlinfo.user.id_no[i] +" and " + enteredID)
if (xmlinfo.user.id_no[i]==enteredID)
{
trace("jackpot");
}
else
{
trace("nope");
}
}
}
idBtn.addEventListener(MouseEvent.MOUSE_UP, checkUser);
}
my xml is just
<root>
<user>
<id_no>a</id_no>
<username>Jane Doe</username>
<banned>-1</banned>
<equip_out>-1</equip_out>
</user>
</root>
my output is :
1
id_no[i] before lowered a
id_no[i] after lowered a
with noting entered in text-box
before if a and
nope
with q entered in text-box
before if a and q
nope
with a entered in text box (this is what i want to return the jackpot trace at)
before if a and a
nope

I think you're comparing an XML with a String.
Try this:
if (xmlinfo.user.id_no[i].toString()==enteredID)
{
trace("jackpot");
}
else
{
trace("nope");
}

Related

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();
}

How to check if a textbox contains a specific string or not?

I have an input textfield named "textbox" and a button named "submit".I also have two text messages "mc_error" and "form_submitted" which are not visible from the beginning. Upon clicking the button, I want it to check if the textfield contains "#" in it. I have tried the below code that uses indexOf but it always returns the value -1 and therefore upon execution always "mc_error" becomes visible.
var str:String = textbox.text;
submit.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
mc_error.visible = false;
form_submitted.visible = false;
function fl_MouseClickHandler(event:MouseEvent):void
{
var index:int = str.indexOf("#");
if(index == -1)
{
mc_error.visible=true;
}
else
{
form_submitted.visible=true;
}
}
Would be grateful if got some immediate answers as i need it working in 2 days.Thanks
Because you set variable before user inputs anything there and it is always "". Just don't use that variable (or read it in the function body as shown below) and it will be fine.
function fl_MouseClickHandler(event:MouseEvent):void
{
var str:String = textbox.text;
var index:int = str.indexOf("#");
if(index == -1)
{
mc_error.visible=true;
}
else
{
form_submitted.visible=true;
}
}

Read a string in AS3

I have a question regarding to my project which is how to read a string in AS3.
Actually, I have an text file named test.txt. For instance:
It consists of:
Sun,Mon,Tue,Wed,Thu,Fri,Sat
and then I want to put all of them into an array and then a string to show them in the dynamic text Box called text_txt:
var myTextLoader:URLLoader = new URLLoader();
myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(e:Event):void
{
var days:Array = e.target.data.split(/\n/);
var str:String;
stage.addEventListener(MouseEvent.CLICK, arrayToString);
function arrayToString(e:MouseEvent):void
{
for (var i=0; i<days.length; i++)
{
str = days.join("");
text_txt.text = str + "\n" + ";"; //it does not work here
}
}
}
myTextLoader.load(new URLRequest("test.txt"));
BUT IT DOES NOT show them in different line and then put a ";" at the end of each line !
I can make it to show them in different line, but I need to put them in different line in txt file and also I still do not get the ";" at the end of each line unless put it in the next file also at the end of each line.
And then I want to read the string and show an object from my library based on each word or line. for example:
//I do not know how to write it or do we have a function to read a string and devide it to the words after each space or line
if (str.string="sun"){
show(obj01);
}
if (str.string="mon"){
show(obj02);
}
I hope I can get the answer for this question.
Please inform me if you can not get the concept of the last part. I will try to explain it more until you can help me.
Thanks in advance
you must enable multiline ability for your TextField (if did not)
adobe As3 DOC :
join() Converts the elements in an array to strings, inserts the
specified separator between the elements, concatenates them, and
returns the resulting string. A nested array is always separated by a
comma (,), not by the separator passed to the join() method.
so str = days.join(""); converts the Array to a single string, and as your demand ( parameter passed to join is empty "") there is no any thing between fetched lines. and text_txt.text = str + "\n" + ";"; only put a new line at the end of the text once.
var myTextLoader:URLLoader = new URLLoader();
var days:Array;
myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(e:Event):void
{
days = e.target.data.split(/\n/);
var str:String;
stage.addEventListener(MouseEvent.CLICK, arrayToString);
}
myTextLoader.load(new URLRequest("test.txt"));
function arrayToString(e:MouseEvent):void
{
text_txt.multiline = true;
text_txt.wordWrap = true;
text_txt.autoSize = TextFieldAutoSize.LEFT;
text_txt.text = days.join("\n");
}
also i moved arrayToString out of onLoaded
for second Question: to checking existance of a word, its better using indexOf("word") instead comparing it with "==" operator, because of invisible characters like "\r" or "\n".
if (str.indexOf("sun") >= 0){
show(obj01);
}
if (str.indexOf("mon") >= 0){
show(obj02);
}
Answer to the first part:
for (var i=0; i<days.length; i++)
{
str = days[i];
text_txt.text += str + ";" + "\n";
}
I hope I understand you correctly..
I wrote from memory, sorry for typos if there are...
For the second part, add a switch-case
switch(str) {
case "sun":
Show(??);
break;
.
.
.
}

AS3 load variables from a txt file which has && formatting

I'm trying to load a txt file of variables into my AS3 project. The problem I have though seems to be down to the fact that the txt file (which is pre formatted and cannot be changed) is formatted using double amphersands... e.g.
&name=mark&
&address=here&
&tel=12345&
I'm using the following code to load the txt file
myLoader.addEventListener(Event.COMPLETE, onLoaded, false, 0, true);
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlRqSend = new URLRequest(addressToTxt.txt);
public function onLoaded(e:Event):void {
trace(myLoader.data);
}
Using URLLoaderDataFormat.VARIABLES generates the following error:
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
If I use URLLoaderDataFormat.TEXT I can load the data successfully but I'm not able (or don't know how to) access the variables.
Would anyone have any ideas or work arounds to this please.
Thanks,
Mark
I had that kind of problem some time ago.
I suggest you to load first as a text, remove those line breaks, the extra amphersands and parse manually:
var textVariables:String;
var objectVariables:Object = new Object();
...
myLoader.addEventListener(Event.COMPLETE, onLoaded, false, 0, true);
myLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlRqSend = new URLRequest(addressToTxt.txt);
public function onLoaded(e:Event):void {
textVariables = myLoader.data;
textVariables = textVariables.split("\n").join("").split("\r").join(""); // removing line breaks
textVariables = textVariables.split("&&").join("&"); // removing extra amphersands
var params:Array = textVariables.split('&');
for(var i:int=0, index=-1; i < params.length; i++)
{
var keyValuePair:String = params[i];
if((index = keyValuePair.indexOf("=")) > 0)
{
var key:String = keyValuePair.substring(0,index);
var value:String = keyValuePair.substring(index+1);
objectVariables[key] = value;
trace("[", key ,"] = ", value);
}
}
}
I wrote that code directly here, I don't have any AS3 editor here, so, maybe you'll find errors.
If you have data in String and it has a structure just like you wrote, you can do a workaround:
dataInString = dataInString.split("\n").join("").split("\r").join(""); // removing EOL
dataInString = dataInString.slice(0,-1); // removing last "&"
dataInString = dataInString.slice(0,1); // removing first "&"
var array:Array = dataInString.split("&&");
var myVariables:Object = new Object();
for each(var item:String in array) {
var pair:Array = item.split("=");
myVariables[pair[0]] = pair[1];
}
That should make you an object with proper variables.

Restrict input to a specified language

I use a TextInput component of Flex 4.5 to enter some text in English. I use the restrict attribute to ... restrict the keyboard input to characters a-zA-Z only. The problem is that if i copy/paste a word in another language, i can then paste it into the TextInput component. Is there a way to avoid that? If no, how can i validate the input against a specified language?
I found out that the unicode set of Chinese+ language symbols is \u4E00 to \u9FFF. So i write the following:
var chRE:RegExp = new RegExp("[\u4E00-\u9FFF]", "g");
if (inputTI.text.match(chRE)) {
trace("chinese");
}
else {
trace("other");
}
But if i type in the TextInput the word 'hello' then it validates...What is the error?
Since i cannot (my fault? or a bug?) use unicode range with RegExp, i wrote the following function to check if a word is in Chinese and that's it.
private function isChinese(word:String):Boolean
{
var wlength:int = word.length;
for (var i:int = 0; i < wlength; i++) {
var charCode:Number = word.charCodeAt(i);
if (charCode <= 0x4E00 || charCode >= 0x9FFF) {
return false;
}
}
return true;
}
The String.match() method returns an array which will always test to true, even if it's empty (see docs here: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/String.html#match%28%29)
Use the RegExp.test() method instead to see if it matches:
// Check your character ranges:
//var chRE:RegExp = new RegExp("[\u4E00-\u9FFF]", "g"); // \u9FFF is unrecognised and iscausing issues.
var chRE:RegExp = new RegExp("[\u4E00]+", "g"); // This works.
if (chRE.test(inputTI.text)) {
trace("chinese");
}
else {
trace("other");
}
You'll need to check the character ranges too - I couldn't get it to match with \u9FFF in the regex.