private JsValue AddAttachment(JsValue self, JsValue[] args) { JsValue attachmentReference = null; string name = null; // will preserve original name switch (args.Length) { case 2: if (args[0].IsString() == false) { ThrowInvalidSriptMethodCall($"First argument of {Transformation.AddAttachment}(name, attachment) must be string"); } name = args[0].AsString(); attachmentReference = args[1]; break; case 1: attachmentReference = args[0]; break; default: ThrowInvalidSriptMethodCall($"{Transformation.AddAttachment} must have one or two arguments"); break; } if (attachmentReference.IsNull()) { return(self); } if (attachmentReference.IsString() == false || attachmentReference.AsString().StartsWith(Transformation.AttachmentMarker) == false) { var message = $"{Transformation.AddAttachment}() method expects to get the reference to an attachment while it got argument of '{attachmentReference.Type}' type"; if (attachmentReference.IsString()) { message += $" (value: '{attachmentReference.AsString()}')"; } ThrowInvalidSriptMethodCall(message); } _currentRun.AddAttachment(self, name, attachmentReference); return(self); }
public static Object FromJsValue(this JsValue val) { switch (val.Type) { case Types.Boolean: return(val.AsBoolean()); case Types.Number: return(val.AsNumber()); case Types.String: return(val.AsString()); case Types.Object: var obj = val.AsObject(); var node = obj as DomNodeInstance; return(node != null ? node.Value : obj); case Types.Undefined: return(Undefined.Text); case Types.Null: return(null); } return(val.ToObject()); }
public static string Render(string template, string data, int attemptsLeft = TEMPLATE_AQUIRE_ATTEMPTS) { int templateHashCode = template.GetHashCode(); if (!functions.ContainsKey(templateHashCode)) { ConcurrentQueue <JsValue> queue = new ConcurrentQueue <JsValue>(); for (int i = 0; i < TEMPLATE_FUNCTIONS_PER_TEMPLATE; i++) { queue.Enqueue(Create(template)); } functions[templateHashCode] = queue; } ConcurrentQueue <JsValue> functionQueue = functions[templateHashCode]; JsValue function; if (functionQueue.TryDequeue(out function)) { JsValue result = function.Invoke(new JsValue(data)); functionQueue.Enqueue(function); return(result.AsString()); } else { if (attemptsLeft > 0) { Thread.Sleep(TEMPLATE_AQUIRE_FAILURE_DELAY_MS); return(Render(template, data, attemptsLeft - 1)); } else { throw new Exception("Could not aquire template function"); } } }
public static ObjectInstance ToObject(Engine engine, JsValue value) { if (value.IsObject()) { return(value.AsObject()); } if (value == Undefined.Instance) { throw new JavaScriptException(engine.TypeError); } if (value == Null.Instance) { throw new JavaScriptException(engine.TypeError); } if (value.IsBoolean()) { return(engine.Boolean.Construct(value.AsBoolean())); } if (value.IsNumber()) { return(engine.Number.Construct(value.AsNumber())); } if (value.IsString()) { return(engine.String.Construct(value.AsString())); } throw new JavaScriptException(engine.TypeError); }
public ObjectInstance GetOrCreate(JsValue key) { BlittableObjectProperty property = default; if (OwnValues?.TryGetValue(key, out property) == true && property != null) { return(property.Value.AsObject()); } property = GenerateProperty(key.AsString()); OwnValues ??= new Dictionary <JsValue, BlittableObjectProperty>(Blittable.Count); OwnValues[key] = property; Deletes?.Remove(key); return(property.Value.AsObject()); BlittableObjectProperty GenerateProperty(string propertyName) { var propertyIndex = Blittable.GetPropertyIndex(propertyName); var prop = new BlittableObjectProperty(this, propertyName); if (propertyIndex == -1) { prop.Value = new ObjectInstance(Engine); } return(prop); } }
public static object ConvertToNative(this JsValue self) { switch (self.Type) { case Types.None: case Types.Undefined: case Types.Null: return(null); case Types.Boolean: return(self.AsBoolean()); case Types.String: return(self.AsString()); case Types.Number: double value = self.AsNumber(); if (Math.Abs(value - (int)value) < Double.Epsilon) { return((int)value); } return(value); case Types.Object: throw new ArgumentException("Cannot convert object to a native value"); default: throw new ArgumentOutOfRangeException(nameof(self)); } }
internal JToken ConvertBack(JsValue value) { switch (value.Type) { case Jint.Runtime.Types.None: throw new NotSupportedException(); case Jint.Runtime.Types.Undefined: return(JValue.CreateUndefined()); case Jint.Runtime.Types.Null: return(JValue.CreateNull()); case Jint.Runtime.Types.Boolean: return(new JValue(value.AsBoolean())); case Jint.Runtime.Types.String: return(JValue.CreateString(value.AsString())); case Jint.Runtime.Types.Number: return(new JValue(value.AsNumber())); case Jint.Runtime.Types.Object: var ntsObjectInstance = value.AsObject() as NTSObjectInstance; if (ntsObjectInstance != null) { return(ntsObjectInstance.root); } return(new JObject(value.AsObject().Properties.Where(kvp => !kvp.Value.Enumerable.HasValue || kvp.Value.Enumerable.Value).Select(kvp => new JProperty(kvp.Key, ConvertBack(kvp.Value.Value ?? JsValue.Undefined))))); default: throw new NotSupportedException(); } }
public override PropertyDescriptor GetOwnProperty(JsValue property) { EnsurePropertiesInitialized(); var propertyName = property.AsString(); return(fieldProperties.GetOrAdd(propertyName, this, (k, c) => new ContentDataProperty(c, new ContentFieldObject(c, new ContentFieldData(), false)))); }
public override PropertyDescriptor GetOwnProperty(JsValue property) { EnsurePropertiesInitialized(); var propertyName = property.AsString(); return(valueProperties?.GetOrDefault(propertyName) ?? PropertyDescriptor.Undefined); }
public override bool Set(JsValue property, JsValue value, JsValue receiver) { var propertyName = property.AsString(); vars[propertyName] = value.ToObject(); return(base.Set(property, value, receiver)); }
public void Alert(JsValue title, JsValue message) { var config = new AlertConfig(); config.Title = title.AsString(); config.Message = message.AsString(); UserDialogs.Instance.Alert(config); }
public override bool Set(JsValue property, JsValue value, JsValue receiver) { EnsurePropertiesInitialized(); var propertyName = property.AsString(); fieldProperties.GetOrAdd(propertyName, this, (k, c) => new ContentDataProperty(c)).Value = value; return(true); }
private void PrepareOutput(out string?newState, out string?newSharedState, out EmittedEventEnvelope[]?emittedEvents) { emittedEvents = _emitted.Count > 0 ? _emitted.ToArray() : null; _emitted.Clear(); if (_definitionBuilder.IsBiState && _state.IsArray()) { var arr = _state.AsArray(); if (arr.TryGetValue(0, out var state)) { if (_state.IsString()) { newState = _state.AsString(); } else { newState = ConvertToStringHandlingNulls(_json, state); } } else { newState = ""; } if (arr.TryGetValue(1, out var sharedState)) { newSharedState = ConvertToStringHandlingNulls(_json, sharedState); } else { newSharedState = null; } } else if (_state.IsString()) { newState = _state.AsString(); newSharedState = null; } else { newState = ConvertToStringHandlingNulls(_json, _state); newSharedState = null; } }
public void Confirm(JsValue title, JsValue message, JsValue callback) { var config = new ConfirmConfig(); config.Title = title.AsString(); config.Message = message.AsString(); config.OnAction = (result) => callback.Invoke(result); Acr.UserDialogs.UserDialogs.Instance.Confirm(config); }
public override void RemoveOwnProperty(JsValue property) { var propertyName = property.AsString(); fieldsToDelete ??= new HashSet <string>(); fieldsToDelete.Add(propertyName); fieldProperties?.Remove(propertyName); MarkChanged(); }
public void SetUnderline(JsValue value) { if (value.IsString()) { Font.Underline = _underline.FromString(value.AsString(), FontUnderlineType.None); } else { Font.Underline = value.ConvertToBoolean().GetValueOrDefault() ? FontUnderlineType.Single : FontUnderlineType.None; } }
private static string GetValueString(JsValue jsValue, bool useLiterals) { string result; switch (jsValue.Type) { case Types.String: result = jsValue.AsString(); break; case Types.Undefined: result = useLiterals ? "undefined" : null; break; case Types.Null: result = useLiterals ? "null" : null; break; case Types.Boolean: result = jsValue.AsBoolean().ToString(); break; case Types.Number: result = jsValue.AsNumber().ToString(); break; case Types.Object: result = jsValue.ToObject().ToString(); break; case Types.None: result = string.Empty; break; default: result = jsValue.AsString(); break; } return(result); }
public string AsNativeString(JsValue jsValue) { if (jsValue.IsNull() || jsValue.IsUndefined()) { return(null); } if (jsValue.IsString()) { return(jsValue.AsString()); } return(jsValue.ToString()); }
public override PropertyDescriptor GetOwnProperty(JsValue property) { EnsurePropertiesInitialized(); var propertyName = property.AsString(); if (propertyName.Equals("toJSON", StringComparison.OrdinalIgnoreCase)) { return(PropertyDescriptor.Undefined); } return(fieldProperties.GetOrAdd(propertyName, this, (k, c) => new ContentDataProperty(c, new ContentFieldObject(c, new ContentFieldData(), false)))); }
public override PropertyDescriptor GetOwnProperty(JsValue property) { EnsurePropertiesInitialized(); var propertyName = property.AsString(); if (propertyName.Equals("toJSON", StringComparison.OrdinalIgnoreCase)) { return(PropertyDescriptor.Undefined); } return(valueProperties?.GetOrDefault(propertyName) ?? PropertyDescriptor.Undefined); }
public object ConvertFromJs(JsValue jsValue) { if (jsValue == _getEngine().Global) { return(_global); } if (jsValue.IsUndefined()) { return(null); } if (jsValue.IsObject()) { switch (jsValue.AsObject()) { case IObjectWrapper wrapper: return(wrapper.Target); case ClrPrototype proto: return(proto); case ObjectInstance objInst: //todo: instantiate object instead of distionary return(objInst.GetOwnProperties().ToDictionary(x => x.Key, x => ConvertFromJs(objInst.Get(x.Key)))); } return(jsValue); } if (jsValue.IsBoolean()) { return(jsValue.AsBoolean()); } if (jsValue.IsString()) { return(jsValue.AsString()); } if (jsValue.IsNumber()) { return(jsValue.AsNumber()); } return(null); }
internal JToken ConvertBack(JTokenType type, JsValue value) { switch (type) { case JTokenType.Array: if (value.IsArray()) { var array = value.AsArray(); return(new JArray(array.Properties.Where(k => ArrayInstance.IsArrayIndex(new JsValue(k.Key))).Select(kvp => ConvertBack(kvp.Value.Value ?? JsValue.Null)))); } break; case JTokenType.Boolean: if (value.IsBoolean()) { return(new JValue(value.AsBoolean())); } break; case JTokenType.Date: if (value.IsDate()) { return(new JValue(value.AsDate())); } break; case JTokenType.Float: if (value.IsNumber()) { return(new JValue((float)value.AsNumber())); } break; case JTokenType.Integer: if (value.IsNumber()) { return(new JValue((int)value.AsNumber())); } break; case JTokenType.String: if (value.IsString()) { return(JValue.CreateString(value.AsString())); } break; } return(ConvertBack(value)); }
private static string GetErrorMessage(JsValue error) { if (error.IsObject()) { var oi = error.AsObject(); var message = oi.Get("message").AsString(); return(message); } if (error.IsString()) { return(error.AsString()); } return(error.ToString()); }
public override bool DefineOwnProperty(JsValue property, PropertyDescriptor desc) { EnsurePropertiesInitialized(); var propertyName = property.AsString(); if (!fieldProperties.ContainsKey(propertyName)) { fieldProperties[propertyName] = new ContentDataProperty(this) { Value = desc.Value }; } return(true); }
public void ShouldBeAString() { var value = new JsValue("a"); Assert.Equal(false, value.IsBoolean()); Assert.Equal(false, value.IsArray()); Assert.Equal(false, value.IsDate()); Assert.Equal(false, value.IsNull()); Assert.Equal(false, value.IsNumber()); Assert.Equal(false, value.IsObject()); Assert.Equal(true, value.IsPrimitive()); Assert.Equal(false, value.IsRegExp()); Assert.Equal(true, value.IsString()); Assert.Equal("a", value.AsString()); Assert.Equal(false, value.IsUndefined()); }
public void ProcessMessage(object source, Message message) { string jsonScript = "var msg = " + JsonConvert.SerializeXmlNode(message.GetXmlDocument(), Formatting.Indented, true); Engine engine = new Engine(); engine.SetValue("message", message); engine.Execute(jsonScript); engine.Execute(Script); engine.Execute("var jsonMsg = JSON.stringify(msg);"); JsValue obj = engine.GetValue("jsonMsg"); string jsonString = obj.AsString(); var document = JsonConvert.DeserializeXNode(jsonString, "HL7Message"); message.SetValueFrom(document); }
public void Prompt(JsValue title, JsValue message, JsValue placeholder, JsValue callback) { var config = new PromptConfig(); config.Title = title.AsString(); config.Message = message.AsString(); config.Text = placeholder.AsString(); config.OnAction = (result) => { if (result.Ok) { callback.Invoke(result.Text); } }; UserDialogs.Instance.Prompt(config); }
private static string EnsureNonNullStringValue(JsValue parameter, string parameterName) { if (parameter != JsValue.Null && parameter.IsString() && (parameter.AsString() is { } value&& !string.IsNullOrWhiteSpace(value))) { return(value); } if (parameter == JsValue.Null || parameter == JsValue.Undefined || parameter.IsString()) { throw new ArgumentNullException(parameterName); } throw new ArgumentException("string expected", parameterName); }
/// <summary> /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2 /// </summary> /// <param name="o"></param> /// <returns></returns> public static bool ToBoolean(JsValue o) { if (o.IsObject()) { return(true); } if (o == Undefined.Instance || o == Null.Instance) { return(false); } if (o.IsBoolean()) { return(o.AsBoolean()); } if (o.IsNumber()) { var n = o.AsNumber(); if (n.Equals(0) || double.IsNaN(n)) { return(false); } else { return(true); } } if (o.IsString()) { var s = o.AsString(); if (String.IsNullOrEmpty(s)) { return(false); } else { return(true); } } return(true); }
/// <summary> /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2 /// </summary> /// <param name="o"></param> /// <returns></returns> public static bool ToBoolean(JsValue o) { if (o.IsObject()) { return true; } if (o == Undefined.Instance || o == Null.Instance) { return false; } if (o.IsBoolean()) { return o.AsBoolean(); } if (o.IsNumber()) { var n = o.AsNumber(); if (n.Equals(0) || double.IsNaN(n)) { return false; } else { return true; } } if (o.IsString()) { var s = o.AsString(); if (String.IsNullOrEmpty(s)) { return false; } else { return true; } } return true; }
public void ActionSheet(JsValue title, JsValue options, JsValue callback) { var config = new ActionSheetConfig(); config.Title = title.AsString(); List <ActionSheetOption> choices = new List <ActionSheetOption>(); foreach (var option in options.AsArray()) { var choice = new ActionSheetOption(option.AsString(), () => callback.Invoke(option.AsString())); choices.Add(choice); } config.Options = choices; Acr.UserDialogs.UserDialogs.Instance.ActionSheet(config); }
/// Implementation from ObjectInstance official specs as the one /// in ObjectInstance is optimized for the general case and wouldn't work /// for arrays public override void Put(string propertyName, JsValue value, bool throwOnError) { if (!CanPut(propertyName)) { if (throwOnError) { throw new JavaScriptException(Engine.TypeError); } return; } if (InternalArray != null) { int ind; if (int.TryParse(propertyName, out ind)) { object val; switch (value.Type) { case Types.Undefined: val = null; break; case Types.Null: val = null; break; case Types.Boolean: val = value.AsBoolean(); break; case Types.String: val = value.AsString(); break; case Types.Number: val = value.AsNumber(); break; case Types.Object: val = value; var ow = ((JsValue)val).AsObject() as ObjectWrapper; if (ow != null) { val = ow.Target; } break; default: throw new ArgumentOutOfRangeException(); } if (ind >= InternalArray.Count) { for (int i = InternalArray.Count; i <= ind; i++) { if (val != null) InternalArray.Add(GetDefault(val.GetType())); else InternalArray.Add(null); } } InternalArray[ind] = val; } } var ownDesc = GetOwnProperty(propertyName); if (ownDesc.IsDataDescriptor()) { var valueDesc = new PropertyDescriptor(value: value, writable: null, enumerable: null, configurable: null); DefineOwnProperty(propertyName, valueDesc, throwOnError); return; } // property is an accessor or inherited var desc = GetProperty(propertyName); if (desc.IsAccessorDescriptor()) { var setter = desc.Set.Value.TryCast<ICallable>(); setter.Call(new JsValue(this), new[] { value }); } else { var newDesc = new PropertyDescriptor(value, true, true, true); DefineOwnProperty(propertyName, newDesc, throwOnError); } }
/// <summary> /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.3 /// </summary> /// <param name="o"></param> /// <returns></returns> public static double ToNumber(JsValue o) { // check number first as this is what is usually expected if (o.IsNumber()) { return o.AsNumber(); } if (o.IsObject()) { var p = o.AsObject() as IPrimitiveInstance; if (p != null) { o = p.PrimitiveValue; } } if (o == Undefined.Instance) { return double.NaN; } if (o == Null.Instance) { return 0; } if (o.IsBoolean()) { return o.AsBoolean() ? 1 : 0; } if (o.IsString()) { var s = o.AsString().Trim(); if (String.IsNullOrEmpty(s)) { return 0; } if ("+Infinity".Equals(s) || "Infinity".Equals(s)) { return double.PositiveInfinity; } if ("-Infinity".Equals(s)) { return double.NegativeInfinity; } // todo: use a common implementation with JavascriptParser try { if (!s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { var start = s[0]; if (start != '+' && start != '-' && start != '.' && !char.IsDigit(start)) { return double.NaN; } double n = Double.Parse(s, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowExponent, CultureInfo.InvariantCulture); if (s.StartsWith("-") && n.Equals(0)) { return -0.0; } return n; } int i = int.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); return i; } catch (OverflowException) { return s.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity; } catch { return double.NaN; } } return ToNumber(ToPrimitive(o, Types.Number)); }
/// <summary> /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.8 /// </summary> /// <param name="o"></param> /// <returns></returns> public static string ToString(JsValue o) { if (o.IsObject()) { var p = o.AsObject() as IPrimitiveInstance; if (p != null) { o = p.PrimitiveValue; } } if (o.IsString()) { return o.AsString(); } if (o == Undefined.Instance) { return Undefined.Text; } if (o == Null.Instance) { return Null.Text; } if (o.IsBoolean()) { return o.AsBoolean() ? "true" : "false"; } if (o.IsNumber()) { return NumberPrototype.ToNumberString(o.AsNumber()); } return ToString(ToPrimitive(o, Types.String)); }
public JsValue Serialize(JsValue value, JsValue replacer, JsValue space) { _stack = new Stack<object>(); // for JSON.stringify(), any function passed as the first argument will return undefined // if the replacer is not defined. The function is not called either. if (value.Is<ICallable>() && replacer == Undefined.Instance) { return Undefined.Instance; } if (replacer.IsObject()) { if (replacer.Is<ICallable>()) { _replacerFunction = replacer; } else { var replacerObj = replacer.AsObject(); if (replacerObj.Class == "Array") { _propertyList = new List<string>(); } foreach (var property in replacerObj.GetOwnProperties().Select(x => x.Value)) { JsValue v = _engine.GetValue(property); string item = null; if (v.IsString()) { item = v.AsString(); } else if (v.IsNumber()) { item = TypeConverter.ToString(v); } else if (v.IsObject()) { var propertyObj = v.AsObject(); if (propertyObj.Class == "String" || propertyObj.Class == "Number") { item = TypeConverter.ToString(v); } } if (item != null && !_propertyList.Contains(item)) { _propertyList.Add(item); } } } } if (space.IsObject()) { var spaceObj = space.AsObject(); if (spaceObj.Class == "Number") { space = TypeConverter.ToNumber(spaceObj); } else if (spaceObj.Class == "String") { space = TypeConverter.ToString(spaceObj); } } // defining the gap if (space.IsNumber()) { if (space.AsNumber() > 0) { _gap = new System.String(' ', (int)System.Math.Min(10, space.AsNumber())); } else { _gap = string.Empty; } } else if (space.IsString()) { var stringSpace = space.AsString(); _gap = stringSpace.Length <= 10 ? stringSpace : stringSpace.Substring(0, 10); } else { _gap = string.Empty; } var wrapper = _engine.Object.Construct(Arguments.Empty); wrapper.DefineOwnProperty("", new PropertyDescriptor(value, true, true, true), false); return Str("", wrapper); }
public static ObjectInstance ToObject(Engine engine, JsValue value) { if (value.IsObject()) { return value.AsObject(); } if (value == Undefined.Instance) { throw new JavaScriptException(engine.TypeError); } if (value == Null.Instance) { throw new JavaScriptException(engine.TypeError); } if (value.IsBoolean()) { return engine.Boolean.Construct(value.AsBoolean()); } if (value.IsNumber()) { return engine.Number.Construct(value.AsNumber()); } if (value.IsString()) { return engine.String.Construct(value.AsString()); } throw new JavaScriptException(engine.TypeError); }