Sending console commands / using windows variables - vb.net

A two-part question but they tie in together. - I'm experimenting with VB.net console applications and I'm wandering how I send command line commands to the console window. Take the below Sub.
Sub initialLoad()
Console.WriteLine("Started # " + %date% %time%)
Console.WriteLine("Test")
End Sub
I'm trying to add the equivalent of echo. which would add a line break, I tried using the string Console.WriteLine("Test", vbCrLf) but the vbCrLF made no difference and did not add a line break after the text.
The %date% and %time% variables when used on a Batch script for example will give the current date and time and is recognised and defined automatically within the CMD window. Am I able to send these CMD commands to the console or must I use VB.net equivalents to achieve this.
I found that instead of pause>nul I had to use Console.ReadLine() to make the console window pause.
Am I incorrect in assuming I can use CMD commands? I know in C++ I can send all the commands but is there something similar in VB.net? Thanks.

For environment variables use Environment.GetEnvironmentVariable
For new line use Environment.NewLine
For commands see here: How To: Execute command line in C#, get STD OUT results - this is in C# but you can use the same objects in VB.NET.

Related

Shell hitting Run-Time error '5' trying to call R script in Access VBA

I made a simplified version of my code that directly highlights the issue.
I have read dozens of similar issues/solution.
Part of my workflow in VBA in Microsoft Access involves calling an R script that does some logic and returns information to a table in the same database.
It was working until we moved the location of the R installation to a new drive. Changing the path to this new install location does not work. No other code is changed.
cmd = "C:\R\bin\i386\Rscript.exe C:\R\test.R"
Debug.Print cmd
Shell cmd
I get
runtime error '5'
I am using the immediate window to check the paths are correct and copying them into RUN to verify that they do work.
The above outputs:
C:\R\bin\i386\Rscript.exe C:\R\test.R
It works in RUN.
The first thing I found when searching online is to add more (") as shell can handle them weirdly:
cmd = """C:\R\bin\i386\Rscript.exe""" & " " & """C:\R\test.R"""
Or any iterations of using "s in different places, output:
"C:\R\bin\i386\Rscript.exe" "C:\R\test.R"
Same error but works in RUN. I also tried them all successfully in CMD.
It seems just Shell refuses to launch R from that path. I have moved it elsewhere on my C drive with same effect.
I cannot recreate the original R installation path as that shared drive is now completely dead.
EDIT:
I changed to using ShellExecute simply to try and make Notepad ++ open, again works in cmd.
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "C:\N\notepad++.exe", "C:\R\test_in.csv", "", "open", 1
This time I hit a "suspicious macro error" that leads me to believe that it may be an antivirus setting (macros are enabled in Access) blocking Shell from calling anything.
After days of testing I have found the solution, hopefully this can help anyone else in a similar situation. Windows Defender only blocks shell calls to non-Microsoft products, so I nested a call to PowerShell within the call to Shell:
Shell ("powershell.exe C:\R\bin\i386\Rscript.exe C:\R\test.R")
Take note you need to play around with the "s a lot ot get it working, my actual pipeline has more arguments and I had to enclose them in 5 sets of "s for it to pass through to powershell properly. IE:
Dim codePath As String: codePath = """""\\example\example"""""
Try these variations using Start or a second Command:
cmd = "Start C:\R\bin\i386\Rscript.exe C:\R\test.R"
or:
cmd = "cmd /c ""C:\R\bin\i386\Rscript.exe C:\R\test.R"""

Is there a way to write a command directly by code in the immediate window?

I'm trying to save all lines from the output window into a log-file. That works fine when I enter the command directly into the immediate window. However, I need a way to enter the command line by code.
I searched for a way to enter a command into the immediate window so the log-file I want will be created and filled with data. That's not happening and I don't know if this is even possible. Searching Google didn't help so far.
My command line is:
> Tools.LogCommandWindowOutput C:\Users\user\AppData\test.log
And I try to get it into the immediate window by
Debug.Print("> Tools.LogCommandWindowOutput C:\Users\user\AppData\test.log")
The command line works fine when put directly into the immediate window (either by typing it in or pasting it in). When I try to do that by code, nothing happens. Is there a way to do that or do I have to try another option and if so, what option is it?
EDIT:
I've tried the solution provided by RobertBaron with the following changes:
'Dim dummy = $"C:\\log\\outputfileAddOn_{Date.Now:yyyy_MM_dd_HH_mm_ss}.log"
'cmdWindow.SendInput($"Tools.LogCommandWindowOutput {dummy}", True)
cmdWindow.SendInput("Tools.LogCommandWindowOutput C:\log\outputfile_AddOn.log", True)
(I want a new file to be written every time, so I tried to add the date at the end to have unique file names)
It creates the file but doesn't log anything in it. What do I do wrong?
Another solution I have found was to add a command parameter in project-properties-debug-command parameter:
> C:\log\outputfile.log
This creates the file and inserts all of the data from the output window. The only problem that I have now is that this file will be overwritten every time the program is started. Is there a way I can set the logging from the second, third, … start at the end of the file? (adding /on at the end of the command Parameter didn't help) Or can I provide something like "outputfile_yyyy_MM_dd_HH_mm_ss.log" (for example: outputfile_2019_07_23_15_47_45.log)?
Thank you for your help!
You need to create a Visual Studio Extension project.
Add a new Custom Command item to the VSIX project.
This will create the Command1.vb. This is where you implement the code that you want to execute inside Visual Studio. The code executes whenever you select the entry Invoke Command1 from the Tools menu.
At the bottom of the Command1.vb file, there is the Execute() Sub. It displays a message just to show that the command is working. You can remove this eventually. But for now, just run the project. Another instance of Visual Studio will start. This is where you can test and debug your code. Once the second instance of Visual Studio has started, go to its Tools menu, and select the Invoke Command1 entry. A message box will display. Stop execution.
Now we want to modify the Execute() Sub so that our code gets executed when Invoke Command1 is selected. Here is the Sub that will execute the command that you want. Add it to the Command1 class.
Public Sub ExecCommandWindow()
Dim dte As EnvDTE.DTE = CType(Microsoft.VisualStudio.Shell.Package.GetGlobalService(GetType(Microsoft.VisualStudio.Shell.Interop.SDTE)), EnvDTE.DTE)
Dim cmdWindow As CommandWindow = CType(dte.Windows.Item(EnvDTE.Constants.vsWindowKindCommandWindow).Object, CommandWindow)
'Display some text in the command window
cmdWindow.OutputString("Executing command from the automation OM...")
'Send some command strings to the command window and execute them...
'This command will start logging all input/output in the command window to the specified file
cmdWindow.SendInput("Tools.LogCommandWindowOutput cmdwindow.log", True)
''Open a file in a code editor:
'' 1. We use an alias, 'of', for the File.OpenFile command
'' 2. This command takes quote-delimited parameters (in this case,
'' the name of the editor to load the file in)
'Dim cmd As String = "of "
'cmd = (cmd + """""C:\Contoso\ContosoCommonFramework\Integration.cs""""")
'cmd = (cmd + "/e:""""CSharp Editor""""")
'cmdWindow.SendInput(cmd, True)
'cmdWindow.SendInput("Edit.Find MessageTrxId", True)
'Turn off logging
cmdWindow.SendInput("Tools.LogCommandWindowOutput /off", True)
End Sub
Change the Execute() Sub to call ExecCommandWindow().
You can change the name of the command by changing its title in the Command1 class.
The Visual Studio extension needs to be installed by each user. Just distribute the .vsix file. To install, double-click it.
It's not the best solution, but it works (for now):
adding
>> C:\log\outputfile.log
(with two '>' before the path for the log file) attaches every log at the end of the file. So I get all Information and nothing is being overwritten.
As I want to know if there is a better solution, I will keep this thread open if that is permitted.

How to call java object in VBA with classpath

We use a CMD to call a PowerShell script. In the PowerShell script, a Java program is called. Both files are in the same directory. I want this all replaced by VBA within Microsoft Access. I have found several related topics but I can't decide whether it is possible or not based on these topics. Topics like Launch jar file from VBA code
The CMD contains the following code:
SET CLASSPATH=.\yyyyy.jar
powershell .\startscript.ps1
The PowerShell script contains the following sample:
& java '-Djavax.net.ssl.trustStore="zzzz.keystore"' com.router.router.router.Router -user:... etc.
We also run the same Java program in a different setting, only with the use of one .CMD-file. This is made like:
SET USR=user
SET CLASSPATH=.\yyyyy.jar
java -Djavax.net.ssl.trustStore=zzzz.keystore com.router.router.router.Router -user:%USR% etc.
Preferably both PowerShell and CMD become obsolete and the parameters like "-user" are fed with variables from the VBA code.
Does someone have a usable link, example or code? Please advice.
What you are trying to do is to run a command via the command line. It just happens that this command runs java, as far as the VBA code is concerned it may run anything that the shell would understand.
A sample code to run a command via a shell in VBA is the following (note there are many ways and it's super easy to find these samples on internet, I'm just using the first one I found):
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = False
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C " & yourCommand
... where yourCommand is the litteral string you would run in your command prompt. Now, it's all about string concatenation in VBA. Following your sample (and adding the username directly from VBA):
user = Environ("UserName")
yourCommand = "java -Djavax.net.ssl.trustStore=zzzz.keystore com.router.router.router.Router -user:" & user
(please note that I replaced %USR% - which asks the shell to retrieve the username - with a variable user that I've defined in VBA, even though in this specific example, the function Environ is asking environment variables so it's still asking it to a shell).

CMD file executed from VBA leads to different results

PROBLEM IS SOLVED ALREADY
this should be fairly simple, but I can't figure out what's wrong.
I have a cmd file in V:\something\XYZ.cmd, which takes 1 parameter.
When I execute it manually, e.g. Windows-Explorer and double-click the cmd, I get my result.
Now I have a XLSM file on my Desktop and a macro should invoke this cmd instead.
Problem is, when executed that way, I get some "file-not-found errors" in the cmd itself.
So how could I simulate the manual execution of the cmd.
There must be some path related problem...
This is how I execute from VBA:
Call Shell("cmd.exe /c " & "V:\something\XYZ.cmd" & " " & someParameter, vbNormalFocus)
I tried to put a
ChDir "V:\something\"
right before the call, but that doesn't change anything...
Where's the problem?
thank you, I just found the error myself:
There was a %root% used inside the script, this was the error. Changed it to absolute path, now it works

Add time and date in custom/user Code Snippet in XCode

How can I add date time in my custom code snippet?
I need frequent use to add my codes on other codes, and for others, I need to add my name and date time.
I created a code snippet with shortcut _ase, but I am not finding any help on net how can I add time to it.
You can't add date or time automatically using the native Xcode snippet grammar.
Snippets do not have anything other than token substitution using the <#VisibleTokenName#> syntax.
File templates are generated differently and have token substitution for a small subset of predefined tokens (like ___DATE___) in addition to the ability for custom tokens gathered in the UI.
You could write a bash script (or whatever) to update the snippet file for you with the correct date.
Looks like you can't do this using XCode snippets but I can suggest a quick workaround using apple script:
set str to "// Created by Anoop Vaidya on " & (do shell script "date '+%d/%m/%Y'")
tell application "Xcode"
activate
set the clipboard to (str as text)
tell application "System Events"
keystroke "v" using command down
end tell
end tell
You can set date using apple script:
set str to ("// Created by Anoop Vaidya on " & day of (current date) & "/" & ((month of (current date)) as integer) as string) & "/" & year of (current date)
but it is not so convenient as using shell script.
Now you need only to bind that script to some shortcut (using FastScripts for example) and use it.
You can add some additional functionality to the script like saving previous value from clipboard and then restoring it or may be just using some XCode scripting properties to directly insert text without clipboard.