I'm trying to delete a content control in Word and I'm going through these docs: https://dev.office.com/reference/add-ins/word/contentcontrol
This is my code:
let mycc = context.document.contentControls.getByTag('mycc');
if (mycc) {
context.load(mycc, 'text');
context.sync().then(() => {
mycc.items[0].delete(true);
context.sync().then(() => { ... })
})
}
No error is thrown and the code inside the inner most sync works (inserting another content control).
What am I doing wrong?
EDIT: Found the issue. The content control was indeed being deleted, but I wanted to delete the content, as well. Instead of passing true to delete, I should have passed false.
I'm unable to reproduce the issue that you've described. Given that the code that you've posted does not include any error-handling logic, I'd suspect that perhaps an error is silently being thrown, but you're not detecting it.
The following code snippet successfully deletes the first content control that has the tag mycc, and includes a catch statement that handles any error which might occur inside of the Word.run.
Word.run(function (context) {
var myContentControls = context.document.contentControls.getByTag("mycc");
if (myContentControls) {
context.load(myContentControls, "text");
return context.sync()
.then(function () {
myContentControls.items[0].delete(true);
return context.sync()
.then(function () {
console.log("Done!");
});
});
}
}).catch(OfficeHelpers.Utilities.log);
Related
I am trying to check states after sending requests to the server by using axios. I designed the server that if you submitted the form with an empty input, you will get an error. If you can see in the code, I have tried to check the states in finally block but it is not working properly. Like when I submitted the form initially with no inputs, the console log displays no errors and when I try to submit the form with the inputs, it doesn't display anything in the console. I just want to check if there is an error with the request because I want to run a function between them.
The server I used is live and running and you can get the data/submitted form by changing the URL into /getUser
Code here: https://codesandbox.io/s/quizzical-danny-dv1l7?file=/src/App.js
It doesnt works like that.
const [error, setError] = useState("");
error is the initial value (empty string). In dont realy knows how useState is working but, error is a string so it s a value, not a reference. There is no way this variable get updated it the finaly block.
The simple answer is you are setting your state inside the function and then trying to read it as your "current state". Try this instead...
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post("https://testing-name-app.herokuapp.com/create", {
first,
last
});
} catch (error) {
console.log("error found");
return setError(error.response.data.errorMessage);
}
// be CAREFUL with this pattern! This just means the request came back
// with no errors, but there may be a message from your call that
// contained an error from your db/server etc
return console.log("no errors");
};
And here's a way to quickly see what's going on in your call...
const handleSubmit = async (e) => {
e.preventDefault();
let res
try {
res = await axios.post("https://testing-name-app.herokuapp.com/create", {
first,
last
});
} catch (error) {
res = error
console.log("error found");
setError(error.response.data.errorMessage);
}
finally {console.log('res: ', res)}
};
I made a script which inserts all the objects from a JSON file into my DB collection, and a script that deletes everything from the same collection. The delete one works fine, however, the insert one only inserts the first object of the JSON file. I've required FS, I've parsed the file as JSON, hell, it inserts the first one properly. Also checked my JSON file, no problems with it, all the curly brackets and commas are where they're supposed to be. The error, for some reason, is undefined? Any help is greatly aprreciated.
//IMPORT DATA INTO DATABASE
const importData = async () => {
try {
await Tour.create(tours);
console.log('Data successfully loaded!');
} catch {
console.log(err);
}
process.exit();
};
//DELETE ALL DATA FROM COLLECTION
const deleteData = async () => {
try {
await Tour.deleteMany();
console.log('Data successfully deleted!');
} catch {
console.log('Error!');
}
process.exit();
};
I actually got it to work. Rewrote the import script into an if else, and the error showed "duplicate indexes/keys" in my DB. So I simply ran db.collection.dropIndexes() before importing, and it works great now!
I'm writing a script that is intended to load some stuff from .txt files and then perform multiple ( in a loop) requests to a website with node.js` browser emulator nightmare.
I have no problem with reading from the txt files and so no, but managing to make it run sync and without exceptions.
function visitPage(url, code) {
new Promise((resolve, reject) => {
Nightmare
.goto(url)
.click('.vote')
.insert('input[name=username]', 'testadmin')
.insert('.test-code-verify', code)
.click('.button.vote.submit')
.wait('.tag.vote.disabled,.validation-error')
.evaluate(() => document.querySelector('.validation -error').innerHTML)
.end()
.then(text => {
return text;
})
});
}
async function myBackEndLogic() {
try {
var br = 0, user, proxy, current, agent;
while(br < loops){
current = Math.floor(Math.random() * (maxLoops-br-1));
/*...getting user and so on..*/
const response = await visitPage('https://example.com/admin/login',"code")
br++;
}
} catch (error) {
console.error('ERROR:');
console.error(error);
}
}
myBackEndLogic();
The error that occurs is:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'webContents' of undefined
So the questions are a few:
1) How to fix the exception
2) How to make it actually work sync and emulate everytime the address ( as in a previous attempt, which I didn't save, I fixed the exception, but the browser wasn't actually openning and it was basically skipped
3) (Not so important) Is it possible to select a few objects with
.wait('.class1,.class2,.validation-error')
and save each value in different variables or just get the text from the first that occured? ( if no any of these has occurred, then return 0 for example )
I see a few issues with the code above.
In the visitPage function, you are returning a Promise. That's fine, except you don't have to create the wrapping promise! It looks like nightmare returns a promise for you. Today, you're dropping an errors that promise returns by wrapping it. Instead - just use an async function!
async function visitPage(url, code) {
return Nightmare
.goto(url)
.click('.vote')
.insert('input[name=username]', 'testadmin')
.insert('.test-code-verify', code)
.click('.button.vote.submit')
.wait('.tag.vote.disabled,.validation-error')
.evaluate(() => document.querySelector('.validation -error').innerHTML)
.end();
}
You probably don't want to wrap the content of this method in a 'try/catch'. Just let the promises flow :)
async function myBackEndLogic() {
var br = 0, user, proxy, current, agent;
while(br < loops){
current = Math.floor(Math.random() * (maxLoops-br-1));
const response = await visitPage('https://example.com/admin/login',"code")
br++;
}
}
When you run your method - make sure to include a catch! Or a then! Otherwise, your app may exit early.
myBackEndLogic()
.then(() => console.log('donesies!'))
.catch(console.error);
I'm not sure if any of this will help with your specific issue, but hopefully it gets you on the right path :)
I have attached a screenshot of what I am trying to do. This is so basic yet so frustrating. I have to run a data parse after retrieving the array of objects from the first method being called but I can't add my method to the one inside ngOnInit or directly after it inside ngOnInit. Either way the method just simply doesn't run. Any ideas?
Image
ngOnInit() {
this.getSiteContent(this.route.snapshot.params['id']);
//Doesnt work
this.addUpdatedPages();
}
//in use
getSiteContent(id) {
this.http.get('/site-content/'+id).subscribe(data => {
this.siteContent = data;
});
//Doesn't show..
console.log('End of getSiteContent');
}
addUpdatedPages(){
//Doesn't show
console.log('Adding pages...');
for (var i = 0; i < this.siteContent.length; i++) {
this.checkNull(this.siteContent[i].SiteID, this.siteContent[i].SitePageID);
console.log(this.nullCheck[0].SiteID);
if (this.nullCheck.length > 0) {
this.siteContent[i].SitePageContent = this.nullCheck[0].SitePageContent;
}
}
}
Everything points to an unhandled exception when you call this.http.get. You should check your browsers console, that would show it if there was one. One likely reason is that http was not injected or is undefined.
ngOnInit() {
this.getSiteContent(this.route.snapshot.params['id']);
// if the above throws an exception anything below would not be called
this.addUpdatedPages();
}
getSiteContent(id) {
this.http.get('/site-content/'+id).subscribe(data => {
this.siteContent = data;
});
// If the call above to this.http.get throws an exception the code below would not be called
console.log('End of getSiteContent');
}
That being said the method addUpdatedPages should be called in the subscribe of the http.get because you want it to occur after the data base been retrieved. Modify the getSiteContent so that the line is moved into the callback for the observable's subscribe call.
this.http.get('/site-content/'+id).subscribe(data => {
this.siteContent = data;
this.addUpdatedPages();
});
I wrote a function that work like this
onNewZipFileRequested
{get all the necessary data}
.then{download all the files}
.then{create a zipfile with all those file}
.then{upload that zipfile} (*here is the problem)
.than{update the database with the signedUrl of the file}
Here is the relevant code
[***CREATION OF ZIP FILE WORKING****]
}).then(() =>{
zip.generateNodeStream({type:'nodebuffer',streamFiles:true})
.pipe(fs.createWriteStream(tempPath))
.on('finish', function () {
console.log("zip written.");
return bucket.upload(tempPath, { //**** problem****
destination: destinazionePath
});
});
}).then(()=>{
const config = {
action:'read',
expires:'03-09-2391'
}
return bucket.file(destinazionePath).getSignedUrl(config)
}).then(risultato=>{
const daSalvare ={
signedUrl: risultato[0],
status : 'fatto',
dataInserimento : zipball.dataInserimento
}
return event.data.ref.set(daSalvare)
})
On the client side, as soon as the app see the status change and the new Url, a download button (pointing to the new url) appears
Everything is working, but if I try to download the file immediately... there is no file yet!!!
If I wait same time and retry the file is there.
I noted that the time I have to wait depend on the size of the zipfile.
The bucket.upload promise should resolve on the end of the upload, but apparently fires too early.
Is there a way to know exactly when the file is ready?
I may have to make same very big file, it's not a problem if the process takes several minutes, but I need to know when it's over.
* EDIT *
there was a unnecessary nesting in the code. While it was not the error (results are the same before and after refactoring) it was causing some confusion in the answers, so i edited it out.
Id' like to point out that i update the database only after getting the signed url, and i get that only after the upload (i could not otherwise), so to get any result at all the promise chain MUST work, and in fact it does. When on the client side the download button appears (happens when 'status' become 'fatto') it is already linked to the correct signed url, but if i press it too early the file is not there (Failed - No file). If i wait some second (the bigger the file the longer i have to wait) then the file is there.
(English is not my mother language, if i have been unclear ask and i will try to explain myself better)
It looks like the problem could be that the braces are not aligned properly, causing a then statement to be embedded within another. Here is the code with the then statements separated:
[***CREATION OF ZIP FILE WORKING****]}).then(() => {
zip.generateNodeStream({type: 'nodebuffer', streamFiles: true})
.pipe(fs.createWriteStream(tempPath))
.on('finish', function () {
console.log('zip written.')
return bucket.upload(tempPath, {
destination: destinazionePath
})
})
}).then(() => {
const config = {
action: 'read',
expires: '03-09-2391'
}
return bucket.file(destinazionePath).getSignedUrl(config)
}).then(risultato => {
const daSalvare = {
signedUrl: risultato[0],
status : 'fatto',
dataInserimento : zipball.dataInserimento
}
return event.data.ref.set(daSalvare)
})