scriptcs for business and pleasure
TRANSCRIPT
My Contact Information Twitter:
@DavidPerish
Linked In:
https://www.linkedin.com/in/davidperish Email:
[email protected] Website:
http://stonyhillsoftware.com
My Background 14 years of experience in operations, testing and development Developing professionally on the Microsoft stack since VB6 Certifications include MCSD (Web Applications 4.5), MCP (C#), MCTS (Web Applications 4.0) Currently contracting through TEKsystems Recently incorporated Stony Hill Software LLC
Before NuGet & VS 2010
After NuGet & VS 2013
Overview
ScriptCS History Inspired by Node.js Released in February of 2013 Hosted on GitHub: https://github.com/scriptcs Created by Glenn Block (http://github.com/glennblock)
What Is ScriptCS? ScriptCS is a free and open source project hosted on GitHub. Provides a C# script hosting environment, powered by Roslyn & NuGet Removes the need for solution files, project files, main() methods, config files, etc. Allows you to use all of C#’s goodness as .csx files, which can be created with any text-editor Includes mechanism for importing & packaging your .csx files as 'Script Packs' Also provides interactive shell, or 'REPL‘
Roslyn Compiler API Decouples the .Net compilers from Visual Studio Exposes object models for each component of the compiler, no longer a black box Allows access to the workspace API which assists in refactoring, code analysis and dependency
management over entire projects & solutions Provides runtime execution context for evaluating code snippets NuGet Package: Install-Package Microsoft.CodeAnalysis –Pre Source: git clone https://git01.codeplex.com/roslyn
NuGet Package Manager Preinstalled as the default package manager in Visual Studio 2012+ Over 29k 30k packages publically available Allows for private repositories (package sources) for organizations Basis for the Chocolatey package manager for windows desktop & console applications Home page: https://www.nuget.org/
REP a what L? REPL = Read – Evaluate – Print – Loop As opposed to the Edit – Compile – Run - Debug cycle typically used in modern IDEs Allows you quickly explore the language and framework without all the rigor of Visual Studio Many other popular languages now provide one
Python Ruby Haskell F# JavaScript (via F12 tools)
REPLs were the default shell on many early personal computers
Apple ][
Comodore 64
Microsoft COLOR Basic
What’s ScriptCS Good For? The REPL provides instant feedback to the developer Perfect environment for doing code katas Exploring framework libraries in a much more interactive way Great for prototyping services to complement front-end & SPA development As an extensibility mechanism
ConfigR
https://github.com/config-r/config-r
Glimpse
http://www.nuget.org/packages/Glimpse.ScriptCs
Installation
Installation Requirements .Net 4.5 Framework
-or- Mono Development Tools 3.0 Administrator privileges Internet connection (for installation via Chocolatey)
Installing Chocolatey
Home Page: https://chocolatey.org Installing Chocolatey with administrative command shell or powershell:
C:\> @powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin
PS> iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
Installing ScriptCS with Chocolatey Installing ScriptCS:
C:\> choco install scriptcs
Command.exe Alternatives Not necessary, but does make the console experience less painful on Windows A few notables:
ConsoleZ:
> choco install consolez Cmder:
> choco install cmder ComEmu:
> choco install comemu Total Command Console:
> choco install tcc
Notepad.exe Alternatives Notepad will suffice, but a better editor wouldn’t hurt either: A few notables:
Atom:
> choco install atom Notepad++:
> choco install notepadplusplus Sublime Text:
> choco install sublimetext3 Nano:
> choco install nano
[Hello World Demo]
Referencing Existing Assemblies External DLLs can be included with:
#r “MyAssembly.Name”
Using statements work the same as in normal C#
using MyAssembly.Name.Class
This can be done in/out of REPL mode
CSX Files
scriptcs.exe options -? Shows usage -script [file] Script filename -repl Executes csx file
and stays in interactive mode
-debug Emits PDB debug symbols -cache Compiles script as dll -log [mode] Emits logging information
with one of the following levels:
Error, Info, Debug, Trace
-install Installs & restores packages
specified in packages.config
-config [file] Specifies options file to hold
default command line args -output [file] Writes all output to
specified file
Script Arguments Specified with double dash
scriptcs myscript.csx -- “My Argument”
Should appear after scriptcs.exe single dash arguments
scriptcs –log info –repl myscript.csx – “My Argument”
Can be accessed with the Env.ScriptArgs readonly collection
Env.ScriptArgs[n]
[SpeakR.csx Demo]#r "System.Speech";using System.Speech.Synthesis;
public static void Speak(string value) { using (var ss = new SpeechSynthesizer()) {
Console.WriteLine(value); ss.Speak(value);
}}
if (Env.ScriptArgs.Count > 0) { Speak(Env.ScriptArgs[0]);
}
-cache option Compiles script as DLL file Saved in .cache sub-directory First time –cache option is used the file will be compiled to a DLL Subsequent calls with –cache will use the pre-compiled DLL Any calls to the script without –cache will always be parsed dynamically The only way to refresh is to remove the DLL and call the script again with the –cache option
-repl option Keeps ScriptCS in interactive mode, versus just exiting after executing the script This is the default when no script is specified Can alternatively use #load “MyFile.csx”; after starting scriptcs.exe with no script
argument
-log option Allows you to specify one of the following log levels
Info Error Debug Trace
Can be used in script or repl mode
Packages
Referencing Scripts & Script Packs #load directive can be used to load local scripts in both csx and repl modes
Should be placed at the top of csx files
Script Packs behave in much the same way, but can be loaded remotely via NuGet using
scriptcs – install ScriptCs.SomeScriptPack
Once script pack has been downloaded, there is no need to use #r or using statements to reference it, which makes scripts easier to write without intellisense
Can simply assign an implicitly typed variable to Require<SomeScriptPack>()
var someObj = Require<SomeScriptPack>();
In addition to Script Packs and locally loaded files, ScriptCS also supports modules, which can be used to further customize the script hosting environment and even provide new repl commands
[ScriptCs.WebApi demo]#load "speakr.csx";
public class SpeakRController : ApiController {public string Get() {
Speak("Someone is calling your webservice"); return "Hello Web Client!";
}}
var webApi = Require<WebApi>();var server = webApi.CreateServer("http://localhost:8888");server.OpenAsync().Wait();
Console.WriteLine("Listening...");Console.ReadKey();server.CloseAsync().Wait();
[ScriptCS.Request demo]var client = Require<Request>();var result = client.Get("http://localhost:8888/SpeakR");Console.WriteLine(result);
Package Management Switches-Install (-I) Installs and restores packages which are specified in packages.config
-Global (-g) Installs and restores global packages which are specified in packages.config
-Save (-S) Creates a packages.config file based on the packages directory
-Clean (-Cl) Cleans installed packages from working directory
-AllowPreRelease (-pre) Allows installation of packages' prelease versions
-PackageVersion (-P) Defines the version of the package to install. Used in conjunction with -install
Other Popular Packages ScriptCs.AzureManagement
Script Pack that provides management of Windows Azure resources via the Windows Azure Management Libraries
ScriptCs.AzureMediaServices Script pack for using Azure Media Services.
ScriptCs.AzureMobileServices Script pack for accessing Azure Mobile Services.
ScriptCs.FluentAutomation FluentAutomation Script Pack
ScriptCs.Gui
A lightweight GUI toolkit for ScriptCS.
ScriptCs.NUnit NUnit script pack for scriptcs
ScriptCs.ScriptPackBoilerplate A template for building ScriptCS script packs
ScriptCs.ServiceStack ServiceStack Script Pack
ScriptCs.SignalR Script pack for self-hosting SignalR
ScriptCs.SsRedis Script Pack that facilitates working with Redis
Debugging
Using Visual Studio To Debug scriptcs.exe can be opened as a project in Visual Studio Set the following properties on the exe:
Arguments: yourscript.csx –debug – “your args” Working Directory: C:\MyProject
Save as a Visual Studio solution file Add yourscript.csx to the project in the solution explorer via ‘Add Existing Item’ Set a breakpoint in your script Hit F5 to begin debugging
Extensibility
ScriptCS With Glimpse GitHub Project: https://github.com/filipw/Glimpse.ScriptCs ScriptCS extensibility for Glimpse.AspNet is provided via the following nuget packages:
scriptcs.core scriptcs.hosting scriptcs.engine.Roslyn glimpse.aspnet glimpse.scriptcs
ScriptCS With ConfigR GitHub project: https://github.com/config-r/config-r ConfigR uses CSX files to provide strongly typed configuration files. One-package install via nugget:
> Install-Package ConfigR
Create myprogram.exe.csx file in the root of the application Set ‘Copy To Output Directory’ to ‘Copy Always’ in the properties window Create settings in the CSX file with:
Add(“name”, value);
Retrieve settings with: Config.Global.Get<T>(“name”);
Alternative C# Shells / REPL-Like Resources C# REPL (Mono)
http://www.mono-project.com/docs/tools+libraries/tools/repl/
C# Pad (Web)
http://csharppad.com/
LinqPad
http://www.linqpad.net/
Coding Kata .Net
http://codingkata.net/
Odds and Ends
ScriptCS Resources ScriptCS
Blog - http://blog.scriptcs.net/
Wiki - https://github.com/scriptcs/scriptcs/wiki
Twitter - https://twitter.com/scriptcsnet (@ScriptCSNet)
Samples - https://github.com/scriptcs/scriptcs-samples
StackOverflow Tag - http://stackoverflow.com/questions/tagged/scriptcs Chocolatey – http://chocolatey.org/ Pluralsight - http://www.pluralsight.com/courses/introduction-scriptcs Roslyn
Roslyn Walkthroughs - http://www.microsoft.com/en-us/download/details.aspx?id=27745
Questions, Comments, Rants? Twitter:
@DavidPerish
Linked In:
https://www.linkedin.com/in/davidperish Email:
[email protected] Website:
http://stonyhillsoftware.com