Run batch script before Debugging - c#

I want to run a batch script every time before starting program for debugging.
For the build events, such functionality is realized using pre-build event, post-build event.
For actual debugging, I could not find any pre-Debug, post-Debug events.
How to realize this scenario?
I am using VS2008, .net framework 3.5, c# application.
I am opposed to idea of creating some extra lines of code within the application that would fire-up external batch file.

I realise you wished to avoid additional code, but in your Main function you could use Debugger.IsAttached() to kick off your work for you.
For example:
if (Debugger.IsAttached)
{
System.Diagnostics.Process.Start(#"C:\myBatchFile.bat");
}

You can use a VS macro.
I had the same issue and this is the best I came with so far
Dim MustUpdateDB As Boolean
Private Sub DebuggerEvents_OnEnterRunMode(ByVal Reason As EnvDTE.dbgEventReason) Handles DebuggerEvents.OnEnterRunMode
If (MustUpdateDB) Then
MsgBox("Start debug operation", MsgBoxStyle.OkOnly, "TITLE")
REM DO WHATEVER COMMAND HERE
REM System.Diagnostics.Process.Start("C:\listfiles.bat")
MustUpdateDB = False
End If
End Sub
Private Sub BuildEvents_OnBuildDone(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildDone
MsgBox("Build Done", MsgBoxStyle.OkOnly, "Title")
MustUpdateDB = True
End Sub
There is a pretty good explanation on how to add event handlers to a macro
here
The only issue I have so far is to figure out how to get the currently debugged application active directory

A basic solution that worked for me (in VS 2017) was to create a batch file that does the command(s) that should run before debugging, and also include as the last line some parameters to be passed via command-line, such as this:
rem Place the command(s) you need here:
xcopy pristine.file changed.file
rem Now process passed commands - a few extra placeholders shouldn't hurt anything, to
rem allow for some extra command-line parameters
%1 %2 %3 %4 %5 %6 %7
Now in the debugging properties, set the 'Command' to your batch file, and for 'Command Arguments' include $(TargetPath) as the first argument, followed by any arguments your program uses or needs:
$(TargetPath) my command args
YMMV, but for my simple needs this seems to be working well.

if $(ConfigurationName) == Debug mkdir c:\mydir
You should check out... How to run Visual Studio post-build events for debug build only

So, you have a .bat file that you want to run via the pre-build event?
Try to specify full path to your batch file in the pre-build event command e.g.
cmd /c C:\Path\to\foo.bat
or
cmd C:\windows\system32\cmd.exe /c C:\Path\to\foo.bat

Related

How do you pass parameters into a C# .Net Core project? [duplicate]

I am running an inherited project written in C# inside Visual Studio Code. In order for this application to run, it needs to take command line input (-t, -h, etc). How do I test this from inside Visual Studio?
Currently (I've been learning dotnet, C#, VS, etc as I go) I have a hello world program I can run from vsc's terminal. For a reason I haven't been able to pinpoint, probably how I installed it, dotnet run isn't recognized - I have to feed it an explicit path to dotnet.exe: C:\Program Files\dotnet\dotnet.exe run
How can I do this when the program requires command line input? My shot in the dark of C:\Program Files\dotnet\dotnet.exe run -t predictably didn't work, but I'm not sure what else to try.
Thanks!
If you are using dotnet.exe run to start your application you need add the -- switch statement to instruct dotnet.exe to pass the arguments to your application. For example
Microsoft Documentation
dotnet.exe run -- -arg1 -arg2 (etc) notice the -- after the dotnet arguments and before your program specific arguments.
GitHub Issue
Run with Terminal
When you run your code using terminal you must add ' -- ' to tell dotnet you are running your code with an argument/s
C:>dotnet run -- <your arguments here>
Run with Debugger
Locate your .vscode folder inside your project if not create one.
Open the launch.json file
You will see a json object and add your arguments inside the "args" key.
launch.json
"configurations": [
{
"name": ".NET Core Launch (console)",
"args": [], // PUT YOUR ARGUMENTS HERE
...
}
]
I tried to add a comment to Nico's answer but I lack sufficient reputation points. I was confused by the dash character in front of each arg: "-arg1 -arg2 (etc)". For clarity I would like to point out that .NET Core 2.1 seems to not need this. In the case of my console app, it takes a date for the first arg, an integer for the second, then an operator (+ or -) for the third arg. If I entered the following:
C:\>dotnet run -- -7/13/2018 -30 -+
I found that the leading dash in front of each arg was passed into the program along with the intended arg and I ended up trying to date parse "-7/13/2018"
I got the expected result when I entered it like this:
C:\>dotnet run -- 7/13/2018 30 +
Since OP is specifically asking about how to do this in Visual Studio Code, they are likely using VSCode's run feature (not the dotnet CLI as other answers assume), to run their application. In this case, the proper way to supply command line arguments is via the .vscode\launch.json file.
Add an args array attribute to your configuration and populate it with the arguments you would like to pass.
"configurations": [
{
// ... ,
"args": ["-arg1", "-arg2"]
}
Right click on your project
Click Properties
Click Debug in the Properties window
Under "start options:"
Add a "Command Line Argument:" = run -t
Add a "Working Directory:" try the bin\debug directory

.bat file in Visual Studio 2017

I'm trying to run a .bat file in my application. This .bat calls a JTAG application to load a firmware in microcontroller. However, I don't know why this fail in to execute the software.
If I run the .bat outside of Visual Studio it works perfectly.
I have the GUI and a Button which I will click to execute the firmware loading
To generate the command files I used a software Uniflash. This software generates a folder with all necessary files to execute the JTAG access and load the firmware.
My code is below:
private void Button_Relay_Click(object sender, EventArgs e)
{
Process MSP = new Process();
MSP.StartInfo.WorkingDirectory = #"D:\\Projects\\Test_Fixture\\Test_Fixture_Visual_Studio\uniflash_windows_64";
MSP.StartInfo.FileName = "dslite.bat ";
MSP.Start();
Thread.Sleep(500);
MSP.WaitForExit();
}
However when I executed this code the compilation is ok, but when I run this code appear this error:
Questions:
I will always generate specific bat files for each application and include the .bat folder inside the folder of VS C#, how I set up the directory path to check automatically in my software folder?
Why the VS can't find the files if the path is right?
After my .bat run I would like to read the status of the programming ( Success or fail ) How I do it?
Success
Fail:
Ad 2)
About the error:
That's because you may have specified the path wrong:
Instead of
MSP.StartInfo.WorkingDirectory = #"D:\\Projects\\Test_Fixture\\Test_Fixture_Visual_Studio\uniflash_windows_64";
either use \\ everywhere (there is only one \ between Test_Fixture_Visual_Studio and uniflash_windows_64) and skip the # OR use the # and just use one \ instead of two. So replace your line with this one:
MSP.StartInfo.WorkingDirectory = #"D:\Projects\Test_Fixture\Test_Fixture_Visual_Studio\uniflash_windows_64";
Ad 3)
About the result of your prcess:
In my opinion it is easier to not call a batch file but to call the process itself directly. In this way you can retrieve the Process.ExitCode property to retrieve the exit code of the executable (if it returns it's state via the exit code).
You can check this by calling the executable in the command shell and check the error level of the last execution by calling
echo %ERRORLEVEL%
Usually 0 indicates success, everything else indicates a failure of some kind.

Running a C# program with command line prompts in Visual Studio Code

I am running an inherited project written in C# inside Visual Studio Code. In order for this application to run, it needs to take command line input (-t, -h, etc). How do I test this from inside Visual Studio?
Currently (I've been learning dotnet, C#, VS, etc as I go) I have a hello world program I can run from vsc's terminal. For a reason I haven't been able to pinpoint, probably how I installed it, dotnet run isn't recognized - I have to feed it an explicit path to dotnet.exe: C:\Program Files\dotnet\dotnet.exe run
How can I do this when the program requires command line input? My shot in the dark of C:\Program Files\dotnet\dotnet.exe run -t predictably didn't work, but I'm not sure what else to try.
Thanks!
If you are using dotnet.exe run to start your application you need add the -- switch statement to instruct dotnet.exe to pass the arguments to your application. For example
Microsoft Documentation
dotnet.exe run -- -arg1 -arg2 (etc) notice the -- after the dotnet arguments and before your program specific arguments.
GitHub Issue
Run with Terminal
When you run your code using terminal you must add ' -- ' to tell dotnet you are running your code with an argument/s
C:>dotnet run -- <your arguments here>
Run with Debugger
Locate your .vscode folder inside your project if not create one.
Open the launch.json file
You will see a json object and add your arguments inside the "args" key.
launch.json
"configurations": [
{
"name": ".NET Core Launch (console)",
"args": [], // PUT YOUR ARGUMENTS HERE
...
}
]
I tried to add a comment to Nico's answer but I lack sufficient reputation points. I was confused by the dash character in front of each arg: "-arg1 -arg2 (etc)". For clarity I would like to point out that .NET Core 2.1 seems to not need this. In the case of my console app, it takes a date for the first arg, an integer for the second, then an operator (+ or -) for the third arg. If I entered the following:
C:\>dotnet run -- -7/13/2018 -30 -+
I found that the leading dash in front of each arg was passed into the program along with the intended arg and I ended up trying to date parse "-7/13/2018"
I got the expected result when I entered it like this:
C:\>dotnet run -- 7/13/2018 30 +
Since OP is specifically asking about how to do this in Visual Studio Code, they are likely using VSCode's run feature (not the dotnet CLI as other answers assume), to run their application. In this case, the proper way to supply command line arguments is via the .vscode\launch.json file.
Add an args array attribute to your configuration and populate it with the arguments you would like to pass.
"configurations": [
{
// ... ,
"args": ["-arg1", "-arg2"]
}
Right click on your project
Click Properties
Click Debug in the Properties window
Under "start options:"
Add a "Command Line Argument:" = run -t
Add a "Working Directory:" try the bin\debug directory

How to execute a batch file from C#?

(See end for solution)
I didn't think this was going to be hard. I have a commmand file, d:\a.cmd which contains:
copy /b d:\7zS.sfx + d:\config.txt + d:\files.7z d:\setup.exe
But these lines of C# won't execute it:
Process.Start("d:\\a.cmd");
Process.Start("cmd", "/c d:\\a.cmd");
Throws Win32Exception: "%1 is not a valid Win32 application."
Process.Start opens .pdf files...why not execute command files?
This works if I type it in a cmd window:
cmd /c d:\a.cmd
Windows XP, MS Visual Studio 2008.
Thanks in advance,
Jim
SOLUTION
I'm only SLIGHTLY embarrassed :( There was a file named cmd.exe, size zero in my app's dir. I have no idea how it got there but it is now toast and both of the above C# statements now work. I'm off to find a Harry Potter book so I can get some self-punishment ideas from Dobby...
I've got four things for you that you can try out:
(1) Try providing the full path for cmd.exe (e.g. on my machine: C:\WINDOWS\SYSTEM32\CMD.EXE).
(2) Try adding call to the command to be executed:
Process.Start(#"C:\WINDOWS\SYSTEM32\CMD.EXE", #"/c call D:\a.cmd");
(3) Besides that, I can only guess where the %1 in the Win32Exception is coming from. Maybe your file associations are set-up incorrectly.
If you type the following on the command-line:
> assoc .cmd
You will likely get a mention of cmdfile. If you then look up this token with:
> ftype cmdfile
You might get an answer along the lines of:
cmdfile="%1" %*
Those settings are stored in the registry, and this is how the command-line interpreter knows how to execute files with custom extensions. (You can find out how a PDF document is started by executing the above two statements for the .pdf extension.)
(4) If you start to suspect that your machine might be mis-configured, start regedit (the registry editor) and locate the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor.
On my Windows XP machine (and your Process.Start example works on my machine, with different filenames though), I've got the following values stored in there:
// Name Type Value
// -----------------------------------------------
// (standard) REG_SZ (not set)
// AutoRun REG_SZ
// CompletionChar REG_DWORD 0x00000040 (64)
// DefaultColor REG_DWORD 0x00000000 (0)
// EnableExtensions REG_DWORD 0x00000001 (1)
// PathCompletionChar REG_DWORD 0x00000040 (64)
Of those, the AutoRun value might be of some interest. I think it corresponds to the /d command-line switch of cmd.exe, which controls whether cmd.exe attempts to start files with custom extensions. Usually, this is enabled. Maybe, on your machine, it isn't?
Or you can do a .bat file, then call this file through System.Diagnostics.Process.Start(). It won't redirect output to Console Application, but it would certainly execute the commands inside.
You need to specify the process full name (cmd.exe).
You should try
Environment.GetFolderPath(Environment.SpecialFolder.System) + "cmd.exe"
So you can be sure to execute the right file even if a cmd.exe is in your applications directory.
It looks like something wrong with your computer. Try running this on another machine. This should work. Process.Start(string) uses ShellExecuteEx to launch the file, so it's pretty much the same thing as double-clicking the file in Explorer, as you supposed.
A simple test worked for me.
B:\foo.cmd:
#echo Hello from foo.cmd!
#pause
Program.cs:
class Program{
static void Main(){
System.Diagnostics.Process.Start("B:\\foo.cmd");
}
}
This works as expected.
Your error message is suspicious, "%1 is not a valid Win32 application." The value in my registry at HKCR\cmdfile\shell\open\command is
"%1" %*
The %1 gets replaced by the file name, and the %* can be ignored here (it indicates that any further command-line arguments should be passed along, but we're not concerned with that right now).
The fact that the file itself is launched to handle this type of file indicates that Windows itself knows how to launch this type of file. On a normal installation of Windows, the following extensions should be set up similarly:
.exe Windows and DOS executable files
.com DOS "command" files
.bat Windows and DOS batch files
.cmd Windows NT batch files
.pif Windows shortcuts to DOS executable files
If you go to HKCR\.xxx (where xxx is any of the above), the "(Default)" value should be xxxfile. If you then go to HKCR\xxxfile\shell\open\command, the "(Default)" value should be "%1" %*. Also the "(Default)" value of HKCR\xxxfile\shell should be either not set or open.
If you have anything else in any of these values, then some program has attempted to insert itself into the execution process. Viruses sometimes do this (Sircam, for example).
Have you tried executing cmd.exe, and passing the .cmd file to it as an argument?
hmm try:
System.Diagnostics.Process myproc = new System.Diagnostics.Process();
myproc.EnableRaisingEvents=false;
myproc.StartInfo.FileName="d:\\a.cmd";
myproc.Start();
MessageBox.Show("did the command");
Have you tested your batch file in the directory, context it's going to run? The error message with %1 looks like the problem may be in there?

Xpath error due to miscorrected paths

When i start to debug application i am getting this error Can any one give me the solution
Error 1 The command "xcopy "F:\asoadmin_ML_view\leaf\Console\Bin\Debug\Console.*" "F:\leafPRODUCT\Bin" /f /e /y /i
xcopy "F:\leafPRODUCT..\voyagerhtml\Operations Sentinel Console Help*.chm" "F:\leafPRODUCT\Help" /f /e /y /i
" exited with code 4.
According to this, error code 4 means either you do not have enough memory to perform debugging, or (much more likely) you have invalid syntax. The answer to this thread suggests placing double quotes around your entire path.
Your build process likely has a pre/post build step associated with it that is executing the XCopy commands. Error code 4 implies either insufficient disk space to perform the copy, or a syntax error in the command.
To edit your project's pre/post build steps, right click on your project, then select Properties -> Build Events. To diagnose these commands, try running them from the command line after you build your project.
Maybe the user with which you try to execute the 'xcopy' doesn't have enough permissions (according to this thread: http://social.msdn.microsoft.com/Forums/en-US/tfsbuild/thread/5c4a55e2-243a-427f-800d-39b42c9e860e).

Categories