XSharper has many command line options to run, debug and compile scripts.
It's difficult to remember all XSharper options. It's even more difficult to remember all XSharper actions and parameters. And it's impossible to remember all classes in .NET framework.
Yes, there is Internet, and MSDN, and Visual Studio, but I often find myself in a situation I need a brief piece of help. Command syntax perhaps. Exact parameter order. Fast.
To get help about XSharper command line options:
To list all XSharper built-in actions:
To learn about a specific XSharper built-in action:
To print all loaded .NET types with type matching *Con*:
To print all public methods and properties of a specific .NET type:
To run hello.xsh just
Same, but disable output to info stream:
Same as above, but also copy script output to a file (it will be still displayed in the console)
Require script elevation if the current user is not an administrator:
Run code from a URL (signature validation is forced)
To run hello.xsh just
Same, but disable output to info stream:
Same as above, but also copy script output to a file (it will be still displayed in the console)
Require script elevation if the current user is not an administrator:
Run code from a URL (signature validation is forced)
Same, but using a shorter syntax
.NET programs are crazy about configuration files. Many popular frameworks put lots and lots of program data, and even program logic into XML configuration files. While I'm not a big fan of replacement of code verified during compile time with code verified only on runtime, and System.Configuration namespace is a huge beast that takes hundreds of milliseconds to load even on a decent machine, the configuration files do have their legitimate uses.
A big problem with scripting languages is that configuration files are usually loaded by .NET looking at the executable name and location. Not a problem for compiled XSharper scripts. For interpreted scripts, however, the executable is always xsharper.exe and .NET will expect to find its .config file in the binary directory, not where your script is located.
To solve this problem for interpreted scripts, XSharper allows to explicitly specify what configuration file should be used via //config parameter:
To make the config madness complete, the script itself may reside in the configuration file (template may be produced via //genconfig):
This can be executed by providing . (dot) as script name:
XSharper can run scripts directly from command line, which is often faster than dealing with files, and replaces interactive mode. There are three special switches:
Evaluate expression from /// until the end of the line. By default it is treated as a piece of C# code:
Usually it's a good idea to wrap everything into double quotes (so <, > and " characters are not interpreted by command line interpreter).
XSharper command-line processing code replaces ` (back quote) with " in the expression to keep it simpler. In the unfortunate event you do need the ` character, just use "\x60" in C# code, or (char)0x60 in XSharper multi-expressions (there is no escaping there).
Print ASCII table of the first 96 printable characters (by generating array of bytes and calling XSharper.Core.Utils.ToHexDump on it):
If the expression starts with < it is treated as XML
Finally, if the expression starts with =, it is treated as interpreted multi-expression with relaxed rules
Aside of protecting from the wrongdoings of Windows command processor, if the first character of the expression is ", only the string inside the quotes is considered to be a script, and the rest are treated as arguments that can be accessed via ${=$argv[0]}, ${=$argv[1]} and so on. This looks a bit confusing but allows writing simple one liners with arguments.
For example, display the length of file passed as first argument:
If the first character is not ", expression is evaluated until the end of the line:
Also, additional assemblies may be specified in the command line as an assembly name, or DLL path. Multiple names may be specified in comma or semicolon separated list.
Load the image specified in the first command line argument and copy it to clipboard:
Actually the code above may be shortened via prefixing assembly names with @, which adds assembly names into default namespace (does the right thing for Windows.Forms, System.Diagnostics where namespace matches assembly name):
And now, with one more parameter, we produce a complete utility img2clipboard (more about it in Compiling scripts):
Evaluate expression (either C#, or multi-expression if starts with =) that returns value, and write the value with WriteLine .
Read c:\windows\win.ini and print each line within [[ ... ]]:
Print first 64 bytes of explorer.exe as HEX dump:
Evaluate expression (either C#, or multi-expression if starts with =) that returns value, and dump the value.
In some special cases it may be useful to read script from standard input, instead of the command line. In that case specify - (minus) instead of the expression.
You are on a machine via Remote Desktop, there is no Visual Studio in sight, nor you can install, nor you want to install anything, and script does not work. What's next?
Enable script debug output (you'll need DebugView for Windows to see the output)
If //debug is specified, if script fails with exception, a complete error message is produced. For example, there is a script:
You are on a machine via Remote Desktop, there is no Visual Studio in sight, nor you can install, nor you want to install anything, and script does not work. What's next?
Enable script debug output (you'll need DebugView for Windows to see the output)
If //debug is specified, if script fails with exception, a complete error message is produced. For example, there is a script:
which when executed attempts to divide by 0:
To enable debug output and print it to console there is //debugc switch (debugc= debug to console)
Same, but enable debug output and print it to console, including script engine details, is done via //verbose:
Same, as above, but also trace lines of code as they execute
Measure script execution time, display exit code and ask for a key press before exit
Using the previous steps you may determine where the program throws an exception, how execution goes, how to print debug messages etc.
It is as important to see variables defined at critical script points. Of couse, can use the usual ToString method, but it often produces rather useless results for complex objects.
XSharper has a few special methods for converting objects variables:
Shortcut name | Full method name | Description |
---|---|---|
.ToDump | Dump.ToDump | Convert a .NET object graph to string |
.ToDumpAll | ScriptContext.ToDumpAll | Convert all defined XSharper variables to string (a filter may be specified to dump only some variables |
.Dump | ContextWriter.Dump | Shortcut for ContextWriter.WriteDump.ToDump(object)) |
.Dump | ScriptContext.Dump | Shortcut for Out.Write(Dump.ToDump(object)) |
What it all means is easier to demonstrate:
prints
XSharper requires no installation. Sometimes this is not good enough.
Imagine a situation when you wrote a script that needs to be used by someone else. It is an inconvenience to explain to users of your script all the prerequisites, from where to download what, and how to specify command line parameters, and alike. It can go wrong and it will.
It is also an inconvenience to distribute an MSI or setup.exe, that may require admin rights, will have to be launched, and then users will need to dive into c:\program files (x86)\your-application\something.bat (that will launch xsharper.exe yourscript.xsh) . Nor you want to distribute a bunch of DLLs and .config files for "XCopy deployment" which used to be a popular buzz-word when .NET was introduced.
Simple single .EXE , that just works, is the best option here. It's very simple with XSharper too.
For the purpose of demonstration, let's the hello.xsh script be
This operation is as simple as (hello.exe is actually optional and may be skipped)
Now there is a single hello.exe, which can be run as
//genexe produces a Windows console executable but a Windows executable may be produced instead. There will be no console output in this case though.
and that produces windir.exe, which if executed displays
What C# code does XSharper generate and compile?
In the produced file you would see something like
You may control the name of the generated class and namespace via //namespace and //class parameters, which come handy if the generated code is included into another project.
Note that using the new C# 3.0 syntax makes the generated code relatively readable, yet it's possible to revert back to a less readable, but slightly faster, C# 2.0 notation with //forcenet20 parameter.
//gencs parameter by default produces only script source code, without any boiler plate code. void static Main and all the whistles may be added by //main option, which is added automatically when .EXE files are produced.
It's also possible to produce full and complete source code, including all needed DLLs, icons, manifests and a batch file to build it:
compile_hello.bat will invoke C# compiler and produce the very same hello.exe .
Another not-so-hypothetical situation. Once upon a time you wrote a useful script hello.xsh that just works, which was compiled into to an executable.
Now, 18 months later, it does not work anymore because it has Hello, World hardcoded into it, yet now the missing exclamation sign was detected and Hello, World! must be there instead. Source code of the original utility is, well, somewhere. Long deleted from your hard-drive, perhaps it's on one of those backup discs of the late year, on that shelf, or may be the other, oh well...
Writing from scratch is possible but no volunteers. There is an option to use Reflector to decompile the code into a Visual Studio project, that can be then compiled and run. That's again something to download and install.
With XSharper there is a better way. Just run the hello.exe with //save:
Another use of the //save option is to provide a way out of too long command lines. For example, there is a fine command line piece that prints first 64 bytes of explorer.exe:
Now it needs to be converted into a more generic program that accepts a command-line parameter with the filename to be dumped. Instead of writing everything from scratch, the script may be saved into a file:
And now it can be easily changed to use a command line parameter instead:
There are 4 essential utilities included with XSharper: display version info, zip files, unzip archive, and to download a file from URL. They are not replacements for real zip/unzip/wget utilities, but do provide sufficient functionality for many scenarios and batch scripts w/o the need to download and install additional tools.
These utilities are actually XSharper scripts embedded into xsharper.exe, and source code can be seen/modified by adding //save parameter to command lines (e.g. xsharper //zip //save zip.xsh) .
Display version info and Xsharper's environment variables.
Store C:\Hello directory into a .ZIP archive C:\hello.zip:
There are many additional parameters available, for recursive compression, password protection, to help with hidden files & directories etc. Run xsharper //zip /? for more details.
Extract C:\hello.zip to C:\Hello2 (created if does not exist):
Run xsharper //unzip /? for more details.
wget it is not. Simply download data from the specified URL and save it to a file. If filename is not specified, file is saved to the current directory.
C:\>xsharper //download http://www.xsharper.com/xsharper.exe Downloading http://www.xsharper.com/xsharper.exe => C:\xsharper.exe ... ... Completed. 343040 bytes downloaded.
In Vista and Windows 7, at least by default, even administrator does not have administrative privileges all the time. If something administrative needs to be done, user must explicitly put on his admin's hat and launch an "elevated" process, which will then have administrative privileges.
If a program needs to perform an administrative action on Vista/W7, it must contain a special XML resource called manifest, to indicate that the program must be "elevated" before execution.
This manifest may (and will be) embedded when XSharper script is compiled with //requireAdmin parameter. Then, when the script is executed, Vista/Windows7 will produce an elevation screen.
Alternatively, the option may be specified in the script itself:
Either way, if this script is executed under Vista/Windows7, it will produce:
As you see, it's possible to see from this screen which script has requested the privilege. If access is granted, XSharper reuses the original console instead of spawning the new one, thus not breaking batch files which rely on user output:
What's interesting is that in interactive mode, where script is not compiled, there are two xsharper processes running in this scenario: one w/o administrative rights, that spawned a new elevated one, which talks back to the original process via .NET remoting.
Upgrade XSharper in-place
To check if you run the latest version of XSharper, and automatically upgrade if you don't, run
Display execution time and exit code
If you run XSharper through Start Menu -> Run ( or through keyboard via Windows + R ), when script terminates, its window disappears by default.
To make the window stay, display execution time & exit code use //wait parameter:
Generate sample script
Just to produce a sample XSharper script that does, well, does not do anything really:
Likewise, a configuration file may be created: