C# Process.Start is messing with URI's inside a batch file - c#-4.0

This is just a quick question that I am sure someone will be able to answer quickly as I am most likely just missing something.
Lets say I have the following directory layout
Folder1
-> CurrentlyRunning.EXE
-> Folder2
ProcessToStart.Bat
ApplicationToStartFromBat.exe
This is the code inside the applications.
CurrentlyRunning.EXE:
var proc = new Process
{
StartInfo =
{
FileName = "Folder2/ProcessToStart.Bat",
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = false
}
};
proc.Start();
ProcessToStart.Bat:
START ApplicationToStartFromBat.exe
Now, if I run ProcessToStart.Bat by double clicking on it, it will open ApplicationToStartFromBat.exe with no problems (which is good). If I run CurrentlyRunning.EXE (which will execute the code I posted above) the BAT file fails saying it can't find my EXE (which is really weird).
If I change the BAT file to:
START Folder2/ApplicationToStartFromBat.exe
and then run CurrentlyRunning.EXE, the bat will then properly open ApplicationToStartFromBat.exe. My problem is I can not change the code inside the bat for one reason or another.
Why is proc.Start() causing the bat file search root directory to change, and how do I stop this from happening?
Thanks

I think it is to do with where the working directory is for your exe file.
Try using ProcessStartInfo.WorkingDirectory to set the correct directory for your batch file.
var proc = new Process
{
StartInfo =
{
FileName = "Folder2/ProcessToStart.Bat",
WorkingDirectory = "DirectoryPath";
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = false
}
};
proc.Start();

Related

VS Code Extension. How to get the directory of the current open file?

I ran into a problem while writing an extension for Visual Studio Code!
I keep getting messages like this "Cannot read properties of undefined (reading 'uri')", etc.
const defaultCompiler = 'g++';
// define the command for compiling C++ code with each compiler
const compilerCommands = {
'g++': 'g++ -S -o "{oFile}" "{cFile}"',
'clang++': 'clang++ -S -o "{oFile}" "{cFile}"'
};
let currentlyOpenFilePath = vscode.window.activeTextEditor;
// let curDir = vscode.workspace.workspaceFolders[0].uri.path
let cFile = currentlyOpenFilePath.document.uri.path;
let dirPath = path.dirname(cFile);
let oFile = path.join(dirPath, 'output.s');
let command = compilerCommands[this.currentCompiler].replace('{cFile}', currentlyOpenFilePath).replace('{oFile}', oFile);
I surfed all over Google in search of a solution to the problem, but everything I found did not help me. I tried various combinations in variables currentlyOpenFilePath, curDir, cFile (currently open file), dirPath, oFile.
My system is MacOS and also needs to work on Windows.
And also the extension is local (the previous version of the code took the path not of the current open file, but the path to the extension)
I need this plugin, when called, to successfully process the command "g++ -S -o {oFile} {cFile}" or "clang++ -S -o {oFile} {cFile}" by changing {cFile} to the current path to the open .cpp file in editor a in {oFile}, same path as {cFile} but saved as output.s
let workspacePath = '';
if (vscode.workspace.workspaceFolders?.length) {
workspacePath = workspace.workspaceFolders[0].uri.fsPath;
workspacePath = path.normalize(workspacePath);
}
Try to see if it's what you want

Azure Batch with C# Application using System.Diagnostics.Process

I am using Azure Batch with a C# application. The overall C# application is responsible for doing many things. Unfortunately, 1 operation that works on my local machine does not work within an Azure Batch application.
The operation that works locally but not as an Azure C# application is programmatically starting a System.Diagnostics. A process that executes a FFmpeg argument to take a screenshot of a video. The process seems to run, but, the jpg file is not created. Locally, the code will create a jpg but as an Azure Batch app, the file is not created.
I have set the image file to be created in the AZ_BATCH_TASK_WORKING_DIR folder. I have reduced the code to just do the 1 operation that does not work as an Azure application and here it is:
using System;
using System.Diagnostics;
using System.IO;
namespace BatchAppWithFfmpegProcess
{
internal class Program
{
static void Main(string[] args)
{
#if DEBUG
string workingDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
#else
/*
Within each Tasks directory, the Batch service creates a working directory (wd) whose unique path is
specified by the AZ_BATCH_TASK_WORKING_DIR environment variable. This directory provides read/write access
to the task. The task can create, read, update, and delete files under this directory.
This directory is retained based on the RetentionTime constraint that is specified for the task.
The stdout.txt and stderr.txt files are written to the Tasks folder during the execution of the task.
*/
string workingDirectory = Environment.GetEnvironmentVariable("AZ_BATCH_TASK_WORKING_DIR");
#endif
var applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
string ffmpegPath = Path.Combine(applicationPath, #"lib\");
string videoFilePath = Path.Combine(applicationPath, "MichaelJacksonSmoothCriminal_Trimmed.mp4");
string thumbnailFilePath = Path.Combine(workingDirectory, "MichaelJacksonSmoothCriminal_Trimmed.jpg");
if (File.Exists(thumbnailFilePath))
{
File.Delete(thumbnailFilePath);
}
string arguments = $"-i \"{videoFilePath}\" -ss 00:00:01.000 -frames:v 1 \"{thumbnailFilePath}\"";
var startInfo = new ProcessStartInfo
{
FileName = ffmpegPath + $"\\ffmpeg.exe",
Arguments = arguments,
RedirectStandardError = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
UseShellExecute = false,
WorkingDirectory = ffmpegPath
};
using (var process = new Process { StartInfo = startInfo })
{
process.Start();
process.WaitForExit();
}
if (File.Exists(thumbnailFilePath))
{
Console.WriteLine("Hurray, it worked!!!");
}
else
{
Console.WriteLine("File was not created.");
}
}
}
}
Perhaps it is impossible to use System.Diagnostics.Process to create files? I have tried to make this as easy as possible to reproduce with the following:
clone the code at:
https://github.com/Dapp3rDanH/AzBatchFfmpegProcess.git
Using Visual Studio 2022, "Publish" BatchAppWithFfmpegProcess code to a Folder using
"Deployment mode" = Self-Contained
Target Framework of net5.0
Target runtime = win-x64.
Create a BatchAppWithFfmpegProcess.zip zip file of the publish folder. Make sure the BatchAppWithFfmpegProcess.exe is in the root of the zip.
Create a Batch account.
Add a Batch application using the BatchAppWithFfmpegProcess.zip file with appId of BatchAppWithFfmpegProcess and a version of 1.
Add a Pool called "Pool1" with 1 dedicated node using microsoftwindowsserver windowsserver 2022-datacenter-core (latest). Add BatchAppWithFfmpegProcess version 1 to Pool1.
Create a new Job with a Task with the command of:
cmd /c %AZ_BATCH_APP_PACKAGE_BatchAppWithFfmpegProcess#1%\BatchAppWithFfmpegProcess.exe
If you check out the stdout.txt file of the task, you will see "File was not created". Any way to get this to work?
Thanks!
Dan
The issue was related to my pool being based upon "microsoftwindowsserver windowsserver 2022-datacenter-core (latest)".
Switching to microsoftwindowsserver windowsserver 2016-datacenter (latest) fixed the issue.

How to execute a .bat or exe file from CodedUI script using Process.Start()?

I am new to Coded UI. I have written a simple code to execute a .bat file from a CodedUITestMethod1() as below:
thisProcess.StartInfo.CreateNoWindow = true;
thisProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
thisProcess.StartInfo.FileName = #"C:\BVTBatch\PlayBack.bat";
thisProcess.StartInfo.UseShellExecute = false;
thisProcess.StartInfo.RedirectStandardOutput = true;
thisProcess.Start();
thisProcess.WaitForExit();
strException = thisProcess.StandardOutput.ReadToEnd();
Problem statement: When I debug the script, it gets executed but the batch file does not run. I tried executing iexplorer.exe, and observed same issue. The script gets executed with pass, but IE browser does not start.
However if I execute the same code from other console application or Unit Test project method, it gets executed successfully.
Can someone suggest what is the reason behind this? and how can we fix this in CodedUI?
Thanks in advance.
This would seem legit:
thisProcess.StartInfo.FileName = ("C:\BVTBatch\PlayBack.bat");
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo = new ProcessStartInfo ("C:\BVTBatch\PlayBack.bat");
p.Start();

Open a text file in C# programmatically

I want to open a text file programmatically using C#. I have used :
System.Diagnostics.Process.Start(test.txt);
but this code is causing OS command injection problem when scanning for threats.
Is there any way that i can open a text file programmatically?? or way to bypass that OS command injection?
Thank you
You should call a program, say notepad:
Process.Start("notepad.exe", fileName);
the argument is the file name:
Process.Start("notepad.exe", "Test.txt");
See the problem with your code in the comments of this post:
Open a file with Notepad in C#
Try:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new
System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
string _path = "c:/filepath";
startInfo.Arguments = string.Format("/C start {0}", _path);
process.StartInfo = startInfo;
process.Start();

Write to file via jenkins post-groovy script on slave

I'd like to do something very simple: Create/write to a file located in the remote workspace of a slave via the jenkins groovy post-build script plug-in
def props_file = new File(manager.build.workspace.getRemote() + "/temp/module.properties")
def build_num = manager.build.buildVariables.get("MODULE_BUILD_NUMBER").toInteger()
def build_props = new Properties()
build_props["build.number"] = build_num
props_file.withOutputStream { p ->
build_props.store(p, null)
}
The last line fails, as the file doesn't exist. I'm thinking it has something to do with the output stream pointing to the master executor, rather than the remote workspace, but I'm not sure:
Groovy script failed:
java.io.FileNotFoundException: /views/build_view/temp/module.properties (No such file or directory)
Am I not writing to the file correctly?
While writing onto slave you need to check the channel first and then you can successfully create a file handle and start reading or writing to that file:
if(manager.build.workspace.isRemote())
{
channel = manager.build.workspace.channel;
}
fp = new hudson.FilePath(channel, manager.build.workspace.toString() + "\\test.properties")
if(fp != null)
{
String str = "test";
fp.write(str, null); //writing to file
versionString = fp.readToString(); //reading from file
}
hope this helps!
Search for words The post build plugin runs on the manager and doing it as you say will fail if you are working with slaves! on the plugin page (the link to which you've provided) and see if the workaround there helps.
Does the folder /views/build_view/temp exist?
If not, you will need to do new File( "${manager.build.workspace.remote}/temp" ).mkdirs()

Resources