Javascript array when referenced errors with object not found - javascript

I am trying to retrieve the data from a ADO recordset and load it into an array using javascript.
The data seems to be loading in fine ( as the alert shows the correct length) but when i try to reference one of the object values it give the following "Object is no longer valid"
The code is as follows
var adoConn = new ActiveXObject("ADODB.Connection");
var adoRS = new ActiveXObject("ADODB.Recordset");
var db_name = "C:\\HMRC\\xxx.accdb";
var csv = "user_id, date_corrected, tot_corrected \n";
var rec_obj = {};
function get_record()
{
var i = 0 ;
var master_arr = [];
adoConn.Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + db_name);
adoRS.Open("Select * From tot_corr_ent", adoConn, 1, 3);
while (!adoRS.eof)
{
rec_obj["user_id"] = adoRS.Fields("user_id");
rec_obj["date_corrected"] = adoRS.Fields("date_corrected");
rec_obj["tot_ent"] = adoRS.Fields("tot_ent");
master_arr.push(rec_obj);
adoRS.MoveNext;
i++;
}
alert ( "Out of the loop ");
adoRS.close();
adoConn.close();
alert ( "connection closed ");
alert("Final alert: " + master_arr.length);
alert("Final alert 2: " + master_arr[0].user_id); -- **errors at this line**
}
Thanks in advance!

The error you are seeing is likely to be because you are storing a reference to the ADODB Field and not the value. This reference goes out of scope when you closed the connection. You need to copy the value you want from the Field object into your object. I don't know ADODB but it looks like you need to access the Value property of the Field
As #Rajesh said in his comment you are adding n copies of the same reference into master_arr. Change the while loop to:
while (!adoRS.eof) {
var rec_obj = {}
rec_obj["user_id"] = adoRS.Fields("user_id").Value;
rec_obj["date_corrected"] = adoRS.Fields("date_corrected").Value;
rec_obj["tot_ent"] = adoRS.Fields("tot_ent").Value;
master_arr.push(rec_obj);
adoRS.MoveNext;
i++;
}

Related

Why isn't rs.update, updating my access database? Is it copying to another file instead?

I have a form that works on IE that connects to a database. This works great. However, when I fill in the text boxes the data does not get transferred to the database. I have checked the field.value and it always equals what I input. The record set is pointing at the right table, as I have checked the names of the rows as it goes through each iteration. However, the data from the boxes never actually gets updated?
function parkRecordSet(){
var conn = accesDB()
var cmdDI = CreateCommand(conn, "tblPark");
var rsDI = CreateRecordSet(cmdDI);
inputData(rsDI)
UpdateData(conn, rsDI);
}
So this part works well. The input data takes in an array that will be passed into the function below as recordData. I put an alert to see if the values I was getting were correct.
function AddNewDataToRecordSet(rs, recordData){
rs.AddNew();
var myFields = rs.Fields;
var myEnum = new Enumerator(myFields);
var indexRecordData = 0;
var fieldItem;
myEnum.moveFirst();
for ( ; !myEnum.atEnd(); myEnum.moveNext() ){
fieldItem = myEnum.item();
//alert( "Field Name is: " + fieldItem.Name + " Value is: [" + fieldItem.Value + "]" + "Attr=" + fieldItem.Attributes)
if (fieldItem.Attributes & adFldIsNullable) { //bit-wise test
fieldItem.Value = recordData[indexRecordData];
//alert(fieldItem.Value)
indexRecordData = indexRecordData + 1;
} //end of IF
rs.Fields("ParkName") = "In Process"
}
return;
}
function UpdateData(conn, rs) {
conn.BeginTrans();
rs.Update();
conn.CommitTrans();
// Performing the update
rs.Close();
return;
}

Storing functions within arrays

I'm having a issue with something very simple. I am just wondering as to I can store these functions within an array. Check out some of the code below. I am unsure as to if this is correct as to how I am storing these functions. I am unsure as to if these functions should be within a object literal or array.This is not necessarily for a project, just good practice. Thanks!
//declaring a function
function alert_name(){
//declaring variables within a function asking user their name.
var username = prompt("Hey there, what is your name."," ");
//generating user input
var chameleon = "Welcome " + username;
//combinators
//alert("Welcome " + chameleon+ ", This is 'the website");
};
// inserting quotes into a string that is being alerted from the browser.
function otherTHings(){
var single = 'He said \'RUN\' ever so softly.';
//alert(single);
};
//running these functions and actually carry out the operations
//that have actually been declared into code above.
//string operations
function string_opertaions(){
var complete = "Com" + "plete";
//alert(complete);
// using combinators to do the same thing.
var sentance1 = "My name is";
var sentance2 = "someone";
var totalsenatces = sentance1 += sentance2;
//alert(totalsenatces);
};
//Booleans or true false values
function booleanys(){
var lying = false;
var truthful = true;
};
//Arrays very important. very similar to a object literal but different.
//Arrays store information or values or varibales/data.
var rack = [];
rack[0] = alert_name();
rack[1] = otherTHings();
rack[2] = string_opertaions();
rack[3] = booleanys();
//alert_name();
//otherTHings();
//string_opertaions();
//booleanys();
You are invoking the function and storing the result!
var rack = [];
rack[0] = alert_name;
rack[1] = otherTHings;
rack[2] = string_opertaions;
rack[3] = booleanys;

Convert active directory query from VBS to Javascript for the Global Catalog

Can anyone fill in the blanks here.
I have been trying to get a script I could run to query all available users in the Global Catalog for active directory and finally managed it in VBS -looking for any particular username as below:
Const ADS_SECURE_AUTHENTICATION = 1
Set oGC = GetObject("GC:")
For Each child In oGC
Set oEntrprise = child
Exit For
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("AD.txt", True)
' Setup ADO.
Set oConn = CreateObject("ADODB.Connection")
Set oComm = CreateObject("ADODB.Command")
oConn.Provider = "ADsDSOObject"
oConn.Properties("ADSI Flag") = ADS_SECURE_AUTHENTICATION
oConn.Open
oComm.ActiveConnection = oConn
' Set the search command and filter.
objFile.WriteLine(oEntrprise.ADsPath)
oComm.CommandText = "<" & oEntrprise.ADsPath & ">;(&(objectCategory=person)(objectClass=user)(givenName=aaron*));cn,distinguishedName;subTree"
' Execute the query.
Set oRS = oComm.Execute
' Print the results.
oRS.MoveFirst
While Not oRS.EOF
For Each field In oRS.Fields
objFile.WriteLine(field)
Next
objFile.WriteLine("")
oRS.MoveNext
Wend
WScript.Echo "Finished"
Im now trying to convert it to JS but I cannot replicate it.
I cannot find the golden answer for looping through GetObject("GC:"). For each doesnt seem to work like for like in this case. Is anyone aware of how to do this?
So in effect i need the JS equivelant of oEntrprise in the above script.
var oConn = WScript.CreateObject("ADODB.Connection");
var oComm = WScript.CreateObject("ADODB.Command");
var keyname = "samaccountname";
var keyvalue = "aaron";
oConn.Provider = "ADsDSOObject";
oConn.Properties("ADSI Flag") = 1;
oConn.Open;
oComm.ActiveConnection = oConn;
var objRootDSE = GetObject("GC:");
for (var i = 0; i < objRootDSE.length; i++) {
WriteToFile("Moahhh");
var oEntrprise = objRootDSE[i];
oComm.CommandText = "<" + oEntrprise.ADsPath + ">;(&(objectCategory=person)(objectClass=user)(givenName=a*));cn,distinguishedName;subTree";
var oRS = oComm.Execute;
}
function WriteToFile(sText){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FileObject = fso.OpenTextFile("C:\\builds\\LogFile.txt", 8, true,0); // 8=append, true=create if not exist, 0 = ASCII
FileObject.write(sText)
FileObject.close()
}
In JScript you need to use an Enumerator to step over the elements of a collection
var objRootDSE = GetObject('GC:');
for (var childs = new Enumerator(objRootDSE) ; !childs.atEnd(); childs.moveNext()){
var child = childs.item();
WScript.Echo( child.Name );
};
Thanks for the suggested answer - answers the impossible loop I could not solve but I have now found a way to query the Global Catalogue for users directly without a need for the loop:
var aoi = WScript.CreateObject("ADSystemInfo");
var gcBase = aoi.ForestDNSName;
var ado = WScript.CreateObject("ADODB.Connection");
ado.Provider = "ADSDSOObject";
ado.Open;
WriteToFile(aoi.ForestDNSName);
var objectList = ado.Execute("<GC://" + gcBase + ">;(&(objectCategory=person)(objectClass=user)("+keyname+"="+keyvalue+"*));cn,distinguishedName;subTree");
if(!objectList.EOF)
{
WriteToFile(objectList("distinguishedName").value);
}
function WriteToFile(sText){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FileObject = fso.OpenTextFile("C:\\LogFile.txt", 8, true,0); // 8=append, true=create if not exist, 0 = ASCII
FileObject.write(sText)
FileObject.close()
}
Never again.
Whoever finds this I will help Google get here - Global Catalog JavaScript query for Active Directory!

Google javascript - accessing and renaming numeric object names

I imported json data into google scripts with:
var doc = Utilities.jsonParse(txt);
I can access most of the objects like such...
var date = doc.data1.dateTime;
var playerName = doc.data1.playerName;
var playerId = doc.data1.playerID;
var teamNumber = doc.data2.personal.team;
A bunch of objects I need to access have numbers as object names...
doc.data2.personal.team.87397394.otherdata
doc.data2.personal.team.87397395.otherdata
doc.data2.personal.team.87397396.otherdata
doc.data2.personal.team.87397397.otherdata
...but when I try to read the data with...
var teamId = doc.data2.personal.team.87397394;
... I get an error "Missing ; before statement."
I tried this...
var teamId = doc.data2.personal.team[87397394];
... and get "teamId undefined" in the log.
I also tied this with the same result...
var teamId = doc.data2.personal.team[+'6803761'];
I can read in the names as strings very easily with "For In", but can't get to the objects themselves. Every example I've found so far uses the brackets so I'm stumped what to try next.
Thank you!
Brian
UPDATE
I used this per your suggestions to get the object name into a variable and using the variable in brackets. No error but var test remains "undefined"...
for(var propertyName in doc.data2.personal.team) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
Logger.log (propertyNames);
var test = doc.data2.personal.team[propertyName];
}
The log shows the object names, as expected...
87397394
87397395
87397396
87397397
I'm thinking it's a bug in Google's implementation. Here is an example if anyone wants to verify it. test will return undefined...
function myFunction1() {
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = Utilities.jsonParse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
Logger.log (propertyName);
var test = doc.datablock_battle_result.vehicles[propertyName];
}
}
The problem seems to be in the Utitlies.jsonParse. The following works fine
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = JSON.parse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
var vehicle = doc.datablock_battle_result.vehicles[propertyName];
Logger.log('Vehicle id is ' + propertyName);
Logger.log('Vehicle value is ' + JSON.stringify(vehicle));
break;
}

How do I overwrite object properties in an array?

I would like to overwrite a certain allOrders[i] with data, similar to how I create a new one. For some reason I can't figure out what to search on.
I have an array of objects allOrders.
I have an object BusinessCard. I take the form fields, serialize() them, clean up the data with a regex, then push the them into an array.
allOrders.push(new BusinessCard(currentOrder.quantity, currentOrder.FullName, currentOrder.Title, currentOrder.CellNumber, currentOrder.OfficeNumber, currentOrder.FaxNumber, currentOrder.EmailAddress, currentOrder.Address, currentOrder.website, currentOrder.price));
I've tried searching for overwriting existing object properties in an array and the likes and haven't figured out what to do here.
My best guess was allOrders[i].push -- but it seems to me that I have to write a new function to replace each property in the object.
Right now I am using(because using serialize() on the form inputs doesn't help me at all:
allOrders[i].quantity = $('#bcQuantity').val();
allOrders[i].fullname = $('#fullName').val();
allOrders[i].title = $('#Title').val();
allOrders[i].cell = $('#CellNumber').val();
allOrders[i].office = $('#OfficeNumber').val();
allOrders[i].fax = $('#FaxNumber').val();
allOrders[i].email = $('#EmailAddress').val();
allOrders[i].address = $('#Address').val();
allOrders[i].website = $('#website').val();
allOrders[i].price = $('#bcCostBeforeCart').text();
There has to be a smarter way to do this. Thank you.
EDIT:
function getFormData(formId) {
var currentForm = '#' + formId;
var currentPrice = $('#bcCostBeforeCart').text();
var currentFormData = $(currentForm).serialize();
var currentFormDataFinal = currentFormData + '&price=' + currentPrice;
return JSON.parse('{"' + decodeURI(currentFormDataFinal.replace(/\+/g, " ").replace(/&/g, "\",\"").replace(/=/g, "\":\"")) + '"}');
}
MEANING i could be using
currentOrder = getFormData('businessCardForm');
then
allOrders[i] = currentOrder;
Seems odd that you would be updating all items with the selector's you're using, but I would wrap up getting the updated order information then, you can run thru a loop.
Depending on your output, as long as it's outputing the respective properties and values of an order object you could just do:
for(int i =0; i < allOrders.length; i++){
var currentFormId = '' // update this for each iteration.
allOrders[i] = getFormData(currentFormId);
}
allOrders[i] = getUpdatedOrder();
function getUpdatedOrder() {
var order = {};
order.quantity = $('#bcQuantity').val();
order.fullname = $('#fullName').val();
order.title = $('#Title').val();
order.cell = $('#CellNumber').val();
order.office = $('#OfficeNumber').val();
order.fax = $('#FaxNumber').val();
order.email = $('#EmailAddress').val();
order.address = $('#Address').val();
order.website = $('#website').val();
order.price = $('#bcCostBeforeCart').text();
return order;
}

Categories