Editor extension onDidCloseTerminal() causes editor to freeze - javascript

I am trying to write an extension for vscode, and I am trying to handle closing of the terminal, but whenever I click on the trash on the terminal to delete the terminal, the editor freezes. Here is how I am handling how the editor is closed. Am I doing something wrong?
I have multiple terminals, and I am opening one that is not named Server Terminal, it is called Add Package so it doesn't go into the if statement which is what I want in this case. So, what is causing the editor to freeze? I tried adding an else { t.dispose() } but the editor still freezes.
export function activate(context: ExtensionContext) {
window.onDidCloseTerminal(t => {
// Watch for when the server terminal closes.
if (t.name === 'Server Terminal') {
Serve.server = undefined
showMessage(`The server has been stopped on "http://${Serve.host}:${Serve.port}"`)
}
})
}

So, for me, it seems as if to solve this issue I need to first kill the process manually, then I can set Serve.server to undefined. This seems to solve the issue of the editor freezing:
window.onDidCloseTerminal(async t => {
// Watch for when the server terminal closes.
if (t.name === 'Server Terminal') {
const id = await t.processId
id && kill(id)
Serve.server = undefined
}
})

Related

Unable to load a specific URL with Cypress

I’m unable to load the following URL with Cypress. Getting timeout error. I have set the page load time to 2 mins, still same issue. General URLs eg. (https://www.google.co.nz/) works fine.
it(‘First Test’, () => {
cy.visit(‘https://shop.countdown.co.nz/‘)
})
Here's a way, not the best, could be improved...
The Countdown site has an aversion to being run in an iframe, but it can be tested in a child window, see custom command here Cypress using child window
Cypress.Commands.add('openWindow', (url, features) => {
const w = Cypress.config('viewportWidth')
const h = Cypress.config('viewportHeight')
if (!features) {
features = `width=${w}, height=${h}`
}
console.log('openWindow %s "%s"', url, features)
return new Promise(resolve => {
if (window.top.aut) {
console.log('window exists already')
window.top.aut.close()
}
// https://developer.mozilla.org/en-US/docs/Web/API/Window/open
window.top.aut = window.top.open(url, 'aut', features)
// letting page enough time to load and set "document.domain = localhost"
// so we can access it
setTimeout(() => {
cy.state('document', window.top.aut.document)
cy.state('window', window.top.aut)
resolve()
}, 10000)
})
})
Can test with that like this
cy.openWindow('https://shop.countdown.co.nz/').then(() => {
cy.contains('Recipes').click()
cy.contains('Saved Recipes', {timeout:10000}) // if this is there, have navigated
})
I bumped the setTimeout() in custom command to 10 seconds, cause this site drags it's feet a bit.
Configuration:
// cypress.json
{
"baseUrl": "https://shop.countdown.co.nz/",
"chromeWebSecurity": false,
"defaultCommandTimeout": 20000 // see below for better way
}
Command timeout error
Using Gleb's child window command, there's a timeout error that I can't track the source of.
To avoid it I set "defaultCommandTimeout": 20000 in config, but since it's only needed for the openWindow call it's better to remove the global setting and use this instead
cy.then({timeout:20000}, () => {
cy.openWindow('https://shop.countdown.co.nz/', {}).then(() => {
cy.contains('Recipes').click()
cy.contains('Saved Recipes', {timeout:10000}) // if this is there, have navigated
})
})
To check if the long command timeout only applies once, break one of the inner test commands and check that that it times out in the standard 4000 ms.
cy.then({timeout:20000}, () => {
cy.openWindow('https://shop.countdown.co.nz/', {}).then(() => {
cy.contains('Will not find this').click() // Timed out retrying after 4000ms
The quotes are wrong. Try the below code:
it('First Test', ()=>{ cy.visit('https://shop.countdown.co.nz/') })
On trying to visit the URL I am getting the error:
cy.visit() failed trying to load:
https://shop.countdown.co.nz/
We attempted to make an http request to this URL but the request
failed without a response.
We received this error at the network level:
Error: ESOCKETTIMEDOUT
Common situations why this would fail:
you don't have internet access
you forgot to run / boot your web server
your web server isn't accessible
you have weird network configuration settings on your computer
Error Screenshot:
Lets look into the common situations where this might happen:
you don't have internet access: I have a internet access, so this can be ruled out.
you forgot to run / boot your web server - Your site is accessible from a normal browser, this can be ruled out as well.
your web server isn't accessible - This is a possibility where may be there are firewall settings at the server end because of which cypress is not getting any response when accessing the site.
you have weird network configuration settings on your computer - This can be ruled out as well.
I had a similar issue, so what I observed in my case was that the URL was not getting added to the iframe src property and hence cy.visit() was getting timed out each time.
So, I added the URL manually to the src property of the iframe.
Here's my custom command for reference:
Cypress.Commands.add('goto', url => {
return new Promise(res => {
setTimeout(() => {
const frame = window.top.document.getElementsByClassName('aut-iframe')[0];
frame.src = url;
var evt = window.top.document.createEvent('Event');
evt.initEvent('load', false, false);
window.dispatchEvent(evt);
res();
}, 300);
});
});
Now use cy.goto('https://yoururl.com') and you are good to go.

Call a clipboard access prompt in IE 11 with JS after user has refused it

When a user has refused a clipboard access prompt, the message is not showing while next copy attempts, until the page will be reloaded. Is there a way to call the prompt manually without the page reload?
I am using React with copy-to-clipboard 3.3.1 npm package. According to the Niet the Dark Absol's advice, my copy function looks like
copyToClipboard(phone: string) {
copy(phone, {
format: 'text/plain',
onCopy: (clipboardData: DataTransfer) => {
const copiedPhone = clipboardData.getData('text/plain');
if (copiedPhone === phone) {
this.setState({showMessage: true});
}
}
});
}
Means that I show 'Success' message when text was copied

How debug a nodejs API

I've been worked on a vue project.
This vue project use the nodejs API I've created, in simple way, they are two entire differents project which are not located in the same directory and they are launched separately.
The problem is whenever I debug a route with node --inspect --debug-break event_type.controller.js for example named:
"/eventtype/create"
exports.create = (req, res) => {
const userId = jwt.getUserId(req.headers.authorization);
if (userId == null) {
res.status(401).send(Response.response401());
return;
}
// Validate request
if (!req.body.label || !req.body.calendarId) {
res.status(400).send(Response.response400());
return;
}
const calendarId = req.body.calendarId; // Calendar id
// Save to database
EventType.create({
label: req.body.label,
}).then((eventType) => {
Calendar.findByPk(calendarId).then((calendar) => {
eventType.addCalendar(calendar); // Add a Calendar
res.status(201).send(eventType);
}).catch((err) => {
res.status(500).send(Response.response500(err.message));
});
}).catch((err) => {
res.status(500).send(Response.response500(err.message));
});
};
Even if I create a breakpoint on const userId = jwt.getUserId(req.headers.authorization);
and from my vue app I trigger the api createEventType event, my break point is not passed.
Also when I press f8 after the breakpoint on my first line with the debugger, my file close automatically.
I do not use VS Code but Vim for coding but I've heard that maybe Vs Code could allow a simplified way to debug nodesjs application.
NOTE: I use the V8 node debugger.
For newer NodeJS versions (> 7.0.0) you need to use
node --inspect-brk event_type.controller.js
instead of
node --inspect --debug-break event_type.controller.js
to break on the first line of the application code. See https://nodejs.org/api/debugger.html#debugger_advanced_usage for more information.
The solution (even if it's not really a solution) has been to add console.log to the line I wanted to debug.

Executing FolderBrowserDialog in powershell from client browser using javascript

I'm trying to trigger some sort of Folder Selection Dialog, I have a working model with nodejs and the powershell but it only works when the server and client are on the same machine. I need the prompt to occur on the client side triggered from the browser. From what i understand I can not trigger Powershell from Chrome? So is there an alternative or am i just screwed?
My current Powershell script
{
param([string]$Description="Select Folder",[string]$RootFolder="Desktop")
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null
$objForm = New-Object System.Windows.Forms.FolderBrowserDialog
$objForm.Rootfolder = $RootFolder
$objForm.Description = $Description
$Show = $objForm.ShowDialog()
If ($Show -eq "OK")
{
Return $objForm.SelectedPath
}
Else
{
Write-Error "Operation cancelled by user."
}
}
$folder = Select-FolderDialog # the variable contains user folder selection
write-host $folder
My javascript function
async function asyncfindDir() {
//executes powershell script
let promise = new Promise((resolve, reject) => {
const Shell = require('node-powershell');
const ps = new Shell({
executionPolicy: 'Bypass',
noProfile: true
});
ps.addCommand('./selectfolder.ps1');
ps.invoke()
.then(output => {
//console.log(output);
var shelloutput = output;
console.log (shelloutput + '^^from external script');
res.send(shelloutput);
})
.catch(err => {
console.log('please select a directory path')
//console.log('err');
});
});
};
Is there anyway to get that working locally?
Is there a trigger i'm not aware of to access that kind of dialog from the browser? I know i'm not the only person with this issue but i have yet to see a real solution.
Short answer: No.
Longer answer, is best illustrated by rephrasing your question with a different script name:
Using my browser, can I click on a link to visit a website, and have it run a random
PowerShell script called Delete_All_Files.ps1?
Answers why you will never be able to run a PowerShell script from a browser, on a remote machine, and why browsers will deliberately block you from doing it, because people usually don't want to have all their files deleted when they click on a random link in their email.
If you want to run PowerShell scripts on remote machines, then you should look into PSRemoting and Enter-PSSession.
#kuzimoto is right. If you just want to display a folder dialog box, there are easier ways to do that and Fine Uploader is an easier way.
Replying to your comment: If you want to specify a directory name, the reason you can't do it is because you are essentially asking:
Using my browser, can I click on a link to visit a website, and have
it run a script that will enumerate through all the files and folders
in my C:\ so that it can choose the folder C:\users\Justin
Miller\Desktop\SECRET FILES\?
The reason both operations do not work is because both operations require local computer access. i.e. local script execution access, and local directory knowledge access. Security-wize, we, in general, don't want to visit a random website and have it execute random code, or know what files/folders I have on my machine, which is why you won't be able to do what you want to try to do.

Access is denied error in Windows Store App using Javascript

I'm trying to launch a save dialog in my windows RT app when someone tries to close a file which has not been saved. However, I keep getting a 0x80070005 - JavaScript runtime error: Access is denied error
This is the code I'm using the launch the message dialog. When "Don't Save" is chosen (and BlankFile() is run) everything runs ok. However when you choose "Save File" it throws the access denied error when it tries to run .pickSaveFileAsync()
function createNewFile()
{
if (editedSinceSave)
{
// Create the message dialog and set its content
var msg = new Windows.UI.Popups.MessageDialog("Save this file?",
"Save Changes");
// Add commands
msg.commands.append(new Windows.UI.Popups.UICommand("Don't Save",
function (command) {
BlankFile();
}));
msg.commands.append(new Windows.UI.Popups.UICommand("Save File",
function (command) {
//saveFile(true, true);
testPop("test");
}));
// Set the command that will be invoked by default
msg.defaultCommandIndex = 2;
// Show the message dialog
msg.showAsync();
}
}
function testPop(text) {
var msg = new Windows.UI.Popups.MessageDialog(text, "");
msg.showAsync();
}
Your core problem is you are tying to show a message dialog ontop of another. I discuss the details, and the solution here:
What is the alternative to `alert` in metro apps?
However, you flow naturally needs this is to happen -- I suggest looking at building a different type of flow rather than stacking dialogs.
The way around this seems to be to set a command id and catch it in the done() function of showAsync(), like so
function createNewFile()
{
if (editedSinceSave)
{
// Add commands and set their CommandIds
msg.commands.append(new Windows.UI.Popups.UICommand("Dont Save", null, 1));
msg.commands.append(new Windows.UI.Popups.UICommand("Save File", null, 2));
// Set the command that will be invoked by default
msg.defaultCommandIndex = 1;
// Show the message dialog
msg.showAsync().done(function (command) {
if (command) {
if (command.id == 1){
BlankFile();
}
else {
saveFile(true, true);
}
}
});
}
}
This doesn't throw any errors. I don't know why doing it the other way throws errors as it doesn't seem to be any different!

Categories