C:\Program Files (x86)\Microsoft Visual Studio 14.0>csi
Microsoft (R) Visual C# Interactive Compiler version 1.1.0.51014
Copyright (C) Microsoft Corporation. All rights reserved.
Type "#help" for more information.
> System.Console.WriteLine("Hello! My name is Inigo Montoya");
Hello! My name is Inigo Montoya
>
> ConsoleColor originalConsoleColor = Console.ForegroundColor;
> try{
. Console.ForegroundColor = ConsoleColor.Red;
. Console.WriteLine("You killed my father. Prepare to die.");
. }
. finally
. {
. Console.ForegroundColor = originalConsoleColor;
. }
You killed my father. Prepare to die.
> IEnumerable<Process> processes = Process.GetProcesses();
> using System.Collections.Generic;
> processes.Where(process => process.ProcessName.StartsWith("c") ).
. Select(process => process.ProcessName ).Distinct()
DistinctIterator { "chrome", "csi", "cmd", "conhost", "csrss" }
> processes.First(process => process.ProcessName == "csi" ).MainModule.FileName
"C:\\Program Files (x86)\\MSBuild\\14.0\\bin\\csi.exe"
> quot;The current directory is { Environment.CurrentDirectory }."
"The current directory is C:\\Program Files (x86)\\Microsoft Visual Studio 14.0."
>#r ".\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll"
#load "Mashape.csx" // Sets a value for the string Mashape.Key
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class Spell
{
[JsonProperty("original")]
public string Original { get; set; }
[JsonProperty("suggestion")]
public string Suggestion { get; set; }
[JsonProperty(PropertyName ="corrections")]
private JObject InternalCorrections { get; set; }
public IEnumerable<string> Corrections
{
get
{
if (!IsCorrect)
{
return InternalCorrections?[Original].Select(
x => x.ToString()) ?? Enumerable.Empty<string>();
}
else return Enumerable.Empty<string>();
}
}
public bool IsCorrect
{
get { return Original == Suggestion; }
}
static public bool Check(string word, out IEnumerable<string> corrections)
{
Task <Spell> taskCorrections = CheckAsync(word);
corrections = taskCorrections.Result.Corrections;
return taskCorrections.Result.IsCorrect;
}
static public async Task<Spell> CheckAsync(string word)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
quot;https://montanaflynn-spellcheck.p.mashape.com/check/?text={ word }");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers = new WebHeaderCollection();
// Mashape.Key is the string key available for
// Mashape for the montaflynn API.
request.Headers.Add("X-Mashape-Key", Mashape.Key);
using (HttpWebResponse response =
await request.GetResponseAsync() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
using(Stream stream = response.GetResponseStream())
using(StreamReader streamReader = new StreamReader(stream))
{
string strsb = await streamReader.ReadToEndAsync();
Spell spell = Newtonsoft.Json.JsonConvert.DeserializeObject<Spell>(strsb);
// Assume spelling was only requested on first word.
return spell;
}
}
}
}
(await Spell.CheckAsync("entrepreneur")).IsCorrect
> #help
Keyboard shortcuts:
Enter If the current submission appears to be complete, evaluate it.
Otherwise, insert a new line.
Escape Clear the current submission.
UpArrow Replace the current submission with a previous submission.
DownArrow Replace the current submission with a subsequent
submission (after having previously navigated backward).
REPL commands:
#help Display help on available commands and key bindings.
Microsoft (R) Visual C# Interactive Compiler version 1.1.0.51014
Copyright (C) Microsoft Corporation. All rights reserved.
Usage: csi [option] ... [script-file.csx] [script-argument] ...
Executes script-file.csx if specified, otherwise launches an interactive REPL (Read Eval Print Loop).
Options:
/help Display this usage message (alternative form: /?)
/i Drop to REPL after executing the specified script
/r:<file> Reference metadata from the specified assembly file
(alternative form: /reference)
/r:<file list> Reference metadata from the specified assembly files
(alternative form: /reference)
/lib:<path list> List of directories where to look for libraries specified
by #r directive (alternative forms: /libPath /libPaths)
/u:<namespace> Define global namespace using
(alternative forms: /using, /usings, /import, /imports)
@<file> Read response file for more options
-- Indicates that the remaining arguments should not be
treated as options
# This file contains command-line options that the C# REPL
# will process as part of every compilation, unless
# \"/noconfig\" option is specified in the reset command.
/r:System
/r:System.Core
/r:Microsoft.CSharp
/r:System.Data
/r:System.Data.DataSetExtensions
/r:System.Xml
/r:System.Xml.Linq
SeedUsings.csx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
> class Customer {
. public string firstName {get; set;}
. public string lastName {get; set; }
. public string fullName() {
. return firstName + " " + lastName;
. }
. }
> Customer cust = new Customer();
> cust.firstName = "Peter";
> cust.lastName = "Vogel";
> string fname = cust.fullName();
> fname
"Peter Vogel"
csi <name of your script file>.csx
CustomerRepo cr = new CustomerRepo();
Customer cust = cr.GetCustomer("A123");
string fName = cust.GetFirstName();
ReferencePaths.Add(@"C:\Users\<user name>\Source\Repos\<solution name>\<project name>\bin\debug\");
> #r "<project name>.dll"
> using <project namespace>;
#load "C:\Users\peter\Source\Repos\SampleClassLibrary\SampleClassLibrary\ExerciseAddCustomer.csx"
#reset core
using System;
using System.IO;
var today = DateTime.Now.ToString();var message = quot;Hello World, This file is created at {today}";
// Some fancy comment here
class Foo{ public void Bar() { Console.WriteLine("Hello World!"); }}
var obj = new Foo();obj.Bar();
Console.WriteLine(message);C:\>where csiC:\Program Files\Mono\bin\csiC:\Program Files\Mono\bin\csi.bat> csi sample-job1.csxHello World!Hello World, This file is created at 19/12/2019 11:40:37// You need to reference your Assembly dlls file like this#r "Newtonsoft.Json.dll"
using System;using Newtonsoft.Json;
class Product{ public Guid Id{get;set;} public string Name{get;set;} public bool Enabled{get;set;}}
var productObj = new Product { Id = Guid.NewGuid(), Name = "FooBar", Enabled = true};
Console.WriteLine(JsonConvert.SerializeObject(productObj));> csi sample-job2.csx{"Id":"5611f423-9819-4f02-887e-4d39e9a9b0b8","Name":"FooBar","Enabled":true}C:\>csiMicrosoft (R) Visual C# Interactive Compiler version 3.3.1-beta4-19462-11 ()Copyright (C) Microsoft Corporation. All rights reserved.Type "#help" for more information.> var message= "Hello World";> Console.WriteLine(message);Hello World>#r “nuget: PackageId, version”// for e.g:// #r “nuget: Newtonsoft.Json, 12.0.3”// Make sure you define the version of Nuget package for caching!
#r "nuget: Newtonsoft.Json, 12.0.3"
using System;using Newtonsoft.Json;
class Product{ public Guid Id{get;set;} public string Name{get;set;} public bool Enabled{get;set;}}
var productObj = new Product { Id = Guid.NewGuid(), Name = "FooBar", Enabled = true};
Console.WriteLine(JsonConvert.SerializeObject(productObj));> dotnet script sample-job3.csx{"Id":"5f14b3be-d634-414d-95e2-b015fda6d383","Name":"FooBar","Enabled":true}> dotnet-script initCreating VS Code launch configuration file...'\path\.vscode\launch.json' [Created]Creating OmniSharp configuration file...'\path\omnisharp.json' [Created]Creating default script file 'main.csx'Creating 'main.csx'...'\path\main.csx' [Created]# install it with chocolatycinst scriptcsC:\>scriptcsMoving directory '.cache' to '.scriptcs_cache'...scriptcs (ctrl-c to exit or :help for help)> var message = "Hello World";> Console.WriteLine(message);Hello World>C:\>scriptcs -install Newtonsoft.JsonInstalling packages...Installed: Newtonsoft.JsonPackage installation succeeded.Saving packages in scriptcs_packages.config...Creating scriptcs_packages.config...Added Newtonsoft.Json (v9.0.1, .NET 4.5) to scriptcs_packages.configSuccessfully updated scriptcs_packages.config.using System;using Newtonsoft.Json;
class Product{ public Guid Id{get;set;} public string Name{get;set;} public bool Enabled{get;set;}}
var productObj = new Product { Id = Guid.NewGuid(), Name = "FooBar", Enabled = true};
Console.WriteLine(JsonConvert.SerializeObject(productObj));C:\>scriptcs sample-job2.csx{"Id":"e3a9d76e-d558-46d1-8d1a-b831c8013e16","Name":"FooBar","Enabled":true}> mkdir foo-bar> cd foo-bar> dotnet-script init foobarCreating VS Code launch configuration file...'\foo-bar\.vscode\launch.json' [Created]Creating OmniSharp configuration file...'\foo-bar\omnisharp.json' [Created]Creating 'foobar'...'\foo-bar\foobar.csx' [Created]code ..-----------------.------.-------.----------------.--------.| Name | Repl | Nuget | Cross-Platform | Debug |:-----------------+------+-------+----------------+--------:| Mono/Roslyn CSI | Yes | No | Yes | No |:-----------------+------+-------+----------------+--------:| Script-CS | Yes | Yes | No | Yes(1) |:-----------------+------+-------+----------------+--------:| Dotnet-Script | Yes | Yes | Yes | Yes |'-----------------'------'-------'----------------'--------'1. Script-CS supports debugging but it requies complete Visual Studio and it's not easy to do
// This code was recorded by TestComplete:>> function Test(){ var p, w; p = Sys["Process"]("notepad"); w = p["Window"]("Notepad", "*"); w["Activate"](); w["Window"]("Edit")["VScroll"]["Pos"] = 0; w["Window"]("Edit")["Click"](9, 9); Sys["Keys"]("Test"); w["MainMenu"]["Click"]("File|Exit");}
// This code was imported to a C# Connected Application:>using AutomatedQA.script;using AutomatedQA.TestComplete;
void Test(){ var p, w; p = Sys["Process"]("notepad"); w = p["Window"]("Notepad", "*"); w["Activate"](); w["Window"]("Edit")["VScroll"]["Pos"] = 0; w["Window"]("Edit")["Click"](9, 9); Sys["Keys"]("Test"); w["MainMenu"]["Click"]("File|Exit");}var p, w;Log["Message"]("My Message", "My Message Description", 0, 1);Log.Message("My Message", "My Message Description", 0, 1);i = Sys["MouseX"]; //Getting the Sys.MouseX propertySys["MouseX"] = 120; // Setting the Sys.MouseX property// Getting the first object in the TestedApps collectionvar TestedAppObj = TestedApps["Items"](0);//Saving the object to the TestedApps listTestedApps["Items"](2) = MyTestedAppObj;
// C#Script in TestComplete:function Test(){ …
// C#Script in a C# Connected Application:void Test(){…// Script code in a class inherited from the Connect classLog["Message"]("My message"); // Calls the Log.Message methodSys["Desktop"]["ActiveWindow"](); // Calls the Sys.Desktop.ActiveWindow methodint i = Sys["MouseX"]; // Getting the Sys.MouseX propertySys["MouseX"] = 120; // Setting the Sys.MouseX property// Script code in a class that is not inherited from the Connect classConnect.Log["Message"]("My message"); // Calls the Log.Message methodConnect.Sys["Desktop"]["ActiveWindow"](); // Calls the Sys.Desktop.ActiveWindow methodint i = Connect.Sys["MouseX"]; //Getting the Sys.MouseX propertyConnect.Sys["MouseX"] = 120; // Setting the Sys.MouseX propertyprivate void axEventControl1_OnLogError(object sender, AxEventControl.ItcControlEvents_OnLogErrorEvent e){ var lp = (var)e.logParams; // Incorrect lp["AdditionalText"] = "Message"; // <-- An error occurs …}private void axEventControl1_OnLogError(object sender, AxEventControl.ItcControlEvents_OnLogErrorEvent e){ var lp = new var(e.logParams); // Correct! lp["AdditionalText"] = "Message"; // Correct! …}// Getting the first object in the TestedApps collectionvar TestedAppObj = TestedApps["Items"](0);// Saving the object to the TestedApps listTestedApps["Items", 2] = MyTestedAppObj;// We assume that the testing code is inside of the class inherited from the Connect class,// so we do not use Connect to get to the TestComplete Sys objectvar p = Sys["Process"]("MyProcess", 1);var w = p["Window"]("My Windows Class", "My Window Caption");void FindProcessMultiple(){ // Creates arrays of properties and values String[] PropArray = new String[2]; String[] ValuesArray = new String[2];
// Specifies property names PropArray[0] = "ProcessName"; PropArray[1] = "UserName";
// Specifies the property values ValuesArray[0] = "*"; ValuesArray[1] = Connect.Sys["UserName"];
// Searches for the process var p = Connect.Sys; var res = p["FindAllChildren"](new var(PropArray), new var(ValuesArray), 1);
// Posts the search results if (Connect.BuiltIn["VarArrayHighBound"](res, 1) >= 0) { object[] ManagedArray = (object[])res.UnWrap(); for (int i = 0; i < ManagedArray.Length; i++) { var ArrayEntry = new var(ManagedArray[i]); Connect.Log["Message"]("Found: " + ArrayEntry["ProcessName"].UnWrap()); } } else Connect.Log["Message"]("Not found");}using AutomatedQA.script; ...class TestClass{ void Test() { var wrd = new var().GetObject("Word.Application"); /* The following code performs some operations with the COM Server */ wrd["Visible"] = true; wrd["Documents"]["Add"](); wrd["Selection"]["InsertAfter"]("Hello, world!"); }}css -helpcscs -new script.csusing System;
Console.WriteLine(user());
string user() => Environment.UserName; css .\script.cs Install-Package CS-Script public interface ICalc{ int Sum(int a, int b);}...// you can but don't have to inherit your script class from ICalcICalc calc = CSScript.Evaluator .LoadCode<ICalc>(@"using System; public class Script { public int Sum(int a, int b) { return a+b; } }");int result = calc.Sum(1, 2);
dynamic script = CSScript.Evaluator .LoadMethod(@"int Product(int a, int b) { return a * b; }");
int result = script.Product(3, 2);
public interface ICalc{ int Sum(int a, int b); int Div(int a, int b);}...ICalc script = CSScript.Evaluator .LoadMethod<ICalc>(@"public int Sum(int a, int b) { return a + b; } public int Div(int a, int b) { return a/b; }");int result = script.Div(15, 3);
var log = CSScript.Evaluator .CreateDelegate(@"void Log(string message) { Console.WriteLine(message); }");
log("Test message");Model.Tables["FactInternetSales"].Measures["Sales Amount"]Model.Tables["FactInternetSales"].Measures["Sales Amount"].FormatString = "0.0%";Model.Tables["FactInternetSales"].Measures["Sales Amount"].DisplayFolder = "New Folder";
Collection.First([predicate]) Returns the first object in the collection satisfying the optional [predicate] condition. Collection.Any([predicate]) Returns true if the collection contains any objects (optionally satisfying the [predicate] condition). Collection.Where(predicate) Returns a collection that is the original collection filtered by the predicate condition. Collection.Select(map) Projects each object in the collection into another object according to the specified map. Collection.ForEach(action) Performs the specified action on each element in the collection.m => m.Name.Contains("Reseller").Where(obj => { if(obj is Column) { return false; } return obj.Name.Contains("test");})Selected.Measures .Rename("Amount", "Value"); Selected.Measures .ForEach(m => if(m.Name.Contains("Reseller")) m.Name += " DEPRECATED"); Selected.Measures .Where(m => m.Name.Contains("Reseller")) .ForEach(m => m.Name += " DEPRECATED"); void Output(object value) - halts script execution and displays information about the provided object. When the script is running as part of a command line execution, this will write a string representation of the object to the console.void SaveFile(string filePath, string content) - convenient way to save text data to a file.string ReadFile(string filePath) - convenient way to load text data from a file.string ExportProperties(IEnumerable<ITabularNamedObject> objects, string properties) - convenient way to export a set of properties from multiple objects as a TSV string.void ImportProperties(string tsvData) - convenient way to load properties into multiple objects from a TSV string.void CustomAction(string name) - invoke a macro by name.void CustomAction(this IEnumerable<ITabularNamedObject> objects, string name) - invoke a macro on the specified objects.string ConvertDax(string dax, bool useSemicolons) - converts a DAX expression between US/UK and non-US/UK locales. If useSemicolons is true (default) the dax string is converted from the native US/UK format to non-US/UK. That is, commas (list separators) will be converted to semicolons and periods (decimal separators) will be converted to commas. Vice versa if useSemicolons is set to false.void FormatDax(this IEnumerable<IDaxDependantObject> objects, bool shortFormat, bool? skipSpace) - formats DAX expressions on all objects in the provided collectionvoid FormatDax(this IDaxDependantObject obj) - queues an object for DAX expression formatting when script execution is complete, or when the CallDaxFormatter method is called.void CallDaxFormatter(bool shortFormat, bool? skipSpace) - formats all DAX expressions on objects enqueued so farvoid Info(string) - Writes an informational message to the console (only when the script is executed as part of a command line execution).void Warning(string) - Writes a warning message to the console (only when the script is executed as part of a command line execution).void Error(string) - Writes an error message to the console (only when the script is executed as part of a command line execution).T SelectObject(this IEnumerable<T> objects, T preselect = null, string label = "Select object") where T: TabularNamedObject - Displays a dialog to the user prompting to select one of the objects specified. If the user cancels the dialog, this method returns null.void CollectVertiPaqAnalyzerStats() - If Tabular Editor is connected to an instance of Analysis Services, this runs the VertiPaq Analyzer statistics collector.long GetCardinality(this Column column) - If VertiPaq Analyzer statistics are available for the current model, this method returns the cardinality of the specified column// Assembly references must be at the very top of the file:#r "System.IO.Compression"
// Using keywords must come before any other statements:using System.IO.Compression;using System.IO;
var xyz = 123;
// Using statements still work the way they're supposed to:using(var data = new MemoryStream())using(var zip = new ZipArchive(data, ZipArchiveMode.Create)) { // ...}
By default, Tabular Editor applies the following using keyword (even though they are not specified in the script), to make common tasks easier:
using System;using System.Linq;using System.Collections.Generic;using Newtonsoft.Json;using TabularEditor.TOMWrapper;using TabularEditor.TOMWrapper.Utils;using TabularEditor.UI;
In addition, the following .NET Framework assemblies are loaded by default:
System.Dll System.Core.Dll System.Data.Dll System.Windows.Forms.Dll Microsoft.Csharp.Dll Newtonsoft.Json.Dll TomWrapper.Dll TabularEditor.Exe Microsoft.AnalysisServices.Tabular.Dllc:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Roslyn-langversion:8.0dotnet new -i CitizenFX.Templatesmkdir MyResourcecd MyResourcedotnet new cfx-resourcecd /d [PATH TO THIS RESOURCE]mklink /d X:\cfx-server-data\resources\[local]\MyResource distusing CitizenFX.Core;
namespace MyResourceNameClient{ public class Class1 : BaseScript { public Class1() {
} }}using System;using System.Collections.Generic;using CitizenFX.Core;using static CitizenFX.Core.Native.API;
namespace MyResourceNameClient{ public class Class1 : BaseScript { public Class1() { EventHandlers["onClientResourceStart"] += new Action<string>(OnClientResourceStart); }
private void OnClientResourceStart(string resourceName) { if (GetCurrentResourceName() != resourceName) return;
RegisterCommand("car", new Action<int, List<object>, string>((source, args, raw) => { // TODO: make a vehicle! fun! TriggerEvent("chat:addMessage", new { color = new[] {255, 0, 0}, args = new[] {"[CarSpawner]", quot;I wish I could spawn this {(args.Count > 0 ? quot;{args[0]} or" : "")} adder but my owner was too lazy. :("} }); }), false); } }}EventHandlers["onClientResourceStart"] += new Action<string>(OnClientResourceStart);if (GetCurrentResourceName() != resourceName) return;RegisterCommand("car", new Action<int, List<object>, string>((source, args, raw) =>{ // TODO: make a vehicle! fun! TriggerEvent("chat:addMessage", new { color = new[] {255, 0, 0}, args = new[] {"[CarSpawner]", quot;I wish I could spawn this {(args.Count > 0 ? quot;{args[0]} or" : "")} adder but my owner was too lazy. :("} });}), false);// 0x5fa79b0f// RegisterCommandvoid REGISTER_COMMAND(char* commandName, func handler, BOOL restricted);RegisterCommand("car", new Action<int, List<object>, string>(async (source, args, raw) =>{ // account for the argument not being passed var model = "adder"; if (args.Count > 0) { model = args[0].ToString(); }
// check if the model actually exists // assumes the directive `using static CitizenFX.Core.Native.API;` var hash = (uint) GetHashKey(model); if (!IsModelInCdimage(hash) || !IsModelAVehicle(hash)) { TriggerEvent("chat:addMessage", new { color = new[] { 255, 0, 0 }, args = new[] { "[CarSpawner]", quot;It might have been a good thing that you tried to spawn a {model}. Who even wants their spawning to actually ^*succeed?" } }); return; }
// create the vehicle var vehicle = await World.CreateVehicle(model, Game.PlayerPed.Position, Game.PlayerPed.Heading); // set the player ped into the vehicle and driver seat Game.PlayerPed.SetIntoVehicle(vehicle, VehicleSeat.Driver);
// tell the player TriggerEvent("chat:addMessage", new { color = new[] {255, 0, 0}, args = new[] {"[CarSpawner]", quot;Woohoo! Enjoy your new ^*{model}!"} });}), false);Assembly _compiledAssembly = _compilerResults.CompiledAssembly;
//Create an instace of the class that contains the script methodvar _customScriptClassInstance = _compiledAssembly.CreateInstance("ScriptingSampleApp.Scripts.ScriptClass");
//Get the Type info for the script classvar _typeInfo = _customScriptClassInstance.GetType();//Get the method info that contains the script codesvar _methodInfo = _typeInfo.GetMethod("ExportPersonList");//Invoke the method with the required parameters (pass null as the second parameter if method has no parameters)var oReturnValue = _methodInfo.Invoke(_customScriptClassInstance, new object[] { m_PersonList });cinst scriptcscup scriptcscinst scriptcs -pre -source https://www.myget.org/F/scriptcsnightly/C:\> scriptcsscriptcs (ctrl-c or blank to exit)
> var message = "Hello, world!";> Console.WriteLine(message);Hello, world!>
C:\>using Raven.Client;using Raven.Client.Embedded;using Raven.Client.Indexes;
Console.WriteLine("Starting RavenDB server...");
EmbeddableDocumentStore documentStore = null;try{ documentStore = new EmbeddableDocumentStore { UseEmbeddedHttpServer = true }; documentStore.Initialize();
var url = string.Format("http://localhost:{0}", documentStore.Configuration.Port); Console.WriteLine("RavenDB started, listening on {0}.", url);
Console.ReadKey();}finally{ if (documentStore != null) documentStore.Dispose();} scriptcs app.csxINFO : Starting to create execution componentsINFO : Starting executionStarting RavenDB server..... snip ..RavenDB started, listening on http://localhost:8080.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();scriptcs server.csx <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello world!</string>#load "controller.csx"scriptcs server.csx <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello world!</string>#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();
// This code was recorded by TestComplete:
function Test(){ var p, w; p = Sys["Process"]("notepad"); w = p["Window"]("Notepad", "*"); w["Activate"](); w["Window"]("Edit")["VScroll"]["Pos"] = 0; w["Window"]("Edit")["Click"](9, 9); Sys["Keys"]("Test"); w["MainMenu"]["Click"]("File|Exit");}
// This code was imported to a C++ Connected Application:
#include "c:\TestComplete\Connected Apps\C++\script.h"using namespace TestComplete;IMPLEMENT_TESTCOMPLETE_GLOBAL_OBJECTS function Test(){ var p, w; p = Sys["Process"]("notepad"); w = p["Window"]("Notepad", "*"); w["Activate"](); w["Window"]("Edit")["VScroll"]["Pos"] = 0; w["Window"]("Edit")["Click"](9, 9); Sys["Keys"]("Test"); w["MainMenu"]["Click"]("File|Exit");}var p, w;Log["Message"]("My Message", "My Message Description", 0, 1);Log.Message("My Message", "My Message Description", 0, 1);p = w["Parent"];// Saving property value to a variableSys["MouseX"] = 100; // Assigning property valuevar p = TestedApps["Items"](0); // Getting property valueTestedApps["Items"](0) = "notepad.exe"; // Setting property valueTestedApps[Put("Items")](0) = "notepad.exe";
or
TestedApps[(Put)"Items"](0) = "notepad.exe";TestedApps[Put("Items")](0) = "notepad.exe";
or
TestedApps[(Put)"Items"](0) = "notepad.exe";TestedApps[Put("Items")](0) = "notepad.exe";
or
TestedApps[(Put)"Items"](0) = "notepad.exe";typedef void function // The function does not return a value function Func1(){} // The function does not return a valuevoid Func1(){}// orfunction Func1(){} #include "c:\TestComplete\Connected Apps\C++\script.h"...using namespace TestComplete;void Test(){ /* We used the COleInit variable rather than the CoInitializeEx and CoUninitialize API functions. */ COleInit g;
var wrd; /* The GetObject method returns a reference to the desired COM server. It performs the actions, similar to those below: IDispatch * wrdVar; GUID WrdClass; CLSIDFromProgID(L"Word.Application", &WrdClass); CoCreateInstance(WrdClass, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (void **)&wrdVar); wrd = wrdVar; */ wrd.GetObject(L"Word.Application");
/* The following code performs some operations with the COM Server */ wrd["Visible"] = true; wrd["Documents"]["Add"](); wrd["Selection"]["InsertAfter"]("Hello, world!");}// C++ codeChaiScript chai;chai.add(user_type<IBasicGameView>(), "IBasicGameView"). add(user_type<IGameMatchView>(), "IGameMatchView"). add(user_type<IGameMatchView::Player>(), "IGameMatch_Player"). add(user_type<OnlineRoomsView::MatchRoom>(), "OnlineRoomsView_MatchRoom"). add(user_type<Guinyote::RuntimeConfig>(), "RuntimeConfig");// Support inheritance: chai.add(base_class<IBasicGameView, IGameMatchView>()); chai.add(base_class<IGameMatchView, GameMatchView>()); chai.add(base_class<IBasicGameView, GameMenuView>()); chai.add(base_class<IBasicGameView, OnlineRoomsView>());//Register global constantschai.add_global_const(const_var(IGameMatchView::Player::LeftPlayer), "LeftPlayer") .add_global_const(const_var(IGameMatchView::Player::FrontPlayer), "FrontPlayer") .add_global_const(const_var(IGameMatchView::Player::RightPlayer), "RightPlayer") .add_global_const(const_var(IGameMatchView::Player::BottomPlayer),"BottomPlayer"); def nextPlayer(player) { return ((player + 1) % 4)}// typed (optional)def nextPlayer2(int player) { return ((player + 1) % 4)}
def getPlayerPositionRelativeTo(refPlayer, targetPlayer) { if (refPlayer == targetPlayer) { return BottomPlayer } var diff = 0 var curr = nextPlayer(refPlayer) ++diff while (curr != targetPlayer) { curr = nextPlayer(curr) ++diff } if (diff == 0) { return BottomPlayer } else if (diff == 1) { return LeftPlayer } else if (diff == 2) { return FrontPlayer } else if (diff == 3) { return RightPlayer } else { throw("Error calculating the player position. This is a bug") }}def maybeCallMe(x) : x > 2 && x < 5 {
}
def maybeCallMe(x) : x >= 5 {}
maybeCallMe(3) // Calls the top onemaybeCallMe(6) // Calls the second onetry { myFunc(2);}catch (e) : type(e, "int") {}class GameView { var playerNumber var cppView def GameView(playerNumber) { // Uses copy constructor playerNumber = playerNumber // does not use copy constructor cppView := createGameView("MatchView") } def someFunction(parameter) { // Parameter can be printed via a "to_string" function print("Hello ${parameter}") }}auto myView = GameView(2)myView.someFunction(MyPrintableClass())class JsonObject { var contents def JsonObject(string jsonStr) { this.contents = from_json(jsonStr) } def JsonObject(Map contents) { this.contents = contents } def has_attrib(name) { var c := this.contents if (type_name(c) == "Map") { var found = false c.for_each(fun[name, found](elem) { if (elem.first == name) { found = true } }) return found } else { return false } } def method_missing(string name, Vector v) { var field := this.contents[name] if (field.type_name() == "Map") { return JsonObject(field) } else { return field } }}// C++ side// void f(std::function<void (MyRegisteredClass)> callback);...chai.add(fun(f), "f");
//chaiscript sidef([](myObject) {})class Counter { construct new(withValue) { _currentValue = withValue } increment() { _currentValue = _currentValue + 1 } value { _currentValue }}
var c = Counter.new(0)for (v in in 1...10.where{|e| e % 2 == 0) { System.print("%(v)") c.increment() System.print("%(c.value)")}for (e in ["hello", "world"]) { System.print("%(e)")}import "environment" for Envimport "guinyoteview" for IBasicGameView, TrySelectEventimport "inputsystem" for Inputimport "guinyoteutils" for MouseClickedEvent, MouseReleasedEvent
class InputSystem { construct new(inputSystem) { _input = inputSystem } getEvents() { return _input.getEvents() }}
class GameView { construct new() { _gameScreen = IBasicGameView.create("GameMenu") _gameScreen.setConfig(Env.config) _gameScreen.onInit(Env.videoManager) // This is downcasting, basically. A trick not needed in ChaiScript _menuScreen = _gameScreen.getAsGameMenu() _menuScreen.setUserAvatarIfExists() _menuScreen.setUserNameIfExists() } consumeEvent(evt) { return _gameScreen.consumeEvent(evt) } draw() { _gameScreen.draw() } // playerName is a read-only property playerName { return _menuScreen.playerName }}class Main { static makeMenuChoice(choice) { if (choice == 0) { return "OnlineRoomsScreen" } else { return "" } } static createViewFiber() { return Fiber.new{|events| var gv = GameView.new() var menuChoice = -1 while (menuChoice == -1 || gv.playerName == null || gv.playerName == "") { if (events) { for (event in events.where{|e| e is MouseReleasedEvent}) { menuChoice = gv.consumeEvent(TrySelectEvent.new(event.x, event.y)) } } } gv.draw() events = Fiber.yield() } Fiber.yield([makeMenuChoice(menuChoice), gv.playerName]) } static createInputFiber() { return Fiber.new{ var inputSystem = InputSystem.new(Input) var events = null while (true) { events = inputSystem.getEvents() if (events.count > 0) { Fiber.yield(events) } Fiber.yield(null) } } } static main(args) { var inputFiber = createInputFiber() var viewFiber = createViewFiber() var events = null var results = null while (!results) { events = inputFiber.call() results = viewFiber.call(events) if (results != null) break } return results }}// 1. Create a struct to be able to expose some fieldsstruct ScriptEnv { std::shared_ptr<spdlog::logger> gameLog; Guinyote::View::VideoManager * videoManager; RuntimeConfig const * config; std::string orsAddress; };// Create a C++ instance to pass the data to wrenScriptEnv scriptEnv{ .gameLog = logger_, .videoManager = i_->videoManager, .config = i_->config, .orsAddress = i_->orsAddress };// Register in environment moduleauto & m = vm->module("environment");// Register ScriptEnv fields, etc.auto & wrenEnvClass = m.klass<ScriptEnv>("ScriptEnv");// Small nicety via C++17: template do-not-repeat-yourself// auto template parameter for passing members to pointers wrenEnvClass.varReadonly<&ScriptEnv::gameLog>("log"); wrenEnvClass.varReadonly<&ScriptEnv::videoManager>("videoManager");wrenEnvClass.varReadonly<&ScriptEnv::config>("config");// Create a Wren global to expose the C++ Script envm.append("var Env = null");// Emit Wren code for a class that will set Envm.append(R"--(class EnvSetter { static set(env) { Env = env } } )--");// run the module codevm->runFromSource("environment", m.str());// Use the set and expose the C++-side variablevm->find("environment", "EnvSetter").func("set(_)")(&scriptEnv);auto vec = []vec.push_back(MyClass()) // Worksvec[0] = 5 // Failsvar aVar // is_var_undefined() == trueaVar = Mytype() // It works, now aVar has MyType()aVar = 3 // Failsv = CppExposedClass() //Call copy constructorw = PureChaiClass() // no copy constructor called!v := CppExposedClass() // No copy constructor called, used :=// Uses reference semantics for C++-side classes. In ChaiScript// classes you always avoid the copy constructorvar v := something// These two are equivalent:var & v = somethingauto & v = somethingvar lmbda = [v]() { ...} // No copy in capture for surevar f = Fn.new { ....}// This fails, you cannot call itf()//Use explicit syntaxf.call()int HotLoaderImpl::reload(LevelSpec* specs, GameServices* services) { if (_dlhandle) { dlclose(_dlhandle); }
_dlhandle = dlopen(_dlpath.c_str(), RTLD_LOCAL | RTLD_LAZY); if (!_dlhandle) { error("Unable to load level specs library: {}", dlerror()); exit(EXIT_FAILURE); }
_get_level_specs = (GET_LEVEL_SPECS_CB) dlsym(_dlhandle, "get_level_specs"); if (_get_level_specs == nullptr) { error("Unable to load level specs function."); exit(EXIT_FAILURE); }
return _get_level_specs(specs, services);}% fswatch -o puzzles_src | xargs -I {} \ cmake --build .release -- puzzles_dll class GameServices { public: static GameServices* create(); static void destroy(GameServices*);
virtual Environment* environment() = 0; virtual Grid* grid() = 0; virtual Player* player() = 0; virtual LocalSettings* settings() = 0;
virtual ~GameServices() = default;};class GameImpl : public GameServices { public: GameImpl() { ... } ~GameImpl() { ... }
Environment* environment() final { ... } Grid* grid() final { ... } Player* player() final { ... } LocalSettings* settings() final { ... }};
GameServices* GameServices::create() { return new GameImpl(); }void GameService#include <stdio.h>s::destroy(GameServices* game) { delete game; }#include <stdio.h>printf("hello world\n")#include <stdio.h>
void _01_hello_world() { printf("foo\n");};#include <iostream>
void _02_hello_world(){ std::cout << "Hello world" << std::endl;}#include <QtWidgets/qapplication.h>#include <QtWidgets/qpushbutton.h>
void _03_basic_qt(){ int argc = 0; QApplication app(argc, nullptr);
QPushButton button("Hello world"); QObject::connect(&button, &QPushButton::pressed, &app, &QApplication::quit); button.show();
app.exec();}cling -I/usr/include/x86_64-linux-gnu/qt5 -fPIC -lQt5Widgets 03_basic_qt.cpp
0 comments