Giter Site home page Giter Site logo

scriptcs-sublime's Introduction

scriptcs

Chocolatey Version Chocolatey Downloads NuGet version (ScriptCs.Hosting)

*nix Build Status Windows Build Status Coverity Scan Build Status

Issue Stats Issue Stats

What is it?

scriptcs makes it easy to write and execute C# with a simple text editor.

While Visual Studio, and other IDEs, are powerful tools, they can sometimes hinder productivity more than they promote it. You don’t always need, or want, the overhead of a creating a new solution or project. Sometimes you want to just type away in your favorite text editor.

scriptcs frees you from Visual Studio, without sacrificing the advantages of a strongly-typed language.

  • Write C# in your favorite text editor.
  • Use NuGet to manage your dependencies.
  • The relaxed C# scripting syntax means you can write and execute an application with only one line of code.
  • Script Packs allow you to bootstrap the environment for new scripts, further reduces the amount of code necessary to take advantage of your favorite C# frameworks.

Getting scriptcs

Releases and nightly builds should be installed using Chocolatey. To install Chocolatey, execute the following command in your command prompt:

@powershell -NoProfile -ExecutionPolicy Unrestricted -Command "iex ((New-Object Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin

If the above fails with the error indicating that proxy authentication is required (i.e. HTTP 407) then try again with the following on the command prompt that uses your default credentials:

@powershell -NoProfile -ExecutionPolicy Unrestricted -Command "[Net.WebRequest]::DefaultWebProxy.Credentials = [Net.CredentialCache]::DefaultCredentials; iex ((New-Object Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin

Note: If you are using a version of Chocolatey > 0.9.9.0 you can pass the -y into the install and upgrade commands to prevent the confirmation that will appear.

Installing scriptcs

Once Chocolatey has been installed, you can install the latest stable version of scriptcs from your command prompt:

choco install scriptcs

Chocolatey will install scriptcs to %LOCALAPPDATA%\scriptcs\ and update your PATH accordingly.

Note: You may need to restart your command prompt after the installation completes.

Staying up-to-date

With Chocolatey, keeping scriptcs updated is just as easy:

choco upgrade scriptcs

Note: If you are using a version of Chocolatey < 0.9.0.0 you will need to use choco update scriptcs, but also think about updating Chocolatey itself.

Nightly builds

Nightly builds are hosted on MyGet, and can also be installed through with Chocolatey:

choco install scriptcs -pre -source https://www.myget.org/F/scriptcsnightly/ 

Building from source

Windows

  1. Ensure you have .NET Framework 4.6.1 installed.

  2. Execute the build script.

    build.cmd

Linux

  1. Ensure you have Mono 5.12 or later installed.

  2. Execute the build script

    ./build.sh

Getting Started

Using the REPL

The scriptcs REPL can be started by running scriptcs without any parameters. The REPL allows you to execute C# statements directly from your command prompt.

C:\> scriptcs
scriptcs (ctrl-c or blank to exit)

> var message = "Hello, world!";
> Console.WriteLine(message);
Hello, world!
> 

C:\>

REPL supports all C# language constructs (i.e. class definition, method definition), as well as multi-line input. For example:

C:\> scriptcs
scriptcs (ctrl-c or blank to exit)

> public class Test {
    public string Name { get; set; }
  }
> var x = new Test { Name = "Hello" };
> x
{Name: "Hello"}

C:\>

Writing a script

  • In an empty directory, create a new file named app.csx:
using Raven.Client;
using Raven.Client.Embedded;
using Raven.Client.Indexes;

Console.WriteLine("Starting RavenDB server...");

using (var documentStore = new EmbeddableDocumentStore { UseEmbeddedHttpServer = true })
{
    documentStore.Initialize();
    Console.WriteLine($"RavenDB started, listening on http://localhost:{documentStore.Configuration.Port}");
    Console.ReadKey();
}
scriptcs -install RavenDB.Embedded
  • Execute your script. Note that listening on a port requires that the command prompt be launched using the Run as Administrator option.
> scriptcs app.csx
INFO : Starting to create execution components
INFO : Starting execution
Starting RavenDB server...
.. snip ..
RavenDB started, listening on http://localhost:8080.
  • Navigating to the URL that Raven is listening on will now bring up the RavenDB management studio.

Bootstrap scripts with Script Packs

Script Packs can be used to further reduce the amount of code you need to write when working with common frameworks.

  • In an empty directory, install the ScriptCs.WebApi script pack from NuGet. The script pack automatically imports the Web API namespaces and provides a convenient factory method for initializing the Web API host. It also replaces the default ControllerResolver with a custom implementation that allows Web API to discover controllers declared in scripts.
scriptcs -install ScriptCs.WebApi
  • Script packs can be imported into a script by calling Require<TScriptPack>(). Create a file named server.csx that contains the following code:
public class TestController : ApiController {
    public string Get() {
        return "Hello world!";
    }
}

var webApi = Require<WebApi>();
var server = webApi.CreateServer("http://localhost:8888");
server.OpenAsync().Wait();

Console.WriteLine("Listening...");
Console.ReadKey();
server.CloseAsync().Wait();
  • In a command prompt running as administrator, execute the server.csx file.
scriptcs server.csx 
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello world!</string>

Referencing scripts

  • Move the TestController class from the previous example into a new file named controller.csx with the following content.

  • On the first line of server.csx, reference controller.csx using the #load directive. Note: #load directives must be placed at the top of a script, otherwise they will be ignored.

#load "controller.csx"
  • In a command prompt running as administrator, execute the server.csx file.
scriptcs server.csx 
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello world!</string>

Referencing assemblies

You can reference additional assemblies from the GAC or from the bin folder in your script's directory using the #r directive:

#r "nunit.core.dll"
#r "nunit.core.interfaces.dll"

var path = "UnitTests.dll";
var runner = TestSetup.GetRunner(new[] {path});
var result = runner.Run(new ConsoleListener(msg => Console.WriteLine(msg)), TestFilter.Empty, true,     LoggingThreshold.All);

Console.ReadKey();

Debugging

Instructions for debugging scripts using Visual Studio can be found on the wiki.

Package installation

You can install any NuGet packages directly from the scriptcs CLI. This will pull the relevant packages from NuGet, and install them in the scriptcs_packages folder.

Once the packages are installed, you can simply start using them in your script code directly (just import the namespaces - no additional bootstrapping or DLL referencing is needed).

The install command will also create a scriptcs_packages.config file if you don't have one - so that you can easily redistribute your script (without having to copy the package binaries).

  • scriptcs -install {package name} will install the desired package from NuGet.

    For example:

     scriptcs -install ServiceStack
    
  • scriptcs -install (without package name) will look for the scriptcs_packages.config file located in the current execution directory, and install all the packages specified there. You only need to specify top level packages.

For example, you might create the following scriptcs_packages.config:

<?xml version="1.0" encoding="utf-8"?>
<packages>
	<package id="Nancy.Hosting.Self" version="0.16.1" targetFramework="net40" />
	<package id="Nancy.Bootstrappers.Autofac" version="0.16.1" targetFramework="net40" />
	<package id="Autofac" version="2.6.3.862" targetFramework="net40" />
</packages>

And then just call:

scriptcs -install

As a result, all packages specified in the scriptcs_packages.config, including all dependencies, will be downloaded and installed in the scriptcs_packages folder.

Contributing

Samples and Documentation

Additional samples can be contributed to our samples repository. Documentation can be found on our wiki.

Community

Want to chat? In addition to Twitter, you can find us on Google Groups and JabbR!

Coordinators

Core Committers

Credits

  • Check out the list of developers responsible for getting scriptcs to where it is today!
  • Special thanks to Filip Wojcieszyn for being the inspiration behind this with his Roslyn Web API posts.
  • Thanks to the Roslyn team who helped point me in the right direction.

License

Apache 2 License

scriptcs-sublime's People

Contributors

aaronpowell avatar filipw avatar follesoe avatar glennblock avatar jrusbatch avatar khellang avatar paulbouwer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

scriptcs-sublime's Issues

Error on Build

I get the following error when I select build:

[Error 6] The handle is invalid
[cmd: [u'scriptcs', u'C:\dev\scriptcs\play\test.csx']]
[dir: C:\dev\scriptcs\play]
[path: C:\blah blah blah...;C:\dev\scriptcs\src\Scriptcs\bin\debug]
[Finished]

The same test.csx works fine from the command line.

Any ideas?

Command to run scriptcs with clean flag

Running scriptcs.exe -clean should remove any assemblies that were placed in the project's directory by scriptcs including, but not limited to, assemblies that are included in the packages declared in the packages.config file. All other binaries in the directory should be left alone.

This flag should be exposed as a Sublime Text command so that we can use a keyboard shortcut to invoke it.

Build system for C# Scripts

A Build System will enable developers to use a single shortcut to build and run a script.

The most basic Build System would look something like this:

{
    "cmd": ["scriptcs", "$file"],
    "selector": "source.csx"    
}

This will call scriptcs, passing in the active file as its argument. The selector requires a language definition, but once that is in place, we can have it automatically detect that *.csx-files should use the ScriptCs build system.

Syntax highlighting for C# Scripts

Sublime Text ships with syntax highlighting for C#. However, C# script has a slightly different syntax. For instance is it allowed to write code not belonging to a explicit class or method. This will prevent Sublime Text from correctly highlighting the code (see screenshot).

I think it would make sense to use the official Sublime Text C# language definitions as a starting-point, and extend these to with new syntax rules. Preferably with as few changes as possible.

syntaxt-highlight

Arg to auto close REPL after running script

When running a script via scriptcs {file} -repl it would be nice to be able to pass another argument such as -autoclose which automatically exits scriptcs once it has completed running the file. It would also be handy to be able to mute the extra output such as "INFO: Loading preseeded script:" etc.

This would be useful for the sublime text plugin to allow for running simple scripts without having to use Console.WriteLine for output - we would benefit from the repl auto-dumping.

I'll see if I can get a pull request going which has a rough outline of what I want to achieve.

Sublime output doesn't behavior as command line execution.

I have a simple script

#r "System.ComponentModel.DataAnnotations"
using System.ComponentModel.DataAnnotations;

class Person
{
    [Required]
    public string Name { get; set; }

    [Required]
    public int Age { get; set; }

    [Required, MaxLength(4)]
    public string Nickname { get; set; }
}

var pessoa = new Person();

pessoa.Name = "Alberto";
pessoa.Age = 25;
pessoa.Nickname = "Alberto Monteiro";

var validationContext = new ValidationContext(pessoa);
var results = new List<ValidationResult>();
var valid = Validator.TryValidateObject(pessoa, validationContext, results, true);

foreach (var result in results) 
{
    Console.WriteLine(result.ErrorMessage);
}

When running on Sublime and pressing CTRL + B

I got this output:

[Finished in 5.5s]

When running on command line using this commnad:

PS C:\Temp> scriptcs -script .\Validacao.csx -cache false

I got this output

O campo Nickname deve ser uma cadeia de caracteres ou tipo de matriz com comprimento máximo de '4'.

Why the sublime output doesn't work properly?

PS C:\Temp> scriptcs -v
               _       _
 ___  ___ _ __(_)_ __ | |__ ___ ___
/ __|/ __| '__| | '_ \| __// __/ __|
\__ \ (__| |  | | |_) | |_| (__\__ \
|___/\___|_|  |_| .__/ \__\\___|___/
                |_| Version: 0.14.1
Sublime Build: 3083
SO: Windows 8.1 Enterprise
scriptcs plugin version: v2014.11.02.23.17.05

CTRL+C indicates termination in Sublime Text but mono-sgen is still running

I have the following scriptcs script file start.csx using the ScriptCs.Nancy nuget as follows:

Require<NancyPack>().Get("/", _ => "Hello, world!").Host();

When compiling in Sublime Text via CMD+B then CTRL+C to terminate Sublime Text indicates that the process has been [Cancelled]but the mono-sgen process is still running and holding on to the default port 8888.

I'm guessing that this is due to scriptcs-sublime expecting the script to have a natural exit from the implied "main" method rather than staying open / running?

I'm not sure if this is something that my code should handle or whether CTRL+C is not being sent correctly to mono scriptcs.exe (as it works fine from the command line).

notreallycancelled

Linqpad type output

Any way to add a linqpad type output so whe running a script which outputs a IEnumerable uquery it shows in a "grid" or collapsable tree view or something?

Create ScriptCs.Sublime Chocolatey package

The package could have a dependency on Sublime so that it installs if the user doesn't already have it, and automatically add the scriptcs package to the installation.

Command to run scriptcs with install flag

Running scriptcs file.csx --install will copy NuGet binaries into scripts bin directory. This should be exposed as a Sublime Text command, so that it can be invoked by a short-cut.

Error occurs when running a script that uses Console.Readkey / ReadLine

Found package reference: C:\code\scriptcs\samples\servicestackhost\packages\ServiceStack.3.9.37\lib\net35
Found package reference: C:\code\scriptcs\samples\servicestackhost\packages\ServiceStack.Common.3.9.37\lib\net35
Found package reference: C:\code\scriptcs\samples\servicestackhost\packages\ServiceStack.Redis.3.9.37\lib\net35
Found package reference: C:\code\scriptcs\samples\servicestackhost\packages\ServiceStack.Text.3.9.37\lib\net35
listening on http://*:999/

Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.
   at System.Console.ReadKey(Boolean intercept)
   at Submission#0..ctor(Session session, Object& submissionResult)
   at Submission#0.<Factory>(Session session)
   at Roslyn.Scripting.CommonScriptEngine.Execute[T](String code, String path, DiagnosticBag diagnostics, Session session, Boolean isInteractive)
   at Roslyn.Scripting.Session.Execute(String code)
   at ScriptCs.Wrappers.SessionWrapper.Execute(String code) in c:\code\scriptcs\src\ScriptCs.Core\Wrappers\SessionWrapper.cs:line 17
   at ScriptCs.ScriptExecutor.Execute(String script, IEnumerable`1 paths, IEnumerable`1 scriptPacks) in c:\code\scriptcs\src\ScriptCs.Core\ScriptExecutor.cs:line 47
   at ScriptCs.Program.Main(String[] args) in c:\code\scriptcs\src\ScriptCs\Program.cs:line 28
[Finished in 10.6s]

Looks like a buffer needs to be passed the process.

Cannot load external assembly

Maybe this is more of a Roslyn than a ScriptCs-Sublime question, but trying here for help anyhow. Given the following csx, referring to an external assembly with a given namespace and Person class :

#r "MyExternalTestAssembly.dll"

using System;
using MyExternalTestAssemblyNamespace;


var person = new Person();
for(int i =1; i < 6; i++)
{
    var person = new Person();
    var spoken = person.Speak();
    Console.WriteLine(spoken);
}

When I try to build with the Sublime ScriptCs build, I get

(1,1): error CS0006: Metadata file 'MyExternalTestAssembly.dll' could not be found
[Finished in 0.4s with exit code -1]

I've tried to put the dll into the packages folder as well, but that does not seem to help neither. What path does it use for looking up references?

Unexpected named argument: inMemory

  • Reproduction :
  • Have scriptcs installed
  • Have Sublime Text 3 installed
  • Install scriptcs package from package control
  • Write a simple script
var foo = 12;
Console.WriteLine(foo);
  • Build
  • Get the below error message
Unexpected named argument: inMemory
ERROR: Usage: scriptcs options

   OPTION                    DESCRIPTION                                                              
   -scriptname (-s)          Script file name, must be specified first                                
   -help (-?)                Displays help                                                            
   -debug (-debug)           Flag which switches on debug mode                                        
   -loglevel (-log)          Flag which defines the log level used.                                   
   -install (-install)       Installs and restores packages which are specified in packages.config    
   -restore (-restore)       Restores installed packages, making them ready for using by the script   
   -save (-save)             Creates a packages.config file based on the packages directory           
   -clean (-clean)           Cleans installed packages from working directory                         
   -allowprerelease (-pre)   Allows installation of packages' prelease versions                       
   -version (-version)       Outputs version information                                              

   EXAMPLE: scriptcs server.csx -debug
   Shows how to start the script with debug mode switched on


[Finished in 0.5s]
Additional information

C:\Users\Ashutosh>scriptcs -version
scriptcs version 0.5.0.0


Command to run scriptcs with restore flag

Running scriptcs file.csx -restore will copy the binaries from the packages folder to the bin folder. Should be exposed as a Sublime Command so that we can use a keyboard shortcut to issue the command.

File must be saved for build to work

Currently if you create a new file, set the build system / syntax to scriptcs and hit ctrl + b you get an exception and scriptcs crashes.

If possible, it would be nice if the plugin was clever enough to save your file to a temp location and run that file.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.