Firefox addon could not convert to bootstrap - javascript

Below I have the code for xul addon which works expectedly.
i.e. shows username and password input at the browser startup and whenever the topic is http-on-examine-response it validates and write in specified file.
But when I try to convert it to a bootstrapped extension it won't even show the username password input at the browser startup and nothing is showing in the console when I compile and run.
I couldn't figure out the wrong thing after I changed the components... to Cu/Cc/etc.
I referred below links
https://developer.mozilla.org/en/Add-ons/Bootstrapped_extensions
What does paragraph about figuring out XUL elements mean in MDN document: "How to convert an overlay extension to restartless"
https://github.com/Noitidart/l10n/tree/xhtml-xul
Below is my code:
const {Cc, Ci, Cu, components} = require("chrome");
Cu.import('resource://gre/modules/XPCOMUtils.jsm');
function Tdatacounter() {
var Tdatacounter = {
observe: function(subject, topic, data) {
if (topic == "http-on-examine-response") {
var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
if (httpChannel.responseStatusText == "OK")
{
var buffer = httpChannel.URI.spec;
var pw = buffer.search("pub.tdata.com/releasepic");
if (pw > 0)
{
var date = new Date();
var TimeStamp = date.toLocaleString();
var pfum = buffer.search("flag=unmap");
if (pfum > 0 )
{
var flagname = "unmap";
var flagnum = 4;
}
if (flagnum > 0)
{
buffer += "^" + ThisUserName + "^" + ThisComputerName + "^" + TimeStamp + "^" + flagname + "\r\n";
fos.write(buffer, buffer.length);
}
}
}
}
}
};
var nsIEnvironment = Cc["#mozilla.org/process/environment;1"]
.getService(Ci.nsIEnvironment);
var prompts = Cc["#mozilla.org/embedcomp/prompt-service;1"]
.getService(Ci.nsIPromptService);
var usernamelist = ["user1","user2","user3"];
var passlist = ["e%cd1","kowgirl23","bhava1204"];
var ThisUserName = null;
var username = {value: "UserName"}; // default the username to user
var password = {value: "pass"}; // default the password to pass
var check = {value: false}; // default the checkbox to true
var GetUserName = prompts.promptUsernameAndPassword(null, "ProcName", "Enter username and password:", username, password, null, check);
while (GetUserName === true) {
var a = usernamelist.indexOf(username.value);
var b = passlist[a];
if (password.value == b) {
var ThisUserName = username.value;
break;
} else {
var GetUserName = prompts.promptUsernameAndPassword(null, "ProcName", "Enter username and password:", username, password, null, check);
}
}
if (ThisUserName !== null) {
var ThisComputerName = nsIEnvironment.get("ComputerName");
var FileUtils = Cu.import("resource://gre/modules/FileUtils.jsm").FileUtils;
var d = new Date();
var dd = d.getDate();
if (dd < 10)
dd = "0" + dd;
var mm = (d.getMonth()+1);
if (mm < 10)
mm = "0" + mm;
var yyyy = d.getFullYear();
var file = new FileUtils.File( "\\\\STJ\\Proc1\\-\\" + yyyy + "\\" + mm + "\\" + dd );
if (!file.exists()) {
file.create(file.DIRECTORY_TYPE, 0755);
}
var filename = "HM_" + ThisUserName + yyyy + "-" + mm + "-" + dd + ".txt";
file.append(filename);
var fos = Cc["#mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
// PR_WRONLY | PR_CREATE_FILE | PR_APPEND
fos.init(file, 0x02 | 0x08 | 0x10, -1, 0);
var date = new Date();
var TimeStamp = date.toLocaleString();
var StartTime = "LoginTime=" + TimeStamp + " at " + ThisComputerName + "\r\n";
fos.write(StartTime, StartTime.length);
var observerService = Cc["#mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
observerService.addObserver(Tdatacounter, "http-on-examine-response", false);
}}
Tdatacounter.prototype.classID = components.ID('{d4a9bb50-b9b2-11e0-a4dd-0800200c9a66}');
Tdatacounter.prototype.classDescription = 'tdata Counter';
Tdatacounter.prototype.contractID = '#tdata/TdataCounter;1';
var NSGetFactory = XPCOMUtils.generateNSGetFactory([TdataCounter]);

I figured out what I've missed. As a beginner in firefox javascript, I missed to add 'register', 'unregister' functions. What a silly mistake I did? Phew. anyhow I hope this answer will be helpful for the novices like me.
Thank you.

Related

I've got stuck with daterangepicker, Im triying to validate ranges dates, it works but Im inside a loop

This is my situation; the daterangepicker is working, everything is working indeed, but there is a loop I cant find a way to avoid. Each time I choose a date range with invalid date Ive got the alert message but this never stop popping up. In fact, I found that if I hide all the code insideisInvalidDate and I just write a console.log, there is still a loop. Ive tried to take the validaterange function outside but as the variables are locals, the function doesnt work.
This is my .js:
$(document).ready(function () {
idRoom = document.getElementById("room_name").value;
$.ajax({
url: "getData/" + idRoom,
type: "get",
dataType: "json",
success: function (response) {
var today = new Date();
var day =
today.getFullYear() +
"/" +
today.getMonth() +
+1 +
"/" +
today.getDate();
$('input[name="daterange"]').daterangepicker({
opens: "right",
drops: "up",
minDate: day,
maxSpan: {
days: 15,
},
locale: {
format: "YYYY/MM/DD",
},
isInvalidDate: function (date) {
var len = response["data"].length;
for (var i = 0; i < len; i++) {
var Str = response["data"][
i
].reservation_checkout.replace(/-/g, ","); //quitamos 1 dia al checkout para que ese dia este disponible
var newStr = new Date(Str);
newStr.setDate(newStr.getDate() - 1);
var newdate = new Date(newStr);
date[i] = newdate.toISOString().split("T")[0];
}
var dateRanges = []; //obtenemos los datos checking/checkout y los metemos en datepicker
for (var i = 0; i < len; i++) {
dateRanges.push({
start: moment(
response["data"][i].reservation_checking
),
end: moment(date[i]),
});
}
var dateRangesfix = [];
for (var i = 0; i < len; i++) {
var startDatefix = moment(
response["data"][i].reservation_checking
).format("DD-MM-YYYY");
var endDatefix = moment(
response["data"][i].reservation_checkout
).format("DD-MM-YYYY");
dateRangesfix.push(startDatefix, endDatefix);
}
$('input[name="daterange"]').on(
"apply.daterangepicker",
function validateDateRange() {
var txtStartDate = $(
'input[name="daterange"]'
).data("daterangepicker").startDate;
var txtEndDate = $('input[name="daterange"]').data(
"daterangepicker"
).endDate;
var startDate;
var endDate;
var tempDate;
if (txtStartDate == "") return false;
if (txtEndDate == "") return false;
startDate = new Date(txtStartDate);
endDate = new Date(txtEndDate);
for (i = 0; i < 2 * len; i++) {
var temp = dateRangesfix[i].split("-");
tempDate = new Date(
temp[2],
temp[1] - 1,
temp[0]
);
if (
startDate < tempDate &&
endDate > tempDate
) {
alert("Invalid Date Range");
return false;
}
}
}
);
return dateRanges.reduce(function (bool, range) {
return (
bool || (date >= range.start && date <= range.end)
);
}, false);
},
});
},
});
});
$("#button1").click(function (event) {
startDate = $('input[name="daterange"]').data("daterangepicker").startDate;
var d = new Date(startDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
start_Date_fix = year + "-" + month + "-" + day;
document.getElementById("start_Date").value = start_Date_fix;
endDate = $('input[name="daterange"]').data("daterangepicker").endDate;
var d = new Date(endDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
end_Date_fix = year + "-" + month + "-" + day;
document.getElementById("end_Date").value = end_Date_fix;
//calcular numero de noches
var date = $('input[name="daterange"]').val();
var str = date.split("-");
var startDate = str[0];
var startDate_f = startDate.split("/");
var startDate_fo = new Date(
startDate_f[0],
startDate_f[1] - 1,
startDate_f[2]
);
var endDate = str[1];
var endDate_f = endDate.split("/");
var endDate_fo = new Date(endDate_f[0], endDate_f[1] - 1, endDate_f[2]);
var Difference_In_Days = Math.round(
(endDate_fo - startDate_fo) / (1000 * 60 * 60 * 24)
);
var year = startDate_f[0];
var month = startDate_f[1];
var day = startDate_f[2].replace(/\s+/g, "");
var guests = document.getElementById("guests").value;
$.ajax({
url:
"calculatePrice/" +
year +
"/" +
month +
"/" +
day +
"/" +
Difference_In_Days +
"/" +
idRoom +
"/" +
guests,
type: "get",
dataType: "json",
data: {},
success: function (data) {
document.getElementById("total_amount").value = data;
},
});
});
I pasted a full copy but I suppose the problem should be in those lines. As youll see Im an newbie and I hope you understand my poor level of English. I've spent some time reading post but Im not really sure about this.
Thank you so much.
I've solved, Ive just been able to take the function out like this;
$(document).ready(function () {
idRoom = document.getElementById("room_name").value;
$.ajax({
url: "getData/" + idRoom,
type: "get",
dataType: "json",
success: function (response) {
var today = new Date();
var day =
today.getFullYear() +
"/" +
today.getMonth() +
+1 +
"/" +
today.getDate();
$('input[name="daterange"]').daterangepicker({
opens: "right",
drops: "up",
minDate: day,
maxSpan: {
days: 15,
},
locale: {
format: "YYYY/MM/DD",
},
isInvalidDate: function (date) {
var len = response["data"].length;
for (var i = 0; i < len; i++) {
var Str = response["data"][
i
].reservation_checkout.replace(/-/g, ","); //quitamos 1 dia al checkout para que ese dia este disponible
var newStr = new Date(Str);
newStr.setDate(newStr.getDate() - 1);
var newdate = new Date(newStr);
date[i] = newdate.toISOString().split("T")[0];
}
var dateRanges = []; //obtenemos los datos checking/checkout y los metemos en datepicker
for (var i = 0; i < len; i++) {
dateRanges.push({
start: moment(
response["data"][i].reservation_checking
),
end: moment(date[i]),
});
}
return dateRanges.reduce(function (bool, range) {
return (
bool || (date >= range.start && date <= range.end)
);
}, false);
},
});
var len = response["data"].length;
var dateRangesfix = [];
for (var i = 0; i < len; i++) {
var startDatefix = moment(
response["data"][i].reservation_checking
).format("DD-MM-YYYY");
var endDatefix = moment(
response["data"][i].reservation_checkout
).format("DD-MM-YYYY");
dateRangesfix.push(startDatefix, endDatefix);
}
$('input[name="daterange"]').on(
"apply.daterangepicker",
function validateDateRange() {
var txtStartDate = $('input[name="daterange"]').data(
"daterangepicker"
).startDate;
var txtEndDate = $('input[name="daterange"]').data(
"daterangepicker"
).endDate;
var startDate;
var endDate;
var tempDate;
if (txtStartDate == "") return false;
if (txtEndDate == "") return false;
startDate = new Date(txtStartDate);
endDate = new Date(txtEndDate);
for (i = 0; i < 2 * len; i++) {
var temp = dateRangesfix[i].split("-");
tempDate = new Date(temp[2], temp[1] - 1, temp[0]);
if (startDate < tempDate && endDate > tempDate) {
alert("Invalid Date Range");
return false;
}
}
}
);
},
});
});
$("#button1").click(function (event) {
startDate = $('input[name="daterange"]').data("daterangepicker").startDate;
var d = new Date(startDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
start_Date_fix = year + "-" + month + "-" + day;
document.getElementById("start_Date").value = start_Date_fix;
endDate = $('input[name="daterange"]').data("daterangepicker").endDate;
var d = new Date(endDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
end_Date_fix = year + "-" + month + "-" + day;
document.getElementById("end_Date").value = end_Date_fix;
//calcular numero de noches
var date = $('input[name="daterange"]').val();
var str = date.split("-");
var startDate = str[0];
var startDate_f = startDate.split("/");
var startDate_fo = new Date(
startDate_f[0],
startDate_f[1] - 1,
startDate_f[2]
);
var endDate = str[1];
var endDate_f = endDate.split("/");
var endDate_fo = new Date(endDate_f[0], endDate_f[1] - 1, endDate_f[2]);
var Difference_In_Days = Math.round(
(endDate_fo - startDate_fo) / (1000 * 60 * 60 * 24)
);
var year = startDate_f[0];
var month = startDate_f[1];
var day = startDate_f[2].replace(/\s+/g, "");
var guests = document.getElementById("guests").value;
$.ajax({
url:
"calculatePrice/" +
year +
"/" +
month +
"/" +
day +
"/" +
Difference_In_Days +
"/" +
idRoom +
"/" +
guests,
type: "get",
dataType: "json",
data: {},
success: function (data) {
document.getElementById("total_amount").value = data;
},
});
});
I would recommend validating the date ranges server-side with Laravel's Validation
tools and Carbon if formatting is required. Instead of using the GET method on the price calculator route:
$.ajax({
url:
"calculatePrice/" +
year +
"/" +
month +
"/" +
day +
"/" +
Difference_In_Days +
"/" +
idRoom +
"/" +
guests,
You would make a post request and use the Request $request typehint or Request facade to access incoming data and simply return the data from the calculator OR continue to use the GET method and pass the date input as a wildcard/route-parameter to.
If you require front-end validation, I would recommend using a Vue component and a package such as Vuelidate to simplify the process. In my experience, front-end validation is very time-consuming without using Vuelidate. This would be my recommendation, as there are plenty of date-picker Vue components available as well which can be configured to format on the front-end also.
(If by "alert" you meant an actual alert window and not a bootstrap component)
Sidenote: using Alerts to report validation errors is not practical and in my personal opinion, shouldn't be used. Instead, validate server-side and return error messages, check for error messages on the front end, and then display those messages near the input it's for.
It looks like you answered your own issue while I was typing this, so I'll leave it here anyway.

log file not created when date change nodejs

i have problem when i try make log for everytime date change it make new file and stop log when end date , for example
20200709_Chatlog.txt for
2020-07-09 21:56:12:91 - connect null
2020-07-09 21:56:15:952 - a user connected
20200710_Chatlog.txt for
2020-07-10 21:56:12:91 - connect null
2020-07-10 21:56:15:952 - a user connected
but my file is always overwrite in the same file date like this
20200709_Chatlog.txt
2020-07-09 21:56:12:91 - connect null
2020-07-09 21:56:15:952 - a user connected
2020-07-10 21:56:12:91 - connect null
2020-07-10 21:56:15:952 - a user connected
, but everytime i restart the server new file created
my code is
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function logDate(){
var d = new Date();
var yy = addZero(d.getFullYear());
var mm = addZero(d.getMonth() + 1);
var dd = addZero(d.getDate());
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var s = addZero(d.getSeconds());
var ms = addZero(d.getMilliseconds(), 3);
var tanggal = "";
return tanggal = +yy+ "-" +mm+ "-" +dd+ " " +h+ ":" +m+ ":" +s+ ":" +ms + " ";
}
function fileDate(){
var d = new Date();
var yy = addZero(d.getFullYear());
var mm = addZero(d.getMonth() + 1);
var dd = addZero(d.getDate());
var tanggal = "";
return tanggal = +yy+ "" +mm+ "" +dd+ "_";
}
var fs = require('fs');
var util = require('util');
var logFile = fs.createWriteStream(fileDate()+'Chatlog.txt', { flags: 'a' }); // 'w' to truncate
var logStdout = process.stdout;
console.log = function () {
logFile.write(logDate()+" - " + util.format.apply(null, arguments)+ '\n');
logStdout.write(logDate()+" - " + util.format.apply(null, arguments) + '\n');
}
console.error = console.log;
am i do something wrong, please help , and thanks for helping , sorry if my english bad

Google Apps Script Execution API: Script error message: Script function not found:【JavaScript】

I am an absolute beginner of web development.
I would like to implement Google Apps Script Execution API into my project.
I have two questions on Google Apps Script Execution API to ask.
(1) I have no idea how to solve the error below.
Script error message: Script function not found: make_date_array(month)
Although my Google Apps Script has the function 'make_date_array(month)' in it, the error above comes out when I call google apps execution api. So I just don't know what to do.
function send_mail() {
var date = new Date()
date.setDate(new Date().getDate())
date = date.getFullYear() + "-" + zero_padding(date.getMonth() + 1)
runSingleRowQuery(0, date)
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName("Data");
var message = "";
var tmp_message = sheet.getRange(1,1,58 ,2).getValues();
for(var i = 0;i < tmp_message.length ;i++){
message += tmp_message[i][0] + ":" + tmp_message[i][1] + "<br>"
}
MailApp.sendEmail({
to: 'I put my email address here'
subject: 'BigQuery',
htmlBody: message
});
}
function runSingleRowQuery(develop_mode, target_month) {
// Replace this value with the project ID listed in the Google
// Developers Console project.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var queries_sheet = spreadsheet.getSheetByName("Single row queries");
var result_sheet = spreadsheet.getSheetByName("Data");
if(target_month == null){
var target_month = queries_sheet.getRange(1, 2).getValue();
}
make_date_array(target_month);
result_sheet.getRange(1, 2).setValue(queries_sheet.getRange(1, 2).getValue())
for (var i = 2; i <= queries_sheet.getLastRow(); i++) {
var query = queries_sheet.getRange(i, 2).getValue();
if (query_variation(query) != false) {
query = query_variation(query)
Logger.log(queries_sheet.getRange(i, 1).getValue());
Logger.log("# run query: \n " + query);
if (develop_mode != 1) {
Logger.log('\n#####################Run Query#########################');
var request = {
query: query
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
// Check on status of the Query Job.
var sleepTimeMs = 500;
while (!queryResults.jobComplete) {
Utilities.sleep(sleepTimeMs);
sleepTimeMs *= 2;
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId);
}
// Get all the rows of results.
var rows = queryResults.rows;
while (queryResults.pageToken) {
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId, {
pageToken: queryResults.pageToken
});
rows = rows.concat(queryResults.rows);
}
result_sheet.getRange(i, 2).setValue(rows[0].f[0].v);
result_sheet.getRange(i, 1).setValue(queries_sheet.getRange(i, 1).getValue());
result_sheet.getRange(i, 3).setValue(queries_sheet.getRange(i, 3).getValue());
}
}
else {
result_sheet.getRange(i, 1).setValue(queries_sheet.getRange(i, 1).getValue());
result_sheet.getRange(i, 2).setValue(queries_sheet.getRange(i, 2).getFormula());
}
}
}
function make_date_array(month) {
month = month.split('-');
var last_month = {};
var more_last_month = {};
Logger.log((parseFloat(month[0] - 1).toFixed(0)))
if (parseFloat(month[1] - 1).toFixed(0) < 1) {
last_month[0] = (parseFloat(month[0]) - 1).toFixed(0);
last_month[1] = 12;
} else {
last_month[0] = (parseFloat(month[0])).toFixed(0);
last_month[1] = (parseFloat(month[1]) - 1).toFixed(0);
}
if (last_month[1] < 10) {
last_month[1] = '0' + last_month[1];
}
if (parseFloat(last_month[1] - 1).toFixed(0) < 1) {
more_last_month[0] = (parseFloat(last_month[0]) - 1).toFixed(0);
more_last_month[1] = 12;
} else {
more_last_month[0] = (parseFloat(last_month[0])).toFixed(0);
more_last_month[1] = (parseFloat(last_month[1]) - 1).toFixed(0);
}
if (more_last_month[1] < 10) {
more_last_month[1] = '0' + more_last_month[1];
}
date_array['Ym01'] = month[0] + month[1] + '01';
date_array['last_Ym01'] = last_month[0] + last_month[1] + '01';
date_array['more_last_Ym01'] = more_last_month[0] + more_last_month[1] + '01';
date_array['y-m-10_h:s'] = month[0] + '-' + month[1] + '-' + '10 00:00';
date_array['last_y-m-10_h:s'] = last_month[0] + '-' + last_month[1] + '-' + '10 00:00';
date_array['more_last_y-m-10_h:s'] = more_last_month[0] + '-' + more_last_month[1] + '-' + '01 00:00';
date_array['y-m-10'] = month[0] + '-' + month[1] + '-' + '10';
date_array['last_y-m-10'] = last_month[0] + '-' + last_month[1] + '-' + '10';
Logger.log(date_array['last_y-m-10'])
}
(2) Does anyone know how I am supposed to call multiple functions? I used the sample code provided by Google. However, I am not sure if I follow the right way to call several functions.
// Create an execution request object.
var request = {
'function': 'send_mail',
'function': 'runSingleRowQuery(develop_mode, target_month)',
'function': 'make_date_array(month)',
};
If you have had similar problems before, could you please help deal with the two issues above? English is not my first language, so if this post does not make sense to you or need more information, please leave your comments. Any advise would be appreciated. Thanks in advance.
In additional to link in the comment I think this code
if(target_month == null){
var target_month = queries_sheet.getRange(1, 2).getValue();
}
You have to change to (no var)
if(target_month == null){
target_month = queries_sheet.getRange(1, 2).getValue();
}

JavaScript extract continues failing intermittently

I've taken on a new role in the tech support team and tasked to resolve an on going and intermittent issue with one of our nightly data extracts failing.
The extract process sends a data file every night containing a record of transactions completed that day. A scheduled task runs each night, with a second run if the first failed, then sends an email notification based on the status.
The scheduled task opens a CMD file which then runs a JS script command to execute a custom stored procedure on the SQL database.
Each night the file is replaced with a new file and this logic writes the status to file.
The below is the output log information which indicates an invalid call error:
Custom_Extract_Second_Run.js started at Tuesday, 19 January 2016 8:15:00 PM
C:\DataExtract\Custom_Extract_Second_Run.js(341, 4) Microsoft JScript runtime error: Invalid procedure call or argument
Custom_Extract.js started at Wednesday, 20 January 2016 8:03:00 PM
Script causes an exception.
Exception number: 0x5007
Description:'objRs.EOF' is null or not an object
Task ended at Wednesday, 20 January 2016 8:08:13 PM. Total Messages Sent: 0
Custom_Extract_Second_Run.js started at Wednesday, 20 January 2016 8:15:00 PM
Task ended at Wednesday, 20 January 2016 8:20:00 PM. Total Messages Sent: 1
Custom_Extract.js started at Thursday, 21 January 2016 8:03:01 PM
Script causes an exception.
Exception number: 0x5007
Description:'objRs.EOF' is null or not an object
Task ended at Thursday, 21 January 2016 8:07:56 PM. Total Messages Sent: 0
Custom_Extract_Second_Run.js started at Thursday, 21 January 2016 8:15:00 PM
Script causes an exception.
Exception number: 0x3704
Description:Operation is not allowed when the object is closed.
Task ended at Thursday, 21 January 2016 8:19:49 PM. Total Messages Sent: 0
Custom_Extract.js started at Friday, 22 January 2016 8:03:00 PM
C:\DataExtract\Custom_Extract.js(318, 4) Microsoft JScript runtime error: Invalid procedure call or argument
Custom_Extract_Second_Run.js started at Friday, 22 January 2016 8:15:00 PM
C:\DataExtract\Custom_Extract_Second_Run.js(341, 4) Microsoft JScript runtime error: Invalid procedure call or argument
We had to reverse-engineer the scripts used to work out how it actually behaves, however not at a confident level to make changes. The extract logic was developed a long time ago (10 to 12 years ago), therefore likely very old and outdated logic.
Below is the javascript logic used in the extract.
var QUERY_NAME_1 = "Custom_Extract";
var QUERY_NAME_2 = "Custom_Extract_UpdateDate";
var LOG_FILE_NAME = "DataExtract_error.log";
var EXTRACT_FILE_NAME = "Extract";
var DB_SERVER_NAME = "sql6";
var DB_DATABASE_NAME = "database_name";
var DB_DATABASE_USER_NAME = "username";
var DB_DATABASE_PASSWORD = "password";
var DateTimeNow = new Date();
var DATE_VALUE = DateTimeNow.getDate() + "/" + (DateTimeNow.getMonth() + 1) + "/" + DateTimeNow.getFullYear();
var EMAIL_SUBJECT_HEADER = "Email Extract Header - Extract Date - " + DATE_VALUE;
var EMAIL_SUBJECT = EMAIL_SUBJECT_HEADER + " Successful";
var EMAIL_SUBJECT_ERROR = "Unsuccessful - " + EMAIL_SUBJECT_HEADER;
var EmailCount = 0;
var DELIMITER = "|";
var STRING_SQL_FAILED = "SQL Failed";
var strScript = "";
var strMsg = "";
var ARG_REPORT_PATH = "";
var ARG_MAIL_SERVER = "";
var ARG_KEEP_BACKUP_COPIES = 0;
var ARG_EMAIL_FROM = "";
var ARG_EMAIL_TO = "";
function ParseCommandLineParams() {
var cmdArgs = WScript.Arguments;
for (i = 0; i < cmdArgs.length; i++) {
// Get next argument
arg = cmdArgs(i);
// Each argument is in the form a=b. Split the two components
j = arg.search(/=/);
if (j == -1) {
WScript.Echo("Invalid arguments arg = " + arg);
return false;
}
argName = arg.substring(0, j);
argValue = arg.substring(j + 1, arg.length);
switch (argName) {
case "/reportPath":
ARG_REPORT_PATH = argValue;
break;
case "/mailServer":
ARG_MAIL_SERVER = argValue;
break;
case "/keepBackupCopies":
ARG_KEEP_BACKUP_COPIES = parseInt(argValue);
break;
case "/from":
ARG_EMAIL_FROM = argValue;
break;
case "/to":
ARG_EMAIL_TO = argValue;
break;
default:
WScript.Echo("Invalid arguments. Name = '" + argName + "' Value = '" + argValue + "'");
return false;
}
}
return true;
}
function DisplayUsage() {
WScript.Echo("Usage: cscript DataExtract.js");
WScript.Echo(" [/m=<Report path directory where it creates file>]");
WScript.Echo(" [/from=<from-line in email>] [/to=<to-line in email>]");
WScript.Echo(" [/machinename=<Email Server name>] [/databaseConfig=<Database Config Setting file>]");
WScript.Echo(" ");
WScript.Echo(" /m - unc path to mail directory (default: ..\\reports\\)");
WScript.Echo(" /from - from-line in email (default: Tejas Magia <>");
WScript.Echo(" /to - to-line in email (default: Tejas Magia <>");
WScript.Echo(" /machinename - email server name (default: EXCHANGE2 ");
WScript.Echo(" /databaseConfig - DataBase Setup Config (default: ..\\..\\..\\..\\config\\config.txt ");
return;
}
function DisplayParameters() {
WScript.Echo("Parameters:");
WScript.Echo(" ARG_REPORT_PATH=[" + ARG_REPORT_PATH + "]");
WScript.Echo(" ARG_EMAIL_FROM=[" + ARG_EMAIL_FROM + "]");
WScript.Echo(" ARG_EMAIL_TO=[" + ARG_EMAIL_TO + "]");
WScript.Echo(" ARG_MAIL_SERVER=[" + ARG_MAIL_SERVER + "]");
WScript.Echo(" DB_SERVER_NAME=[" + DB_SERVER_NAME + "]");
WScript.Echo(" DB_DATABASE_NAME=[" + DB_DATABASE_NAME + "]");
return;
}
function GetConfigCDO() {
var objConf = WScript.CreateObject("CDO.Configuration");
objFields = objConf.Fields;
objFields.Item("http://schemas.Microsoft.com/cdo/configuration/sendusing") = 2;
objFields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = ARG_MAIL_SERVER;
objFields.Item("http://schemas.Microsoft.com/cdo/configuration/smtpserverport") = 25;
objFields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 30;
objFields.Update();
return objConf;
}
function GetDatabaseConnection() {
// SQLOLEDB is very sensitive to noise between client & server, and always mistaken certain
// noise as returned result set; ODBC is better way to go for now
var objCon = WScript.CreateObject("ADODB.Connection");
objCon.Open(
"Driver={Sql Server};APP=" + strScript +
";Server=" + DB_SERVER_NAME +
";Database=" + DB_DATABASE_NAME +
";user id=" + DB_DATABASE_USER_NAME +
";password=" + DB_DATABASE_PASSWORD +
";OLE DB Services=0"
);
return objCon;
}
//
// BEGIN MAIN PROGRAM
//
strMsg = "**************************************************";
WScript.Echo(strMsg);
WScript.StdErr.WriteLine(strMsg);
strScript = String(WScript.ScriptName);
DateTimeNow = new Date();
strMsg = strScript + " started at " + DateTimeNow.toLocaleString();
WScript.Echo(strMsg);
WScript.StdErr.WriteLine(strMsg);
if (!ParseCommandLineParams()) {
DisplayUsage();
WScript.Quit(0);
}
DisplayParameters();
try {
var objCon = GetDatabaseConnection();
var objCmd = WScript.CreateObject("ADODB.Command");
objCmd.ActiveConnection = objCon;
objCmd.CommandText = QUERY_NAME_1;
objCmd.CommandType = 4; // adCmdStoredProc
objCmd.CommandTimeout = 1800;
var objParam = objCmd.CreateParameter("Return", 3, 4); // adInteger, adParamReturnValue
objCmd.Parameters.Append(objParam);
WScript.Echo("Before execution");
if (ARG_KEEP_BACKUP_COPIES == 1) {
var objFSO = WScript.CreateObject("Scripting.FileSystemObject");
if (objFSO.FileExists(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "3.txt")) {
var File3 = objFSO.GetFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "3.txt");
File3.Delete();
}
if (objFSO.FileExists(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "2.txt")) {
var File2 = objFSO.GetFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "2.txt");
File2.Move(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "3.txt");
}
if (objFSO.FileExists(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "1.txt")) {
var File1 = objFSO.GetFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "1.txt");
File1.Move(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "2.txt");
}
if (objFSO.FileExists(ARG_REPORT_PATH + EXTRACT_FILE_NAME + ".txt")) {
var File0 = objFSO.GetFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + ".txt");
File0.Move(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "1.txt");
}
}
var objRs = null;
try {
objRs = objCmd.Execute();
} catch (er) {
try {
objRs = objCmd.Execute();
} catch (er2) {
try {
objRs.Close();
} catch (er3) {
WScript.Echo("Error found even after 2nd run attempt!");
}
var strError = "First run failed";
// Send error email
var objConf = GetConfigCDO();
var objMsg = WScript.CreateObject("CDO.Message");
objMsg.Configuration = objConf;
// objMsg.To = ARG_EMAIL_TO;
objMsg.To = "support#sumtotal.com.au";
objMsg.From = ARG_EMAIL_FROM;
objMsg.Subject = EMAIL_SUBJECT_ERROR;
objMsg.TextBody = strError;
objMsg.send();
// Log error in output file
var objTStreamLE = objFSO.CreateTextFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + ".txt", true);
objTStreamLE.WriteLine(strError);
objTStreamLE.Close();
}
}
if (objRs.EOF) {
objRs.Close();
// check return code after closing the record set
var rc = objCmd(0);
if (rc == 100010) {
WScript.Echo("Another instance is running. Bail out");
} else if (rc == 0) {
WScript.Echo("Found no records for users");
} else {
var objError = new Error(rc, STRING_SQL_FAILED);
throw objError;
}
} else {
// Update Last Update Date
objCmd.ActiveConnection = objCon;
objCmd.CommandText = QUERY_NAME_2;
objCmd.CommandType = 4; // adCmdStoredProc
objCmd.CommandTimeout = 1800;
objCmd.Execute();
var objTStreamLE = objFSO.CreateTextFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + ".txt", true);
while (true) {
if (objRs.EOF) {
// we have to send the last mail
strContentType = "";
} else {
var strApplicantID = new String(objRs("EmpID"));
var strCourse_Code = new String(objRs("Event_Code"));
var strCourse_Name = new String(objRs("Course_Name"));
var strCompletion_Date = new String(objRs("Completion_Date"));
var strGrade_Name = new String(objRs("Grade_Name"));
var strBodyInfo = strApplicantID + DELIMITER +
strCourse_Code + DELIMITER +
strCourse_Name + DELIMITER +
strCompletion_Date + DELIMITER +
strGrade_Name;
WScript.Echo(strBodyInfo);
objTStreamLE.WriteLine(strBodyInfo);
}
if (objRs.EOF) {
break;
}
objRs.MoveNext;
}
objTStreamLE.Close();
objRs.Close();
}
var objConf = GetConfigCDO();
var objMsg = WScript.CreateObject("CDO.Message");
objMsg.Configuration = objConf;
objMsg.To = ARG_EMAIL_TO;
objMsg.From = ARG_EMAIL_FROM;
objMsg.Subject = EMAIL_SUBJECT;
objMsg.TextBody = EMAIL_SUBJECT;
objMsg.send();
EmailCount++; // How many email sent. it will be always one email in this case.
objCon.Close();
} catch (e) {
var objFSO = WScript.CreateObject("Scripting.FileSystemObject");
var objTStreamErrorLog = objFSO.CreateTextFile(errorFile, true);
objTStreamErrorLog.WriteLine(strMsg);
if (e.description == STRING_SQL_FAILED) {
strMsg = "Failed to execute " + QUERY_NAME_1 + ".\nReturn code:" + String(e.number);
} else {
strMsg = "Script causes an exception.\nException number: 0x" + String(e.number & 0xFFFF) + "\nDescription:" + e.description;
}
objTStreamErrorLog.WriteLine(strMsg);
objTStreamErrorLog.close();
var errorFile = ARG_REPORT_PATH + LOG_FILE_NAME;
var theFile_1_Abs = objFSO.GetAbsolutePathName(errorFile);
var objConf = GetConfigCDO();
var objMsg = WScript.CreateObject("CDO.Message");
objMsg.Configuration = objConf;
objMsg.To = ARG_EMAIL_TO + ";" + ARG_EMAIL_FROM;
objMsg.From = ARG_EMAIL_FROM;
objMsg.Subject = EMAIL_SUBJECT_ERROR;
objMsg.TextBody = "The attached file contains a error log file of any issues that arose during the DataExtract process";
objMsg.AddAttachment(theFile_1_Abs);
objMsg.send();
WScript.StdErr.WriteLine(strMsg);
WScript.Echo(strMsg);
objFSO.DeleteFile(errorFile); // delete log file generated.
var objShell = WScript.CreateObject("WScript.Shell");
if (!objShell.LogEvent(1, "iX Learning Server Task(" + strScript + "): " + strMsg)) {
WScript.StdErr.WriteLine("Failed to log an event");
}
}
DateTimeNow = new Date();
strMsg = "Task ended at " + DateTimeNow.toLocaleString() + ". Total Messages Sent: " + EmailCount.toString();
WScript.Echo(strMsg);
WScript.StdErr.WriteLine(strMsg);
//
// END MAIN PROGRAM
//
2nd run
var QUERY_NAME_1 = "Custom_Extract_Second_Run";
var QUERY_NAME_2 = "Custom_Extract_UpdateDate";
var QUERY_NAME_3 = "Custom_Extract_GetRunStatus";
var LOG_FILE_NAME = "DataExtract_error.log";
var EXTRACT_FILE_NAME = "Extract";
var DB_SERVER_NAME = "sql6";
var DB_DATABASE_NAME = "database_name";
var DB_DATABASE_USER_NAME = "username";
var DB_DATABASE_PASSWORD = "password";
var DateTimeNow = new Date();
var DATE_VALUE = DateTimeNow.getDate() + "/" + (DateTimeNow.getMonth()+1) + "/" + DateTimeNow.getFullYear();
var EMAIL_SUBJECT_HEADER = "Email Extract Header - Extract Date - " + DATE_VALUE;
var EMAIL_SUBJECT = EMAIL_SUBJECT_HEADER + " Successful";
var EMAIL_SUBJECT_ERROR = "Unsuccessful - " + EMAIL_SUBJECT_HEADER;
var EmailCount = 0;
var DELIMITER = "|";
var STRING_SQL_FAILED = "SQL Failed";
var strScript = "";
var strMsg = "";
var ARG_REPORT_PATH = "";
var ARG_MAIL_SERVER = "";
var ARG_KEEP_BACKUP_COPIES = 0;
var ARG_EMAIL_FROM = "";
var ARG_EMAIL_TO = "";
function ParseCommandLineParams()
{
var cmdArgs = WScript.Arguments;
for(i = 0; i < cmdArgs.length; i++)
{
// Get next argument
arg = cmdArgs(i);
// Each argument is in the form a=b. Split the two components
j = arg.search(/=/);
if(j == -1)
{
WScript.Echo("Invalid arguments arg = " + arg);
return false;
}
argName = arg.substring(0, j);
argValue = arg.substring(j+1, arg.length);
switch(argName)
{
case "/reportPath":
ARG_REPORT_PATH = argValue;
break;
case "/mailServer":
ARG_MAIL_SERVER = argValue;
break;
case "/keepBackupCopies":
ARG_KEEP_BACKUP_COPIES = parseInt(argValue);
break;
case "/from":
ARG_EMAIL_FROM = argValue;
break;
case "/to":
ARG_EMAIL_TO = argValue;
break;
default:
WScript.Echo("Invalid arguments. Name = '" + argName + "' Value = '" + argValue + "'");
return false;
}
}
return true;
}
function DisplayUsage()
{
WScript.Echo("Usage: cscript DataExtract.js");
WScript.Echo(" [/m=<Report path directory where it creates file>]");
WScript.Echo(" [/from=<from-line in email>] [/to=<to-line in email>]");
WScript.Echo(" [/machinename=<Email Server name>] [/databaseConfig=<Database Config Setting file>]");
WScript.Echo(" ");
WScript.Echo(" /m - unc path to mail directory (default: ..\\reports\\)");
WScript.Echo(" /from - from-line in email (default: Tejas Magia <>");
WScript.Echo(" /to - to-line in email (default: Tejas Magia <>");
WScript.Echo(" /machinename - email server name (default: EXCHANGE2 ");
WScript.Echo(" /databaseConfig - DataBase Setup Config (default: ..\\..\\..\\..\\config\\config.txt ");
return;
}
function DisplayParameters()
{
WScript.Echo("Parameters:");
WScript.Echo(" ARG_REPORT_PATH=[" + ARG_REPORT_PATH + "]");
WScript.Echo(" ARG_EMAIL_FROM=[" + ARG_EMAIL_FROM + "]");
WScript.Echo(" ARG_EMAIL_TO=[" + ARG_EMAIL_TO +"]");
WScript.Echo(" ARG_MAIL_SERVER=["+ ARG_MAIL_SERVER +"]");
WScript.Echo(" DB_SERVER_NAME=[" + DB_SERVER_NAME + "]");
WScript.Echo(" DB_DATABASE_NAME=[" + DB_DATABASE_NAME+ "]");
return;
}
function GetConfigCDO()
{
var objConf = WScript.CreateObject("CDO.Configuration");
objFields = objConf.Fields;
objFields.Item("http://schemas.Microsoft.com/cdo/configuration/sendusing") = 2;
objFields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = ARG_MAIL_SERVER;
objFields.Item("http://schemas.Microsoft.com/cdo/configuration/smtpserverport") = 25;
objFields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 30;
objFields.Update();
return objConf;
}
function GetDatabaseConnection()
{
// SQLOLEDB is very sensitive to noise between client & server, and always mistaken certain
// noise as returned result set; ODBC is better way to go for now
var objCon = WScript.CreateObject("ADODB.Connection");
objCon.Open(
"Driver={Sql Server};APP=" + strScript +
";Server=" + DB_SERVER_NAME +
";Database=" + DB_DATABASE_NAME +
";user id=" + DB_DATABASE_USER_NAME +
";password=" + DB_DATABASE_PASSWORD +
";OLE DB Services=0"
);
return objCon;
}
//
// BEGIN MAIN PROGRAM
//
strMsg = "**************************************************";
WScript.Echo(strMsg);
WScript.StdErr.WriteLine(strMsg);
strScript = String(WScript.ScriptName);
DateTimeNow = new Date();
strMsg = strScript + " started at " + DateTimeNow.toLocaleString();
WScript.Echo(strMsg);
WScript.StdErr.WriteLine(strMsg);
if (!ParseCommandLineParams())
{
DisplayUsage();
WScript.Quit(0);
}
DisplayParameters();
try
{
var objCon = GetDatabaseConnection();
var objCmd = WScript.CreateObject("ADODB.Command");
var objRs = null;
var runStatus = 0;
try
{
// Get Run Status
objCmd.ActiveConnection = objCon;
objCmd.CommandText = QUERY_NAME_3;
objCmd.CommandType = 4; // adCmdStoredProc
objCmd.CommandTimeout = 1800;
objRs = objCmd.Execute();
runStatus = objRs("Status");
}
catch (er5)
{
}
if (runStatus < 1)
{
objCmd.ActiveConnection = objCon;
objCmd.CommandText = QUERY_NAME_1;
objCmd.CommandType = 4; // adCmdStoredProc
objCmd.CommandTimeout = 1800;
var objParam = objCmd.CreateParameter("Return", 3, 4); // adInteger, adParamReturnValue
objCmd.Parameters.Append(objParam);
WScript.Echo("Before execution");
if (ARG_KEEP_BACKUP_COPIES == 1)
{
var objFSO = WScript.CreateObject("Scripting.FileSystemObject");
if (objFSO.FileExists(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "3.txt"))
{
var File3 = objFSO.GetFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "3.txt");
File3.Delete();
}
if (objFSO.FileExists(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "2.txt"))
{
var File2 = objFSO.GetFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "2.txt");
File2.Move(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "3.txt");
}
if (objFSO.FileExists(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "1.txt"))
{
var File1 = objFSO.GetFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "1.txt");
File1.Move(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "2.txt");
}
if (objFSO.FileExists(ARG_REPORT_PATH + EXTRACT_FILE_NAME + ".txt"))
{
var File0 = objFSO.GetFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + ".txt");
File0.Move(ARG_REPORT_PATH + EXTRACT_FILE_NAME + "1.txt");
}
}
try
{
objRs = objCmd.Execute();
}
catch (er)
{
try
{
objRs = objCmd.Execute();
}
catch (er2)
{
try
{
objRs.Close();
}
catch (er3)
{
WScript.Echo("Error found even after 2nd run attempt!");
}
var strError = "An unexpected error has occured during the run of this routine. " +
"and send through a manual extract. If you do not hear back from us by 1pm, please do not hesitate to call " +
".";
// Send error email
var objConf = GetConfigCDO();
var objMsg = WScript.CreateObject("CDO.Message");
objMsg.Configuration = objConf;
objMsg.To = ARG_EMAIL_TO + ";email#email.com.au";
// objMsg.To = ARG_EMAIL_TO;
objMsg.From = ARG_EMAIL_FROM;
objMsg.Subject = EMAIL_SUBJECT_ERROR;
objMsg.TextBody = strError;
objMsg.send();
// Log error in output file
var objTStreamLE = objFSO.CreateTextFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + ".txt", true);
objTStreamLE.WriteLine(strError);
objTStreamLE.Close();
}
}
if (objRs.EOF)
{
objRs.Close();
// check return code after closing the record set
var rc = objCmd(0);
if (rc == 100010)
{
WScript.Echo("Another instance is running. Bail out");
}
else if (rc == 0)
{
WScript.Echo("Found no records for users");
}
else
{
var objError = new Error(rc, STRING_SQL_FAILED);
throw objError;
}
}
else
{
// Update Last Update Date
objCmd.ActiveConnection = objCon;
objCmd.CommandText = QUERY_NAME_2;
objCmd.CommandType = 4; // adCmdStoredProc
objCmd.CommandTimeout = 1800;
objCmd.Execute();
var objTStreamLE = objFSO.CreateTextFile(ARG_REPORT_PATH + EXTRACT_FILE_NAME + ".txt", true);
while (true)
{
if (objRs.EOF)
{
// we have to send the last mail
strContentType = "";
}
else
{
var strApplicantID = new String(objRs("EmpID"));
var strCourse_Code = new String(objRs("Event_Code"));
var strCourse_Name = new String(objRs("Course_Name"));
var strCompletion_Date = new String(objRs("Completion_Date"));
var strGrade_Name = new String(objRs("Grade_Name"));
var strBodyInfo = strApplicantID + DELIMITER +
strCourse_Code + DELIMITER +
strCourse_Name + DELIMITER +
strCompletion_Date + DELIMITER +
strGrade_Name;
WScript.Echo(strBodyInfo);
objTStreamLE.WriteLine(strBodyInfo);
}
if (objRs.EOF)
{
break;
}
objRs.MoveNext;
}
objTStreamLE.Close();
objRs.Close();
}
var objConf = GetConfigCDO();
var objMsg = WScript.CreateObject("CDO.Message");
objMsg.Configuration = objConf;
objMsg.To = ARG_EMAIL_TO;
objMsg.From = ARG_EMAIL_FROM;
objMsg.Subject = EMAIL_SUBJECT;
objMsg.TextBody = EMAIL_SUBJECT;
objMsg.send();
EmailCount++; // How many email sent. it will be always one email in this case.
}
objCon.Close();
}
catch (e)
Following a great deal of testing and analysis, we're unable to pinpoint the root cause as both jobs seem to fail intermittently, some nights the extract produces data and other nights no data at all.
Below are our test results based on manual run via cmd and via the task both producing intermittent failed and success results, with no particular pattern.
Test results:
Execute 1st run via command prompt
1st run - Fail
2nd run - Fail
3rd run - Successful
4th run - Successful
5th run - Successful
Execute Scheduled task - 'First run'
1st run - Successful
2nd run - Successful
3rd run - Successful
4th run - Fail - Scheduler failed
5th run - Fail - Scheduler failed
Execute Scheduled task - Sequential First followed by Second run
1st run - First run successful, second run successful but no file generated
2nd run - First run unsuccessful, ran second job - successful
3rd run - First run successful, second run successful but no file generated
4th run - First run unsuccessful, ran second job - successful
A possible cause may be due to timeout; however, each run takes the same time to complete (approx. 3 minutes) whether failed or successful.
We recently upgraded the environment from Windows Server 2005 to Windows Server 2008 and noticed the issue starting occurring after implementation. No change was made to the logic or SQL procedures.
Would Server 2008 handle the logic in such a way to break the routine?

FireFox Addon getElementById on http-on-examine-response didn't return any value

I am trying to get a value from an element in active page on http-on-examine-response. My below script works well as an addon without lines between
var tabs = require("sdk/tabs");
and
contentScript: contentScriptString
But when I add those lines it access the text file but doesn't write Anything. I can't see any error message in console because I don't use SDK because the new SDK uses complex things which I have to learn more on this. (For Now I just edit js file in components folder and update chrome.manifest and install.rdf if any and zip them then rename it as xpi and open it in firefox and it works well). I googled how to debug this script with which sdk and tried many scripts titled 'getelementbyid firefox addon' and had no luck. It would be helpful even if you say which sdk should use (a dumb question. But couldnt help myself).
Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
function GetCity() {
var GetCity = {
observe: function(subject, topic, data) {
if (topic == "http-on-examine-response") {
var httpChannel = subject.QueryInterface(Components.interfaces.nsIHttpChannel);
if (httpChannel.responseStatusText == "OK")
{
var buffer = httpChannel.URI.spec;
var pw = buffer.search("mywebsite.com/release");
if (pw > 0)
{
var date = new Date();
var TimeStamp = date.toLocaleString();
var pfum = buffer.search("flag=release1");
if (pfum > 0 )
{
var flagname = "1";
var flagnum = 4;
}
var pfuk = buffer.search("flag=release2");
if (pfuk > 0 )
{
var flagname = "2";
var flagnum = "1";
}
var pfup = buffer.search("flag=release3");
if (pfup > 0 )
{
var flagname = "3";
var flagnum = 2;
}
var pfap = buffer.search("flag=release4");
if (pfap > 0 )
{
var flagname = "4";
var flagnum = 3;
}
if (flagnum > 0)
{
var tabs = require("sdk/tabs");
var contentScriptString = 'var cityname = document.getElementById("city").value ;'
tabs.activeTab.attach({
contentScript: contentScriptString
});
buffer += "^" + ThisUserName + "^" + ThisComputerName + "^" + TimeStamp + "^" + flagname + "\r\n";
fos.write(buffer, buffer.length);
}
}
}
}
}
};
var nsIEnvironment = Components.classes["#mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment);
var ThisUserName = nsIEnvironment.get("UserName");
var ThisComputerName = nsIEnvironment.get("ComputerName");
var FileUtils = Components.utils.import("resource://gre/modules/FileUtils.jsm").FileUtils;
var d = new Date();
var dd = d.getDate();
if (dd < 10)
dd = "0" + dd;
var mm = (d.getMonth()+1);
if (mm < 10)
mm = "0" + mm;
var yyyy = d.getFullYear();
var file = new FileUtils.File( "T:\\-\\CityList\\" + yyyy + "\\" + mm + "\\" + dd );
if (!file.exists()) {
file.create(file.DIRECTORY_TYPE, 0755);
}
var filename = "HM_" + ThisUserName + yyyy + "-" + mm + "-" + dd + ".txt";
file.append(filename);
var fos = Components.classes["#mozilla.org/network/file-output-stream;1"]
.createInstance(Components.interfaces.nsIFileOutputStream);
// PR_WRONLY | PR_CREATE_FILE | PR_APPEND
fos.init(file, 0x02 | 0x08 | 0x10, -1, 0);
var observerService = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(HotelMappingCounter, "http-on-examine-response", false);
}
var NSGetFactory = XPCOMUtils.generateNSGetFactory([CityList]);

Categories

Resources