Java Script - export and import - javascript

I am developing a Java script Missing Part evaluation tool for Excel-Add-In. For this purpose firstly I developed a class Part.js in Microsoft Visual Studio 2015:
export class Part {
function Part(number) {
if (this instanceof Part) {
this.number = number;
} else {
return new Person(firstName)
}
}
};
module.exports = Part;
Additionally, I wrote the class MissingPartSummary .js
(function () {
"use strict";
import * as Part from 'Part';
Office.initialize = function (reason) {
$(document).ready(function () {
//app.initialize();
$('#create-difference-maps').click(createDifferenceMaps)
});
};
function createDifferenceMaps() {
Excel.run(function (context) {
var part = new Part("N1022181");
var dataSheet = context.workbook.worksheets.getActiveWorksheet();
//dataSheet.getRange("A1:C3").values = 7;
var rangeAddress = "F11 : J12";
var range = dataSheet.getRange(rangeAddress);
//range.load('cellCount');
range.load('values');
return context.sync().then(function () {
//console.log("Number of cells: " + range.cellCount);
console.log("Text: " + range.values);
});
context.sync();
}).catch(function (error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.debug("Debug info:" + JSON.stringify(error.debugInfo));
}
});
}
})();
Unfortunately, if I try to execute this code, MS Visual Studio says that there is a syntax error in line 4. The Import of Part fails. Why? Both files Part.js and MissingPartSummary.js are in the same folder ../App/Home/
There is the error message from Visual Studio that I get, if I try to start the Visual Studio Project:

I've already solved the problem myself. The point about Javascript there exists two types "text/javascript" and "module". Because I've defined type="text/javascript" in MissingPartSummary.html, it lead to the import error. If I change the type to module, there will be no error. But there will be problems on other places. So I decided in favour of text/javascript rather than module. After this I changed Part.js.
var p = p || {};
p.Part = function (row) {
this.bestellstatus = row[0];
this.bezeichnung = row[1];
this.teilenummer = row[2];
this.teilenummer = this.teilenummer.concat(row[3]);
this.teilenummer = this.teilenummer.concat(row[4]);
this.teilenummer = this.teilenummer.concat(row[5]);
this.teilenummer = this.teilenummer.concat(row[6]);
this.prozesssteurer = row[19];
this.bemerkung = row[22];
};
p.Part.prototype = (function () {
var _isValid = function () {
var valid = false;
if (typeof this.bestellstatus == 'string') {
valid = (this.bestellstatus != "Info");
}
if (typeof this.teilenummer == 'string') {
valid = valid & (this.teilenummer != "");
}
return valid
};
return {
isValid: _isValid
};
}());
In the next step, I wrote
<script src="Part.js" type="text/javascript"> </script>
in MissingPartSummary.html. By this way, I can use the Part.js in MissingPartSummary.js in the following way.
var rangeAddressA = "D8 : Z30";
var rangeA = dataSheet.getRange(rangeAddressA);
rangeA.load(['values', 'text', 'rowCount', 'columnCount']);
return context.sync().then(function () {
var text = rangeA.text;
var numOrRows = rangeA.rowCount;
for (var i = 1; i < numOfRows; i++) {
var part = new p.Part(text[i]);
}
});

Since you're using ES6 Modules (export class Part and import * as Part from 'Part';), you don't need to specify the module exports in Part.js. So you shouldn't need the last line, module.exports = Part;.
Furthermore, in MissingPartSumary.js, you'll need to specify the relative path to Part.js in your import statement. Instead of import * as Part from 'Part';, it should be import * as Part from './Part.js';.

Related

Fetch operation is a lot slower when calling it from a JavaScript code then when calling it from react-native

So I have developed an app that crawl data from a some html sites.
I wanted to keep the parser code separated from the app. So when I want to make changes to a parser I wont have to republish my app. So I could have my parsers JS files on Github for example and then let my app download and parse those parsers.
I have been able to accomplish that but then I got a weird problem. When calling fetch from the code in react-native(typescript) is a lot faster then when I call those fetch operation from the JavaScript.
Why is that? I am using the same HttpClient object the different is that I am calling it from different place.
Here is one of the Parser
Here is the parser translator.
private async loadParser() {
try {
this.script = await HttpClient.GetText(this.onlineParserURI);
if (this.script && this.script.length >= 5) {
this.searchFunction = new Function(...this.parameter, "filter", "page", this.script + "\n return search(filter, page);");
this.getNovelFunction = new Function(...this.parameter, "novelUrl", this.script + "\n return getNovel(novelUrl);");
this.latestFunction = new Function(...this.parameter, "page", this.script + "\n return latest(page);");
this.getChapterFunction = new Function(...this.parameter, "url", this.script + "\n return getChapter(url);");
var detaliFunc = new Function(...this.parameter, this.script + "\n return parserDetali();");
var item = detaliFunc(...this.types); // the constructor eg name, url etc
this.url = item.url;
this.latestUrl = item.latestUrl;
this.searchUrl = item.searchUrl;
this.id = item.id;
this.parserLanguage = item.parserLanguage;
this.name = item.name;
this.panination = item.panination;
this.searchPagination = item.searchPagination;
this.icon = item.icon;
this.parserSearchSettings = item.parserSearchSettings;
this.detaliItemType = item.detaliItemType;
this.onlineDefaultFilter = item.defaultFiter;
this.onlineSections = item.sections;
Object.assign(this, item); // add the extra fields
this.state = "ready";
}
else
this.state = "failed";
} catch (error) {
console.log(error);
this.state = "failed";
}
return this;
}
And here is how I call the methods in the parser
async latest(page: number): Promise <LightItem[]> {
try {
if (this.latestFunction)
return await this.latestFunction(...this.types, page);
} catch (error) {
console.log(error);
}
return [];
}
Here is the default types and parameters that I import
this.types = [this,
Chapter,
LightItem,
Filter,
DetaliItem,
ParserSearchSettings,
labelValue,
DetaliItemType,
Section,
NovelReviews,
HttpClient,
]
this.parameter: Array <string> = [
"parser",
"Chapter",
"LightItem",
"Filter",
"DetaliItem",
"ParserSearchSettings",
"labelValue",
"DetaliItemType",
"Section",
"NovelReviews",
"HttpClient"
];
This is the method that takes to long
There is 10 calls, the first 3 calls are fast then it gets slow for some reasion.
note: the methods (await HttpClient.getHtml(url)) get html is what taking long, it gets stuck for sometimes
async function getChapters(novelUrl) {
var page = 1;
var result = [];
while (page > 0) {
var url = novelUrl + "/page-" + page;
var container = parser.jq(await HttpClient.getHtml(url)).find(".chapter-list a");
if (!items.hasElements()) {
page = 0;
break;
}
var resultA = items.map((x) => {
var ch = new Chapter(x.attr("title").text(), x.attr("href").url());
if (result.find((a) => a.chapterUrl == ch.chapterUrl && a.name == ch.name) === undefined)
return ch;
return undefined;
}, [])
if (resultA.length <= 0) {
page = 0;
break;
}
resultA.forEach((x) => {
result.push(x);
});
page++;
}
return result;
}
Any Idea why this is happening?

JavaScript Web Resource issue: getGrid() suddenly started failing

I have a few different JavaScript web resources that use the getGrid(), all of which started failing this week after I enabled the 2020 Wave 1 Updates in D365. The error message shows:
"Error occurred :TypeError: Unable to get property 'getGrid' of undefined or null reference"
Here is my code:
function GetTotalResourceCount(executionContext) {
console.log("function started");
var execContext = executionContext;
var formContext = executionContext.getFormContext();
var resourceyescount = 0;
try {
var gridCtx = formContext._gridControl;
var grid = gridCtx.getGrid();
var allRows = grid.getRows();
var duplicatesFound = 0;
//loop through rows and get the attribute collection
allRows.forEach(function (row, rowIndex) {
var thisRow = row.getData().entity;
var thisRowId = thisRow.getId();
var thisResource = "";
var thisResourceName = "";
var thisResourceID = "";
console.log("this row id=" + thisRowId);
var thisAttributeColl = row.getData().entity.attributes;
thisAttributeColl.forEach(function (thisAttribute, attrIndex) {
var msg = "";
if (thisAttribute.getName() == "new_resource") {
thisResource = thisAttribute.getValue();
thisResourceID = thisResource[0].id;
thisResourceName = thisResource[0].name;
console.log("this resource name=" + thisResourceName)
}
});
var allRows2 = formContext.getGrid().getRows();
//loop through rows and get the attribute collection
allRows2.forEach(function (row, rowIndex) {
var thatRow = row.getData().entity;
var thatRowId = thatRow.getId();
var thatAttributeColl = row.getData().entity.attributes;
var thatResource = "";
var thatResourceName = "";
var thatResourceID = "";
thatAttributeColl.forEach(function (thatAttribute, attrIndex) {
if (thatAttribute.getName() == "new_resource") {
thatResource = thatAttribute.getValue();
thatResourceID = thatResource[0].id;
thatResourceName = thatResource[0].name;
if (thatResourceID == thisResourceID && thatRowId != thisRowId) {
duplicatesFound++;
var msg = "Duplicate resource " + thatResource;
console.log("duplicates found= " + duplicatesFound);
}
}
});
});
});
if (duplicatesFound > 0) {
console.log("duplicate found");
Xrm.Page.getAttribute("new_showduplicateerror").setValue(true);
Xrm.Page.getControl("new_showduplicateerror").setVisible(true);
Xrm.Page.getControl("new_showduplicateerror").setNotification("A duplicate resource was found. Please remove this before saving.");
} else {
Xrm.Page.getAttribute("new_showduplicateerror").setValue(false);
Xrm.Page.getControl("new_showduplicateerror").setVisible(false);
Xrm.Page.getControl("new_showduplicateerror").clearNotification();
}
} catch (err) {
console.log('Error occurred :' + err)
}
}
Here is a separate web resource that triggers the function:
function TriggerSalesQDResourceCount(executionContext){
var formContext = executionContext.getFormContext();
formContext.getControl("s_qd").addOnLoad(GetTotalResourceCount);
}
Any ideas how I can fix this? Is this a known issue with the new D365 wave 1 update?
Thanks!
This is the problem with unsupported (undocumented) code usage, which will break in future updates.
Unsupported:
var gridCtx = formContext._gridControl;
You have to switch to these supported methods.
function doSomething(executionContext) {
var formContext = executionContext.getFormContext(); // get the form Context
var gridContext = formContext.getControl("Contacts"); // get the grid context
// Perform operations on the subgrid
var grid = gridContext.getGrid();
}
References:
Client API grid context
Grid (Client API reference)

Export Function and Prototype from one file to another

I need to export all things (function and prototype) from one file (name:config.js) to another file (name:index.js) that will use them
I need to create ws in Javascript with Node.js on "Sublime",
and the error said when in ran my code at cmd that 'plus' in not defined.
code :(config.js)-first file
var Ranking=function(){
this.rank= 5;
events.EventEmitter.call(this);
};
var printName=function(){
console.log("spa name is: sea spa");
};
Ranking.prototype.plus =function(sum){
this.rank += sum;
this.emit("change");
};
Ranking.prototype.minus =function(sum){
this.rank -= sum;
this.emit("change");
};
var addingStar=function(){
console.log("the ranking is: " + this.rank);
};
var changeNoZero=function(){
if(this.rank<0){
console.log("bad reviews " + this.rank);
}
};
module.exports=Ranking;
index.js -second file
var events = require('events');
var util = require('util');
var Ranking = require('./config');
var ranking = new Ranking();
util.inherits(Ranking ,events.EventEmitter);
ranking.on("change",printName);
ranking.on("change",addingStar);
ranking.on("change",changeNoZero);
ranking.plus(1);
ranking.minus(6);
ranking.plus(3);
You can try something as below :
Config.js file ----
var defaultValues = module.exports
defaultValues.GetApiURL = function () {
var apiURL = "http://localhost:1000/api/"
return apiURL;
}
index.js ----
var defaultValues = require('./config.js');
var apiUrl= defaultValues.GetApiURL();

Javascript (node) error: Unexpected token function

I am trying the learn younode workshop, the make it modular step to be precise. I wrote the code in the link and am getting the "error in the title". I have checked brackets and parenthesis but can not seem to find where i got it wrong. Any help would be appreciated (i just started with node).
My code is this and you can find it also at this link:
http://pastebin.com/G8x2GH7h
module.exports = function (directoryPath, extention, function(error, arrayOfNames) {
var fs = require('fs');
var path = require('path');
var FileNamesArray = [];
fs.readdir(directoryPath,function (error,list){
list.forEach(function (file) {
if (path.extname(file) === '.' + extention) {
FileNamesArray.push(file);
}
});
});
return FileNamesArray;
}){
return ArrayOfNames;
}
Your problem is that you are declaring function inside of function declaration.
It should be like this
exports.functionName = function() {
// your code
};
And then In you app.js you can use
var abc = require('path to file name');
abc.functionName();
example
// square.js
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
// app.js
var square = require("./square.js");
var mySquare = square(2);
console.log('The area of my square is ' + mySquare.area());
Remove the anonymous function inside your function and hopefully it should work for you.
You are missing the title of you function in the export section, should be in this way:
module.exports = {
getFileNamesList : function (directoryPath, extention, function(error, arrayOfNames) {
var fs = require('fs');
var path = require('path');
var FileNamesArray = [];
fs.readdir(directoryPath,function (error,list){
list.forEach(function (file) {
if (path.extname(file) === '.' + extention) {
FileNamesArray.push(file);
}
});
});
return FileNamesArray;
}){
return ArrayOfNames;
}
}

Firefox Addon. How to determine is the element of the array a file or a directory?

I am trying to get a list of files and directories in Firefox Add-ons.
var io_file = require("sdk/io/file");
var HomePath = require('sdk/system').pathFor("Home");
var list_files = io_file.list(HomePath);
How to determine is the element of the array a file or a directory?
Do console.log('debug:', list_files) and then press Ctrl + Shift + J and then click on the link next to list_files, then it opens in varaible viewer and you can explore it there.
like this, notice the "Browser Console" box and see the "Properties" section below, tha comes up when I clicked on "[object MouseEvent]"s you see in the logs above.
const fileIO = require("sdk/io/file");
let path = "/Users/Work/";
let list = fileIO.list(path);
for (i = 0; i < list.length; i++) {
let item = fileIO.join(path, list[i]);
if (fileIO.isFile(item)) {
console.log(item + " is a file");
}
else {
console.log(item + " is a directory");
}
}
or
const {Cu} = require("chrome");
const {TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
var iterator = new OS.File.DirectoryIterator('/home/user');
var promise = iterator.forEach(
function onEntry(entry) {
if (entry.isDir) { // is Directory
console.log(JSON.stringify(entry));
} else { // is File
console.log(JSON.stringify(entry));
}
}
);
promise.then(
function onSuccess() {
iterator.close();
return subdirs;
},
function onFailure(reason) {
iterator.close();
throw reason;
}
);

Categories

Resources