So recently, as an exercise, I wanted to see about moving one of my simpler ASOC (AppleScript ObjectiveC) applications to a different language. Then I thought, why not two? So the first one I’ve been working with is C# via Visual Studio on the Mac (the 2022 preview). It’s um…interesting. First, you still need Xcode to do all the UI setup. I’m not sure why, and it’s a bit janky, but it’s not bad per se.
I think the Xamarin docs need a lot more sample code, it’s really intimidating if you’re new to the platform. But anyway, part of this app, ScutilUtil (https://github.com/johncwelch/ScutilUtil) uses the scutil command to pull info about the computer’s host name. (There may be a “proper” way to do it, but that’s not worth the search when scutil is right there.) To do so, you run scutil with various switches. i.e.
/usr/sbin/scutil --get ComputerName to get the computer name.
In ASOC, this is trivial, literally one line thanks to AppleScript’s ‘do shell script’ command:
set my theCurrentComputerName to do shell script "/usr/sbin/scutil --get ComputerName"
Easy-peasy. In C#/Xamarin…sigh. The best way I found was:
Process scutilTest = new Process(); scutilTest.StartInfo.UseShellExecute = false; scutilTest.StartInfo.RedirectStandardOutput = true; scutilTest.StartInfo.FileName = "/usr/sbin/scutil"; scutilTest.StartInfo.Arguments = " --get LocalHostName"; scutilTest.Start(); string localHostName = scutilTest.StandardOutput.ReadToEnd(); scutilTest.WaitForExit();
Like, it works right? But really? I mean, yes, this is a very cross-platform way to do it, but all that to run a single one-line command…it seems unelegant, and it seems unelegant on any of the platforms C#/Xamarin run on. Like, macOS/Linux/Windows all have a command line environment. They all have command line utilities that ship with the OS you might want to use because they’re there, and pretty fast.
Why make calling them so hard? Why not have something that gets you closer to do shell script. I mean, out of all of them, the only command/script environments you will never see on all three is cmd.exe, that’s windows-only and AppleScript is macOS – only, (but not something you’d run often in cases like this.) But shell? All three can have it. PowerShell? All three.
So wouldn’t it make more sense to have a way to test for the presence of a command environment, and a way to just use a command environment? Like say:
string localHostName = RunCommand -Environment zsh -Command "/usr/sbin/scutil" -Arguments "--get localHostName" -NoNewWindow -Wait
I’m using PowerShell-ish syntax here, because VS and .NET et al, but you get the idea. You could even have a way to check for a specific command environment if you wanted to be fancy, etc. Again, all the non-phone/non-tablet .NET platforms have a command-line environment of some form. Why not just allow for that to be used easily?
It’s times like these I wish Visual Studio Mac supported PowerShell as a language. Sigh.