1

Recently I updated my Visual Studio and start using the extention Macro Explorer.

I tried to use one of the sample macros "removes and sorts all", but I realized if I have a open documents, it doesn't run. So I closed all my open documents and try again this time it open all documents and close them but it doesn't work either.

The problem is the command executed before the document completely load. If there was a event or timer that can help wait until document load completely the problem will solve.

Here is my code. I marked where I want to add wait function:

function formatFile(file) {
    dte.ExecuteCommand("View.SolutionExplorer");
    if (file.Name.indexOf(".cs", file.Name.length - ".cs".length) !== -1) {
        file.Open();
        file.Document.Activate();

//here i want to wait for 1 second
        dte.ExecuteCommand("Edit.RemoveAndSort");

        file.Document.Save();
        file.Document.Close();
    }
}

I appreciate any sort of help.

Macro Explorer on GitHub: https://github.com/Microsoft/VS-Macros

Christian.K
  • 42,600
  • 9
  • 89
  • 127
Mohammad
  • 2,482
  • 5
  • 24
  • 48

1 Answers1

1

According to the code snippet you shared in your original post and I also clone the project from GitHub, your code should be JavaScript code.

In JavaScript code, there has setTimeout() or setInterval() functions. For example, if you use setTimeout(), you need to move the code that you need to run after the pause into the setTimeout() callback.

Please modify your code as below.

function formatFile(file) {
dte.ExecuteCommand("View.SolutionExplorer");
if (file.Name.indexOf(".cs", file.Name.length - ".cs".length) !== -1) {
    file.Open();
    file.Document.Activate();


    setTimeout(function () {
        //move the code that you want to run after 1 second
        dte.ExecuteCommand("Edit.RemoveAndSort");
        file.Document.Save();
        file.Document.Close();
    }, 1000);

}

And there are lots of thread about sleep() in Javascript code. Please refer to:

What is the JavaScript version of sleep()?

JavaScript sleep/wait before continuing

Weiwei
  • 3,415
  • 1
  • 6
  • 12
  • @David Do you have tried above code and what's the result? If any problem, please let me know. – Weiwei Sep 15 '17 at 01:12
  • thanks dear @wendy. i tried your code but i catch this exception: – Mohammad Sep 15 '17 at 08:19
  • Line 32: Object expected. – Mohammad Sep 15 '17 at 08:19
  • According to the original source code, the line 32 is "file.Document.Activate();", which should run correctly in original code. Do you have change any other code and what's the line of code at line 32 in your editor? The error is caused by passing a non-JavaScript object to a built-in function that expects a JavaScript object. So please make sure the object you are passing in as a parameter is of the correct type. Please refer to: https://docs.microsoft.com/en-us/scripting/javascript/misc/javascript-object-expected – Weiwei Sep 20 '17 at 01:34