Reference error: "Workbook" is not defined - javascript

I wanna use the next java script code:
function dumpVal(file) {
if (file !=null) {
var wb = new Workbook.create(file);
var sheet = wb.getSheet("Tabelle1");
for (myrow = 1; !isCellEmpty(sheet, myrow, 0); myrow++) {
dataset.setColumnValue("A",getNumericValue(sheet,myrow,0));
dataset.storeResultRow();
}
}
return;
}
but when I am compiling it I receive the next error message: ReferenceError: "Workbook" is not defined.
Can someone to tell me what am I doing wrong?

You recieve the error with the followig line of code:
var wb = new Workbook;
At the point where you create the workbook (new Workbook) you refer to a class called "Workbook". At this point your script dont have a class called Workbook it.
Solution:
You should check your scripts if the class is included and its naming.
Maybe the class is initialized later!
For debug purposes you can try to create the class a line before:
class Workbook{ }
If you recieve an error now because Workbook needs a method called "create", you know that the class is just missing.

I assume that you want to parse excel file from your web application, the library that you are using is for developing add-ins for excel not web application :
Excel JavaScript API programming overview
This article describes how to use the Excel JavaScript API to build add-ins for Excel 2016. It introduces key concepts that are fundamental to using the APIs, such as RequestContext, JavaScript proxy objects, sync(), Excel.run(), and load(). The code examples at the end of the article show you how to apply the concepts.
source :
https://dev.office.com/docs/add-ins/excel/excel-add-ins-javascript-programming-overview
If you want to parse Excel in your web application I suggest to use this library :
https://github.com/SheetJS/js-xlsx
I did not use it so I cant garanty it, but you can look for similar librarys.

Related

Unable to create / save a word document with OpenXml with angular / typescript / javascript

I'm unable to create a document with Xml (OpenXml) in my angular - typescript application - file gets created but opened shows "found unreadable content in document..." error. When I open the file in notepad, all I see is the Xml.
let blob = new Blob([openXmlString)], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
fileSaverService.save(blob, "Document.docx");
Using the same xml, I can create a document that actually works in C# using this code, trying to replicate this in my angular - typescript app
using (var doc = WordprocessingDocument.FromFlatOpcString(openXmlString))
{
doc.SaveAs("Document.docx").Close();
}
Could someone please let me know what I may be missing?
Thanks in advance.

Call VBScript from Node.js

To answer a request from the client, Node.js needs to export charts from Excel files in images into a repository.
I chose to use a VBA Macro because I don't think I have other solutions.
The VBA code is working properly (when I call it manually) but I wish I could connect it with Node.js events.
VBScript allows me to call a VBA Macro in my script.vbs file :
Option Explicit
On Error Resume Next
CallVBA
Sub CallVBA()
Dim ApplicationExcel
Dim ClasseurExcel
Set ApplicationExcel = CreateObject("Excel.Application")
Set ClasseurExcel = ApplicationExcel.Workbooks.Open("H:/macrosVBA.xlsm")
ApplicationExcel.Visible = False
ApplicationExcel.Run "ChartUpload"
ApplicationExcel.Quit
Set ClasseurExcel = Nothing
Set ApplicationExcel = Nothing
End Sub
My problem now is to run the VBScript in the JavaScript file :
var objShell = new ActiveXObject("WScript.shell");
objShell.run('H:/script.vbs');
I get the error :
ReferenceError: ActiveXObject is not defined
Adding win32ole and winax doesn't change anything, they don't seem to work anymore.
I'm looking for your help to have another solution or to fix my error with ActiveXObject.
Thanks in advance
Your Node.js is probably 64bit, whilst your Office/Excel is probably the 32bit version.
You need to run the 32bit VBScript interpreter in order to access the 32bit CreateObject("Excel.Application")
const { spawn } = require("child_process");
const bat = spawn("C:\\Windows\\SysWOW64\\wscript.exe", ["H:\\script.vbs"]);

How can I access Python code from JavaScript in PyQT 5.7?

I used to do it by attaching an object
self.page().mainFrame().addToJavaScriptWindowObject("js_interface", self.jsi)
In 5.7 I do:
self.page().setWebChannel(self.jsi)
But I understandibly get a JavaScript error when I try to access exposed functions:
js: Uncaught ReferenceError: js_interface is not defined
Googling around I found that I should use qwebchannel.js, but I couldn't find the file or instructions on how to use it anywhere (there was some info, but only in some examples provided when installing QT, not PyQT).
You can include qwebchannel.js into html page using the script tag:
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
Then, create a web channel on the python side:
from PyQt5.QtCore import QObject, pyqtSlot
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView
class CallHandler(QObject):
#pyqtSlot()
def test(self):
print('call received')
view = QWebEngineView()
channel = QWebChannel()
handler = CallHandler()
channel.registerObject('handler', handler)
view.page().setWebChannel(channel)
JS code that interacts with the web channel:
new QWebChannel(qt.webChannelTransport, function (channel) {
window.handler = channel.objects.handler;
window.handler.test();
});
Take a look at this page. It contains a useful example (in c++ but easily translatable into python).
First of all, you have to use a websocket to communicate from html to your app and viceversa.
Then you can set up your QWebChannel.
I think it's big drawback, JS cannot directly communicate with Python in PyQT5.9+ like it used to with "addToJavaScriptWindowObject" command.
And using websockets... what if Firewall is heavy and all ports blocked.
I guess I will rely on simple callback (long pooling type from Python to JS checking for changes/commands) method and no QTWebChannel usage.

How to read and write to a file (Javascript) in ui automation?

I want to identify few properties during my run and form a json object which I would like to write to a ".json"file and save it on the disk.
var target = UIATarget.localTarget();
var properties = new Object();
var jsonObjectToRecord = {"properties":properties}
jsonObjectToRecord.properties.name = "My App"
UIALogger.logMessage("Pretty Print TEST Log"+jsonObjectToRecord.properties.name);
var str = JSON.stringify(jsonObjectToRecord)
UIALogger.logMessage(str);
// -- CODE TO WRITE THIS JSON TO A FILE AND SAVE ON THE DISK --
I tried :
// Sample code to see if it is possible to write data
// onto some file from my automation script
function WriteToFile()
{
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/Volumes/DEV/test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
AND
function WriteFile()
{
// Create an instance of StreamWriter to write text to a file.
sw = new StreamWriter("TestFile.txt");
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
sw.Close();
}
But still unable to read and write data to file from ui automation instruments
Possible Workaround ??
To redirect to the stdout if we can execute a terminal command from my ui automation script. So can we execute a terminal command from the script ?
Haven't Tried :
1. Assuming we can include the library that have those methods and give it a try .
Your assumptions are good, But the XCode UI Automation script is not a full JavaScript.
I don't think you can simply program a normal browser based JavaScript in the XCode UI Automation script.
set fso = CreateObject("Scripting.FileSystemObject");
Is not a JavaScript, it is VBScript which will only work in Microsoft Platforms and testing tools like QTP.
Scripting.FileSystemObject
Is an ActiveX object which only exists in Microsoft Windows
Only few JavaScript functions like basic Math, Array,...etc..Are provided by the Apple JavaScript library, so you are limited to use only the classes provided here https://developer.apple.com/library/ios/documentation/DeveloperTools/Reference/UIAutomationRef/
If you want to do more scripting then Try Selenium IOS Driver http://ios-driver.github.io/ios-driver/
Hey so this is something that I was looking into for a project but never fully got around to implementing so this answer will be more of a guide of what to do than step by step copy and paste.
First you're going to need to create a bash script that writes to a file. This can be as simple as
!/bin/bash
echo $1 >> ${filename.json}
Then you call this from inside your Xcode Instruments UIAutomation tool with
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout("your/script/path", ["Object description in JSON format"], 5);
Then after your automation ends you can load up the file path on your computer to look at the results.
EDIT: This will enable to write to a file line by line but the actual JSON formatting will be up to you. Looking at some examples I don't think it would be difficult to implement but obviously you'll need to give it some thought at first.

Is there a way to AutoFormat (Javascript) code in TestComplete?

So similar to ALt-Shift-F in Netbeans, is there a to do this right in the ide in TestComplete? Not sure if this is possible or if anyone can think of a workaround to autoFormat without leaving the TestComplete window.
I'm trying to get the below solution to work with http://jsbeautifier.org/ for javascript / Jscript code in TestComplete.
Thanks
Great question!
There is no built-in function for that. So, we should not expect any solution to be 100% convenient - it is just not a simple task to modify the current script editor contents (if at all possible). So, whatever you do, it will still be some kind of compromise.
In general, the task is three-fold:
Get the current unit code.
Format the code.
Put the code back to the unit.
According to my understanding, items 1 and 3 can be accomplished only by creating a TestComplete plug-in - accessing editors for project nodes is not an easy thing.
UPDATE: silly me! There is a way to access the script editor code - I've updated the below part.
What will help us avoid switching to a different app, are the Script Extensions:
We create a custom Checkpoint in the form of a Script Extension, and install it to TestComplete. As a result, we get a button on the toolbar that we can click to invoke our code.
In the design time action, we call some code that reads the editor contents, then uses external code formatting functionality, and replaces the editor contents with the formatted code.
It would extremely interesting to see the implementations other TestComplete users can suggest! As a start, I am posting a solution that includes using an external web site to format VBScript code (http://www.vbindent.com/). I know that the starter of the post is probably using JScript, but I have not found a JScript formatter yet.
My solution is a simple Script Extension. I can't post a file here, so I will post the code of the two Script Extension files:
Description file:
<!-- Description.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<ScriptExtensionGroup>
<Category Name="Checkpoints">
<ScriptExtension Name="VBScript Code Indent" Author="SmartBear Software" Version="0.1" HomePage="smartbear.com">
<Script Name="VBIndent.js">
<DesignTimeAction Name="Indent Current VBScript Unit" Routine="DesignTimeExecute"/>
</Script>
<Description>
Indents VBScript code in the currently active unit.
</Description>
</ScriptExtension>
</Category>
</ScriptExtensionGroup>
Code file:
// VBIndent.js
function DesignTimeExecute()
{
if (CodeEditor.IsEditorActive)
{
var newCode = IndentVBSCode_Through_VBIndent(CodeEditor.Text);
if (null == newCode)
return;
CodeEditor.Text = newCode;
}
}
function IndentVBSCode_Through_VBIndent(codeToIndent)
{
var URL_VBIndent = "http://www.vbindent.com/?indent";
var httpObj = Sys.OleObject("MSXML2.XMLHTTP");
httpObj.open("POST", URL_VBIndent, false);
httpObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpObj.send("thecode=" + escape(codeToIndent));
var responseText = httpObj.responseText;
// Extract the indented code from the response
var rx = /<textarea name=\"thecode\".*?>((.*\n)*?)<\/textarea>/;
matches = rx.exec(responseText);
if (null == matches)
{
return null;
}
codeIndented = matches[1];
return codeIndented;
}
After you create these files, and put them to something like "\Bin\Extensions\ScriptExtensions\VBIndent", and click "File | Install Script Extensions | Reload", you will see a new "Indent Current VBScript Unit" item in the custom checkpoints drop-down button on the Tools toolbar. Clicking the element will format the VBScript code in the currently active editor.
So, this is to give a clear idea of what a solution can look like. Better suggestions are welcome! Share your thoughts!
FYI
I've done. Based on your posts.
JSFormat.tcx
https://drive.google.com/uc?export=download&id=0B1x_73bHRc2Jcm8wbTJ2dUpZQTQ
To install the extension copy attached file JSFormat.tcx to C:\Program Files (x86)\SmartBear\TestComplete 10\Bin\Extensions\ScriptExtensions
To use view next image:
https://drive.google.com/uc?export=download&id=0B1x_73bHRc2Jc3RuLXFpTnlCSnc
Regards

Categories

Resources