how to select text in webview android with JavaScript? - javascript

I am using this code to highlight text in android webview.
public void highlight(int pageNumber) {
dbManager = new DBManager(webView.getContext());
dbManager.open();
cursor = dbManager.getSelectedID(books.get(0).getmDbId());
String quotesDb = cursor.getString(cursor.getColumnIndex("_quote"));
String currnetPage = cursor.getString(cursor.getColumnIndex("_current_page"));
List<String> myList = Arrays.asList(quotesDb.split("½_½"));
webView.evaluateJavascript("function doSearch(text, backgroundColor) {\n" +
" if (window.find && window.getSelection) {\n" +
" var windowHeight = window.scrollY;\n" +
" document.designMode = 'on';\n" +
" var sel = window.getSelection();\n" +
" sel.collapse(document.body, 0);\n" +
" while (window.find(text)) {\n" +
" document.execCommand('HiliteColor', false, backgroundColor);\n" +
" sel.collapseToEnd();\n" +
" }\n" +
" document.designMode = 'off';\n" +
" window.scrollTo(0, windowHeight);\n" +
" }\n" +
"}", null);
Log.e("SAVE_QUOTE ", "LIST_SIZE ----> " + myList.size());
if (pageNumber == Integer.parseInt(currnetPage)) {
for (int j = 0; j < myList.size(); j++) {
webView.evaluateJavascript("doSearch('" + myList.get(j) + "', 'SkyBlue')", null);
// webView.findAllAsync(myList.get(j));
}
}
}
Everything works fine until I select the code with a new line (paragraph). Then I get an error and the text is not highlighted.
/chromium: [INFO:CONSOLE(1)] "Uncaught SyntaxError: Invalid or unexpected token", source: file:///data/user/0/com.mms.tts/cache/W1/index.xhtml (1)

Try using the jQuery .select() function
For example
$(#myList.get(j)).select()
Where #myList.get(j) is a valid HTML id
Note: you will need to reference the jQuery library

Related

Hosted Website loads with errors in <body> that are not in the code

Ahoi,
I am hosting a small debug-website with my "Olimex ESP-32 POE". The goal is to send some internal data via JSON there to not have to use the Serial-Output from the Arduino IDE (The reasons behind that do not matter).
#include "Arduino.h"
#include <WiFiClient.h>
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
#include <string>
const char* ssid = "SSID";
const char* password = "password";
int looper = 0;
int looperSpeed = 0;
int looperMode = 0;
int looperDestination = 0;
int looperETC = 0;
WebServer webserver(80);
void initWebServer();
void getSettings() {
String response = "{";
response+= "\"speed\": \""+(String) looperSpeed+"\"";
response+= ",\"mode\": \""+(String) looperMode+"\"";
response+= ",\"dest\": \""+(String) looperDestination+"\"";
response+= ",\"etc\": \""+(String) looperETC+"\"";
if (webserver.arg("signalStrength")== "true"){
response+= ",\"signalStrengh\": \""+String(WiFi.RSSI())+"\"";
}
response+="}";
webserver.send(200, "text/json", response);
}
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += webserver.uri();
message += "\nMethod: ";
message += (webserver.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += webserver.args();
message += "\n";
for (uint8_t i = 0; i < webserver.args(); i++) {
message += " " + webserver.argName(i) + ": " + webserver.arg(i) + "\n";
}
webserver.send(404, "text/plain", message);
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
initWebServer();
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Set not found response
webserver.onNotFound(handleNotFound);
// Start server
webserver.begin();
Serial.println("HTTP server started");
}
void loop() {
webserver.handleClient();
//Some test values are changed here periodically (looperXYZ)
}
}
And the part which creates the website:
std::string online_output = "Test";
const char* serverIndex() {
const char* o = online_output.c_str();
const char* r =
(std::string("") +
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>" +
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>" +
"<input type='file' name='update'>" +
"<input type='submit' value='Update'>" +
"</form>" +
"<div id='prg'>Progress: 0%</div>" +
"<div id='output' style=\"font-family: monospace; border: 1px solid black; width: 350px;min-height:398px;\">" +
"</div>" +
"<script>" +
"var id = 0;" +
"var removeId = 0;" +
"setInterval(function(){" +
/*"var xhReq = new XMLHttpRequest();" +
"xhReq.open('GET', '/JSON', false);" +
"xhReq.send(null);" +
"var jsonObject = JSON.parse(xhReq.responseText);" +*/
"var data = {};" +
"$.ajax({" +
"type: 'GET'," +
"url: '/JSON'," +
"data: data," +
"async: true," +
"beforeSend: function (xhr) {" +
"if (xhr && xhr.overrideMimeType) {" +
"xhr.overrideMimeType('application/json;charset=utf-8');" +
"}" +
"}," +
"dataType: 'json'," +
"success: function (data) {" +
"document.getElementById('output').innerHTML = \"<p id=\" + id + \" style='margin:0;padding:0px;'>\" + \"Mode: \" + fill(data.mode,2) + \" | Speed: \" + fill(data.speed,4) + \" | Dest: \" + fill(data.dest,4) + \" | ETC: \" + fill(data.etc,5) + \"</p>\" + document.getElementById('output').innerHTML;" +
// "if (document.getElementById('output').offsetHeight > 400) document.getElementById('output').innerHTML = \"<p style='margin:0;padding:0px;'>\" + data.name + \"</p>\";" +
"if (document.getElementById('output').offsetHeight > 400) { document.getElementById(removeId).remove(); removeId++;}" +
"id++;" +
"console.log(data);" +
"}" +
"});" +
"}, 50);" +
"function fill(n,m) { " +
"var pre=\"\";" +
"var dec=10;" +
"for(var i=1;i<m;i++) { if(n<dec) { pre+=\".\"; } dec*=10; }" +
"pre = pre + n;" +
"return pre; }" +
"$('form').submit(function(e){" +
"e.preventDefault();" +
"var form = $('#upload_form')[0];" +
"var data = new FormData(form);" +
" $.ajax({" +
"url: '/update'," +
"type: 'POST'," +
"data: data," +
"contentType: false," +
"processData:false," +
"xhr: function() {" +
"var xhr = new window.XMLHttpRequest();" +
"xhr.upload.addEventListener('progress', function(evt) {" +
"if (evt.lengthComputable) {" +
"var per = evt.loaded / evt.total;" +
"$('#prg').html('progress: ' + Math.round(per*100) + '%');" +
"}" +
"}, false);" +
"return xhr;" +
"}," +
"success:function(d, s) {" +
"console.log('success!')" +
"}," +
"error: function (a, b, c) {" +
"}" +
"});" +
"});" +
"</script>").c_str();
return r;
}
const char* host = "esp32";
void initWebServer() {
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
/*return index page which is stored in serverIndex */
webserver.on("/", HTTP_GET, []() {
webserver.sendHeader("Connection", "close");
webserver.send(200, "text/html", serverIndex());
});
webserver.on("/JSON", HTTP_GET, []() {
getSettings();
});
/*handling uploading firmware file */
webserver.on("/update", HTTP_POST, []() {
webserver.sendHeader("Connection", "close");
webserver.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}, []() {
HTTPUpload& upload = webserver.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Update.printError(Serial);
}
}
});
webserver.begin();
}
This is testing code, so there might be left-overs from previous tests - FYI.
When loading the website (currently I am using Chrome) it sometimes works, sometimes nothing is loaded (THIS SITE IS NOT WORKING, and then an empty page) and sometimes I get a result like: xV­ºùÿý?øÿý?;"> which is the only output on the screen.
In detail it shows the following:
<html><head></head><body>xV­ºùÿý?øÿý?;"><script>var id = 0; [...the rest of the <script> part is loaded properly...]
I just noticed that in front of these strange characters are 364 centered points (·) but I cannot actually copy them, no editor is displaying them besides the Chrome->Inspect->"Sources"-Tab.
So basically the body is broken and these characters appear, they also do not change currently.
Can someone point me into a direction to solve this on my own, so that the website is always correctly loaded or knows what the error is?
The error seems to be on the following line:
const char* r = (std::string("") + “...”).c_str();
You are creating and std::string which allocates the raw c string on the heap. You then get the c representation of the string with .c_str(). The issue is that the string is freed since you have not assigned the string to a variable of type std::string. As a result, you were accessing memory that was not yours. When its memory wasn’t yet reused, it worked, but want is was reused by another program, it failed since you got basically random bytes from memory.
You can solve the issue by adding the following:
auto my_str = std::string("") + “...”;
Because you don’t need the raw pointer.
For the server index function, it should look like:
std::string serverIndex() {
For your init web server function:
webserver.on("/", HTTP_GET, []() {
webserver.sendHeader("Connection", "close");
auto r = serverIndex();
webserver.send(200, "text/html", r.c_str());
});
Disclaimer: this code wasn’t tested as it was only written in the app.

Selenium - Unable to find the hidden element

I am trying to create an framework where I want to find whether an webelement is hidden or not before performing an action on the web element.
I have a password field which is hidden and is structured as below
<div class=hidepassword>
<input password field >
<div>
When I query the input tag with the following lines
Isvisible1 = (string)js1.ExecuteScript("return (window.getComputedStyle?window.getComputedStyle(arguments[0], null):arguments[0].currentStyle).visibility;", myCurElement);
Isvisible2 = (string)js1.ExecuteScript("return (window.getComputedStyle(arguments[0], null).getPropertyValue('display'));", myCurElement);
Isvisible3 = (bool)js1.ExecuteScript("return !(arguments[0].offsetHeight <= 1);", myCurElement);
I am getting all the values indicating it as visible.
Later , got to know that the class which the preceding div has is making the input invisible.
I tried to get the value of overflow which is made available in the .css file for the class hidepassword
But unfortunately, there are lot of css values for the class hidepassword and when I use the below javascript function, I am able to get only one of its CSS value
public string getStyle(string ClassName)
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
return (String)js.ExecuteScript(
"function getStyle(ClassName) {" +
"var styleSheets = window.document.styleSheets;" +
"var styleSheetsLength = styleSheets.length;" +
"for (var i = 0; i < styleSheetsLength; i++)" +
"{" +
" var classes = styleSheets[i].rules || styleSheets[i].cssRules;" +
" if (!classes)" +
" continue;" +
" var classesLength = classes.length;" +
" for (var x = 0; x < classesLength; x++)" +
" {" +
" if (classes[x].selectorText == ClassName)" +
" {" +
" var ret;" +
" if (classes[x].cssText)" +
" {" +
" ret = classes[x].cssText;" +
" }" +
" else" +
" {" +
" ret = classes[x].style.cssText;" +
" }" +
" if (ret.indexOf(classes[x].selectorText) == -1)" +
" {" +
" ret = classes[x].selectorText + ret ;" +
" }" +
" return ret;" +
" }" +
" }" +
"}" +
"}return getStyle(arguments[0]);", ClassName);
}
Is there a way to get all the css values for the particular class name and then based on the css values for the class, we can make a call whether the element is visible or not visible. ?
Thanks in advance for all your help on this.
Selenium had supply api:isDisplayed() to detect element visibility, why you want to implement it as such complex by yourself

BIRT (maximo data): overloaded fetch script in scripted dataSet

I've inherited a BIRT .rptdesign that isn't returning any records in "preview results." There is one open script involved, as well as a fetch script that has approximately 5 more sql queries inside of it. Much of what I have tried for solutions involves breaking out these queries involved in the fetch script into their own dataSet, and then relating them to the open script (alternatively I've tried forming a joint data set, with no luck). Even after taking out a small query from the fetch script, I'm not able to generate records in result preview. I tried to upload an image of the layout, but don't have the reputation to do so...Please let me know if you need the design file to help visualize where everything is landing!
Open script:
maximoDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), this.getName());
maximoDataSet.open();
var sqlText = new String();
var printed = params["Printed"].toUpperCase().replace("Y","1");
var printed1 = printed.replace("N","0");
var where = new String(params["where"]);
if (params["Printed"].value)
where += " and workorder.em_printed = '" + printed1 + "' ";
// Add query to sqlText variable.
sqlText = "select workorder.wonum, workorder.workorderid as workorderid1, (select min(w2.workorderid) from maximo.workorder w2 where w2.istask=1 and w2.parent=workorder.wonum and w2.siteid=workorder.siteid) as workorderid, "
+ " workorder.pmnum as pmnum, workorder.targstartdate, workorder.siteid, workorder.description as wdesc, workorder.worktype, a.assetnum, a.description as adesc, a.em_relaymajor, a.em_relayminor, "
+ " workorder.location, l.description as ldesc, a.em_circuit, a.em_manfmodl, a.serialnum, j.em_craft, a.assetuid, "
+ " (select al.description from alndomain al where al.value=j.em_craft and al.domainid='EM_CRAFT') as cdesc, "
+ " (select wt.wtypedesc from maximo.worktype wt where wt.worktype=workorder.worktype) as wtdesc "
+ " from maximo.workorder "
+ " left outer join maximo.asset as a on a.assetnum=workorder.assetnum and a.siteid=workorder.siteid "
+ " left outer join maximo.jobplan as j on j.jpnum=workorder.jpnum and j.pluscrevnum=workorder.pluscjprevnum "
+ " left outer join maximo.locations as l on l.location=workorder.location and l.siteid=workorder.siteid"
// Include the Maximo where clause
+ " where workorder.istask=0 and workorder.status='INPRG' and workorder.siteid='EM' and " + where
;
maximoDataSet.setQuery(sqlText);
Fetch Script:
if (!maximoDataSet.fetch())
return (false);
// Add a line for each output column
// The specific get method should match the data type of the output column.
row["wonum"] = maximoDataSet.getString("wonum");
row["workorderid"] = maximoDataSet.getString("workorderid");
row["workorderid1"] = maximoDataSet.getString("workorderid1");
row["wdesc"] = maximoDataSet.getString("wdesc");
row["worktype"] = maximoDataSet.getString("worktype");
row["assetnum"] = maximoDataSet.getString("assetnum");
row["location"] = maximoDataSet.getString("location");
row["adesc"] = maximoDataSet.getString("adesc");
row["ldesc"] = maximoDataSet.getString("ldesc");
row["em_circuit"] = maximoDataSet.getString("em_circuit");
row["em_manfmodl"] = maximoDataSet.getString("em_manfmodl");
row["serialnum"] = maximoDataSet.getString("serialnum");
row["em_craft"] = maximoDataSet.getString("em_craft");
row["cdesc"] = maximoDataSet.getString("cdesc");
row["wtdesc"] = maximoDataSet.getString("wtdesc");
row["pmnum"] = maximoDataSet.getString("pmnum");
row["siteid"] = maximoDataSet.getString("siteid");
row["assetuid"] = maximoDataSet.getString("assetuid");
row["em_relaymajor"] = maximoDataSet.getString("em_relaymajor");
row["em_relayminor"] = maximoDataSet.getString("em_relayminor");
row["targstartdate"] = maximoDataSet.getTimestamp("targstartdate");
// Long Description
longDescDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "longDescDataSet");
longDescDataSet.open();
longDescSQL = "select longdescription.ldtext "
+ "from longdescription "
+ "where longdescription.ldownertable='WORKORDER' and longdescription.ldownercol='DESCRIPTION' "
+ "and longdescription.ldownercol='DESCRIPTION' "
+ "and longdescription.ldkey=?";
longDescDataSet.setQuery(longDescSQL);
longDescDataSet.setQueryParameterValue(1, maximoDataSet.getString("workorderid"));
if(longDescDataSet.fetch()) {
row["longdesc"] = longDescDataSet.getString("ldtext");
}
longDescDataSet.close();
// End Long Description
// Last Major
lastmajorDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "lastmajorDataSet");
lastmajorDataSet.open();
lastmajorSQL = "select workorder.wonum as wn1, workorder.workorderid as wid1, workorder.description as d1, p.frequency as f1, p.frequnit as fu1, "
+ "p.lastcompdate as lc1, p.extdate as e1, p.nextdate as n1, workorder.targstartdate as tsd1 "
+ "from workorder "
+ "join pm as p on p.pmnum=workorder.pmnum and p.siteid=workorder.siteid "
+ "where workorder.istask = 0 and workorder.actfinish = (select max(w1.actfinish) from maximo.workorder as w1 where w1.wonum=workorder.wonum and w1.siteid=workorder.siteid) "
+ "and workorder.worktype = 'MAJPM' and workorder.assetnum=? and workorder.siteid=? ";
lastmajorDataSet.setQuery(lastmajorSQL);
lastmajorDataSet.setQueryParameterValue(1, maximoDataSet.getString("assetnum"));
lastmajorDataSet.setQueryParameterValue(2, maximoDataSet.getString("siteid"));
if(lastmajorDataSet.fetch()) {
row["wn1"] = lastmajorDataSet.getString("wn1");
row["wid1"] = lastmajorDataSet.getString("wid1");
row["d1"] = lastmajorDataSet.getString("d1");
row["f1"] = lastmajorDataSet.getString("f1");
row["lc1"] = lastmajorDataSet.getTimestamp("lc1");
row["fu1"] = lastmajorDataSet.getString("fu1");
row["e1"] = lastmajorDataSet.getTimestamp("e1");
row["n1"] = lastmajorDataSet.getTimestamp("n1");
row["tsd1"] = lastmajorDataSet.getTimestamp("tsd1");
}
lastmajorDataSet.close();
// End Last Major
// Last Major Initials
lastmajorIDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "lastmajorIDataSet");
lastmajorIDataSet.open();
lastmajorISQL =" WITH x(key, val, rnum) AS "
+ " (SELECT refwo, em_initials, row_number() over(partition by refwo) "
+ " from maximo.labtrans as labtrans "
+ " join maximo.person as person on person.personid=labtrans.laborcode where labtrans.refwo='" + row["wn1"] + "' and labtrans.siteid=?), "
+ " y(key, str, cnt, cnt_max) AS "
+ " ( SELECT key, VARCHAR('', 1000), 0, MAX(rnum) "
+ " FROM x "
+ " GROUP BY key "
+ " UNION ALL "
+ " SELECT y.key, y.str || RTRIM(CHAR(x.val)) || ',', y.cnt + 1, y.cnt_max "
+ " FROM x, y "
+ " WHERE x.key = y.key AND "
+ " x.rnum = y.cnt + 1 AND "
+ " y.cnt < y.cnt_max ) "
+ " SELECT key, str "
+ " FROM y "
+ " WHERE y.cnt = y.cnt_max ";
lastmajorIDataSet.setQuery(lastmajorISQL);
//lastmajorIDataSet.setQueryParameterValue(1, lastmajorDataSet.getString("wn1"));
lastmajorIDataSet.setQueryParameterValue(1, maximoDataSet.getString("siteid"));
if(lastmajorIDataSet.fetch()) {
row["str"] = lastmajorIDataSet.getString("str");
}
lastmajorIDataSet.close();
// End Last Major Initials
// Last Major Long Description
LMlongDescDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "LMlongDescDataSet");
LMlongDescDataSet.open();
LMlongDescSQL = "select longdescription.ldtext as ldtext1 "
+ "from longdescription "
+ "where longdescription.ldownertable='WORKORDER' and longdescription.ldownercol='DESCRIPTION' "
+ "and longdescription.ldkey=" + row["wid1"];
LMlongDescDataSet.setQuery(LMlongDescSQL);
//LMlongDescDataSet.setQueryParameterValue(1, lastmajorDataSet.getString("wid1"));
if(LMlongDescDataSet.fetch()) {
row["longdesc1"] = LMlongDescDataSet.getString("ldtext1");
}
LMlongDescDataSet.close();
// End Last Major Long Description
// Last Minor
lastminorDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "lastminorDataSet");
lastminorDataSet.open();
lastminorSQL = "select workorder.wonum as wn2, workorder.workorderid as wid2, workorder.description as d2, p.frequency as f2, p.frequnit as fu2, "
+ "p.lastcompdate as lc2, p.extdate as e2, p.nextdate as n2, workorder.targstartdate as tsd2 "
+ "from workorder "
+ "join pm as p on p.pmnum=workorder.pmnum and p.siteid=workorder.siteid "
+ "where workorder.istask = 0 and workorder.actfinish = (select max(w1.actfinish) from maximo.workorder as w1 where w1.wonum=workorder.wonum and w1.siteid=workorder.siteid) "
+ "and workorder.worktype = 'MINPM' and workorder.assetnum=? and workorder.siteid= ? ";
lastminorDataSet.setQuery(lastminorSQL);
lastminorDataSet.setQueryParameterValue(1, maximoDataSet.getString("assetnum"));
lastminorDataSet.setQueryParameterValue(2, maximoDataSet.getString("siteid"));
if(lastminorDataSet.fetch()) {
row["wn2"] = lastminorDataSet.getString("wn2");
row["wid2"] = lastminorDataSet.getString("wid2");
row["d2"] = lastminorDataSet.getString("d2");
row["f2"] = lastminorDataSet.getString("f2");
row["lc2"] = lastminorDataSet.getTimestamp("lc2");
row["fu2"] = lastminorDataSet.getString("fu2");
row["e2"] = lastminorDataSet.getTimestamp("e2");
row["n2"] = lastminorDataSet.getTimestamp("n2");
row["tsd2"] = lastminorDataSet.getTimestamp("tsd2");
}
lastminorDataSet.close();
// End Last Minor
// Last Minor Initials
lastminorIDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "lastminorIDataSet");
lastminorIDataSet.open();
lastminorISQL =" WITH x(key, val, rnum) AS "
+ " (SELECT refwo, em_initials, row_number() over(partition by refwo) "
+ " from maximo.labtrans as labtrans "
+ " join maximo.person as person on person.personid=labtrans.laborcode where labtrans.refwo='" + row["wn2"] + "' and labtrans.siteid=?), "
+ " y(key, str1, cnt, cnt_max) AS "
+ " ( SELECT key, VARCHAR('', 1000), 0, MAX(rnum) "
+ " FROM x "
+ " GROUP BY key "
+ " UNION ALL "
+ " SELECT y.key, y.str1 || RTRIM(CHAR(x.val)) || ',', y.cnt + 1, y.cnt_max "
+ " FROM x, y "
+ " WHERE x.key = y.key AND "
+ " x.rnum = y.cnt + 1 AND "
+ " y.cnt < y.cnt_max ) "
+ " SELECT key, str1 "
+ " FROM y "
+ " WHERE y.cnt = y.cnt_max ";
lastminorIDataSet.setQuery(lastminorISQL);
//lastminorIDataSet.setQueryParameterValue(1, lastminorDataSet.getString("wn2"));
lastminorIDataSet.setQueryParameterValue(1, maximoDataSet.getString("siteid"));
if(lastminorIDataSet.fetch()) {
row["str1"] = lastminorIDataSet.getString("str1");
}
lastminorIDataSet.close();
// End Last Minor Initials
// Last Minor Long Description
LM2longDescDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "LM2longDescDataSet");
LM2longDescDataSet.open();
LM2longDescSQL = "select longdescription.ldtext as ldtext2 "
+ "from longdescription "
+ "where longdescription.ldownertable='WORKORDER' and longdescription.ldownercol='DESCRIPTION' "
+ "and longdescription.ldkey=" + row["wid2"];
LM2longDescDataSet.setQuery(LM2longDescSQL);
//LM2longDescDataSet.setQueryParameterValue(1, lastminorDataSet.getString("wid2"));
if(LM2longDescDataSet.fetch()) {
row["longdesc2"] = LM2longDescDataSet.getString("ldtext2");
}
LM2longDescDataSet.close();
// End Last Minor Long Description
// Asset Long Description
AlongDescDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "AlongDescDataSet");
AlongDescDataSet.open();
AlongDescSQL = "select longdescription.ldtext as ldtext3 "
+ "from longdescription "
+ "where longdescription.ldownertable='ASSET' and longdescription.ldownercol='DESCRIPTION' "
+ "and longdescription.ldkey=?";
AlongDescDataSet.setQuery(AlongDescSQL);
AlongDescDataSet.setQueryParameterValue(1, maximoDataSet.getString("assetuid"));
if(AlongDescDataSet.fetch()) {
row["longdesc3"] = AlongDescDataSet.getString("ldtext3");
}
AlongDescDataSet.close();
// End Asset Long Description
myTxn = MXReportTxnProvider.create(this.getDataSource().getName());
myStmt = myTxn.createStatement();
myStmt.setQuery("update workorder set workorder.em_printed = '1' where workorder.em_printed = '0' and workorder.workorderid = ? ");
myStmt.setQueryParameterValue(1,row["workorderid1"]);
//myStmt.setQueryParameterValue(2,"'"+row["siteid"]+"'");
myTxn.save();
return (true);
enter image description here

How to "postMessage" to host from within pdf when viewed in IE9 object element

I am attempting to do a small PoC with PDFs and have run into an issue. I am looking to post a message to a PDF and have the PDF post a message to the browser.
The deets:
I am viewing the PDF in an "object" element in IE9. I am using itextsharp to prefill a pdf template on the server, inject some app level javascript (post message and on message stuff) and then serve that up to the browser via a filestreamresult. I am using Reader 10 to view the PDF in IE9.
What works:
So far, everything works except for the PDF posting a message to the browser. I can post a message to the PDF, from the browser, no problem and all of the fields are prefilled as desired.
What doesn't work:
When I try using this.hostContainer.postMessage(["something","somethingmore"]) I get an Acrobat Escript window that says "hostContainer is not defined". I have also tried using "event.target.hostContainer" but I get "event.target is not defined". I am at a loss of what to do and any insight would be super helpful.
Reference links:
Acrobat Javascript API
Stackoverflow How-To on this topic
Original guide I used
The code:
My form view:
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
My custom javascript string method:
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(doc.xfa);" +
"console.println('Doc xfa value = ' + doc.xfa);" +
// "event.target.hostContainer.postMessage(['hello from pdf!']);" +
// "this.hostContainer.postMessage(['hello from pdf!']);"+
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}
My method for filling and sending the form to the browser:
public MemoryStream GetFilledRequestForm(string fileDirectory, User user, FormView formView)
{
var pdfStream = new MemoryStream();
var templateFilePath = GetRequestTypeTemplateFilePath(fileDirectory, _requestModule.FormTemplateFileName);
var pdfReader = new PdfReader(templateFilePath);
// pdfReader.RemoveUsageRights();
var stamper = new PdfStamper(pdfReader, pdfStream);
var formFields = GetFormFields(user, formView, pdfReader);
foreach (var field in formFields.Where(f => f.Value != null))
{
stamper.AcroFields.SetField(field.Name, field.Value);
}
stamper.FormFlattening = false;
var newJs = GetCustomJavascript(stamper.Reader.JavaScript);
stamper.AddJavaScript("newJs", newJs);
stamper.Close();
byte[] byteInfo = pdfStream.ToArray();
var outputStream = new MemoryStream();
outputStream.Write(byteInfo, 0, byteInfo.Length);
outputStream.Position = 0;
return outputStream;
}
Ok, so I have resolved it, with some help of course. I found the key at this stack overflow post. I needed to wait for the object to load before assigning the message handler. Additionally, I needed a global variable in the pdf javascript to be able to post the message.
Html/Javascript: (the key here is the loadListener() function)
#model WebModel.FormView
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
<input id="buttonPost" type="button" value="post to pdf"/>
<script type="text/javascript">
var PDFObject = document.getElementById("pdfFrame");
function loadListener() {
if (typeof PDFObject.readyState === 'undefined') { // ready state only works for IE, which is good because we only need to do this for IE because IE sucks in the first place
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
return;
}
if (PDFObject.readyState == 4) {
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
} else {
setTimeout(loadListener, 500);
}
}
function messageFunc(data) {
debugger;
var messagedata = data;
alert('finally!!');
}
function sendToPdf() {
if(PDFObject!= null){
PDFObject.postMessage(
["a", "b"]);
}
}
$('#pdfFrame').ready(function() {
loadListener();
$('#buttonPost').on('click', function() {
sendToPdf();
});
});
</script>
My new function to create the javascript: (the key here is var appHostContainer)
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"var appHostContainer = this.hostContainer;" +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(stringArray);" +
"appHostContainer.postMessage(['hello from pdf!']);" +
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}

How update data by Javascript

How can I, on the OnChange event, update data in my database ?
I have a WebMethod, that returns a HTML, so I can't see those elements, so I think he solution will be a javascript function.
A textarea catch the text from the database, if the user alter this, the database field has to be updated.
[WebMethod]
public static object ListAdvertise(string transaction)
{
StringBuilder retorno = new StringBuilder(160000);
Utilidade.QuebraToken tk2 = new Utilidade.QuebraToken();
string Credenciada = tk2.CarregaToken(1, HttpContext.Current.Request.Cookies["token"].Value);
string select3 = "SELECT * FROM San_Imovel WHERE Status_Id = 1 AND Credenciada_Id = " + Credenciada + " AND Transacao_Id IN (" + transacao + ") ORDER BY NomeCidade, NomeBairro, Imovel_Id ASC";
Utilidade.Conexao c3 = new Utilidade.Conexao();
SqlConnection con3 = new SqlConnection(c3.Con);
SqlCommand cmd3 = new SqlCommand(select3, con3);
con3.Open();
SqlDataReader r3 = cmd3.ExecuteReader();
while (r3.Read())
{
Imovel_Id = r3["Imovel_Id"].ToString();
Endereco = r3["Descricao"].ToString() + " " + r3["Logradouro"].ToString() + " " + r3["Numero"].ToString() + "/" + r3["DscComplemento"].ToString() + " " + r3["Complemento"].ToString() + " - " + r3["NomeBairro"].ToString();
TextoAnuncio = r3["TextoAnuncio"].ToString();
if (count % 2 == 0)
{
classe = "EstiloDalinhaGrid";
}
else
{
classe = "EstiloDalinhaAlternativaGrid";
}
retorno.Append("<tr class='" + classe + "'>");
retorno.Append("<td>");
retorno.Append(Imovel_Id);
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append(Endereco);
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append("<textarea id='txtArea'>");
retorno.Append(TextoAnuncio);
retorno.Append("</textarea>");
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append("<input type='checkbox' class='imoveisMarcados' id='" + Imovel_Id + "' />");
retorno.Append("</td>");
retorno.Append("</tr>");
count++;
}
retorno.Append("</table>");
con3.Close();
return new
{
retorno = string.Format(retorno.ToString())
};
i think you have to use Ajax for you to be able to update your data base .
check this link to learn more about ajax with Php (you chose whatever server side langage you'd like)
Ajax with PHP

Categories