├── .gitattributes ├── .gitignore ├── LICENSE.md ├── README.md ├── active-directory ├── README.md ├── credentials.txt └── start.csx ├── arcgis ├── geocode.csx ├── packages.config ├── query.csx ├── queryandreversegeocode.csx ├── readme.md ├── reversegeocode.csx ├── servicestatus.csx └── start.csx ├── fluentautomation ├── README.md ├── packages.config └── start.csx ├── itextsharp ├── README.md ├── input.pdf ├── packages.config └── start.csx ├── nancy ├── README.md ├── bootstrapper.csx ├── customroutedescriptionprovider.csx ├── module.csx ├── packages.config ├── pathprovider.csx ├── start.csx └── views │ └── index.html ├── net ├── README.md ├── chatClient.csx ├── chatServer.csx └── packages.config ├── nunit-runner ├── MyUnitTests.dll ├── packages.config ├── readme.md ├── setup.csx └── start.csx ├── ravendb ├── README.md ├── packages.config └── start.csx ├── servicestackhost ├── models.csx ├── packages.config ├── service.csx └── start.csx ├── signalr-livereload ├── README.md ├── broadcaster.csx ├── jsonconfiguration.csx ├── models.csx ├── packages.config ├── start.csx └── usings.csx ├── webapihost ├── packages.config ├── start.csx ├── testcontroller.csx └── webapiconfig.csx └── wpf ├── CalculatorView.xaml ├── mvvm.csx ├── start.csx ├── utilities.csx ├── viewmodels.csx └── views.csx /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | # http://davidlaing.com/2012/09/19/customise-your-gitattributes-to-become-a-git-ninja/ 3 | * text=auto 4 | 5 | # Custom for Visual Studio 6 | *.cs diff=csharp 7 | *.sln merge=union 8 | *.csproj merge=union 9 | *.vbproj merge=union 10 | *.fsproj merge=union 11 | *.dbproj merge=union 12 | 13 | # Standard to msysgit 14 | *.doc diff=astextplain 15 | *.DOC diff=astextplain 16 | *.docx diff=astextplain 17 | *.DOCX diff=astextplain 18 | *.dot diff=astextplain 19 | *.DOT diff=astextplain 20 | *.pdf diff=astextplain 21 | *.PDF diff=astextplain 22 | *.rtf diff=astextplain 23 | *.RTF diff=astextplain -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Build Folders (you can keep bin if you'd like, to store dlls and pdbs) 2 | [Bb]in/ 3 | [Oo]bj/ 4 | 5 | # mstest test results 6 | TestResults 7 | 8 | ## Ignore Visual Studio temporary files, build results, and 9 | ## files generated by popular Visual Studio add-ons. 10 | 11 | # User-specific files 12 | *.suo 13 | *.user 14 | *.sln.docstates 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Rr]elease/ 19 | x64/ 20 | *_i.c 21 | *_p.c 22 | *.ilk 23 | *.meta 24 | *.obj 25 | *.pch 26 | *.pdb 27 | *.pgc 28 | *.pgd 29 | *.rsp 30 | *.sbr 31 | *.tlb 32 | *.tli 33 | *.tlh 34 | *.tmp 35 | *.log 36 | *.vspscc 37 | *.vssscc 38 | .builds 39 | 40 | # Visual C++ cache files 41 | ipch/ 42 | *.aps 43 | *.ncb 44 | *.opensdf 45 | *.sdf 46 | 47 | # Visual Studio profiler 48 | *.psess 49 | *.vsp 50 | *.vspx 51 | 52 | # Guidance Automation Toolkit 53 | *.gpState 54 | 55 | # ReSharper is a .NET coding add-in 56 | _ReSharper* 57 | 58 | # NCrunch 59 | *.ncrunch* 60 | .*crunch*.local.xml 61 | 62 | # Installshield output folder 63 | [Ee]xpress 64 | 65 | # DocProject is a documentation generator add-in 66 | DocProject/buildhelp/ 67 | DocProject/Help/*.HxT 68 | DocProject/Help/*.HxC 69 | DocProject/Help/*.hhc 70 | DocProject/Help/*.hhk 71 | DocProject/Help/*.hhp 72 | DocProject/Help/Html2 73 | DocProject/Help/html 74 | 75 | # Click-Once directory 76 | publish 77 | 78 | # Publish Web Output 79 | *.Publish.xml 80 | 81 | # NuGet Packages Directory 82 | packages 83 | 84 | # Windows Azure Build Output 85 | csx 86 | *.build.csdef 87 | 88 | # Windows Store app package directory 89 | AppPackages/ 90 | 91 | # Others 92 | [Bb]in 93 | [Oo]bj 94 | sql 95 | TestResults 96 | [Tt]est[Rr]esult* 97 | *.Cache 98 | ClientBin 99 | [Ss]tyle[Cc]op.* 100 | ~$* 101 | *.dbmdl 102 | Generated_Code #added for RIA/Silverlight projects 103 | 104 | # Backup & report files from converting an old project file to a newer 105 | # Visual Studio version. Backup files are not needed, because we have git ;-) 106 | _UpgradeReport_Files/ 107 | Backup*/ 108 | UpgradeLog*.XML 109 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright 2013 Glenn Block, Justin Rusbatch, Filip Wojcieszyn 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # scriptcs samples 2 | 3 | This repository is a collection of `scriptcs` samples. 4 | 5 | **Note**: to use samples that use HttpListener (Web API, ServiceStack, Nancy) you need to run CMD with elevation! 6 | 7 | ## Installing scriptcs (easy path) 8 | * Install [chocolatey](http://chocolatey.org/) 9 | * Install scriptcs using `cinst scriptcs -pre -source "http://www.myget.org/F/scriptcsnightly/"` 10 | 11 | ## Installing scriptcs (dev path) 12 | * Clone the scriptcs repo at https://github.com/scriptcs/scriptcs and change to the dev branch 13 | * Run the scriptcs build script `build.cmd` 14 | * Add 'src/scriptcs/src/scriptcs/bin/Release' to your path. 15 | 16 | ## Running the samples 17 | * Change to the folder of the sample you want to run. 18 | * Install packages `scriptcs -install` 19 | * Run the app `scriptcs start.csx` 20 | 21 | ## Submit your own! 22 | We are always looking for new, interesting samples and use cases! 23 | Before sending a pull request with a new sample, please follow the below checklist: 24 | 25 | * Include `packages.config` if you rely on Nuget packages. Only include the top level packages. 26 | * Include `readme.md` describing what the sample is about, and how it should be used 27 | * Make sure the sample runs against the latest version of `scriptcs` [dev branch](https://github.com/scriptcs/scriptcs/tree/dev) 28 | 29 | If, during the process of creating a sample, you encounter/discover any issues with scriptcs, please make sure to [file an issue in the scriptcs repo](https://github.com/scriptcs/scriptcs/issues). If you discover an issue with a current sample, [file an issue in this repo](https://github.com/scriptcs/scriptcs.samples/issues) 30 | 31 | ## Community 32 | Want to chat about your sample? You can find us on: 33 | 34 | * [Twitter](https://twitter.com/scriptcsnet) 35 | * [Google Groups](https://groups.google.com/forum/?fromgroups#!forum/scriptcs) 36 | * [JabbR](https://jabbr.net/#/rooms/scriptcs) 37 | 38 | ## License 39 | All samples are available as [Apache 2 License](https://github.com/scriptcs/scriptcs-samples/blob/master/LICENSE.md) 40 | -------------------------------------------------------------------------------- /active-directory/README.md: -------------------------------------------------------------------------------- 1 | # Querying Windows Active Directory (AD) with scriptcs 2 | 3 | ## Running the sample 4 | * Make sure scriptcs is [installed](https://github.com/scriptcs/scriptcs-samples/blob/master/README.md) 5 | * Create a text file called credentials.txt with lines of AD credentials in `DOMAIN\User` format 6 | * Run `scriptcs start.csx` 7 | * A new file will be created called fullnames.txt which includes the account names from AD 8 | 9 | ## Comments 10 | 11 | Sample credentials.txt (between the xxxxx): 12 | 13 | xxxxx
14 | DOMAINA\asm
15 | DOMAINA\ani
16 | DOMAINA\gan
17 | DOMAINB\bte
18 | xxxxx 19 | 20 | Sample fullnames.txt output file (between the xxxxx): 21 | 22 | xxxxx
23 | DOMAINA\asm, Andrew Smith
24 | DOMAINA\ani, Adam Nice
25 | DOMAINA\gan, George Andrews
26 | DOMAINB\bte, Brian Tennison
27 | xxxxx -------------------------------------------------------------------------------- /active-directory/credentials.txt: -------------------------------------------------------------------------------- 1 | DOMAINA\asm 2 | DOMAINA\ani 3 | DOMAINA\gan 4 | DOMAINB\bte -------------------------------------------------------------------------------- /active-directory/start.csx: -------------------------------------------------------------------------------- 1 | #r "System.DirectoryServices" 2 | 3 | using System.DirectoryServices; 4 | using System.IO; 5 | 6 | var fullNames = new List(); 7 | 8 | foreach (var credential in File.ReadAllLines("credentials.txt")) 9 | { 10 | if (credential.IndexOf('\\') > 0) 11 | { 12 | var domain = credential.Substring(0, credential.IndexOf('\\')); 13 | var name = credential.Substring(credential.IndexOf('\\') + 1); 14 | 15 | var de = new DirectoryEntry("LDAP://" + domain.ToUpper()); 16 | var search = new DirectorySearcher(de); 17 | search.Filter = String.Format("(SAMAccountName={0})", name); 18 | search.PropertiesToLoad.Add("cn"); 19 | SearchResult result = search.FindOne(); 20 | 21 | if (result == null) 22 | { 23 | Console.WriteLine("{0} not found.", credential); 24 | } 25 | else 26 | { 27 | fullNames.Add(string.Format("{0}, {1}", credential, result.Properties["cn"][0].ToString())); 28 | } 29 | } 30 | } 31 | 32 | File.WriteAllLines("fullnames.txt", fullNames); -------------------------------------------------------------------------------- /arcgis/geocode.csx: -------------------------------------------------------------------------------- 1 | var arcgis = Require(); 2 | 3 | var gateway = arcgis.CreateGateway("http://geocode.arcgis.com/arcgis"); 4 | var geocode = new SingleInputGeocode("/World/GeocodeServer/".AsEndpoint()) 5 | { 6 | Text = "London" 7 | }; 8 | var resultGeocode = gateway.Geocode(geocode).Result; 9 | foreach (var result in resultGeocode.Results) 10 | { 11 | var feature = result.Feature; 12 | Console.WriteLine(String.Format("{0}, x:{1:N6}, y:{2:N6}", result.Name, feature.Geometry.X, feature.Geometry.Y)); 13 | } 14 | -------------------------------------------------------------------------------- /arcgis/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /arcgis/query.csx: -------------------------------------------------------------------------------- 1 | var arcgis = Require(); 2 | 3 | var gateway = arcgis.CreateGateway("http://sampleserver3.arcgisonline.com/ArcGIS"); 4 | var query = new Query(@"/Earthquakes/EarthquakesFromLastSevenDays/MapServer/0".AsEndpoint()) 5 | { 6 | Where = "magnitude > 4.5", 7 | ReturnGeometry = true, 8 | OutFields = new List { "magnitude" } 9 | }; 10 | 11 | var result = gateway.Query(query).Result; 12 | 13 | foreach (var feature in result.Features) 14 | { 15 | Console.WriteLine(String.Format("Magnitude {0} quake at x:{1:N6}, y:{2:N6}", feature.Attributes["magnitude"], feature.Geometry.X, feature.Geometry.Y)); 16 | } 17 | -------------------------------------------------------------------------------- /arcgis/queryandreversegeocode.csx: -------------------------------------------------------------------------------- 1 | var arcgis = Require(); 2 | 3 | var gateway = arcgis.CreateGateway("http://sampleserver3.arcgisonline.com/ArcGIS"); 4 | var query = new Query(@"/Earthquakes/EarthquakesFromLastSevenDays/MapServer/0".AsEndpoint()) 5 | { 6 | Where = "magnitude > 5.2", 7 | ReturnGeometry = true, 8 | OutFields = new List { "magnitude" } 9 | }; 10 | 11 | var result = gateway.Query(query).Result; 12 | var gatewayGeocode = arcgis.CreateGateway("http://geocode.arcgis.com/arcgis"); 13 | 14 | foreach (var feature in result.Features) 15 | { 16 | var reverseGeocode = new ReverseGeocode("/World/GeocodeServer/".AsEndpoint()) 17 | { 18 | Location = new Point 19 | { 20 | X = feature.Geometry.X, 21 | Y = feature.Geometry.Y, 22 | SpatialReference = new SpatialReference 23 | { 24 | Wkid = result.SpatialReference.Wkid 25 | } 26 | }, 27 | Distance = 1000 28 | }; 29 | try 30 | { 31 | var resultGeocode = gatewayGeocode.ReverseGeocode(reverseGeocode).Result; 32 | Console.WriteLine(String.Format("Magnitude {0} quake at {1}, {2}, {3}, {4}", 33 | feature.Attributes["magnitude"], 34 | resultGeocode.Address.AddressText, 35 | resultGeocode.Address.City, 36 | resultGeocode.Address.Region, 37 | resultGeocode.Address.CountryCode)); 38 | } 39 | catch (Exception ex) 40 | { 41 | // some locations may not be at a valid address 42 | Console.WriteLine(String.Format("Magnitude {0} quake at x:{1:N6}, y:{2:N6}", feature.Attributes["magnitude"], feature.Geometry.X, feature.Geometry.Y)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /arcgis/readme.md: -------------------------------------------------------------------------------- 1 | # ArcGIS.PCL with ScriptCS 2 | 3 | Demo of [ArcGIS.PCL](https://github.com/davetimmins/ArcGIS.PCL) running on [ScriptCS](https://github.com/scriptcs/scriptcs) 4 | 5 | ## Running the samples 6 | * Make sure scriptcs is [installed](https://github.com/scriptcs/scriptcs-samples/blob/master/README.md) 7 | * Install packages `scriptcs -install` 8 | * Run the sample you want. The following are included 9 | * `scriptcs start.csx` - return a url for each service found for the ArcGIS Server specified 10 | * `scriptcs geocode.csx` - return the location of the text specified 11 | * `scriptcs reversegeocode.csx` - return the address of the location specified 12 | * `scriptcs servicestatus.csx` - check that each service for an ArcGIS Server site is in its configured state. This sample requires access to the ArcGIS Server admin REST API and you will need to put in your own server url, username and password. 13 | * `scriptcs query.csx` - query an ArcGIS Server service for features. In this case get the earthquakes for the past week with a magnitude greater than 4.5 14 | * `scriptcs queryandreversegeocode.csx` - example of combining a query operation with a reverse geocode to try and populate the location of the query results with an address 15 | 16 | ### Comments 17 | 18 | The script pack allows you to create an ArcGIS Server gateway using 19 | 20 | ```csharp 21 | var arcgis = Require(); 22 | var gateway = arcgis.CreateGateway("http://localhost/arcgis"); 23 | ``` 24 | 25 | The returned `gateway` supports the following as typed operations: 26 | 27 | * `Query` - query a layer by attribute and / or spatial filters 28 | * `QueryForCount` - only return the number of results for the query operation 29 | * `QueryForIds` - only return the ObjectIds for the results of the query operation 30 | * `Find` - search across n layers and fields in a service 31 | * `ApplyEdits` - post adds, updates and deletes to a feature service layer 32 | * `Geocode` - single line of input to perform a geocode using a custom locator or the Esri world locator 33 | * `Suggest` - lightweight geocode operation that only returns text results, commonly used for predictive searching 34 | * `ReverseGeocode` - find location candidates for a input point location 35 | * `Simplify` - alter geometries to be topologically consistent 36 | * `Project` - convert geometries to a different spatial reference 37 | * `Buffer` - buffers geometries by the distance requested 38 | * `DescribeSite` - returns a url for every service discovered 39 | * `Ping` - verify that the server can be accessed 40 | * `PublicKey` - admin operation to get public key used for encryption of token requests 41 | * `ServiceStatus` - admin operation to get the configured and actual status of a service 42 | 43 | In all cases above `T` is a geometry type of `Point`, `MultiPoint`, `Polyline`, `Polygon` or `Extent` 44 | 45 | If you need to call secure resources and your ArcGIS Server supports token based authentication then specify a `TokenProvider` in your call to `CreateGateway` 46 | 47 | ```csharp 48 | var arcgis = Require(); 49 | var gateway = arcgis.CreateGateway("http://localhost/arcgis", new TokenProvider("http://localhost/arcgis", "username", "password")); 50 | ``` 51 | -------------------------------------------------------------------------------- /arcgis/reversegeocode.csx: -------------------------------------------------------------------------------- 1 | var arcgis = Require(); 2 | 3 | var gateway = arcgis.CreateGateway("http://geocode.arcgis.com/arcgis"); 4 | var reverseGeocode = new ReverseGeocode("/World/GeocodeServer/".AsEndpoint()) 5 | { 6 | Location = new Point 7 | { 8 | X = 174.775505, 9 | Y = -41.290893, 10 | SpatialReference = new SpatialReference 11 | { 12 | Wkid = SpatialReference.WGS84.LatestWkid 13 | } 14 | } 15 | }; 16 | var result = gateway.ReverseGeocode(reverseGeocode).Result; 17 | Console.WriteLine(String.Format("{0}, {1}, {2}, {3}", 18 | result.Address.AddressText, 19 | result.Address.City, 20 | result.Address.Region, 21 | result.Address.CountryCode)); 22 | -------------------------------------------------------------------------------- /arcgis/servicestatus.csx: -------------------------------------------------------------------------------- 1 | var arcgis = Require(); 2 | 3 | var serverUrl = "https://localhost/arcgis"; 4 | var username= ""; 5 | var password = ""; 6 | if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password)) 7 | { 8 | Console.WriteLine("Uh-oh spaghetti-o, looks like you forgot to set the user credentials."); 9 | } 10 | else 11 | { 12 | var gateway = arcgis.CreateGateway(serverUrl, new TokenProvider(serverUrl, username, password)); 13 | var response = gateway.DescribeSite().Result; 14 | 15 | Console.WriteLine(String.Format("Checking service statuses for {0}", gateway.RootUrl)); 16 | foreach (var resource in response.Services) 17 | { 18 | // requires access to the admin site 19 | var status = gateway.ServiceStatus(resource).Result; 20 | if (!String.Equals(status.Actual, status.Expected, StringComparison.OrdinalIgnoreCase)) 21 | Console.WriteLine(String.Format("NOT {2} : {0} ({1})", resource.Name, resource.Type, status.Expected)); 22 | else 23 | Console.WriteLine(String.Format("{2} : {0} ({1})", resource.Name, resource.Type, status.Actual)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /arcgis/start.csx: -------------------------------------------------------------------------------- 1 | var arcgis = Require(); 2 | 3 | var gateway = arcgis.CreateGateway("http://services.arcgisonline.com/arcgis"); 4 | var response = gateway.DescribeSite().Result; 5 | 6 | Console.WriteLine(String.Format("Discovered services for {0}", gateway.RootUrl)); 7 | foreach (var resource in response.ArcGISServerEndpoints) 8 | { 9 | Console.WriteLine(resource.RelativeUrl); 10 | } 11 | -------------------------------------------------------------------------------- /fluentautomation/README.md: -------------------------------------------------------------------------------- 1 | # scriptcs and FluentAutomation 2 | 3 | ## Running the sample 4 | * Make sure scriptcs is [installed](https://github.com/scriptcs/scriptcs-samples/blob/master/README.md) 5 | * Install packages `scriptcs -install` 6 | * Run `rm packages.config` or manually delete the packages.config from the directory. This is a temporary fix for the script pack not loading properly. 7 | * Run `scriptcs start.csx` (Some users may need to run this command as Administrator) 8 | 9 | ## Comments 10 | 11 | Uses ScriptCs.FluentAutomation script pack to run and present results for automated tests right from your console. -------------------------------------------------------------------------------- /fluentautomation/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /fluentautomation/start.csx: -------------------------------------------------------------------------------- 1 | var Test = Require() 2 | .Init() 3 | .Bootstrap("Chrome") 4 | .Config(settings => { 5 | settings.DefaultWaitUntilTimeout = TimeSpan.FromSeconds(1); 6 | }); 7 | 8 | Test.Run("KnockoutJS Cart Editor", I => { 9 | I.Open("http://knockoutjs.com/examples/cartEditor.html"); 10 | I.Select("Motorcycles").From(".liveExample tr select:eq(0)"); // Select by value/text 11 | I.Select(2).From(".liveExample tr select:eq(1)"); // Select by index 12 | I.Enter(6).In(".liveExample td.quantity input:eq(0)"); 13 | I.Expect.Text("$197.70").In(".liveExample tr span:eq(1)"); 14 | 15 | // add second product 16 | I.Click(".liveExample button:eq(0)"); 17 | I.Select(1).From(".liveExample tr select:eq(2)"); 18 | I.Select(4).From(".liveExample tr select:eq(3)"); 19 | I.Enter(8).In(".liveExample td.quantity input:eq(1)"); 20 | I.Expect.Text("$788.64").In(".liveExample tr span:eq(3)"); 21 | 22 | // validate totals 23 | I.Expect.Text("$986.34").In("p.grandTotal span"); 24 | 25 | // remove first product 26 | I.Click(".liveExample a:eq(0)"); 27 | 28 | // validate new total 29 | I.WaitUntil(() => I.Expect.Text("$788.64").In("p.grandTotal span")); 30 | }); 31 | 32 | Test.Run("YUI Drag and Drop", I => { 33 | I.Open("http://automation.apphb.com/interactive"); 34 | 35 | // wait for page to render properly 36 | I.Wait(TimeSpan.FromMilliseconds(500)); 37 | I.Drag("#pt1").To("#t2"); 38 | I.Drag("#pt2").To("#t1"); 39 | I.Drag("#pb1").To("#b1"); 40 | I.Drag("#pb2").To("#b2"); 41 | I.Drag("#pboth1").To("#b3"); 42 | I.Drag("#pboth2").To("#b4"); 43 | I.Drag("#pt1").To("#pt2"); 44 | I.Drag("#pboth1").To("#pb2"); 45 | }); -------------------------------------------------------------------------------- /itextsharp/README.md: -------------------------------------------------------------------------------- 1 | # PDF manipulation using iTextSharp with scriptcs 2 | 3 | ## Running the sample 4 | * Make sure scriptcs is [installed](https://github.com/scriptcs/scriptcs-samples/blob/master/README.md) 5 | * Install packages `scriptcs -install` 6 | * Run `scriptcs start.csx -- input.pdf output.pdf 1 3` 7 | * Pages 1 - 3 from input.pdf will be extracted and saved as output.pdf 8 | 9 | ## Comments 10 | 11 | The arguments to the script are `inputFile outputFile startPage endPage`. -------------------------------------------------------------------------------- /itextsharp/input.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scriptcs/scriptcs-samples/96ef3e50abe342d2332fa3e1891be80d965a2075/itextsharp/input.pdf -------------------------------------------------------------------------------- /itextsharp/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /itextsharp/start.csx: -------------------------------------------------------------------------------- 1 | // to run this sample, execute:- 2 | // scriptcs start.csx -- input.pdf output.pdf 1 3 3 | 4 | using iTextSharp.text; 5 | using iTextSharp.text.pdf; 6 | 7 | ExtractPages(Env.ScriptArgs[0], Env.ScriptArgs[1], int.Parse(Env.ScriptArgs[2]), int.Parse(Env.ScriptArgs[3])); 8 | 9 | // from http://www.jamesewelch.com/2008/11/14/how-to-extract-pages-from-a-pdf-document/ 10 | public static void ExtractPages(string inputFile, string outputFile, 11 | int start, int end) 12 | { 13 | // get input document 14 | PdfReader inputPdf = new PdfReader(inputFile); 15 | 16 | // retrieve the total number of pages 17 | int pageCount = inputPdf.NumberOfPages; 18 | 19 | if (end < start || end > pageCount) 20 | { 21 | end = pageCount; 22 | } 23 | 24 | // load the input document 25 | Document inputDoc = 26 | new Document(inputPdf.GetPageSizeWithRotation(1)); 27 | 28 | // create the filestream 29 | using (FileStream fs = new FileStream(outputFile, FileMode.Create)) 30 | { 31 | // create the output writer 32 | PdfWriter outputWriter = PdfWriter.GetInstance(inputDoc, fs); 33 | inputDoc.Open(); 34 | PdfContentByte cb1 = outputWriter.DirectContent; 35 | 36 | // copy pages from input to output document 37 | for (int i = start; i <= end; i++) 38 | { 39 | inputDoc.SetPageSize(inputPdf.GetPageSizeWithRotation(i)); 40 | inputDoc.NewPage(); 41 | 42 | PdfImportedPage page = 43 | outputWriter.GetImportedPage(inputPdf, i); 44 | int rotation = inputPdf.GetPageRotation(i); 45 | 46 | if (rotation == 90 || rotation == 270) 47 | { 48 | cb1.AddTemplate(page, 0, -1f, 1f, 0, 0, 49 | inputPdf.GetPageSizeWithRotation(i).Height); 50 | } 51 | else 52 | { 53 | cb1.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); 54 | } 55 | } 56 | 57 | inputDoc.Close(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /nancy/README.md: -------------------------------------------------------------------------------- 1 | $ scriptcs and Nancy 2 | 3 | Demo of the [Nancy](http://nancyfx.org) framework running on [ScriptCS](https://github.com/scriptcs/scriptcs) - Awesome stuff! 4 | 5 | ## Running the sample 6 | * Make sure scriptcs is [installed](https://github.com/scriptcs/scriptcs-samples/blob/master/README.md) 7 | * Install packages `scriptcs -install` 8 | * Run `scriptcs start.csx` (make sure you are running as admin) 9 | * Browse to `http://localhost:1234/` in order to have Nancy server you a view. 10 | 11 | ## Note 12 | Nancy relies heavily on assembly scanning to compose the framework at runtime and to "light up" featured. Due to the fact that ScriptCS compiled into a _dynamic assembly_ and because you cannot use _GetExportedTypes_ on a _dynamic assembly_, you are required to provide a bit of customization in order for Nancy to function correctly. 13 | 14 | The following customizations have been included in this demo 15 | 16 | * Implemented a custom _IRootPathProvider_ to have the application set its root outside the bin folder, so that views can be located correctly 17 | 18 | * Implemented a custom _IRouteDescriptionProvider_ that simply returns an empty string. The default implementation would use assembly scanning 19 | 20 | * Use the _Nancy.Bootstrappers.Autofac_ because the default bootstrapper (which is based on _TinyIoC_) uses assembly scanning which is also affected by the limitations of _GetExportedTypes_ on a _dynamic assembly_ 21 | 22 | * Explicitly set _NancyBootstrapperLocator.Bootstrapper_ to an instance of the custom bootstrapper. Normally you would never assign this, but (again) this is due to the issues with assembly scanning 23 | 24 | * Override the _Module_ property, of the bootstrapper, to explicitly tell Nancy which module to use. Modules can't automatically be discovered due to the scanning limitations 25 | 26 | Hopefully these things will not be required in later releases of _ScriptCS_, but as it stands, it serves as a great testament on how Nancy can be modified, without changing a single line of code in the framework, to make it run in any environment! 27 | 28 | -- The Nancy team -------------------------------------------------------------------------------- /nancy/bootstrapper.csx: -------------------------------------------------------------------------------- 1 | public class Bootstrapper : AutofacNancyBootstrapper 2 | { 3 | protected override IEnumerable Modules 4 | { 5 | get 6 | { 7 | return new [] { 8 | new ModuleRegistration(typeof(IndexModule), typeof(IndexModule).FullName) 9 | }; 10 | } 11 | } 12 | 13 | protected override NancyInternalConfiguration InternalConfiguration 14 | { 15 | get 16 | { 17 | return NancyInternalConfiguration.WithOverrides(x => x.RouteDescriptionProvider = typeof(CustomRouteDescriptionProvider)); 18 | } 19 | } 20 | 21 | protected override IRootPathProvider RootPathProvider 22 | { 23 | get { return new PathProvider(); } 24 | } 25 | } -------------------------------------------------------------------------------- /nancy/customroutedescriptionprovider.csx: -------------------------------------------------------------------------------- 1 | public class CustomRouteDescriptionProvider : IRouteDescriptionProvider 2 | { 3 | public string GetDescription(INancyModule module, string path) 4 | { 5 | return string.Empty; 6 | } 7 | } -------------------------------------------------------------------------------- /nancy/module.csx: -------------------------------------------------------------------------------- 1 | public class IndexModule : NancyModule 2 | { 3 | public IndexModule(IRootPathProvider provider) 4 | { 5 | Get["/"] = x => { 6 | return View["index"]; // "Nancy running on ScriptCS!"; 7 | }; 8 | } 9 | } -------------------------------------------------------------------------------- /nancy/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /nancy/pathprovider.csx: -------------------------------------------------------------------------------- 1 | public class PathProvider : IRootPathProvider 2 | { 3 | public string GetRootPath() 4 | { 5 | return Path.Combine("..\\..\\", Environment.CurrentDirectory); 6 | } 7 | } -------------------------------------------------------------------------------- /nancy/start.csx: -------------------------------------------------------------------------------- 1 | #load "module.csx" 2 | #load "bootstrapper.csx" 3 | #load "pathprovider.csx" 4 | #load "customroutedescriptionprovider.csx" 5 | 6 | using System.IO; 7 | using Autofac; 8 | using Nancy; 9 | using Nancy.Bootstrapper; 10 | using Nancy.Bootstrappers.Autofac; 11 | using Nancy.Hosting.Self; 12 | using Nancy.Routing; 13 | 14 | NancyBootstrapperLocator.Bootstrapper = new Bootstrapper(); 15 | 16 | var address = "http://localhost:1234/"; 17 | 18 | var host = new NancyHost(new Uri(address)); 19 | host.Start(); 20 | 21 | Console.WriteLine("Nancy is running at " + address); 22 | Console.WriteLine("Press any key to end"); 23 | Console.ReadKey(); 24 | 25 | host.Stop(); 26 | -------------------------------------------------------------------------------- /nancy/views/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Nancy + ScriptCS demo 6 | 7 | 8 | 9 | 10 | 32 | 33 | 34 | 35 | 36 |
37 | 38 | Nancy logo 39 | 40 |

Amazing! NANCY is
running on
SCRIPTCS!

41 | for more information visit nancyfx.org 42 |
43 | 44 | 45 | -------------------------------------------------------------------------------- /net/README.md: -------------------------------------------------------------------------------- 1 | # ScriptCs.Net Sample: TCP Chat 2 | Demo of the [ScriptCs.Net](https://github.com/dschenkelman/scriptcs-net) script pack that leverages a TCP server and provides the ability to create various TCP clients to showcase a broadcasting chat. 3 | 4 | ## Prerequisites 5 | * [Install scriptcs](https://github.com/scriptcs/scriptcs-samples/blob/master/README.md). 6 | * Install packages by executing `scriptcs -install`. 7 | 8 | ## Running the server 9 | 1. Run `scriptcs chatServer.csx` (make sure you are running as admin) 10 | 11 | ## Running the clients 12 | 1. Run `scriptcs chatClient.csx` (make sure you are running as admin) 13 | 2. To send messages type and press **ENTER**. You should connect with at least 2 clients to see the messages from one in the other one. 14 | 3. When you want to quit type *:close* and press **ENTER**. 15 | 16 | If you have feedback create an issue in the [ScriptCs.Net repo](https://github.com/dschenkelman/scriptcs-net/issues/1) 17 | -------------------------------------------------------------------------------- /net/chatClient.csx: -------------------------------------------------------------------------------- 1 | var net = Require(); 2 | 3 | var client = net.Connect(8080, "127.0.0.1", onConnect: () => Console.WriteLine("Connected to chat room at 127.0.0.1:8080")); 4 | 5 | client.On( 6 | data: data => Console.WriteLine(data.AsString()), 7 | close: () => Console.WriteLine("Exiting chat"), 8 | error: e => Console.WriteLine("Error: {0} \r\nStackTrace: {1}", e.Message, e.StackTrace)); 9 | 10 | var line = Console.ReadLine(); 11 | 12 | while (line != ":close"){ 13 | client.WriteAsync(line.AsBytes()); 14 | 15 | line = Console.ReadLine(); 16 | } 17 | 18 | // still have to troubleshoot an issue when closing the socket 19 | client.Close(); -------------------------------------------------------------------------------- /net/chatServer.csx: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | var net = Require(); 4 | 5 | var mappings = new Dictionary(); 6 | 7 | var members = 0; 8 | 9 | var server = net.CreateServer(socket => 10 | { 11 | members++; 12 | 13 | Console.WriteLine("Member {0} joined", members); 14 | 15 | socket.WriteAsync(string.Format("Welcome member {0}", members).AsBytes()); 16 | 17 | mappings[socket] = members; 18 | 19 | socket.On( 20 | data: data => 21 | { 22 | var message = string.Format("Member {0} says: {1}", mappings[socket], data.AsString()); 23 | foreach (var s in mappings.Keys) 24 | { 25 | if (s != socket) 26 | { 27 | s.WriteAsync(message.AsBytes()); 28 | } 29 | } 30 | }, 31 | close: () => 32 | { 33 | Console.WriteLine(string.Format("Member {0} left", mappings[socket])); 34 | mappings.Remove(socket); 35 | }, 36 | error: e => Console.WriteLine("Error: {0}\r\nStackTrace: {1}", e.Message, e.StackTrace)); 37 | }); 38 | 39 | Console.WriteLine("Listening at 127.0.0.1:8080"); 40 | 41 | server.Listen(8080, "127.0.0.1").Wait(); 42 | 43 | Console.WriteLine("Closing server"); 44 | 45 | server.Close(); -------------------------------------------------------------------------------- /net/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /nunit-runner/MyUnitTests.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scriptcs/scriptcs-samples/96ef3e50abe342d2332fa3e1891be80d965a2075/nunit-runner/MyUnitTests.dll -------------------------------------------------------------------------------- /nunit-runner/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /nunit-runner/readme.md: -------------------------------------------------------------------------------- 1 | 2 | ## NUnit CSX test runner: 3 | 4 | ## Running the sample 5 | * Make sure scriptcs is [installed](https://github.com/scriptcs/scriptcs-samples/blob/master/README.md) 6 | * Install packages `scriptcs -install` 7 | * Run `scriptcs start.csx` 8 | * This will run NUnit unit tests declared in the attached `MyUnitTests.dll` test assembly 9 | 10 | ## Notes 11 | You can replace the test assembly with your own if you want, in the `start.csx`: 12 | 13 | var path = "MyUnitTests.dll"; 14 | var runner = TestSetup.GetRunner(new[] {path}); 15 | 16 | Array of assemblies can be passed too. -------------------------------------------------------------------------------- /nunit-runner/setup.csx: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using NUnit.Core; 3 | 4 | public static class TestSetup 5 | { 6 | public static SimpleTestRunner GetRunner(string[] paths) 7 | { 8 | var runner = new SimpleTestRunner(); 9 | var package = new TestPackage("MyPackage"); 10 | 11 | foreach (var path in paths) { 12 | package.Assemblies.Add(path); 13 | } 14 | 15 | runner.Load(package); 16 | return runner; 17 | } 18 | } 19 | 20 | public class ConsoleListener : EventListener 21 | { 22 | private readonly Action _logger; 23 | 24 | public ConsoleListener(Action logger) 25 | { 26 | _logger = logger; 27 | } 28 | 29 | public void RunStarted(string name, int testCount) 30 | { 31 | _logger(string.Format("Run started ")); 32 | } 33 | 34 | public void RunFinished(TestResult result) 35 | { 36 | _logger(""); 37 | _logger("-------------------------------"); 38 | _logger(string.Format("Overall result: {0} ", result.ResultState)); 39 | } 40 | 41 | public void RunFinished(Exception exception) 42 | { 43 | _logger(string.Format("Exception occurred: {0}", exception.StackTrace.Replace(Environment.NewLine, ""))); 44 | } 45 | 46 | public void SuiteFinished(TestResult result) 47 | { 48 | } 49 | 50 | public void SuiteStarted(TestName testName) 51 | { 52 | } 53 | 54 | public void TestFinished(TestResult result) 55 | { 56 | _logger(string.Format("Result: {0} ", result.ResultState)); 57 | } 58 | 59 | public void TestOutput(TestOutput testOutput) 60 | { 61 | _logger(string.Format(testOutput.Text.Replace(Environment.NewLine, ""))); 62 | } 63 | 64 | public void TestStarted(TestName testName) 65 | { 66 | _logger(""); 67 | _logger(string.Format("Test started: {0} ", testName.FullName.Replace(Environment.NewLine, ""))); 68 | } 69 | 70 | public void UnhandledException(Exception exception) 71 | { 72 | _logger(string.Format("Unhandled exception occurred: {0}", exception.StackTrace.Replace(Environment.NewLine, ""))); 73 | } 74 | } 75 | 76 | CoreExtensions.Host.InitializeService(); 77 | -------------------------------------------------------------------------------- /nunit-runner/start.csx: -------------------------------------------------------------------------------- 1 | #load "setup.csx" 2 | #r "nunit.core.dll" 3 | #r "nunit.core.interfaces.dll" 4 | 5 | var path = "MyUnitTests.dll"; 6 | var runner = TestSetup.GetRunner(new[] {path}); 7 | var result = runner.Run(new ConsoleListener(msg => Console.WriteLine(msg)), TestFilter.Empty, true, LoggingThreshold.All); 8 | 9 | Console.ReadKey(); -------------------------------------------------------------------------------- /ravendb/README.md: -------------------------------------------------------------------------------- 1 | # RavenDB with scriptcs 2 | 3 | ## Running the sample 4 | * Make sure scriptcs is [installed](https://github.com/scriptcs/scriptcs-samples/blob/master/README.md) 5 | * Install packages `scriptcs -install` 6 | * Run `scriptcs start.csx` 7 | * A browser will pop up with the RavenDB managemetn studio 8 | 9 | ## Comments 10 | 11 | You're ouput should be a list of assemblies needed by RavenDB then the following: 12 | 13 | Starting RavenDB Server, Please Be Patient... 14 | RavenDB Started, Listening On http://localhost:8081 15 | 16 | This will start a RavenDB embedded server instance. Currently the directory for you data is C:\scriptcs\ravendb. You can change this in the script to be anywhere you'd like. 17 | 18 | Note: The server instance will only be available as long as the script is running. -------------------------------------------------------------------------------- /ravendb/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /ravendb/start.csx: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using Raven.Client; 3 | using Raven.Client.Embedded; 4 | using Raven.Client.Indexes; 5 | 6 | Console.WriteLine("Starting RavenDB Server, Please Be Patient..."); 7 | 8 | var documentStore = new EmbeddableDocumentStore 9 | { 10 | DataDirectory = "c:/scriptcs/ravendb", 11 | UseEmbeddedHttpServer = true, 12 | }.Initialize() as EmbeddableDocumentStore; 13 | 14 | var url = string.Format("http://localhost:{0}", documentStore.Configuration.Port); 15 | Console.WriteLine("RavenDB Started, Listening On {0}", url); 16 | Process.Start(url); 17 | 18 | Console.ReadKey(); -------------------------------------------------------------------------------- /servicestackhost/models.csx: -------------------------------------------------------------------------------- 1 | public class Hello { 2 | public string Name { get; set; } 3 | } 4 | 5 | public class HelloResponse { 6 | public string Result { get; set; } 7 | } -------------------------------------------------------------------------------- /servicestackhost/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /servicestackhost/service.csx: -------------------------------------------------------------------------------- 1 | using ServiceStack.ServiceInterface; 2 | 3 | public class HelloService : Service 4 | { 5 | public object Any(Hello request) 6 | { 7 | return new HelloResponse { Result = "Hello, " + request.Name }; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /servicestackhost/start.csx: -------------------------------------------------------------------------------- 1 | #load "models.csx" 2 | #load "service.csx" 3 | 4 | using ServiceStack.WebHost.Endpoints; 5 | using System.Reflection; 6 | 7 | public class AppHost : AppHostHttpListenerBase { 8 | public AppHost() : base("StarterTemplate HttpListener", Assembly.GetExecutingAssembly()) { } 9 | 10 | public override void Configure(Funq.Container container) { 11 | Routes 12 | .Add("/hello") 13 | .Add("/hello/{Name}"); 14 | } 15 | } 16 | 17 | var port = "http://*:999/"; 18 | var appHost = new AppHost(); 19 | appHost.Init(); 20 | appHost.Start(port); 21 | 22 | Console.WriteLine("listening on {0}", port); 23 | Console.ReadKey(); -------------------------------------------------------------------------------- /signalr-livereload/README.md: -------------------------------------------------------------------------------- 1 | # SignalR Live Reload # 2 | 3 | ## Setup 4 | 5 | In *your* project that uses SignalR, add the following hub: 6 | 7 | [HubName("liveReload")] 8 | public class LiveReloadHub : Hub 9 | { 10 | public void ReloadAllClients() 11 | { 12 | Clients.Others.reload(); 13 | } 14 | } 15 | 16 | Then, add the relevant markup to your Razor layout: 17 | 18 | 19 | 20 | 21 | 34 | 35 | ## Running the sample 36 | * Make sure scriptcs is [installed](https://github.com/scriptcs/scriptcs-samples/blob/master/README.md) 37 | * Install packages `scriptcs -install` 38 | * Run `scriptcs start.csx` 39 | * Edit `config.json` and fill in the blanks. 40 | * Run `scriptcs start.csx` again. 41 | -------------------------------------------------------------------------------- /signalr-livereload/broadcaster.csx: -------------------------------------------------------------------------------- 1 | public class LiveReloadBroadcaster 2 | { 3 | private bool _initialized; 4 | private string _path; 5 | private string[] _extensions; 6 | private string[] _fileExtensions = { ".cshtml", ".js", ".css", ".html" }; 7 | private FileSystemWatcher _fileSystemWatcher; 8 | private HubConnection _connection; 9 | private IHubProxy _liveReloadHub; 10 | 11 | public LiveReloadBroadcaster(string server, string path, string[] extensions) 12 | { 13 | if (string.IsNullOrEmpty(path)) 14 | { 15 | throw new ArgumentNullException("path"); 16 | } 17 | 18 | _path = Path.GetFullPath(path); 19 | 20 | if (!Directory.Exists(_path)) 21 | { 22 | throw new DirectoryNotFoundException("Could not find " + _path); 23 | } 24 | 25 | _fileExtensions = extensions; 26 | _fileSystemWatcher = new FileSystemWatcher(_path); 27 | _fileSystemWatcher.IncludeSubdirectories = true; 28 | _fileSystemWatcher.Changed += FileSystemChanged; 29 | 30 | _connection = new HubConnection(server); 31 | _connection.Closed += ConnectionClosed; 32 | _connection.Error += ConnectionError; 33 | _connection.Reconnected += ConnectionReconnected; 34 | _liveReloadHub = _connection.CreateHubProxy("liveReload"); 35 | } 36 | 37 | public void ConnectionClosed() 38 | { 39 | Console.WriteLine("Connection closed."); 40 | } 41 | 42 | public void ConnectionError(Exception ex) 43 | { 44 | Console.WriteLine(ex.Message); 45 | } 46 | 47 | public void ConnectionReconnected() 48 | { 49 | Console.WriteLine("Reconnected."); 50 | } 51 | 52 | public void Start() 53 | { 54 | _fileSystemWatcher.EnableRaisingEvents = true; 55 | 56 | _connection.Start().ContinueWith(task => 57 | { 58 | if (task.IsFaulted) 59 | { 60 | Console.WriteLine("There was an error opening the connection:{0}", 61 | task.Exception.GetBaseException()); 62 | } 63 | else 64 | { 65 | Console.WriteLine("Connected"); 66 | } 67 | 68 | }).Wait(); 69 | } 70 | 71 | public void Stop() 72 | { 73 | _fileSystemWatcher.EnableRaisingEvents = false; 74 | } 75 | 76 | public void FileSystemChanged(object sender, FileSystemEventArgs e) 77 | { 78 | if (!_fileExtensions.Contains(Path.GetExtension(e.FullPath))) 79 | { 80 | return; 81 | } 82 | 83 | _liveReloadHub.Invoke("ReloadAllClients").ContinueWith(task => 84 | { 85 | if (task.IsFaulted) 86 | { 87 | Console.WriteLine("There was an error calling send: {0}", 88 | task.Exception.GetBaseException()); 89 | } 90 | else 91 | { 92 | Console.WriteLine(task.Result); 93 | } 94 | }); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /signalr-livereload/jsonconfiguration.csx: -------------------------------------------------------------------------------- 1 | public class JsonConfiguration 2 | { 3 | public static bool Exists(string name) 4 | { 5 | return File.Exists(name); 6 | } 7 | 8 | public static TConfigFile Get(string name) 9 | { 10 | var contents = File.ReadAllText(name); 11 | var config = JsonConvert.DeserializeObject(contents); 12 | return config; 13 | } 14 | 15 | public static void Put(string name, TConfigFile instance) 16 | { 17 | var contents = JsonConvert.SerializeObject(instance, Formatting.Indented); 18 | File.WriteAllText(name, contents); 19 | } 20 | } -------------------------------------------------------------------------------- /signalr-livereload/models.csx: -------------------------------------------------------------------------------- 1 | public class LiveReloadConfig 2 | { 3 | public string Server { get; set; } 4 | public string Path { get; set ; } 5 | public string[] Extensions { get; set; } 6 | } 7 | -------------------------------------------------------------------------------- /signalr-livereload/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /signalr-livereload/start.csx: -------------------------------------------------------------------------------- 1 | #load "usings.csx" 2 | #load "models.csx" 3 | #load "broadcaster.csx" 4 | #load "jsonconfiguration.csx" 5 | 6 | const string ConfigFileName = "config.json"; 7 | 8 | if (!JsonConfiguration.Exists(ConfigFileName)) 9 | { 10 | var defaultInstance = new LiveReloadConfig() 11 | { 12 | Server = "http://localhost:8080/", 13 | Path = ".", 14 | Extensions = new []{ ".cshtml", ".css", ".js", ".html" } 15 | }; 16 | 17 | JsonConfiguration.Put(ConfigFileName, defaultInstance); 18 | 19 | Console.WriteLine("Missing config.json. One has been created for your convenience."); 20 | Console.WriteLine("No thank you necessary..."); 21 | Environment.Exit(0); 22 | } 23 | 24 | Console.WriteLine("Loading config.json"); 25 | 26 | var config = JsonConfiguration.Get(ConfigFileName); 27 | 28 | Console.WriteLine("About to connect to SignalR running at {0}...", config.Server); 29 | Console.WriteLine("About to start watching {0} for changes to {1}", config.Path, string.Join(",", config.Extensions)); 30 | 31 | var broadcaster = new LiveReloadBroadcaster(config.Server, config.Path, config.Extensions); 32 | broadcaster.Start(); 33 | 34 | Console.WriteLine("Press any key to continue..."); 35 | Console.ReadKey(true); 36 | 37 | broadcaster.Stop(); 38 | -------------------------------------------------------------------------------- /signalr-livereload/usings.csx: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using Microsoft.AspNet.SignalR; 3 | using Microsoft.AspNet.SignalR.Client.Hubs; 4 | using Newtonsoft.Json; 5 | -------------------------------------------------------------------------------- /webapihost/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /webapihost/start.csx: -------------------------------------------------------------------------------- 1 | #load "webapiconfig.csx" 2 | #load "testcontroller.csx" 3 | 4 | using System.Reflection; 5 | using System.Web.Http; 6 | using System.Web.Http.SelfHost; 7 | using System.Web.Http.Dispatcher; 8 | 9 | new HttpSelfHostServer(config).OpenAsync().Wait(); 10 | Console.WriteLine("Listening..."); 11 | Console.ReadKey(); 12 | -------------------------------------------------------------------------------- /webapihost/testcontroller.csx: -------------------------------------------------------------------------------- 1 | public class TestController : ApiController 2 | { 3 | public string Get() 4 | { 5 | return "Hello world!"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /webapihost/webapiconfig.csx: -------------------------------------------------------------------------------- 1 | public class ControllerResolver : DefaultHttpControllerTypeResolver 2 | { 3 | public override ICollection GetControllerTypes(IAssembliesResolver assembliesResolver) 4 | { 5 | return Assembly.GetExecutingAssembly().GetTypes() 6 | .Where(x => typeof(System.Web.Http.Controllers.IHttpController).IsAssignableFrom(x)).ToList(); 7 | } 8 | } 9 | 10 | var config = new HttpSelfHostConfiguration(new Uri("http://localhost:8080")); 11 | config.Services.Replace(typeof(IHttpControllerTypeResolver), new ControllerResolver()); 12 | config.Routes.MapHttpRoute( 13 | name: "DefaultApi", 14 | routeTemplate: "api/{controller}/{id}", 15 | defaults: new { id = RouteParameter.Optional }); 16 | -------------------------------------------------------------------------------- /wpf/CalculatorView.xaml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /wpf/mvvm.csx: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Diagnostics; 3 | using System.Windows.Input; 4 | 5 | public class ViewModelBase : INotifyPropertyChanged 6 | { 7 | public event PropertyChangedEventHandler PropertyChanged; 8 | 9 | protected virtual void NotifyPropertyChanged(string propertyName) 10 | { 11 | var handler = PropertyChanged; 12 | if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 13 | } 14 | } 15 | 16 | public class RelayCommand : ICommand 17 | { 18 | private readonly Action _execute; 19 | 20 | private readonly Func _canExecute; 21 | 22 | public RelayCommand(Action execute) : this(execute, null) { } 23 | 24 | public RelayCommand(Action execute, Func canExecute) 25 | { 26 | if (execute == null) throw new ArgumentNullException("execute"); 27 | 28 | _execute = execute; 29 | _canExecute = canExecute; 30 | } 31 | 32 | [DebuggerStepThrough] 33 | public bool CanExecute(object parameter) 34 | { 35 | return _canExecute == null || _canExecute(parameter); 36 | } 37 | 38 | public event EventHandler CanExecuteChanged 39 | { 40 | add { CommandManager.RequerySuggested += value; } 41 | remove { CommandManager.RequerySuggested -= value; } 42 | } 43 | 44 | public void Execute(object parameter) 45 | { 46 | _execute(parameter); 47 | } 48 | } -------------------------------------------------------------------------------- /wpf/start.csx: -------------------------------------------------------------------------------- 1 | #r "PresentationCore" 2 | #r "PresentationFramework" 3 | #r "WindowsBase" 4 | #r "System.Xaml" 5 | #r "System.Xml" 6 | 7 | #load utilities.csx 8 | #load mvvm.csx 9 | 10 | #load viewmodels.csx 11 | #load views.csx 12 | 13 | using System.Windows; 14 | using System.Threading; 15 | using System.ComponentModel; 16 | using System.Diagnostics; 17 | using System.Windows.Input; 18 | 19 | public class App : Application 20 | { 21 | protected override void OnStartup(StartupEventArgs e) 22 | { 23 | var viewModel = new CalculatorViewModel(); 24 | 25 | var window = new CalculatorView 26 | { 27 | DataContext = viewModel, 28 | SizeToContent = SizeToContent.WidthAndHeight 29 | }; 30 | 31 | window.Show(); 32 | } 33 | } 34 | 35 | Utilities.RunInSTAThread(() => new App().Run()); -------------------------------------------------------------------------------- /wpf/utilities.csx: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Threading; 3 | using System.Windows; 4 | using System.Windows.Controls; 5 | using System.Windows.Markup; 6 | 7 | public static class Utilities 8 | { 9 | public static void LoadXaml(ContentControl contentControl, string xamlFile) 10 | { 11 | using (var fileStream = File.OpenRead(xamlFile)) 12 | { 13 | contentControl.Content = XamlReader.Load(fileStream) as DependencyObject; 14 | } 15 | } 16 | 17 | public static void RunInSTAThread(ThreadStart threadStart) 18 | { 19 | var thread = new Thread(threadStart); 20 | thread.SetApartmentState(ApartmentState.STA); 21 | thread.Start(); 22 | thread.Join(); 23 | } 24 | } -------------------------------------------------------------------------------- /wpf/viewmodels.csx: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Windows.Input; 3 | 4 | public class CalculatorViewModel : ViewModelBase 5 | { 6 | private string _display; 7 | 8 | public CalculatorViewModel() 9 | { 10 | Display = "0"; 11 | 12 | NumberCommand = new RelayCommand(param => AddNumber(Convert.ToInt32(param)), param => CanAddNumber); 13 | 14 | AddCommand = CreateOperatorCommand('+'); 15 | SubtractCommand = CreateOperatorCommand('-'); 16 | MultiplyCommand = CreateOperatorCommand('*'); 17 | DivideCommand = CreateOperatorCommand('/'); 18 | 19 | CalculateCommand = new RelayCommand(param => Calculate(), param => CanCalculate); 20 | ClearCommand = new RelayCommand(param => Clear(), param => true); 21 | } 22 | 23 | public string Display 24 | { 25 | get { return _display; } 26 | set 27 | { 28 | _display = value; 29 | NotifyPropertyChanged("Display"); 30 | CommandManager.InvalidateRequerySuggested(); 31 | } 32 | } 33 | 34 | public RelayCommand NumberCommand { get; private set; } 35 | 36 | public RelayCommand AddCommand { get; private set; } 37 | 38 | public RelayCommand SubtractCommand { get; private set; } 39 | 40 | public RelayCommand MultiplyCommand { get; private set; } 41 | 42 | public RelayCommand DivideCommand { get; private set; } 43 | 44 | public RelayCommand CalculateCommand { get; private set; } 45 | 46 | public RelayCommand ClearCommand { get; private set; } 47 | 48 | private int? Operand1 { get; set; } 49 | 50 | private char? Operator { get; set; } 51 | 52 | private int? Operand2 { get; set; } 53 | 54 | private int? Result { get; set; } 55 | 56 | private bool CanApplyOperator 57 | { 58 | get { return Operand1.HasValue && !Operator.HasValue; } 59 | } 60 | 61 | private void ApplyOperator(char @operator) 62 | { 63 | Operator = @operator; 64 | Display = string.Format("{0} {1} ", Display, Operator); 65 | } 66 | 67 | private bool CanAddNumber 68 | { 69 | get { return !Result.HasValue; } 70 | } 71 | 72 | private void AddNumber(int number) 73 | { 74 | if (Operator.HasValue) 75 | { 76 | Operand2 = !Operand2.HasValue ? number : (Operand2 * 10) + number; 77 | Display += number; 78 | return; 79 | } 80 | 81 | Operand1 = !Operand1.HasValue ? number : (Operand1 * 10) + number; 82 | Display += number; 83 | } 84 | 85 | private bool CanCalculate 86 | { 87 | get { return Operand1.HasValue && Operator.HasValue && Operand2.HasValue && !Result.HasValue; } 88 | } 89 | 90 | private void Calculate() 91 | { 92 | switch (Operator) 93 | { 94 | case '+': 95 | Result = Operand1 + Operand2; 96 | break; 97 | case '-': 98 | Result = Operand1 - Operand2; 99 | break; 100 | case '*': 101 | Result = Operand1 * Operand2; 102 | break; 103 | case '/': 104 | Result = Operand1 / Operand2; 105 | break; 106 | } 107 | 108 | Display = Result.ToString(); 109 | } 110 | 111 | private void Clear() 112 | { 113 | Operand1 = null; 114 | Operator = null; 115 | Operand2 = null; 116 | Result = null; 117 | Display = "0"; 118 | } 119 | 120 | private RelayCommand CreateOperatorCommand(char @operator) 121 | { 122 | return new RelayCommand(param => ApplyOperator(@operator), param => CanApplyOperator); 123 | } 124 | } -------------------------------------------------------------------------------- /wpf/views.csx: -------------------------------------------------------------------------------- 1 | public class CalculatorView : Window 2 | { 3 | public CalculatorView() 4 | { 5 | Utilities.LoadXaml(this, "CalculatorView.xaml"); 6 | } 7 | } --------------------------------------------------------------------------------