VB.NET Communicating with console app and sending parameters - vb.net

I'm creating myself a GUI for a program that can be used in CMD, a CLI.
The program has the following input:
Ex: extractor.exe filename.rar newfilename.zip -c <password for achive>
filename.rar = the original file
newfilename.zip = the file to be created with new format
-c a command meaning key
<password...> - here comes the archive password.
It's great on CMD, but I would like to make a GUI.
I do it in VB and so:
For filename.rar I have one textbox that goes filled with a path specified by user using OpenFileDialog1.
For newfilename.zip I use a savefiledialog and a textbox: The textbox gets the path specified by user
Another textbox3 for the password and a button to call extractor.exe:
How can I pass these arguments to extractor?
I have tried with
argument = textbox1.text + textbox2.text + "-c" + textbox3.text
The program starts but simply closes as it simply doesn't get the parameters.
I have also tried this:
Dim psi As ProcessStartInfo
Dim procname = "extractor.exe"
Dim filename = TextBox1.Text
Dim newfile = TextBox3.Text
Dim key = TextBox2.Text
Dim args = ("extract" + filename + newfile + "-k" + key)
psi = New ProcessStartInfo(procname, args)
Dim proc As New Process()
proc.StartInfo = psi
proc.Start()
No luck. I'm able to send 1 parameter if I do like
argument = "extract" but i have multiple arguments that needs to be fetched from textboxes....is there a way?
Thanks!

Related

VB.Net Process.Start - Verb

I want my vb.net Program to launch notepad and elevate the credentials however there is no prompt and the program just opens.
Dim process As System.Diagnostics.Process = Nothing
Dim processStartInfo As System.Diagnostics.ProcessStartInfo
processStartInfo = New System.Diagnostics.ProcessStartInfo()
processStartInfo.FileName = "notepad.exe"
processStartInfo.Verb = "runas"
processStartInfo.Arguments = ""
processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
processStartInfo.UseShellExecute = True
process = System.Diagnostics.Process.Start(processStartInfo)
There's a lot of unnecessary code there. You're using two lines to declare and set your two variables when you only need one each time. You're setting the FileName property explicitly when you can pass an argument to the constructor and you're also setting three properties to their default values. I just stripped it down to the bare minimum:
Dim psi As New ProcessStartInfo("notepad.exe") With {.Verb = "runas"}
Dim proc = Process.Start(psi)
When I ran that code from a new WinForms app with just a Button on the form and I got a UAC prompt as expected.

Process.Start arguments not working

I am trying to start a process with two parameters that will run from a cmd prompt window just fine. The problem comes when I try to launch it via process.start.
In the cmd window, it looks like this.
D:\Projects\MyProg.exe "D:\Projects\MyScript.txt" "D:\Projects\MyInputData.txt"
When I try to build the arguments in .NET it puts double quotes around the entire string and it looks like this. The program doesn't interpret it as two parameters and just stops. If I add double quotes around each argument it still misinterprets it.
I know it is the MyProg.exe issue (vendor program that I can't change) but is there a way to send this command so it will work?
myProcess.StartInfo.Arguments = "D:\Projects\MyScript.txt D:\Projects\MyInputData.txt"
When I add double quotes it sort of works, the program starts but then has a problem and just stops.
myProcess.StartInfo.Arguments = """D:\Projects\MyScript.txt"" ""D:\Projects\MyInputData.txt"""
I'm not quite sure what D:\Projects\MyProg.exe is doing but following sample is working for. Two variable strings are declared. The two strings indicate two argument parameters I want to use with the executable.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'// Set first file parameter to the executable
Dim sourceFileName As String = "source.txt"
'// Set second file parameter to the executable
Dim targetFileName As String = "target.txt"
'// Create a new ProcessStartInfo
Dim p As New ProcessStartInfo
'// Specify the location of the binary
p.FileName = "D:\_working\ConsoleApplication3.exe"
'// Use these arguments for the process
p.Arguments = " """ & sourceFileName & """ """ & targetFileName & """ -optionalPara"
' Use a hidden window
'p.WindowStyle = ProcessWindowStyle.Hidden
' Start the process
Process.Start(p)
End Sub
End Class
See resulting screenshot:

VB FTP code works in Debug (F10) but not when run or F5

I need to FTP a local file to Mainframe and have written the below script to create a local Batch text file using streamwriter and then use this file with the ftp -s: command to run it.
Here is the code.
Shared Sub TestFTP()
' BP DEFINED INPUTS ANDF OUTPUTS
'Inputs
Dim hostname As String
Dim username As String
Dim password As String
Dim mainfile As String
Dim localfile As String
'Outputs
Dim success As Boolean
Dim message As String
'-------------
'Test DATA
'-------------
hostname = "XXIBM2"
username = "USER1"
password = "XXX1234"
mainfile = "XXTSO.USER1.TEST2"
localfile = "D:\TestFTP.txt"
'=============================BP Code========================
Try
Dim localPath As String = "C:\BPFTP"
Dim isExists As Boolean = System.IO.Directory.Exists(localPath)
If (isExists = False) Then
System.IO.Directory.CreateDirectory(localPath)
End If
' Open StreamWriter And create batch file
Using writer As StreamWriter = New StreamWriter(localPath + "\\FTP.txt")
writer.WriteLine("open " + hostname)
writer.WriteLine(username)
writer.WriteLine(password)
writer.WriteLine("put " + localfile + " '" + mainfile + "'")
writer.WriteLine("bye")
writer.WriteLine("exit")
End Using
' Perform FTP
Interaction.Shell("ftp -n -s:C:\BPFTP\FTP.txt")
' Delete batch file
System.IO.File.Delete("C:\\BPFTP\\FTP.txt")
success = True
Catch e As Exception
success = False
message = e.Message
End Try
End Sub
If I run the code using F5 the file does not appear on the mainframe.
If I set a breakpoing at the Shell command and run the code (f5) to here and then F5 to the end the file does not get FTPd to the mainframe.
HOWEVER.
If I run the code to the breakpoint and then simply 'Step Over' the Shell command line using F10 then the file successfully FTPs to the mainframe.
When you run in debug mode, you are forcing a synchronous operation, you need to tell shell and your ftp application to wait in order to completely send the file.
Interaction.Shell("ftp -n -s:C:\BPFTP\FTP.txt", AppWinStyle.MinimizedFocus, True, 30000)
See here
This will force it to wait 30 seconds before continuing, if you set it to -1 it waits forever which can cause undesirable behavior.

How to create .key file with specific text

I've been trying to make a program that is able to create a file with a .key extension, which contains a 5 line text.
It is fundamental to have 5 lines, otherwise it won't work.
I use
Dim filepath As String = TextBox1.Text + "\\rarreg.key"
Dim rarreg As New IO.StreamWriter(filepath, True)
rarreg.Write(String.Join(Environment.NewLine, hiddenTxt))
The hiddenTxt contains all the text needed and it's multilined.
However, when I click on the button to call this functions, it succesfully creates the file, but it comes empty.
Try this
' Add any initialization after the InitializeComponent() call.
Dim filepath As String = ""
Dim dialog As New SaveFileDialog
dialog.DefaultExt = "key"
dialog.FileName = "rarreg.key"
dialog.InitialDirectory = "c:\temp"
Dim results As DialogResult = dialog.ShowDialog()
If results <> Windows.Forms.DialogResult.Cancel Then
filepath = dialog.FileName
End If​

unable to run Exchange Powershell through vb.net application

So I'm going round in circles trying to get this to work, I've been trying for two days and I just can't figure it out.
I have the following vb function that takes a created powershell script, and should run it in powershell. Everything works fine, until the point at which the command pipeline is invoked. At this point, no commands run.
As you can see, I have tried to add the Microsoft.Exchange.Management.PowerShell.E2010 snapin to the runspace, it didn't like that at all stating something along the lines of the snapin didnt exist (which it does), and also when I run the code as shown, no commands are recognised as valid. I even added the specific command "Add-PSSnapin" to try and load any Exchange snapins, but it states that "Add-PSSnapin" is not recognised as a valid command.
If I pause the program just before the commands are involked, I can see every command within the pipeline, in the correct format. If I copy and paste the command text in the pipeline directly into a powershell window, it runs fine.
My code is below, any suggestions welcome.
edit: I have also tried adding the line "Add-PSSnapin Ex" (with an asterisk each side of Ex - I cant figure the formatting out on this, sorry)
to try and load the Exchange PS Snapins as the first thing the script would run (opposed to setting this up in the runspace) but no luck
Private Function scriptRunner(ByVal scripttorun As String) As String
Dim initial As InitialSessionState = InitialSessionState.CreateDefault()
Dim result As String = ""
Dim lineFromScript As String = ""
Dim reader As New StreamReader(tempScript)
Dim rsConfig As RunspaceConfiguration = RunspaceConfiguration.Create()
Dim snapInException As New PSSnapInException
Dim strUserName As String = "DOMAIN\USER"
Dim strPassword As String = "PASSWORD"
Dim SecuredPSWD As New System.Security.SecureString()
For Each character As Char In strPassword
SecuredPSWD.AppendChar(character)
Next
Dim wsmConnectionInfo As WSManConnectionInfo
Dim strSystemURI As String = "http://SERVER.DOMAIN/powershell?serializationLevel=Full"
Dim strShellURI As String = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"
Dim powerShellCredentials As PSCredential = New PSCredential(strUserName, SecuredPSWD)
wsmConnectionInfo = New WSManConnectionInfo(New Uri(strSystemURI), strShellURI, powerShellCredentials)
Dim runspace As Runspace = RunspaceFactory.CreateRunspace(wsmConnectionInfo)
Runspace.Open()
' runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", snapInException)
Dim pipeLine As Pipeline = runspace.CreatePipeline()
Dim command As Command = New Command("")
' TEST >> pipeLine.Commands.Add("Add-PSSnapin *Ex*")
Do While reader.Peek() <> -1
lineFromScript = Nothing
lineFromScript = reader.ReadLine()
pipeLine.Commands.Add(lineFromScript)
'command.Parameters.Add(lineFromScript)
'pipeLine.Commands.Add(command)
Loop
'' Run the contents of the pipeline
Dim psObjCollection As Collection(Of PSObject) = pipeLine.Invoke()
runspace.Close()
runspace.Dispose()
Return ""
End Function
I ended up working around the problem rather than fixing it.
I moved the script code into the vb.net application, and wrote each line to a file, i.e.
writer.WriteLine("Add-PSSnapin *Ex*")
Then I loaded the script through PowerShell as an application;
Dim exeStartInfo As System.Diagnostics.ProcessStartInfo
Dim exeStart As New System.Diagnostics.Process
exeStartInfo = New System.Diagnostics.ProcessStartInfo("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe")
exeStartInfo.Arguments = ("-command work\scriptbuilder.ps1")
exeStartInfo.WorkingDirectory = "C:\ExchangeManager\"
exeStartInfo.UseShellExecute = False
exeStart.StartInfo = exeStartInfo
exeStart.Start()
exeStart.Close()
Not ideal but it got the job done.