// for js event handlers public ScriptObjectEventInfo (ScriptObject callback, Type type) { Callback = callback; this.type = type; NativeMethods.html_object_retain (PluginHost.Handle, Callback.Handle); }
public override bool Execute(ScriptObject scriptObject) { ServiceProvider.ScriptManager.OutPut("Bulb capture started"); Executing = true; if (scriptObject.CameraDevice != null) { if (scriptObject.CameraDevice.IsoNumber != null) scriptObject.CameraDevice.IsoNumber.SetValue(Iso); Thread.Sleep(200); if (scriptObject.CameraDevice.FNumber != null) scriptObject.CameraDevice.FNumber.SetValue(Aperture); Thread.Sleep(200); } scriptObject.StartCapture(); Thread.Sleep(200); for (int i = 0; i < CaptureTime; i++) { if (ServiceProvider.ScriptManager.ShouldStop) break; Thread.Sleep(1000); ServiceProvider.ScriptManager.OutPut(string.Format("Bulb capture in progress .... {0}/{1}", i + 1, CaptureTime)); } scriptObject.StopCapture(); Thread.Sleep(200); Executing = false; IsExecuted = true; ServiceProvider.ScriptManager.OutPut("Bulb capture done"); return true; }
public void HandleNavigate(ScriptObject state) { if (Navigate != null) { Navigate(this, new StateEventArgs() { State = state }); } }
public override bool Execute(ScriptObject scriptObject) { int time = 0; int.TryParse(scriptObject.ParseString(LoadedParams["time"]), out time); Executing = true; DateTime currTime = DateTime.Now; if (LoadedParams["for"] == "camera" && ServiceProvider.DeviceManager.SelectedCameraDevice != null) { ServiceProvider.ScriptManager.OutPut(string.Format("Waiting .... for camera")); while (ServiceProvider.DeviceManager.SelectedCameraDevice.IsBusy) { if (ServiceProvider.ScriptManager.ShouldStop) break; Thread.Sleep(100); } } double dif = time - (DateTime.Now - currTime).TotalSeconds; if (dif > 0) { ServiceProvider.ScriptManager.OutPut(string.Format("Waiting .... {0}s", dif)); while ((DateTime.Now - currTime).TotalSeconds < time) { if (ServiceProvider.ScriptManager.ShouldStop) break; Thread.Sleep(100); } } Executing = false; IsExecuted = true; return true; }
public override bool Execute(ScriptObject scriptObject) { try { int cameranum = 0; if (int.TryParse(scriptObject.ParseString(LoadedParams["cameranum"]), out cameranum)) { if (cameranum > -1 && cameranum < ServiceProvider.DeviceManager.ConnectedDevices.Count) { ServiceProvider.DeviceManager.SelectedCameraDevice = ServiceProvider.DeviceManager.ConnectedDevices[cameranum]; scriptObject.CameraDevice = ServiceProvider.DeviceManager.ConnectedDevices[cameranum]; } else { ServiceProvider.ScriptManager.OutPut("Camera with number " + cameranum + "not exist"); } } else { ServiceProvider.ScriptManager.OutPut("Wrong camera number"); } } catch (Exception exception) { ServiceProvider.ScriptManager.OutPut("Exception on select camera " + exception.Message); } return true; }
public object Call(ScriptObject[] args) { for (int i = 0; i < args.Length; ++i) { output += args[i].ToString() + "\n"; } return null; }
public GMapAPI() { timer.Interval = TimeSpan.FromMilliseconds(100); timer.Tick += new EventHandler(timer_Tick); gload = (ScriptObject)HtmlPage.Window.GetProperty("GLoad"); if (gload == null) { HtmlElement scriptElement = HtmlPage.Document.CreateElement("script"); scriptElement.SetAttribute("type", "text/javascript"); string src = "http://maps.google.com/maps?file=api&v=2"; scriptElement.SetAttribute("src", src); HtmlPage.Document.Body.AppendChild(scriptElement); gload = (ScriptObject)HtmlPage.Window.GetProperty("GLoad"); if (gload == null) { timer.Start(); } else { SetReady(); } } }
/// <summary> /// Initializes the console for silverlight applications. /// </summary> /// <returns><c>true</c> if the console is available; otherwise <c>false</c>.</returns> private bool InitializeConsole() { try { if (_console == null) { if (!_dispatcher.CheckAccess()) { return false; } var window = HtmlPage.Window; var isConsoleAvailable = (bool)window.Eval("typeof(console) != 'undefined' && typeof(console.log) != 'undefined'"); if (isConsoleAvailable) { var createLogFunction = (bool)window.Eval("typeof(catellog) === 'undefined'"); if (createLogFunction) { // Load the logging function into global scope: const string logFunction = @"function catellog(msg) { console.log(msg); }"; string code = string.Format(@"if(window.execScript) {{ window.execScript('{0}'); }} else {{ eval.call(null, '{0}'); }}", logFunction); window.Eval(code); } _console = window.Eval("catellog") as ScriptObject; } } } catch (Exception) { } return (_console != null); }
// must be called on UI thread public static void LoadScript() { //0 indicates that the script was not injected. if (0 != Interlocked.Exchange(ref _scriptInjected, 1)) return; //JavaScript Debug - v0.4 - 6/22/2010 //http://benalman.com/projects/javascript-debug-console-log/ //Copyright (c) 2010 "Cowboy" Ben Alman const string script = @"window.debug=(function(){var i=this,b=Array.prototype.slice,d=i.console,h={},f,g,m=9,c=[""error"",""warn"",""info"",""debug"",""log""],l=""assert clear count dir dirxml exception group groupCollapsed groupEnd profile profileEnd table time timeEnd trace"".split("" ""),j=l.length,a=[];while(--j>=0){(function(n){h[n]=function(){m!==0&&d&&d[n]&&d[n].apply(d,arguments)}})(l[j])}j=c.length;while(--j>=0){(function(n,o){h[o]=function(){var q=b.call(arguments),p=[o].concat(q);a.push(p);e(p);if(!d||!k(n)){return}d.firebug?d[o].apply(i,q):d[o]?d[o](q):d.log(q)}})(j,c[j])}function e(n){if(f&&(g||!d||!d.log)){f.apply(i,n)}}h.setLevel=function(n){m=typeof n===""number""?n:9};function k(n){return m>0?m>n:c.length+m<=n}h.setCallback=function(){var o=b.call(arguments),n=a.length,p=n;f=o.shift()||null;g=typeof o[0]===""boolean""?o.shift():false;p-=typeof o[0]===""number""?o.shift():n;while(p<n){e(a[p++])}};return h})();"; try { HtmlWindow window = HtmlPage.Window; window.Eval(script); // get handle to methods _debugError = window.Eval("debug.error") as ScriptObject; _debugWarn = window.Eval("debug.warn") as ScriptObject; _debugInfo = window.Eval("debug.info") as ScriptObject; _debugLog = window.Eval("debug.log") as ScriptObject; } catch (Exception ex) { Debug.WriteLine("Error loading debug.log script: " + ex); } }
public ScriptObjectEventInfo (string name, ScriptObject callback, EventInfo ei) { Name = name; Callback = callback; EventInfo = ei; NativeMethods.html_object_retain (PluginHost.Handle, Callback.Handle); }
// extract common [SecurityCritical] parts of the public .ctors private ScriptObjectEventInfo (ScriptObject callback) { if (callback == null) throw new ArgumentNullException ("callback"); Callback = callback; NativeMethods.html_object_retain (PluginHost.Handle, Callback.Handle); }
public void readAsArrayBuffer(ScriptObject scriptBlob) { App.Current.RootVisual.Dispatcher.BeginInvoke((Action<ScriptObject>)delegate(ScriptObject blob) { this.readAsArrayBufferSync(blob); }, new object[]{scriptBlob}); }
public void NavigateTo(string controlName, ScriptObject parameterList) { var paramList = parameterList.ConvertTo<List<object>>(); var launcher = pageLaunchers[controlName]; LayoutRoot.Children.Clear(); var form = launcher(paramList); LayoutRoot.Children.Add(form); }
public static void Register(ScriptObject builtins) { if (builtins == null) throw new ArgumentNullException(nameof(builtins)); var mathObject = ScriptObject.From(typeof(MathFunctions)); mathObject.SetValue("round", new DelegateCustomFunction(Round), true); builtins.SetValue("math", mathObject, true); }
public override bool Execute(ScriptObject scriptObject) { foreach (ICameraDevice cameraDevice in ServiceProvider.DeviceManager.ConnectedDevices) { ICameraDevice device = cameraDevice; new Thread(() => Capture(device)).Start(); } return true; }
/** * Conducts an Isolated Storage data retrieval operation on * files identified by or in Objects in a given collection. * @param dataArray a ScriptObject consisting of ScriptObjects that each either identify or contain * identifying and operation related data pertaining to a data item to be retrieved * @param optionsDic a ScriptObject containing auxiliary data pertinent to the to-be-conducted operation * @param operationID a String uniquely identifying this storage operation in the * client-side scripting environment in which it was created */ public void isf_get(ScriptObject dataArraySO, ScriptObject optionsSO, String operationID) { //Will contain key-value pairs each consisting of the name of a file in Isolated Storage //denoted or represented by an element in dataArray, and the contents of that file Dictionary<String, Object> keyValuePairsDic = new Dictionary<String, Object>(); int processedItemCount = 0; /** * Concludes the over-arching retrieval operation, passing to a Javascript function capable of handling * such an event the number of files successfully read along with the data resulting from the operation. * @param e the Exception responsible for concluding the over-arching get operation */ Action<Exception> completeGet = delegate(Exception e) { Object[] argArray = (e == null ? new Object[] { processedItemCount, keyValuePairsDic } : new Object[] { processedItemCount, keyValuePairsDic, e }); complete(operationID, argArray); }; /** * Performs a read operation on the file identified by the currently processing ScriptObject * in {@code dataArraySO} located in the directory specified by {@code optionsSO}. * @param store an IsolatedStorageFile manifestation of the facility containing * the file identified by {@code directoryPath} and {@code dataObject} * @param directoryPath a String of the path to the Directory containing the file to be read * @param dataObject an Object either identifying, or containing identifying and * operation-related data pertaining to a data item to be processed */ Action<IsolatedStorageFile, String, Object> get = delegate(IsolatedStorageFile store, String directoryPath, Object dataObject) { String fileName; String dataFormat; String dataEncoding; if (dataObject is ScriptObject) { ScriptObject dataSO = (ScriptObject)dataObject; fileName = dataSO.GetProperty("key").ToString(); dataFormat = (dataSO.GetProperty("dataFormat") != null ? (String)dataSO.GetProperty("dataFormat") : (String)optionsSO.GetProperty("dataFormat")); dataEncoding = (dataSO.GetProperty("dataEncoding") != null ? (String)dataSO.GetProperty("dataEncoding") : (String)optionsSO.GetProperty("dataEncoding")); } else { fileName = dataObject.ToString(); dataFormat = (String)optionsSO.GetProperty("dataFormat"); dataEncoding = (String)optionsSO.GetProperty("dataEncoding"); } keyValuePairsDic[fileName] = readFile(store, directoryPath + fileName, dataFormat, dataEncoding); processedItemCount++; }; isf_getOrRemove(dataArraySO, optionsSO, get, completeGet); }
public object Call(ScriptObject[] args) { string file = args[0].ToString(); string buffer = args[1].ToString(); string path = Path.GetDirectoryName(file); if (!Directory.Exists(path)) Directory.CreateDirectory(path); if (File.Exists(file)) File.Delete(file); File.WriteAllText(file, buffer, Encoding.UTF8); return null; }
public JavaScriptAdk() { //check if dynatrace ADK is available try { object o = HtmlPage.Window.Eval("dynaTrace"); if (o != null) dynaTraceObject = (ScriptObject)o; } catch (Exception e) { } }
public override ScriptObject Compute(TokenType type, ScriptObject obj) { switch (type) { case TokenType.Plus: return m_Script.CreateObject(Delegate.Combine(m_Delegate, (Delegate)Util.ChangeType(m_Script, obj, ValueType))); case TokenType.Minus: return m_Script.CreateObject(Delegate.Remove(m_Delegate, (Delegate)Util.ChangeType(m_Script, obj, ValueType))); default: throw new ExecutionException(m_Script, "Delegate 不支持的运算符 " + type); } }
internal static void SetReadyStateChange(ScriptObject request, ScriptObject callback) { if (callback == null) { HelperScriptObject.Invoke("setReadyStateChangeToNull", new object[] { request }); } else { HelperScriptObject.Invoke("setReadyStateChange", new object[] { request, callback }); } }
public object Call(ScriptObject[] args) { string path = args[0].ToString(); string parttern = args[1].ToString(); bool recursive = (args[2] as ScriptBoolean).Value; var files = Directory.GetFiles(parttern, parttern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); ScriptArray array = m_script.CreateArray(); foreach (var file in files) { array.Add(m_script.CreateString(file)); } return array; }
/// <summary> /// Registers all scriban builtins to the specified <see cref="ScriptObject"/>. /// </summary> /// <param name="builtins">The builtins object.</param> /// <exception cref="System.ArgumentNullException">If builtins is null</exception> public static void Register(ScriptObject builtins) { if (builtins == null) throw new ArgumentNullException(nameof(builtins)); IncludeFunction.Register(builtins); ObjectFunctions.Register(builtins); ScriptDate.Register(builtins); ScriptTimeSpan.Register(builtins); ArrayFunctions.Register(builtins); StringFunctions.Register(builtins); MathFunctions.Register(builtins); }
public object Call(ScriptObject[] args) { int num = args.Length; if (num == 0) return 0f; double num2 = (args[0] as ScriptNumber).ToDouble(); for (int i = 1; i < num; i++) { double num3 = (args[i] as ScriptNumber).ToDouble(); if (num3 < num2) num2 = num3; } return num2; }
public override object Call(ScriptObject[] parameters) { FunctionParameter parameter; for (int i = 0; i < m_Parameters.Count; i++) { parameter = m_Parameters[i]; if (i >= parameters.Length) { m_Objects[i] = parameter.DefaultValue; } else { m_Objects[i] = Util.ChangeType(m_Script, parameters[i], parameter.ParameterType); } } return m_Delegate.DynamicInvoke(m_Objects); }
public override ScriptObject AssignCompute(TokenType type, ScriptObject obj) { switch (type) { case TokenType.AssignPlus: m_EventInfo.AddEventHandler(m_Target, (Delegate)Util.ChangeType(m_Script, obj, m_HandlerType)); return m_Script.Null; case TokenType.AssignMinus: m_EventInfo.RemoveEventHandler(m_Target, (Delegate)Util.ChangeType(m_Script, obj, m_HandlerType)); return m_Script.Null; default: throw new ExecutionException(m_Script, "event 不支持的运算符 " + type); } }
internal static void SetReadyStateChange(ScriptObject request, ScriptObject callback) { Debug.Assert(request != null, "request != null"); if (callback == null) { HelperScriptObject.Invoke("setReadyStateChangeToNull", request); } else { HelperScriptObject.Invoke("setReadyStateChange", request, callback); } }
public override void Evaluate(TemplateContext context) { var scriptObject = new ScriptObject(); foreach (var member in Members) { var variable = member.Key as ScriptVariable; var literal = member.Key as ScriptLiteral; var name = variable?.Name ?? literal?.Value?.ToString(); scriptObject.SetValue(name, context.Evaluate(member.Value), false); } context.Result = scriptObject; }
/// <summary> /// Constructs a managed closing event from a corresponding JavaScript event. /// </summary> /// <param name="sevent">The JavaScript event argument for the SettingsClosing event.</param> public SettingsClosingEventArgs(ScriptObject sevent) : base() { this.sevent = sevent; byte act = Convert.ToByte(sevent.GetProperty("closeAction")); if (act == 0) Action = CloseAction.Commit; else Action = CloseAction.Cancel; Cancellable = Convert.ToBoolean(sevent.GetProperty("cancellable")); }
/// <summary> /// Trace a debug in Browser output /// </summary> /// <param name="text">The text to display in debug output</param> public static void WriteLine(string text) { if (debugFunction == null) { HtmlElement elem = HtmlPage.Document.CreateElement("script"); elem.SetAttribute("type", "text/javascript"); elem.SetProperty("text", JavascriptDebug); HtmlPage.Document.Body.AppendChild(elem); debugFunction = HtmlPage.Window.GetProperty("_dbg") as ScriptObject; } System.Diagnostics.Debug.WriteLine(text); //HtmlPage.Window.Eval(JavascriptDebug + string.Format(JavascriptDebugExec, (text ?? "").Replace("\\", "\\\\").Replace("'", "\\'"))); debugFunction.InvokeSelf(text); }
private void CaptureAsync(ScriptObject scriptObject) { try { scriptObject.CameraDevice.IsBusy = true; CameraHelper.Capture(scriptObject.CameraDevice); } catch (Exception exception) { scriptObject.CameraDevice.IsBusy = false; ServiceProvider.ScriptManager.OutPut("Capture error " + exception.Message); Log.Debug("Script capture error", exception); } }
public override bool Execute(ScriptObject scriptObject) { ServiceProvider.ScriptManager.Stop(); return(true); }
public TemplateContext(ScriptObject builtin, IEqualityComparer <string> keyComparer) { BuiltinObject = builtin ?? GetDefaultBuiltinObject(); EnableOutput = true; EnableBreakAndContinueAsReturnOutsideLoop = false; EnableRelaxedTargetAccess = false; EnableRelaxedMemberAccess = true; EnableRelaxedFunctionAccess = false; EnableRelaxedIndexerAccess = true; AutoIndent = true; LoopLimit = 1000; RecursiveLimit = 100; LimitToString = 0; ObjectRecursionLimit = 0; MemberRenamer = StandardMemberRenamer.Default; RegexTimeOut = TimeSpan.FromSeconds(10); TemplateLoaderParserOptions = new ParserOptions(); TemplateLoaderLexerOptions = LexerOptions.Default; NewLine = Environment.NewLine; Language = ScriptLang.Default; _outputs = new FastStack <IScriptOutput>(4); _output = new StringBuilderOutput(); _outputs.Push(_output); _globalContexts = new FastStack <VariableContext>(4); _availableGlobalContexts = new FastStack <VariableContext>(4); _availableLocalContexts = new FastStack <VariableContext>(4); _localContexts = new FastStack <VariableContext>(4); _availableStores = new FastStack <ScriptObject>(4); _cultures = new FastStack <CultureInfo>(4); _caseValues = new FastStack <object>(4); _availableTags = new FastStack <Dictionary <object, object> >(4); _sourceFiles = new FastStack <string>(4); _memberAccessors = new Dictionary <Type, IObjectAccessor>(); _listAccessors = new Dictionary <Type, IListAccessor>(); _loops = new FastStack <ScriptLoopStatementBase>(4); BlockDelegates = new FastStack <ScriptBlockStatement>(4); _availablePipeArguments = new FastStack <ScriptPipeArguments>(4); _pipeArguments = new FastStack <ScriptPipeArguments>(4); _availableScriptExpressionLists = new FastStack <List <ScriptExpression> >(4); _availableReflectionArguments = new object[ScriptFunctionCall.MaximumParameterCount + 1][]; _keyComparer = keyComparer; for (int i = 0; i < _availableReflectionArguments.Length; i++) { _availableReflectionArguments[i] = new object[i]; } _isFunctionCallDisabled = false; CachedTemplates = new Dictionary <string, Template>(); Tags = new Dictionary <object, object>(); // Ensure that builtin is registered first PushGlobal(BuiltinObject); }
ScriptFunctionObject objectPrototypeValueOf) Initialise([NotNull] Realm realm, [NotNull] ScriptObject objectPrototype, [NotNull] ScriptObject functionPrototype) { var objectConstructor = Intrinsics.CreateBuiltinFunction(realm, Object, functionPrototype, 1, "Object", ConstructorKind.Base); Intrinsics.DefineFunction(objectConstructor, "assign", 2, realm, Assign); Intrinsics.DefineFunction(objectConstructor, "create", 2, realm, Create); Intrinsics.DefineFunction(objectConstructor, "defineProperties", 2, realm, DefineProperties); Intrinsics.DefineFunction(objectConstructor, "defineProperty", 3, realm, DefineProperty); Intrinsics.DefineFunction(objectConstructor, "entries", 1, realm, Entries); Intrinsics.DefineFunction(objectConstructor, "freeze", 1, realm, Freeze); Intrinsics.DefineFunction(objectConstructor, "getOwnPropertyDescriptor", 2, realm, GetOwnPropertyDescriptor); Intrinsics.DefineFunction(objectConstructor, "getOwnPropertyDescriptors", 1, realm, GetOwnPropertyDescriptors); Intrinsics.DefineFunction(objectConstructor, "getOwnPropertyNames", 1, realm, GetOwnPropertyNames); Intrinsics.DefineFunction(objectConstructor, "getOwnPropertySymbols", 1, realm, GetOwnPropertySymbols); Intrinsics.DefineFunction(objectConstructor, "getPrototypeOf", 1, realm, GetPrototypeOf); Intrinsics.DefineFunction(objectConstructor, "is", 2, realm, Is); Intrinsics.DefineFunction(objectConstructor, "isExtensible", 1, realm, IsExtensible); Intrinsics.DefineFunction(objectConstructor, "isFrozen", 1, realm, IsFrozen); Intrinsics.DefineFunction(objectConstructor, "isSealed", 1, realm, IsSealed); Intrinsics.DefineFunction(objectConstructor, "keys", 1, realm, Keys); Intrinsics.DefineFunction(objectConstructor, "preventExtensions", 1, realm, PreventExtensions); Intrinsics.DefineDataProperty(objectConstructor, "prototype", objectPrototype, false, false, false); Intrinsics.DefineFunction(objectConstructor, "seal", 1, realm, Seal); Intrinsics.DefineFunction(objectConstructor, "setPrototypeOf", 2, realm, SetPrototypeOf); Intrinsics.DefineFunction(objectConstructor, "values", 1, realm, Values); Intrinsics.DefineDataProperty(objectPrototype, "constructor", objectConstructor); Intrinsics.DefineFunction(objectPrototype, "hasOwnProperty", 1, realm, HasOwnProperty); Intrinsics.DefineFunction(objectPrototype, "isPrototypeOf", 1, realm, IsPrototypeOf); Intrinsics.DefineFunction(objectPrototype, "propertyIsEnumerable", 1, realm, PropertyIsEnumerable); Intrinsics.DefineFunction(objectPrototype, "toLocaleString", 0, realm, ToLocaleString); var objectPrototypeToString = Intrinsics.DefineFunction(objectPrototype, "toString", 0, realm, ToString); var objectPrototypeValueOf = Intrinsics.DefineFunction(objectPrototype, "valueOf", 0, realm, ValueOf); return(objectConstructor, objectPrototypeToString, objectPrototypeValueOf); }
public InteriorException(ScriptObject obj) { this.obj = obj; }
public AttributesGlobber(AttributesObject parent, string pattern, bool match, ScriptObject setters) : base(parent) { Match = match; Pattern = pattern; Setters = setters; }
public HtmlPage(ScriptObject parent) : base(parent) { parent.SetValue(SiteVariables.Html, this, true); Head = new HtmlHead(this); SetValue("head", Head, true); }
private void ClearDefinitions() { ScriptObject.Clear(); }
/// <summary> /// Collects the values for an export /// </summary> /// <param name="templateType">Template type</param> /// <param name="parsedTemplate">Parsed scriban template</param> /// <param name="scriptObject">Scriban script object to fill</param> /// <param name="data">Export Data</param> /// <returns>Task</returns> public override async Task CollectValues(TemplateType templateType, Template parsedTemplate, ScriptObject scriptObject, ExportObjectData data) { KortistoNpc inputNpc = data.ExportData[ExportConstants.ExportDataObject] as KortistoNpc; if (inputNpc == null) { return; } _languageKeyGenerator.SetErrorCollection(_errorCollection); GoNorthProject project = await _exportCachedDbAccess.GetUserProject(); TaleDialog dialog = await _taleDbAccess.GetDialogByRelatedObjectId(inputNpc.Id); ExportDialogData parsedDialog = await ParseDialog(inputNpc, project, dialog); ScribanExportDialog exportDialog = await BuildExportDialog(parsedDialog, inputNpc); scriptObject.AddOrUpdate(ExportConstants.ScribanDialogKey, exportDialog); scriptObject.AddOrUpdate(DialogFunctionRenderer.DialogFunctionName, new DialogFunctionRenderer(_templatePlaceholderResolver, _exportCachedDbAccess, _defaultTemplateProvider, _errorCollection, data)); }
public ScriptValue([NotNull] ScriptObject value) { type = Type.Object; doubleValue = 0; objectValue = value; }
public void TestJson() { // issue: https://github.com/lunet-io/scriban/issues/11 // fixed: https://github.com/lunet-io/scriban/issues/15 System.Data.DataTable dataTable = new System.Data.DataTable(); dataTable.Columns.Add("Column1"); dataTable.Columns.Add("Column2"); System.Data.DataRow dataRow = dataTable.NewRow(); dataRow["Column1"] = "Hello"; dataRow["Column2"] = "World"; dataTable.Rows.Add(dataRow); dataRow = dataTable.NewRow(); dataRow["Column1"] = "Bonjour"; dataRow["Column2"] = "le monde"; dataTable.Rows.Add(dataRow); string json = JsonConvert.SerializeObject(dataTable); Console.WriteLine("Json: " + json); var parsed = JsonConvert.DeserializeObject(json); Console.WriteLine("Parsed: " + parsed); string myTemplate = @" [ { {{ for tbr in tb }} ""N"": {{tbr.Column1}}, ""M"": {{tbr.Column2}} {{ end }} }, ] {{tb}} "; // Parse the template var template = Template.Parse(myTemplate); // Render var context = new TemplateContext { MemberRenamer = member => member.Name }; var scriptObject = new ScriptObject(); scriptObject.Import(new { tb = parsed }); context.PushGlobal(scriptObject); var result = template.Render(context); context.PopGlobal(); var expected = @" [ { ""N"": Hello, ""M"": World ""N"": Bonjour, ""M"": le monde }, ] [[[Hello], [World]], [[Bonjour], [le monde]]] "; TextAssert.AreEqual(expected, result); }
private void Initialize(string name, ScriptObject obj) { m_variableDictionary.Add(name, obj); }
private void SetVariableForce(string name, ScriptObject obj) { m_variableDictionary[name] = obj.Assign(); }
public static string ToJsonString(this ScriptObject a) { return(a.ToJsonValue().ToString()); }
public WebGLObject(ScriptObject obj) { Object = obj; }
public static (ScriptObject Generator, ScriptObject GeneratorPrototype, ScriptFunctionObject GeneratorFunction) Initialise([NotNull] Agent agent, [NotNull] Realm realm, [NotNull] ScriptObject functionPrototype) { var generator = agent.ObjectCreate(functionPrototype); var generatorPrototype = agent.ObjectCreate(realm.IteratorPrototype); Intrinsics.DefineDataProperty(generatorPrototype, "constructor", generator, false); Intrinsics.DefineFunction(generatorPrototype, "next", 1, realm, Next); Intrinsics.DefineFunction(generatorPrototype, "return", 1, realm, Return); Intrinsics.DefineFunction(generatorPrototype, "throw", 1, realm, Throw); Intrinsics.DefineDataProperty(generatorPrototype, Symbol.ToStringTag, "Generator", false); var generatorFunction = Intrinsics.CreateBuiltinFunction(realm, GeneratorFunction, realm.Function, 1, "GeneratorFunction", ConstructorKind.Base); Intrinsics.DefineDataProperty(generatorFunction, "prototype", generator, false, false, false); Intrinsics.DefineDataProperty(generator, "constructor", generatorFunction, false); Intrinsics.DefineDataProperty(generator, "prototype", generatorPrototype, false); Intrinsics.DefineDataProperty(generator, Symbol.ToStringTag, "GeneratorFunction", false); return(generator, generatorPrototype, generatorFunction); }
private string ObjectToStringImpl(object value, bool nested) { if (LimitToString > 0 && _currentToStringLength >= LimitToString) { return(string.Empty); } if (value is string str) { if (LimitToString > 0 && _currentToStringLength + str.Length >= LimitToString) { var index = LimitToString - _currentToStringLength; if (index <= 0) { return(string.Empty); } str = str.Substring(0, index); return(nested ? $"\"{StringFunctions.Escape(str)}" : (string)value); } return(nested ? $"\"{StringFunctions.Escape(str)}\"" : (string)value); } if (value == null || value == EmptyScriptObject.Default) { return(nested ? "null" : null); } if (value is bool b) { return(b ? "true" : "false"); } if (value is DateTime dt) { // Output DateTime only if we have the date builtin object accessible (that provides the implementation of the ToString method) bool isStrict = StrictVariables; try { StrictVariables = false; if (GetValue(DateTimeFunctions.DateVariable) is DateTimeFunctions dateTimeFunctions) { return(dateTimeFunctions.ToString(dt, dateTimeFunctions.Format, CurrentCulture)); } } finally { StrictVariables = isStrict; } } // If the value is formattable, use the formatter directly if (value is IFormattable formattable) { return(formattable.ToString(null, this)); } if (value is IConvertible convertible) { return(convertible.ToString(this)); } // If we have an enumeration, we dump it if (value is IEnumerable enumerable) { var result = new StringBuilder(); result.Append("["); _currentToStringLength++; bool isFirst = true; foreach (var item in enumerable) { if (!isFirst) { result.Append(", "); _currentToStringLength += 2; } var itemStr = ObjectToString(item); result.Append(itemStr); if (itemStr != null) { _currentToStringLength += itemStr.Length; } // Limit to size if (LimitToString > 0 && _currentToStringLength >= LimitToString) { return(result.ToString()); } isFirst = false; } result.Append("]"); _currentToStringLength += 1; return(result.ToString()); } // Special case to display KeyValuePair as key, value var type = value.GetType(); var typeName = type.FullName; if (typeName != null && typeName.StartsWith("System.Collections.Generic.KeyValuePair")) { var keyValuePair = new ScriptObject(2); keyValuePair.Import(value, renamer: this.MemberRenamer); return(ObjectToString(keyValuePair)); } if (value is IScriptCustomFunction && !(value is ScriptFunction)) { return("<function>"); } // Else just end-up trying to emit the ToString return(value.ToString()); }
public Page() { InitializeComponent(); Loaded += new RoutedEventHandler(Page_Loaded); jsUpdateElement = (ScriptObject)HtmlPage.Window.GetProperty("updateElement"); }
public static (ScriptFunctionObject number, ScriptObject numberPrototype) Initialise([NotNull] Agent agent, [NotNull] Realm realm, [NotNull] ScriptObject objectPrototype, [NotNull] ScriptObject functionPrototype) { var number = Intrinsics.CreateBuiltinFunction(realm, Number, functionPrototype, 1, "Number", ConstructorKind.Base); Intrinsics.DefineDataProperty(number, "EPSILON", 2.2204460492503130808472633361816E-16, false, false, false); Intrinsics.DefineDataProperty(number, "MAX_SAFE_INTEGER", 9007199254740991, false, false, false); Intrinsics.DefineDataProperty(number, "MAX_VALUE", double.MaxValue, false, false, false); Intrinsics.DefineDataProperty(number, "MIN_SAFE_INTEGER", -9007199254740991, false, false, false); Intrinsics.DefineDataProperty(number, "MIN_VALUE", double.Epsilon, false, false, false); Intrinsics.DefineDataProperty(number, "NaN", double.NaN, false, false, false); Intrinsics.DefineDataProperty(number, "NEGATIVE_INFINITY", double.NegativeInfinity, false, false, false); Intrinsics.DefineDataProperty(number, "POSITIVE_INFINITY", double.PositiveInfinity, false, false, false); Intrinsics.DefineFunction(number, "isFinite", 1, realm, IsFinite); Intrinsics.DefineFunction(number, "isInteger", 1, realm, IsInteger); Intrinsics.DefineFunction(number, "isNaN", 1, realm, IsNaN); Intrinsics.DefineFunction(number, "isSafeInteger", 1, realm, IsSafeInteger); Intrinsics.DefineFunction(number, "parseFloat", 1, realm, ParseFloat); Intrinsics.DefineFunction(number, "parseInt", 2, realm, ParseInt); var numberPrototype = agent.ObjectCreate(objectPrototype, SpecialObjectType.Number); Intrinsics.DefineDataProperty(numberPrototype, "constructor", number); Intrinsics.DefineFunction(numberPrototype, "toExponential", 1, realm, ToExponential); Intrinsics.DefineFunction(numberPrototype, "toFixed", 1, realm, ToFixed); Intrinsics.DefineFunction(numberPrototype, "toLocaleString", 0, realm, ToLocaleString); Intrinsics.DefineFunction(numberPrototype, "toPrecision", 1, realm, ToPrecision); Intrinsics.DefineFunction(numberPrototype, "toString", 1, realm, ToString); Intrinsics.DefineFunction(numberPrototype, "valueOf", 0, realm, ValueOf); Intrinsics.DefineDataProperty(number, "prototype", numberPrototype, false, false, false); return(number, numberPrototype); }
private void Initialize(ScriptContext parent, string name, ScriptObject obj) { m_parent = parent; m_variableDictionary.Clear(); m_variableDictionary.Add(name, obj); }
private static async Task <ContentObject> LoadPageScript(SiteObject site, Stream stream, FileEntry file, ScriptObject preContent) { var evalClock = Stopwatch.StartNew(); // Read the stream var reader = new StreamReader(stream); var content = await reader.ReadToEndAsync(); // Early dispose the stream stream.Dispose(); ContentObject page = null; // Parse the page, using front-matter mode var scriptInstance = site.Scripts.ParseScript(content, file.FullName, ScriptMode.FrontMatterAndContent); if (!scriptInstance.HasErrors) { page = new FileContentObject(site, file, scriptInstance, preContent: preContent); } evalClock.Stop(); // Update statistics var contentStat = site.Statistics.GetContentStat(page); contentStat.LoadingTime += evalClock.Elapsed; return(page); }
public AttributesGlobber UnMatch(string pattern, ScriptObject setters) { return(Match(pattern, false, setters)); }
private async Task <ContentObject> LoadContent(FileEntry file) { ContentObject page = null; var buffer = new byte[16]; var clock = Stopwatch.StartNew(); var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); try { var count = await stream.ReadAsync(buffer, 0, buffer.Length); // Rewind to 0 stream.Position = 0; bool hasFrontMatter = false; bool isBinary = false; int startFrontMatter = 0; // Does it start with UTF8 BOM? If yes, skip it // EF BB BF if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) { startFrontMatter = 3; } // TODO: avoid the chars alloc var charBuffer = Encoding.UTF8.GetChars(buffer, startFrontMatter, buffer.Length - startFrontMatter); foreach (var frontParser in Scripts.FrontMatterParsers) { if (frontParser.CanHandle(charBuffer)) { for (int i = startFrontMatter + 3; i < count; i++) { if (buffer[i] == 0) { isBinary = true; break; } } if (!isBinary) { hasFrontMatter = true; } break; } } // Run pre-content (e.g AttributesPlugin) ScriptObject preContent = null; foreach (var preLoadingContentProcessor in BeforeLoadingContentProcessors) { preLoadingContentProcessor(file.Path, ref preContent); } if (hasFrontMatter) { page = await LoadPageScript(Site, stream, file, preContent); stream = null; } else { page = new FileContentObject(Site, file, preContent: preContent); //// Run pre-processing on static content as well //var pendingPageProcessors = new OrderedList<IContentProcessor>(); //TryProcessPage(page, ContentProcessingStage.AfterLoading, AfterLoadingProcessors, pendingPageProcessors, false); } // Initialize the page loaded page?.Initialize(); } finally { // Dispose stream used stream?.Dispose(); } clock.Stop(); Site.Statistics.GetContentStat(page).LoadingParsingTime += clock.Elapsed; return(page); }
private static IEnumerable <ScriptValue> EnumerableOwnProperties([NotNull] Agent agent, [NotNull] ScriptObject obj, EnumerateType type) { //https://tc39.github.io/ecma262/#sec-enumerableownproperties var ownKeys = obj.OwnPropertyKeys(); var properties = new List <ScriptValue>(); foreach (var key in ownKeys) { if (key.IsString) { var descriptor = obj.GetOwnProperty(key); if (descriptor != null && descriptor.Enumerable) { switch (type) { case EnumerateType.Key: properties.Add(key); break; case EnumerateType.Value: properties.Add(obj.Get(key)); break; case EnumerateType.KeyValue: properties.Add(ArrayIntrinsics.CreateArrayFromList(agent, new[] { key, obj.Get(key) })); break; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } } } } return(properties); }
public override void SetValue(string strName, ScriptObject value) { m_Type.SetValue(Value, strName, value); }
/// <summary> /// Collects the values for an export /// </summary> /// <param name="templateType">Template type</param> /// <param name="parsedTemplate">Parsed scriban template</param> /// <param name="scriptObject">Scriban script object to fill</param> /// <param name="data">Export Data</param> /// <returns>Task</returns> public override async Task CollectValues(TemplateType templateType, Template parsedTemplate, ScriptObject scriptObject, ExportObjectData data) { KortistoNpc inputNpc = data.ExportData[ExportConstants.ExportDataObject] as KortistoNpc; if (inputNpc == null) { return; } StateMachine inputStateMachine = null; if (data.ExportData.ContainsKey(ExportConstants.ExportDataStateMachine)) { inputStateMachine = data.ExportData[ExportConstants.ExportDataStateMachine] as StateMachine; } ScribanExportStateMachine stateMachine = new ScribanExportStateMachine(); stateMachine.States = await BuildStateMachineFunctions(inputNpc, inputStateMachine); scriptObject.AddOrUpdate(ExportConstants.ScribanStateMachineObjectKey, stateMachine); scriptObject.AddOrUpdate(StateMachineFunctionPipeRenderer.StateMachineFunctionName, new StateMachineFunctionPipeRenderer(_templatePlaceholderResolver, _cachedDbAccess, _defaultTemplateProvider, _errorCollection)); }
public void Clone(ScriptObject scriptObject) { var dlg = new CloneToModDialog(); dlg.Init(scriptObject.Filename, scriptObject.LineStart, scriptObject.LineEnd, scriptObject); if (dlg.ShowDialog(CK3ScriptEd.Instance) == DialogResult.OK) { var dir = Core.Instance.GetBaseDirectoryFromContext(dlg.Context); var basePath = scriptObject.Filename; var fullPath = dir.Append(dlg.ChosenFilename); fullPath.IsBase = false; var exists = fullPath.Exists; var textToImplant = dlg.GetTextToImplant(basePath); textToImplant = textToImplant.Replace("\r", ""); if (exists) { // need to insert it into the file.... var text = File.ReadAllText(fullPath.ToFullWindowsFilename()); text = text.Replace("\r", ""); var lines = text.Split('\n').ToList(); var lines2 = textToImplant.Split('\n').ToList(); lines.AddRange(lines2); using (var fs = new FileStream(fullPath.ToFullWindowsFilename(), FileMode.Create)) { // create a new file.... using (var outputFile = new StreamWriter(fs, Encoding.UTF8)) { foreach (var line in lines) { outputFile.WriteLine(line); } } } } else { using (var fs = new FileStream(fullPath.ToFullWindowsFilename(), FileMode.Create)) { // create a new file.... using (var outputFile = new StreamWriter(fs, Encoding.UTF8)) { var lines = textToImplant.Split('\n').ToList(); if (dlg.ScriptObject.Namespace != null) { lines.Insert(0, "\n"); lines.Insert(0, "namespace = " + dlg.ScriptObject.Namespace); } foreach (var line in lines) { outputFile.WriteLine(line); } } } } Core.Instance.ModCK3Library.EnsureFile(fullPath, dlg.ScriptObject.Context); Core.Instance.LoadCK3File(fullPath, false, true); CK3ScriptEd.Instance.projectExplorer.FillProjectView(); CK3ScriptEd.Instance.soExplorer.UpdateScriptExplorer(); CK3ScriptEd.Instance.CloseDocument(true, fullPath); var newLine = Core.Instance.ModCK3Library.GetFile(fullPath).Map[dlg.ScriptObject.Name].LineStart - 1; CK3ScriptEd.Instance.Goto(fullPath, newLine, false); CK3ScriptEd.Instance.Goto(fullPath, newLine, false); } }
Task <object> IJavaScriptEngine.CreateTaskForPromise(ScriptObject promise) { throw new NotImplementedException(); }
public LocalContext(ScriptObject localObject) { LocalObject = localObject; Loops = new FastStack <ScriptObject>(4); }
public override bool Execute(ScriptObject scriptObject) { ServiceProvider.ScriptManager.OutPut(scriptObject.ParseString(LoadedParams["text"])); return(true); }
public static void AssertTemplate(string expected, string input, ScriptLang lang = ScriptLang.Default, bool isRoundtripTest = false, bool supportExactRoundtrip = true, object model = null, bool specialLiquid = false, bool expectParsingErrorForRountrip = false, bool supportRoundTrip = true) { bool isLiquid = lang == ScriptLang.Liquid; var parserOptions = new ParserOptions() { LiquidFunctionsToScriban = isLiquid, }; var lexerOptions = new LexerOptions() { Lang = lang }; if (isRoundtripTest) { lexerOptions.KeepTrivia = true; } if (specialLiquid) { parserOptions.ExpressionDepthLimit = 500; } #if EnableTokensOutput { Console.WriteLine("Tokens"); Console.WriteLine("======================================"); var lexer = new Lexer(input, options: lexerOptions); foreach (var token in lexer) { Console.WriteLine($"{token.Type}: {token.GetText(input)}"); } Console.WriteLine(); } #endif string roundtripText = null; // We loop first on input text, then on roundtrip while (true) { bool isRoundtrip = roundtripText != null; bool hasErrors = false; bool hasException = false; if (isRoundtrip) { Console.WriteLine("Roundtrip"); Console.WriteLine("======================================"); Console.WriteLine(roundtripText); lexerOptions.Lang = lang == ScriptLang.Scientific ? lang : ScriptLang.Default; if (!isLiquid && supportExactRoundtrip) { Console.WriteLine("Checking Exact Roundtrip - Input"); Console.WriteLine("======================================"); TextAssert.AreEqual(input, roundtripText); } input = roundtripText; } else { Console.WriteLine("Input"); Console.WriteLine("======================================"); Console.WriteLine(input); } var template = Template.Parse(input, "text", parserOptions, lexerOptions); var result = string.Empty; var resultAsync = string.Empty; if (template.HasErrors) { hasErrors = true; for (int i = 0; i < template.Messages.Count; i++) { var message = template.Messages[i]; if (i > 0) { result += "\n"; } result += message; } if (specialLiquid && !isRoundtrip) { throw new InvalidOperationException("Parser errors: " + result); } } else { if (isRoundtripTest) { result = template.ToText(); } else { Assert.NotNull(template.Page); if (!isRoundtrip) { // Dumps the roundtrip version var lexerOptionsForTrivia = lexerOptions; lexerOptionsForTrivia.KeepTrivia = true; var templateWithTrivia = Template.Parse(input, "input", parserOptions, lexerOptionsForTrivia); roundtripText = templateWithTrivia.ToText(); } try { // Setup a default model context for the tests if (model == null) { var scriptObj = new ScriptObject { ["page"] = new ScriptObject { ["title"] = "This is a title" }, ["user"] = new ScriptObject { ["name"] = "John" }, ["product"] = new ScriptObject { ["title"] = "Orange", ["type"] = "fruit" }, ["products"] = new ScriptArray() { new ScriptObject { ["title"] = "Orange", ["type"] = "fruit" }, new ScriptObject { ["title"] = "Banana", ["type"] = "fruit" }, new ScriptObject { ["title"] = "Apple", ["type"] = "fruit" }, new ScriptObject { ["title"] = "Computer", ["type"] = "electronics" }, new ScriptObject { ["title"] = "Mobile Phone", ["type"] = "electronics" }, new ScriptObject { ["title"] = "Table", ["type"] = "furniture" }, new ScriptObject { ["title"] = "Sofa", ["type"] = "furniture" }, } }; scriptObj.Import(typeof(SpecialFunctionProvider)); model = scriptObj; } // Render sync { var context = NewTemplateContext(lang); context.PushOutput(new TextWriterOutput(new StringWriter() { NewLine = "\n" })); var contextObj = new ScriptObject(); contextObj.Import(model); context.PushGlobal(contextObj); result = template.Render(context); } // Render async { var asyncContext = NewTemplateContext(lang); asyncContext.PushOutput(new TextWriterOutput(new StringWriter() { NewLine = "\n" })); var contextObj = new ScriptObject(); contextObj.Import(model); asyncContext.PushGlobal(contextObj); resultAsync = template.RenderAsync(asyncContext).Result; } } catch (Exception exception) { hasException = true; if (specialLiquid) { throw; } else { result = GetReason(exception); } } } } var testContext = isRoundtrip ? "Roundtrip - " : String.Empty; Console.WriteLine($"{testContext}Result"); Console.WriteLine("======================================"); Console.WriteLine(result); Console.WriteLine($"{testContext}Expected"); Console.WriteLine("======================================"); Console.WriteLine(expected); if (isRoundtrip && expectParsingErrorForRountrip) { Assert.True(hasErrors, "The roundtrip test is expecting an error"); Assert.AreNotEqual(expected, result); } else { TextAssert.AreEqual(expected, result); } if (!isRoundtrip && !isRoundtripTest && !hasErrors && !hasException) { Console.WriteLine("Checking async"); Console.WriteLine("======================================"); TextAssert.AreEqual(expected, resultAsync); } if (!supportRoundTrip || isRoundtripTest || isRoundtrip || hasErrors) { break; } } }