How to set byte[] property of ActiveX component from Javascript? - javascript

I'd like to set RTF formatted calendar entries, but don't know how to pass the byte[] to the ActiveX object, i.e. the RTFBody property.
The following code reads the RTFBody property after some content has been set - so reading the byte[] is working, but when I try to write exactly the same content (+ trailing 0) back, neither an U/Int8Array nor a Scripting.Directory works.
Maybe it's possible to workaround with some .NET objects, but I don't know how to instanciate those Non-ActiveX components. An alternative solution shouldn't require to script the formattings, e.g. "go to line 2 and make it bold", i.e. I like to generate the rtf via a template and only paste the result into the calendar object.
I'm aware that this has to be eventually encoded in Windows-1252, but for a start I simply want to see the same bytes to be written successfully. The script is executed within a HTA context - so script security is not an issue.
<html>
<head>
<hta:application id="foo" applicationname="foo" version="1" navigable="yes" sysMenu="yes"></hta>
</head>
<script language="JavaScript" type="text/javascript">
function doit2() {
var rtfBody =
"{\\rtf1\\ansi\\ansicpg1252\\deff0\\nouicompat\\deflang1031{\\fonttbl{\\f0\\fswiss\\fcharset0 Calibri;}}\r\n"+
"{\\*\\generator Riched20 14.0.7155.5000;}{\\*\\mmathPr\\mwrapIndent1440}\\viewkind4\\uc1\r\n"+
"\\pard\\f0\\fs22 bla\\par\r\n"+
"}\r\n";
// https://github.com/mathiasbynens/windows-1252
var rtfBody1252 = rtfBody; // windows1252.encode(rtfBody);
var dict = new ActiveXObject("Scripting.Dictionary");
for (var i = 0; i < rtfBody1252.length; i++) {
dict.add(i, rtfBody1252.charCodeAt(i));
}
dict.add(rtfBody1252.length, 0);
// Alternative setting via U/Int8Array also doesn't work ...
// var buf = new ArrayBuffer(rtfBody1252.length+1);
// var bufView = new Int8Array(buf);
// for (var i=0, strLen=rtfBody1252.length; i<strLen; i++) {
// bufView[i] = rtfBody1252.charCodeAt(i);
// }
// bufView[rtfBody1252.length] = 0;
var myOlApp = new ActiveXObject("Outlook.Application");
var nameSpace = myOlApp.GetNameSpace("MAPI");
var recipient = nameSpace.CreateRecipient("user#host.com");
var cFolder = nameSpace.GetSharedDefaultFolder(recipient,9);
var appointment = cFolder.Items.Add(1);
appointment.Subject = "Subject";
appointment.Location = "Location";
appointment.Start = "22.02.2017 17:00";
appointment.Duration = "120";
appointment.Categories = "deleteme";
appointment.Body = "bla";
var va = new VBArray(appointment.RTFBody).toArray();
var bla = String.fromCharCode.apply(null, va);
document.forms[0].output.value = bla;
// var bla2 = windows1252.decode(bla);
appointment.RTFBody = dict.Items();
appointment.ReminderSet = "true";
appointment.Save();
entryId = appointment.EntryId;
appointment.Display();
delete appointment;
delete cFolder;
delete recipient;
delete nameSpace;
delete myOlApp;
}
</script>
<body>
<form>
<input type="button" onclick="doit2()" value="doit"/>
<textarea name="output" rows="5" cols="50"></textarea>
</form>
</body>
</html>

Related

put a save code in a text box and than change a variable to that save code

I'm back and i tried it but is doesn't work anyone that can help??? i have already put in the save mechanism.
(i had to add extra text so this has nothing to do with the script itself)
this is the code that i used to test the save mechanism.
<!DOCTYPE html>
<html>
<body>
<button onclick="point();">points</button>
<button onclick="upgrade()">upgrade</button>
<script language="javascript">
var pointcount = 0;
var totalcliks = 0;
var upgrades = 0;
function point() {
pointcount++;
totalcliks++;
}
function upgrade() {
upgrades++;
pointcount--;
}
function load() {
var testerload = document.getElementById("savecodetextbox").value;
document.getElementById("saveshow").innerHTML = testerload;
}
var pointcounterclock = setInterval(function() {pointcounter()},100);
function pointcounter(){
document.getElementById("points-screen").innerHTML = pointcount+" points";
document.getElementById("clicktotal").innerHTML = totalcliks+" totalcliks";
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
}
let savecode = "1a1a1"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[1];
updates = codes[2];
pointcount = codes[3];
}
</script>
<h3 id="points-screen"></h3>
<h3 id="clicktotal"></h3>
<h3 id="savecode"></h3>
<textarea name="text_area" id="savecodetextbox" rows="4" cols="40"></textarea> <button onclick="load()">load</button>
<h3 id="saveshow"></h3>
</body>
</html>
I'm going to alter your save code so I don't have to confuse you with regular expressions or funky splits:
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
Which means your save code could look something like: 4a6a9
Do a simple split:
let savecode = "4a5a6"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[0];
upgrades = codes[1];
pointcount = codes[2];
}
As for implementing the variables, reload the game after

Display a waiting gif during a javascript function

I write a script to get a text file, to modify this texter file and then I import the file in our software.
The problem is that the import of the file is very slow (just this part of the script could take more than 1 minute sometime).
I would like to display a waiting gif during this process, so the user can see that the process is running, and he need to wait.
Some precision:
- It's only a javascript file with no html page
- The script is launched with a button in our software and I have access to ActiveXObject if necessary
Here is a sample code :
function importFec()
{
var iOpenDlg = 1;
var sPath = "Deskop";
var sTypes = "Fichier Texte (*.txt)|*.txt";
var sExt = "txt";
//Allow me to select a file in Windows
cheminFEC = fileDialog(iOpenDlg, sPath, sTypes, sExt);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1;
var f1 = fso.OpenTextFile(cheminFEC, ForReading);
var texte = f1.ReadAll();
var tableauFEC = [];
var tableauTest = [];
tableauFEC = texte.split(/\r\n/);
tableauTest = tableauFEC[0].split("\t");
var delimiter = "\t";
if (tableauTest.length == 1)
{
tableauTest = tableauFEC[0].split("|");
var delimiter = "|";
}
var nbColonne = tableauTest.length;
for (var i=0;i<tableauFEC.length;i++)
{
var tab = tableauFEC[i].split(delimiter);
tableauFEC[i] = new Array(25);
for (var j=0;j<nbColonne;j++)
{
tableauFEC[i][j] = tab[j];
}
}
//Make some change in the table to adapt my texte file
//Then create a new texte file C:\\FichierFEC\\FECModifie.txt
createNewFEC(tableauFEC);
var cwfConfiguration = Application.ApplicationInfo("ProgramPath")+"\\Library\\ImportFEC\\ImportFEC23032017.vgl"
var oImport = Import(ipASCII)
oImport.ImportComponents = CWImportComponents.icGeneralLedger
oImport.ASCIILayoutFile = cwfConfiguration
oImport.ASCIIDataFile = "C:\\FichierFEC\\FECModifie.txt"
//This is the function which take a long moment to execute
oImport.RunImport()
}
Thanks for your answer and explanation
I finnaly found another solution.
At the beggining of my script, I launch a .hta file with a GIF and a small texte.
At the end of my script, I close the .hta file
Thanks

Textarea to XML automatize the process with big files

UPDATE: The question was resolved by me, enlighted by some busy guy... :)
I have an HTML who contains a textarea called "request", I created the JS code below to transform any text into an xml who fit the needs of some business requirements, the problem is the transformation occurs one time in the first line only, I mean, I clicked on "transform txt2xml" button and only transform the first line pasted in the textarea, and did not continue with the second, third, etc.
I have to process a file who contains 300 or less elements and I want to automatize a bit the process.
Could be any way to paste all elements in the textarea, then separate each line, transform each separated element into xml one after the other in the same textarea?
function ss2xml_v5() {
var headerPart = "<?xml version=\"1.0\" encoding=\"utf-8\"?><A><B><C>";
var body_1 = "<1><2>";
var body_2 = "</2><3><4>";
var body_3 = "</4><5>";
var body_4 = "</5><6>";
var body_5 = "</6></3><7>";
var body_6 = "</7></6></3>";
var footerPart = "</1></C></B></A>";
var lines = $('textarea[name=request]').val().split('\n');
$.each(lines, function(){
for (var i = 0; i < this.length;i++) {
var ID = this.substring(0, 17);
var ID = ID.replace(/^\s+|\s+$/g,'')
var NAME = this.substring(18, 36);
var NAME = NAME.replace(/^\s+|\s+$/g,'');
var LAST_NAME = this.substring(37, 47);
var LAST_NAME = LAST_NAME.replace(/^\s+|\s+$/g,'');
var PHONE = this.substring(48, 58);
var PHONE = PHONE.replace(/^\s+|\s+$/g,'');
var NUMBER = this.substring(59, 62);
var NUMBER = NUMBER.replace(/^\s+|\s+$/g,'');
//Set XML //
var xmlToSet = headerPart+body_1+ID+body_2+NAME+body_3+LAST_NAME+body_4+PHONE+body_5+NUMBER+body_6+footerPart+'\n\n';
}
//Print XML
document.getElementById("response").value += xmlToSet;
});
}
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Press button to transform text to xml:<br/>
<button onClick="ss2xml_v5();">SS to XML</button>
<br/><br/>
<textarea name="request" id="request">AA_Address_AA John Good 2025547416 02
BB_Address_BB John Good 2025547416 02</textarea>
<br/><br/>
<textarea name="response" id="response"></textarea>
</body>
</html>
Some code in the correct position to: Separate each line in the text, then loop the function who transform the text to xml...
var lines = $('textarea[name=request]').val().split('\n');
$.each(lines, function(){
for (var i = 0; i < this.length;i++) {
... ...
}
});

calculating memory usage in javascript

I have written a program in Javascript which reads numbers from a file ,sorts them and then writes them back to the file.But I not able able to find a suitable method or tool to get the memory usage of the program.(something like Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); in java).If someone could please give me a lead I would be thankful.
Here is the code.
<html>
<script>
var oRequest;
var data=new Array();
var b= new Array();
var j
var k;
var temp;
var temp1;
if(document.all) {
oRequest = new ActiveXObject("Microsoft.XMLHTTP")
}
else {
oRequest = new XMLHttpRequest();
}
oRequest.open("GET", "file:///C:/numbers.txt", true);
oRequest.send(null);
numbers= oRequest.responseText.split("\n");
for (var i = 0;i<(numbers.length-1);i++)
{
numbers[i] = parseInt(numbers[i],10);
}
var d = new Date();
var start = d.getTime();
for(var i=0;i<numbers.length;i++)
{
for(j=0;j<(numbers.length-1);j++)
{
if(numbers[j]>numbers[j+1])
{
temp=numbers[j+1];
numbers[j+1] = numbers[j];
numbers[j] = temp;
}
}}
var g = new Date();
var end =g.getTime();
var diff=(end-start);
</script>
<script>
function WriteFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.CreateTextFile("C:\\BubbleJS.txt", true);
for(i=0;i<5000;i++)
{
fh.WriteLine(numbers[i]);
}
fh.WriteLine("\n");
fh.WriteLine("The time required for sorting is "+diff+" Milliseconds");
fh.Close();
}
</script>
<form>
<body background="Bubble.png">
<h1> </h1>
<input type="button" onClick='alert("Directing to Home Page"); window.location = "Home Page.html"' value="Back to Home Page">
<input type="button" onClick=WriteFile(); value="Begin Sorting!"
style="width: 174px; margin-left: 0px">
</form>
</html>
The JavaScript language and core libraries do not provide a way to view or calculate the memory usage of the runtime.
Your only hope is to find a library (e.g. ActiveX plugin, etc.) which can do it for you. Note that the developer tools of some popular web browsers (Chrome, Firefox, possibly others) provide a memory profiling graphical interface, so perhaps there are programmatic hooks you can find; however, if they exist they almost definitely won't work cross-browser.

How do i solve these issues?

I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)

Categories