I am devloping an editor with spell check feature in Flex + AIR using Sqlite as an embedded database.
In database I have a table with the words. The table contains lacs of words. I have written the code to search for the word in table. I have used the sync method for all this. This pauses my application while searching.
I would like to use async method to stop application pause.
The code for Search word is as follows:
public function searchInDictionary(word:String):Boolean
{
if(word == "")
return true;
connection= new SQLConnection();
var query:SQLStatement = new SQLStatement();
query.sqlConnection = connection;
query.text = 'SELECT id FROM tbl_'+ CommonLanguageCode +' WHERE word LIKE "'+word+'"';
try
{
connection.open( dbfile,SQLMode.READ );
}
catch(ex:Error)
{}
if(!connection.connected)
connection.open( dbfile );
query.execute();
var result:SQLResult = query.getResult();
if( result.data == null )
{
return false;
}
else
{
var numRows:uint = result.data.length;
var id:String;
if(numRows>0)
return true;
return false;
}
return false;
}
If this function returns false(word not found) then i have to call the function to to red underline that word.
Please suggest me if I am going wrong. As I am using Sync method & it takes some milli seconds to search a word. & if I am wrting a paragraph then it makes my application sluggish.
Is there any other way I can store the words & search more fastly. If yes then please et me know.
Thanks in advance.
You'll need to reorganize your code a bit so that you call your function that does the red underline when the results come back instead of returning a Boolean from the method.
public function searchInDictionary(word:String):void
{
// Don't bother searching if no word was passed in
if(word == "") return;
// Open db connection asynchronously
var connection:SQLConnection = new SQLConnection();
connection.openAsync(dbfile, SQLMode.READ);
// Create statement
var statement:SQLStatement = new SQLStatement();
statement.sqlConnection = connection;
statement.text = 'SELECT id '
+ 'FROM tbl_'+ CommonLanguageCode +' '
+ 'WHERE word LIKE "' + word + '"';
// Add event listener
statement.addEventListener(SQLEvent.RESULT, function(event:SQLEvent):void{
var result:SQLResult = event.target.getResult();
if(result.data.length == 0) {
// ... call method to red underline word in text ...
}
});
// Execute statement
statement.execute();
}
Related
Please bear with me as I'm rather new to this.
I'm trying to iterate through a recordset using DataReader object, and do something at each iteration, but it doesn't seem to be getting passed the first record. I essentially want to look at each record and then assign a specific image to a specified location based on the data in a column in the recordset.
I'm using Visual Studio 2019 and using OleDataReader to read Access table. I've got the command object working properly, just can't seem to get passed the first record.
this is the method definition in my class
//Giving string variable names to the virtual paths of the images
private string whitePallet = "~/images/White.jpg";
private string redPallet = "~/images/Red.jpg";
private string bluePallet = "~/images/Blue.jpg";
private string blackPallet = "~/images/Black.jpg";
private string greenPallet = "~/images/Green.jpg";
private string racetrack = "~/images/Racetrack.jpeg";
public string Racetrack { get => racetrack; set => racetrack = value; }
public string OpenConnection(string connectString, String selectString)
{
using (OleDbConnection cn = new OleDbConnection(connectString))
{
cn.Open(); //Open the connection.
OleDbCommand cmd = new OleDbCommand(selectString, cn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string pallet;
if (reader["Status"].ToString() == "Blocked Location")
{
pallet = blackPallet;
return pallet;
}
if (reader["Status"].ToString() == "AP Purge")
{
pallet = redPallet;
return pallet;
}
if (reader["Status"].ToString() == "Open")
{
pallet = whitePallet;
return pallet;
}
if (reader["Status"].ToString() == "Order Complete")
{
pallet = greenPallet;
return pallet;
}
if (reader["Status"].ToString() == "Pallet Full")
{
pallet = bluePallet;
return pallet;
}
}
//Close the reader and the related connection.
reader.Close();
return null;
}
}
this is the instantiation of the class/method
'''
Definitions defs = new Definitions();
Image imgRacetrack = Image.FromFile(Server.MapPath(defs.Racetrack));
//Creating image panel to draw upon using w/h of racetrack image
Image img = new Bitmap(imgRacetrack.Width, imgRacetrack.Height);
using (Graphics gr = Graphics.FromImage(img))
{
//Background image
gr.DrawImage(imgRacetrack, new Point(0, 0));
//Defining the points on the left side:
Point p1 = new Point(125, 50);
Image imgPallet = Image.FromFile(Server.MapPath(defs.OpenConnection(connectString,selectString)));
gr.DrawImage(imgPallet, p1);
Point p2 = new Point(125, 100);
Image imgPallet2 = enter code hereImage.FromFile(Server.MapPath(defs.OpenConnection(connectString, selectString)));
gr.DrawImage(imgPallet2, p2);
}
I'm expecting to iterate through each record and then place the image with the correct color into the correct position, but it's only giving the results to each point/location based on the very first record only. What's wrong with my logic??
You declare pallet string pallet; then have several if statements in which you return pallet;.
First, you want to return a string, but you're doing
pallet = blackPallet; // pallet will not be a string.
pallet = "blackPallet"; // pallet will be a string.
Second, when you say return..., you leave the method; you don't continue after that, you are saying you are done - return this value and stop.
So you need to read the value from each row and store them, then return the collection of values. Then you can loop through the collection and plug in each value as needed.
That's one way. I didn't study what you have in complete detail so there might be a better way. Hope that's enough for now.
I tried to select multiple lines using selenium automation like below.
this.selectLineInTable(Locator.LOCATOR_LIST, "name", t1.getName()).
this.selectLineInTable(Locator.LOCATOR_LIST,"name",t2.getName()));
but its not working. Can anyone help me how to solve this issue?
try something like below:
Actions act = new Actions(driver);
act.keyDown(Keys.CONTROL).moveToElement(driver.findElement(By.xpath("first element to select"))).click().build().perform();
act.moveToElement(driver.findElement(By.xpath("second element to select"))).click().release().build().perform();
Actions act = new Actions(driver);
String m1 = this.selectLineInTable(Constant.LOCATOR_LIST_MOFULL, "name",psv.getName());//1st element
String m2=this.selectLineInTable(Constant.LOCATOR_LIST_MOFULL, "name",psTest.getName());// 2nd element
act.keyDown(Keys.CONTROL).moveToElement(driver.findElement(By.name(m1))).click().build().perform();
act.moveToElement(driver.findElement(By.name(m2))).click().release().build().perform();
protected String selectLineInTable(String scLocatorBody, String key, String value) throws Exception {
String scLocatorLine = this.findLineInTable(scLocatorBody, key, value);
if (scLocatorLine == null) {
// No line for key / value
this.logError("The row [" + key + "=" + value + "] does not exist", null);
} else {
// Click on the line
StringBuffer lRow = new StringBuffer();
lRow.append(scLocatorLine).append("col[fieldName=").append(key).append("]/");
this.clickOnElement(lRow.toString());
sleep(500);
}
return scLocatorLine;
}
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"name","selector":"scLocator=//ListGrid[ID=\"ssr_grid\"]/body/row[0]/"}
I'm building a Flash AIR application that will be a kiosk installation for accepting visitor comments, and then displaying previous visitor's comments back. This needs to be highly graphically styled, so returning the query/SQL results back into a datagrid isn't a suitable end result. The database is simply the local one created by the Flash application since this is a non-networked kiosk installation.
I've seen many comments talking about datagrids, and I've seen code that will display all the query results back as a single string - but I'm hoping to populate (without clicking on a datagrid) a series of dynamic text fields with the results of my query.
The Insert statement is working great:
function addData(): void
{
insertStmt = new SQLStatement();
insertStmt.sqlConnection = conn;
var sqlAdd: String = "";
sqlAdd += "INSERT INTO comments (firstName, lastName, homeTown, comment, avatarID, tagID) ";
sqlAdd += "VALUES ('" + inputFirstName + "', ";
sqlAdd += "'" + inputLastName + "', ";
sqlAdd += "'" + inputHomeTown + "', ";
sqlAdd += "'" + inputComment + "', ";
sqlAdd += inputAvatarID + ", ";
sqlAdd += inputTagID;
sqlAdd += ")";
insertStmt.text = sqlAdd;
insertStmt.addEventListener(SQLEvent.RESULT, insertResult);
insertStmt.addEventListener(SQLErrorEvent.ERROR, insertError);
insertStmt.execute();
}
I'm also able to get my Select statement to work when I click a button:
function getData(event: MouseEvent): void
{
selectStmt = new SQLStatement();
selectStmt.sqlConnection = conn;
var sql: String = "SELECT firstName, lastName, comment FROM comments";
selectStmt.text = sql;
selectStmt.addEventListener(SQLEvent.RESULT, selectResult);
selectStmt.addEventListener(SQLEvent.RESULT, traceResult);
selectStmt.addEventListener(SQLErrorEvent.ERROR, selectError);
selectStmt.execute();
}
Where I'm getting completely stuck is extracting this information and either giving each thing a variable name so I can use it later, or at least put the data into a multidimensional array so I reference data with a syntax like
array[1][firstName]
This is the code I've got isn't quite working:
function selectResult(event: SQLEvent): void
{
selectStmt.removeEventListener(SQLEvent.RESULT, selectResult);
selectStmt.removeEventListener(SQLErrorEvent.ERROR, selectError);
var result: SQLResult = selectStmt.getResult();
// The results grid works so I know I'm getting the data back
resultsGrid.dataProvider = new DataProvider(result.data);
var resultsArray01: Array;
var newResultsRow: Array;
if (result != null)
{
// Iterate through each entry
for each(var entry: Object in result.data)
{
// Trace entry -- this works when I test it
trace(entry.firstName,entry.comment, entry.homeTown);
// Add entries to array -- where I get into troubles
// I get TypeError: Error #1009: Cannot access a property or method of a null object reference.
newResultsRow.push(entry.firstName, entry.comment, entry.homeTown);
resultsArray01.push(newResultsRow);
}
}
}
Sorry if this is longwinded. I'm pretty new to AS3, but fairly good with SQL. Any help is appreciated.
You don't need a multidimensional Array for this. You don't even need to create a loop. You can just store the Results as is.
//Declare variable to store the data
var resultsArray:Array;
var result: SQLResult = selectStmt.getResult();
if (result != null)
{
resultsArray = result.data;
}
Then you can just do this...
trace(resultsArray[1]["firstName"]);
Although it is better to use dot syntax
trace(resultsArray[1].firstName);
I have function init, which runs on the creationComplete of the application. The init calls get_login_share_object function, in which objects are created, which are null.
Now my problem is that, I get a null object reference error on the Alert in "init()". How can I avoid that. Is it possible that I can have a check to see, if the objects are null the program should just skip reading the objects.
private function init():void
{
var stored_credentials:Object = get_login_share_object();
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
}
private function get_login_share_object():Object
{
//create or retrieve the current shared object
var so:SharedObject = SharedObject.getLocal("loginData","/");
var dataToLoad:ByteArray = so.data.ws_creds;
if(!dataToLoad)
return null;
//read in our key
var aes_key:String = ServerConfig.aes_key;
var key:ByteArray = new ByteArray();
key = Base64.decodeToByteArray(aes_key);
//read in our encryptedText
var encryptedBytes:ByteArray = new ByteArray();
dataToLoad.readBytes(encryptedBytes);
//decrypt using 256b AES encryption
var aes:ICipher = Crypto.getCipher("simple-aes128-ctr", key, Crypto.getPad("pkcs5"));
aes.decrypt(encryptedBytes);
encryptedBytes.position = 0;
var obj:Object = new Object();
obj.alias = encryptedBytes.readUTF();
obj.password = encryptedBytes.readUTF();
obj.check_remember = encryptedBytes.readUTF();
return obj;
}
You could check for the null like this:
var stored_credentials:Object = get_login_share_object();
if (stored_credentials)
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
else
trace('No Shared Object');
You should find out why those values are null and fix that first. Generally speaking, if you are expecting a value, it should not be null.
If it really is expected that some of those values are null then yes, you can check them first in two ways:
if(value != null) value.doSomething();
or
try{
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
}
catch(e:Error){
// do something else here if the statement under the try failed.
// most likely log the error message and see what it is
}
Your problem is here:
var dataToLoad:ByteArray = so.data.ws_creds;
if(!dataToLoad)
return null;
If there isn't any data to load, you're returning a null. So when you try and access the returned object's properties later, you'll get the null object reference error because you're referencing a null object. :)
There are a couple of easy solutions to this. You can check if the return value is null before you try to reference any properties like so:
if (stored_credentials != null) {
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
}
Or you can stop returning a null from your get_login_share_object function. What you return instead is totally up to you, just make sure it returns an object with all the properties you're referencing.
I am calling a web Method from javascript. The web method returns an array of customers from the northwind database. The example I am working from is here: Calling Web Services with ASP.NET AJAX
I dont know how to write this javascript method: CreateCustomersTable
This would create the html table to display the data being returned. Any help would be appreciated.
My javascript
function GetCustomerByCountry() {
var country = $get("txtCountry").value;
AjaxWebService.GetCustomersByCountry(country, OnWSRequestComplete, OnWSRequestFailed);
}
function OnWSRequestComplete(results) {
if (results != null) {
CreateCustomersTable(results);
//GetMap(results);
}
}
function CreateCustomersTable(result) {
alert(result);
if (document.all) //Filter for IE DOM since other browsers are limited
{
// How do I do this?
}
}
else {
$get("divOutput").innerHTML = "RSS only available in IE5+"; }
}
My web Method
[WebMethod]
public Customer[] GetCustomersByCountry(string country)
{
NorthwindDALTableAdapters.CustomersTableAdapter adap =
new NorthwindDALTableAdapters.CustomersTableAdapter();
NorthwindDAL.CustomersDataTable dt = adap.GetCustomersByCountry(country);
if (dt.Rows.Count <= 0)
{
return null;
}
Customer[] customers = new Customer[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
NorthwindDAL.CustomersRow row = (NorthwindDAL.CustomersRow)dt.Rows[i];
customers[i] = new Customer();
customers[i].CustomerId = row.CustomerID;
customers[i].Name = row.ContactName;
}
return customers;
}
Try to look what is the result variable value in debug mode. If the structure seems the structure that i'm imagining, something like this could work:
function CreateCustomersTable(result) {
var str = '<table>';
str += '<tr><th>Id</th><th>Name</th></tr>';
for ( var i=0; i< result.length; i++){
str += '<tr><td>' + result[i].CustomerId + '</td><td>' + result[i].Name + '</td></tr>';
}
str += '</table>';
return str;
}
And then You can do somethig like this:
var existingDiv = document.getElementById('Id of an existing Div');
existingDiv.innerHTML = CreateCustomersTable(result);
I wish this help you.
Something like this, assuming you have JSON returned in the "result" value. The "container" is a div with id of "container". I'm cloning nodes to save memory, but also if you wanted to assign some base classes to the "base" elements.
var table = document.createElement('table');
var baseRow = document.createElement('tr');
var baseCell = document.createElement('td');
var container = document.getElementById('container');
for(var i = 0; i < results.length; i++){
//Create a new row
var myRow = baseRow.cloneNode(false);
//Create a new cell, you could loop this for multiple cells
var myCell = baseCell.cloneNode(false);
myCell.innerHTML = result.value;
//Append new cell
myRow.appendChild(myCell);
//Append new row
table.appendChild(myRow);
}
container.appendChild(table);
You should pass the array as JSON or XML instead of just the toString() value of it (unless that offcourse is returns either JSON oR XML). Note that JSOn is better for javascript since it is a javascript native format.
Also the person who told you that browser other then IE can not do DOM manipulation should propably have done horrible things to him/her.
If your format is JSON you can just for-loop them and create the elements and print them. (once you figured out what format your service returns we can help you better.)