Exemplo n.º 1
0
        public static ArrayInstance AsArray(this JsValue value)
        {
            if (!value.IsArray())
            {
                ExceptionHelper.ThrowArgumentException("The value is not an array");
            }

            return(value as ArrayInstance);
        }
Exemplo n.º 2
0
        private async Task GetReferencesAsync(ScriptExecutionContext context, DomainId appId, ClaimsPrincipal user, JsValue references, Action <JsValue> callback)
        {
            Guard.NotNull(callback, nameof(callback));

            var ids = new List <DomainId>();

            if (references.IsString())
            {
                ids.Add(DomainId.Create(references.ToString()));
            }
            else if (references.IsArray())
            {
                foreach (var value in references.AsArray())
                {
                    if (value.IsString())
                    {
                        ids.Add(DomainId.Create(value.ToString()));
                    }
                }
            }

            if (ids.Count == 0)
            {
                var emptyContents = Array.Empty <IEnrichedContentEntity>();

                callback(JsValue.FromObject(context.Engine, emptyContents));
                return;
            }

            context.MarkAsync();

            try
            {
                var app = await GetAppAsync(appId);

                var requestContext =
                    new Context(user, app).Clone(b => b
                                                 .WithoutContentEnrichment()
                                                 .WithUnpublished()
                                                 .WithoutTotal());

                var contentQuery = serviceProvider.GetRequiredService <IContentQueryService>();

                var contents = await contentQuery.QueryAsync(requestContext, Q.Empty.WithIds(ids), context.CancellationToken);

                // Reset the time contraints and other constraints so that our awaiting does not count as script time.
                context.Engine.ResetConstraints();

                callback(JsValue.FromObject(context.Engine, contents.ToArray()));
            }
            catch (Exception ex)
            {
                context.Fail(ex);
            }
        }
        public virtual bool TryPropertyReference(Engine engine, Reference reference, ref JsValue value)
        {
            if (reference.GetReferencedName() == "reduce" &&
                value.IsArray() && value.AsArray().GetLength() == 0)
            {
                value = Null.Instance;
                return(true);
            }

            return(value.IsNull() || value.IsUndefined());
        }
Exemplo n.º 4
0
        public static RectOffset FromJsValue(JsValue obj)
        {
            if (obj == null || obj.IsNull() || obj.IsUndefined())
            {
                return(null);
            }

            if (obj.IsNumber())
            {
                var num = (int)obj.AsNumber();
                return(new RectOffset(num, num, num, num));
            }

            if (obj.IsArray())
            {
                var len = obj.AsArray().Length;

                var v0 = obj.AsArray()[0];
                var v1 = obj.AsArray()[1];
                var v2 = obj.AsArray()[2];
                var v3 = obj.AsArray()[3];

                var top    = v0.IsNumber() ? (int)v0.AsNumber() : 0;
                var right  = v1.IsNumber() ? (int)v1.AsNumber() : (len < 2 ? top : 0);
                var bottom = v2.IsNumber() ? (int)v2.AsNumber() : top;
                var left   = v3.IsNumber() ? (int)v3.AsNumber() : right;
                return(new RectOffset(left, right, top, bottom));
            }

            if (obj.IsObject())
            {
                var ob   = obj.AsObject();
                var vert = ob.Get("vertical");
                var hor  = ob.Get("horizontal");

                var v0 = ob.Get("top");
                var v1 = ob.Get("right");
                var v2 = ob.Get("bottom");
                var v3 = ob.Get("left");

                var val1 = vert.IsNumber() ? (int)vert.AsNumber() : 0;
                var val2 = hor.IsNumber() ? (int)hor.AsNumber() : 0;

                var top    = v0.IsNumber() ? (int)v0.AsNumber() : val1;
                var right  = v1.IsNumber() ? (int)v1.AsNumber() : val2;
                var bottom = v2.IsNumber() ? (int)v2.AsNumber() : val1;
                var left   = v3.IsNumber() ? (int)v3.AsNumber() : val2;

                return(new RectOffset(left, right, top, bottom));
            }

            return(null);
        }
Exemplo n.º 5
0
        private async Task GetReferencesAsync(ExecutionContext context, DomainId appId, ClaimsPrincipal user, JsValue references, Action <JsValue> callback)
        {
            Guard.NotNull(callback, nameof(callback));

            var ids = new List <DomainId>();

            if (references.IsString())
            {
                ids.Add(DomainId.Create(references.ToString()));
            }
            else if (references.IsArray())
            {
                foreach (var value in references.AsArray())
                {
                    if (value.IsString())
                    {
                        ids.Add(DomainId.Create(value.ToString()));
                    }
                }
            }

            if (ids.Count == 0)
            {
                var emptyAssets = Array.Empty <IEnrichedAssetEntity>();

                callback(JsValue.FromObject(context.Engine, emptyAssets));
                return;
            }

            context.MarkAsync();

            try
            {
                var app = await GetAppAsync(appId);

                var requestContext =
                    new Context(user, app).Clone(b => b
                                                 .WithoutTotal());

                var assetQuery = serviceProvider.GetRequiredService <IAssetQueryService>();

                var assets = await assetQuery.QueryAsync(requestContext, null, Q.Empty.WithIds(ids), context.CancellationToken);

                callback(JsValue.FromObject(context.Engine, assets.ToArray()));
            }
            catch (Exception ex)
            {
                context.Fail(ex);
            }
        }
Exemplo n.º 6
0
 private string GetDebugValue(JsValue obj, bool recursive)
 {
     if (obj.IsString())
     {
         var debugValue = obj.ToString();
         return(recursive ? '"' + debugValue + '"' : debugValue);
     }
     if (obj.IsArray())
     {
         var sb      = new StringBuilder("[");
         var array   = obj.AsArray();
         var jsValue = (int)array.Get("length").AsNumber();
         for (var i = 0; i < jsValue; i++)
         {
             if (i != 0)
             {
                 sb.Append(",");
             }
             sb.Append(GetDebugValue(array.Get(i.ToString()), true));
         }
         sb.Append("]");
         return(sb.ToString());
     }
     if (obj.IsObject())
     {
         var result = new ScriptRunnerResult(this, obj);
         using (var jsonObj = result.TranslateToObject(_jsonCtx))
         {
             return(jsonObj.ToString());
         }
     }
     if (obj.IsBoolean())
     {
         return(obj.AsBoolean().ToString());
     }
     if (obj.IsNumber())
     {
         return(obj.AsNumber().ToString(CultureInfo.InvariantCulture));
     }
     if (obj.IsNull())
     {
         return("null");
     }
     if (obj.IsUndefined())
     {
         return("undefined");
     }
     return(obj.ToString());
 }
Exemplo n.º 7
0
        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));
        }
Exemplo n.º 8
0
        public static Vector4?FromJsValue(JsValue obj)
        {
            if (obj == null || obj.IsNull() || obj.IsUndefined())
            {
                return(null);
            }

            if (obj.IsNumber())
            {
                var num = (float)obj.AsNumber();
                return(new Vector4(num, num, num, num));
            }

            if (obj.IsArray())
            {
                var len = obj.AsArray().Length;

                var v0 = obj.AsArray()[0];
                var v1 = obj.AsArray()[1];
                var v2 = obj.AsArray()[2];
                var v3 = obj.AsArray()[3];

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                var z = v2.IsNumber() ? (float)v2.AsNumber() : 0;
                var w = v3.IsNumber() ? (float)v3.AsNumber() : 0;
                return(new Vector4(x, y, z, w));
            }

            if (obj.IsObject())
            {
                var ob = obj.AsObject();

                var v0 = ob.Get("x");
                var v1 = ob.Get("y");
                var v2 = ob.Get("z");
                var v3 = ob.Get("w");

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                var z = v2.IsNumber() ? (float)v2.AsNumber() : 0;
                var w = v3.IsNumber() ? (float)v3.AsNumber() : 0;

                return(new Vector4(x, y, z, w));
            }

            return(null);
        }
Exemplo n.º 9
0
        public void ShouldBeANumber()
        {
            var value = new JsValue(2);

            Assert.Equal(false, value.IsBoolean());
            Assert.Equal(false, value.IsArray());
            Assert.Equal(false, value.IsDate());
            Assert.Equal(false, value.IsNull());
            Assert.Equal(true, value.IsNumber());
            Assert.Equal(2, value.AsNumber());
            Assert.Equal(false, value.IsObject());
            Assert.Equal(true, value.IsPrimitive());
            Assert.Equal(false, value.IsRegExp());
            Assert.Equal(false, value.IsString());
            Assert.Equal(false, value.IsUndefined());
        }
Exemplo n.º 10
0
        private static object NullIfEmptyEnumerable(JsValue item)
        {
            if (item.IsArray() == false)
            {
                return(item);
            }

            var itemAsArray = item.AsArray();

            if (itemAsArray.Length == 0)
            {
                return(null);
            }

            return(Yield(itemAsArray));
        }
Exemplo n.º 11
0
        private string Convert(JsValue jsValue)
        {
            if (jsValue.IsArray())
            {
                var arr = jsValue.AsArray();
                return(Converter.Json.ToJson(arr));
            }

            if (jsValue.IsObject())
            {
                return(Converter.Json.ToJson(jsValue.ToObject()));
            }


            return(Converter.Json.ToJson(jsValue));
        }
        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;
            }
        }
Exemplo n.º 13
0
        private static IEnumerable <JsValue> EnumerateValues(JsValue jv)
        {
            if (jv.IsArray())
            {
                var arr = jv.AsArray();
                foreach (var(key, val) in arr.GetOwnProperties())
                {
                    if (key == "length")
                    {
                        continue;
                    }

                    yield return(val.Value);
                }
            }
            else
            {
                yield return(jv);
            }
        }
Exemplo n.º 14
0
        public static List <DomainId> ToIds(this JsValue?value)
        {
            var ids = new List <DomainId>();

            if (value?.IsString() == true)
            {
                ids.Add(DomainId.Create(value.ToString()));
            }
            else if (value?.IsArray() == true)
            {
                foreach (var item in value.AsArray())
                {
                    if (item.IsString())
                    {
                        ids.Add(DomainId.Create(item.ToString()));
                    }
                }
            }

            return(ids);
        }
Exemplo n.º 15
0
        public static Vector2?FromJsValue(JsValue obj)
        {
            if (obj == null || obj.IsNull() || obj.IsUndefined())
            {
                return(null);
            }

            if (obj.IsNumber())
            {
                var num = (float)obj.AsNumber();
                return(new Vector2(num, num));
            }

            if (obj.IsArray())
            {
                var v0 = obj.AsArray()[0];
                var v1 = obj.AsArray()[1];

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                return(new Vector2(x, y));
            }

            if (obj.IsObject())
            {
                var ob = obj.AsObject();

                var v0 = ob.Get("x");
                var v1 = ob.Get("y");

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;

                return(new Vector2(x, y));
            }

            return(null);
        }
        public virtual bool TryPropertyReference(Engine engine, Reference reference, ref JsValue value)
        {
            if (reference.GetReferencedName() == Constants.Documents.Metadata.Key &&
                reference.GetBase() is BlittableObjectInstance boi)
            {
                value = engine.Invoke(ScriptRunner.SingleRun.GetMetadataMethod, boi);
                return(true);
            }
            if (reference.GetReferencedName() == "reduce" &&
                value.IsArray() && value.AsArray().Length == 0)
            {
                value = Null.Instance;
                return(true);
            }

            if (value is DynamicJsNull)
            {
                value = DynamicJsNull.ImplicitNull;
                return(true);
            }

            return(value.IsNull() || value.IsUndefined());
        }
Exemplo n.º 17
0
        public static IJsonValue Map(JsValue value)
        {
            if (value == null || value.IsNull() || value.IsUndefined())
            {
                return(JsonValue.Null);
            }

            if (value.IsString())
            {
                return(JsonValue.Create(value.AsString()));
            }

            if (value.IsBoolean())
            {
                return(JsonValue.Create(value.AsBoolean()));
            }

            if (value.IsNumber())
            {
                return(JsonValue.Create(value.AsNumber()));
            }

            if (value.IsDate())
            {
                return(JsonValue.Create(value.AsDate().ToString()));
            }

            if (value.IsRegExp())
            {
                return(JsonValue.Create(value.AsRegExp().Value?.ToString()));
            }

            if (value.IsArray())
            {
                var arr = value.AsArray();

                var result = JsonValue.Array();

                for (var i = 0; i < arr.GetLength(); i++)
                {
                    result.Add(Map(arr.Get(i.ToString())));
                }

                return(result);
            }

            if (value.IsObject())
            {
                var obj = value.AsObject();

                var result = JsonValue.Object();

                foreach (var kvp in obj.GetOwnProperties())
                {
                    result[kvp.Key] = Map(kvp.Value.Value);
                }

                return(result);
            }

            throw new ArgumentException("Invalid json type.", nameof(value));
        }
Exemplo n.º 18
0
        public static Color?FromJsValue(JsValue obj)
        {
            if (obj == null || obj.IsNull() || obj.IsUndefined())
            {
                return(null);
            }

            var nativeObject = obj.ToObject();

            if (nativeObject is Color c)
            {
                return(c);
            }

            if (obj.IsString())
            {
                var s = obj.ToString();
                ColorUtility.TryParseHtmlString(s, out var color);
                return(color);
            }

            if (obj.IsNumber())
            {
                var num = (float)obj.AsNumber();
                return(new Color(num, num, num, 1));
            }

            if (obj.IsArray())
            {
                var len = obj.AsArray().Length;

                if (len == 0)
                {
                    return(Color.clear);
                }

                var v0 = obj.AsArray()[0];
                var v1 = obj.AsArray()[1];
                var v2 = obj.AsArray()[2];
                var v3 = obj.AsArray()[3];

                if (v0 != null && !v0.IsNumber() && !v0.IsNull() && !v0.IsUndefined())
                {
                    var start = FromJsValue(v0) ?? Color.clear;
                    var end   = FromJsValue(v2);
                    if (end.HasValue)
                    {
                        var t = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                        return(Color.LerpUnclamped(start, end.Value, t));
                    }
                    else
                    {
                        var t = v1.IsNumber() ? (float)v1.AsNumber() : 1;
                        start.a = t;
                        return(start);
                    }
                }

                var r = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var g = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                var b = v2.IsNumber() ? (float)v2.AsNumber() : 0;
                var a = v3.IsNumber() ? (float)v3.AsNumber() : 1;

                return(new Color(r, g, b, a));
            }

            if (obj.IsObject())
            {
                var ob = obj.AsObject();

                var v0 = ob.Get("r");
                var v1 = ob.Get("g");
                var v2 = ob.Get("b");
                var v3 = ob.Get("a");

                var r = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var g = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                var b = v2.IsNumber() ? (float)v2.AsNumber() : 0;
                var a = v3.IsNumber() ? (float)v3.AsNumber() : 1;

                return(new Color(r, g, b, a));
            }

            return(null);
        }
 static bool IsObject(JsValue value)
 {
     return(value.IsObject() && value.IsArray() == false);
 }
Exemplo n.º 20
0
        private RavenJToken ToRavenJToken(JsValue v, string propertyKey, bool recursiveCall)
        {
            if (v.IsBoolean())
            {
                return(new RavenJValue(v.AsBoolean()));
            }
            if (v.IsString())
            {
                const string RavenDataByteArrayToBase64 = "raven-data:byte[];base64,";
                var          valueAsObject = v.ToObject();
                var          value         = valueAsObject != null?valueAsObject.ToString() : null;

                if (value != null && value.StartsWith(RavenDataByteArrayToBase64))
                {
                    value = value.Remove(0, RavenDataByteArrayToBase64.Length);
                    var byteArray = Convert.FromBase64String(value);
                    return(new RavenJValue(byteArray));
                }
                return(new RavenJValue(value));
            }
            if (v.IsNumber())
            {
                var num = v.AsNumber();

                KeyValuePair <RavenJValue, JsValue> property;
                if (propertiesByValue.TryGetValue(propertyKey, out property))
                {
                    var originalValue = property.Key;
                    if (originalValue.Type == JTokenType.Float ||
                        originalValue.Type == JTokenType.Integer)
                    {
                        // If the current value is exactly as the original value, we can return the original value before we made the JS conversion,
                        // which will convert a Int64 to jsFloat.
                        var originalJsValue = property.Value;
                        if (originalJsValue.IsNumber() && Math.Abs(num - originalJsValue.AsNumber()) < double.Epsilon)
                        {
                            return(originalValue);
                        }

                        if (originalValue.Type == JTokenType.Integer)
                        {
                            return(new RavenJValue((long)num));
                        }
                        return(new RavenJValue(num));//float
                    }
                }

                // If we don't have the type, assume that if the number ending with ".0" it actually an integer.
                var integer = Math.Truncate(num);
                if (Math.Abs(num - integer) < double.Epsilon)
                {
                    return(new RavenJValue((long)integer));
                }
                return(new RavenJValue(num));
            }
            if (v.IsNull())
            {
                return(RavenJValue.Null);
            }
            if (v.IsUndefined())
            {
                return(RavenJValue.Null);
            }
            if (v.IsArray())
            {
                var jsArray = v.AsArray();
                var rja     = new RavenJArray();

                foreach (var property in jsArray.Properties)
                {
                    if (property.Key == "length")
                    {
                        continue;
                    }

                    var jsInstance = property.Value.Value;
                    if (!jsInstance.HasValue)
                    {
                        continue;
                    }

                    var ravenJToken = ToRavenJToken(jsInstance.Value, propertyKey + "[" + property.Key + "]", recursiveCall);
                    if (ravenJToken == null)
                    {
                        continue;
                    }

                    rja.Add(ravenJToken);
                }

                return(rja);
            }
            if (v.IsObject())
            {
                return(ToRavenJObject(v, propertyKey, recursiveCall));
            }
            if (v.IsRegExp())
            {
                return(null);
            }

            throw new NotSupportedException(v.Type.ToString());
        }
Exemplo n.º 21
0
        private object ToBlittableValue(JsValue v, string propertyKey, bool recursiveCall)
        {
            if (v.IsBoolean())
            {
                return(v.AsBoolean());
            }

            if (v.IsString())
            {
                const string RavenDataByteArrayToBase64 = "raven-data:byte[];base64,";
                var          valueAsObject = v.ToObject();
                var          value         = valueAsObject?.ToString();
                if (value != null && value.StartsWith(RavenDataByteArrayToBase64))
                {
                    value = value.Remove(0, RavenDataByteArrayToBase64.Length);
                    var byteArray = Convert.FromBase64String(value);
                    return(Encoding.UTF8.GetString(byteArray));
                }
                return(value);
            }

            if (v.IsNumber())
            {
                var num = v.AsNumber();

                KeyValuePair <object, JsValue> property;
                if (_propertiesByValue.TryGetValue(propertyKey, out property))
                {
                    var originalValue = property.Key;
                    if (originalValue is float || originalValue is int)
                    {
                        // If the current value is exactly as the original value, we can return the original value before we made the JS conversion,
                        // which will convert a Int64 to jsFloat.
                        var jsValue = property.Value;
                        if (jsValue.IsNumber() && Math.Abs(num - jsValue.AsNumber()) < double.Epsilon)
                        {
                            return(originalValue);
                        }

                        //We might have change the type of num from Integer to long in the script by design
                        //Making sure the number isn't a real float before returning it as integer
                        if (originalValue is int && (Math.Abs(num - Math.Floor(num)) <= double.Epsilon || Math.Abs(num - Math.Ceiling(num)) <= double.Epsilon))
                        {
                            return((long)num);
                        }
                        return(num); //float
                    }
                }

                // If we don't have the type, assume that if the number ending with ".0" it actually an integer.
                var integer = Math.Truncate(num);
                if (Math.Abs(num - integer) < double.Epsilon)
                {
                    return((long)integer);
                }
                return(num);
            }
            if (v.IsNull() || v.IsUndefined())
            {
                return(null);
            }
            if (v.IsArray())
            {
                var jsArray = v.AsArray();
                var array   = new DynamicJsonArray();

                foreach (var property in jsArray.GetOwnProperties())
                {
                    if (InheritedProperties.Contains(property.Key))
                    {
                        continue;
                    }

                    var jsInstance = property.Value.Value;
                    if (!jsInstance.HasValue)
                    {
                        continue;
                    }

                    var ravenJToken = ToBlittableValue(jsInstance.Value, propertyKey + "[" + property.Key + "]", recursiveCall);
                    if (ravenJToken == null)
                    {
                        continue;
                    }

                    array.Add(ravenJToken);
                }

                return(array);
            }
            if (v.IsDate())
            {
                return(v.AsDate().ToDateTime());
            }
            if (v.IsObject())
            {
                return(ToBlittable(v.AsObject(), propertyKey, recursiveCall));
            }
            if (v.IsRegExp())
            {
                return(null);
            }

            throw new NotSupportedException(v.Type.ToString());
        }
Exemplo n.º 22
0
        private LocalVariable GetLocalVariableJS(string key, JsValue value)
        {
            var result = new LocalVariable()
            {
                Name = key, TypeName = value.Type.ToString()
            };

            if (value.IsArray())
            {
                var trueValue = value.AsArray();
                if (trueValue.GetLength() > 0)
                {
                    var props = trueValue.GetOwnProperties();
                    foreach (var item in props)
                    {
                        var ch = GetLocalVariableJS(item.Key, item.Value.Value);
                        result.Children.Add(ch);
                    }
                }
                //result.Value=trueValue.
            }
            else if (value.IsBoolean())
            {
                var trueValue = value.AsBoolean();
                result.Value = trueValue.ToString();
            }
            else if (value.IsDate())
            {
                var trueValue = value.AsDate();
                result.Value = trueValue.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss");
            }
            else if (value.IsNumber())
            {
                var trueValue = value.AsNumber();
                result.Value = trueValue.ToString();
            }
            else if (value.IsString())
            {
                var trueValue = value.AsString();
                result.Value = trueValue;
            }
            else if (value.IsObject())
            {
                var trueValue = value.AsObject();
                //判断对象是否原生JS
                if (trueValue.GetType().Name == "ObjectInstance")
                {
                    var props = trueValue.GetOwnProperties();
                    foreach (var item in props)
                    {
                        var ch = GetLocalVariableJS(item.Key, item.Value.Value);
                        result.Children.Add(ch);
                    }
                }
                else
                {
                    var csharpValue = value.ToObject();
                    if (csharpValue != null)
                    {
                        //只处理DapperRow
                        result = GetLocalVariableCSharp(key, csharpValue);
                        //csharpValue.
                    }
                }
            }
            return(result);
        }
Exemplo n.º 23
0
        private static object GetValue(JsValue jsValue)
        {
            if (jsValue.IsNull())
            {
                return(null);
            }
            if (jsValue.IsString())
            {
                return(jsValue.AsString());
            }
            if (jsValue.IsBoolean())
            {
                return(jsValue.AsBoolean());
            }
            if (jsValue.IsNumber())
            {
                return(jsValue.AsNumber());
            }
            if (jsValue.IsDate())
            {
                return(jsValue.AsDate());
            }
            if (jsValue is ObjectWrapper ow)
            {
                var target = ow.Target;
                switch (target)
                {
                case LazyStringValue lsv:
                    return(lsv);

                case LazyCompressedStringValue lcsv:
                    return(lcsv);

                case LazyNumberValue lnv:
                    return(lnv);    //should be already blittable supported type.
                }
                ThrowInvalidObject(jsValue);
            }
            else if (jsValue.IsArray())
            {
                var arr   = jsValue.AsArray();
                var array = new object[arr.GetLength()];
                var i     = 0;
                foreach ((var key, var val) in arr.GetOwnProperties())
                {
                    if (key == "length")
                    {
                        continue;
                    }

                    array[i++] = GetValue(val.Value);
                }

                return(array);
            }
            else if (jsValue.IsObject())
            {
                return(jsValue.AsObject());
            }
            if (jsValue.IsUndefined())
            {
                return(null);
            }

            ThrowInvalidObject(jsValue);
            return(null);
        }
Exemplo n.º 24
0
 /// <summary>
 /// Array for value
 /// </summary>
 /// <param name="value">Value</param>
 /// <returns>List of objects</returns>
 public static List <object> ArrayForValue(JsValue value)
 {
     return(value.IsArray() ? value.TryCast <List <object> >() : null);
 }
Exemplo n.º 25
0
        public static JToken Map(JsValue value)
        {
            if (value == null || value.IsNull())
            {
                return(JValue.CreateNull());
            }

            if (value.IsUndefined())
            {
                return(JValue.CreateUndefined());
            }

            if (value.IsString())
            {
                return(new JValue(value.AsString()));
            }

            if (value.IsBoolean())
            {
                return(new JValue(value.AsBoolean()));
            }

            if (value.IsNumber())
            {
                return(new JValue(value.AsNumber()));
            }

            if (value.IsDate())
            {
                return(new JValue(value.AsDate().ToDateTime()));
            }

            if (value.IsRegExp())
            {
                return(JValue.CreateString(value.AsRegExp().Value?.ToString()));
            }

            if (value.IsArray())
            {
                var arr = value.AsArray();

                var target = new JArray();

                for (var i = 0; i < arr.GetLength(); i++)
                {
                    target.Add(Map(arr.Get(i.ToString())));
                }

                return(target);
            }

            if (value.IsObject())
            {
                var obj = value.AsObject();

                var target = new JObject();

                foreach (var kvp in obj.GetOwnProperties())
                {
                    target[kvp.Key] = Map(kvp.Value.Value);
                }

                return(target);
            }

            throw new ArgumentException("Invalid json type.", nameof(value));
        }
Exemplo n.º 26
0
        public static JsValue Show(JavaScriptUi ui, string title, JsValue fields, JsValue validate)
        {
            if (ui == null)
            {
                throw new ArgumentNullException(nameof(ui));
            }

            using (var form = new UiForm())
            {
                if (String.IsNullOrEmpty(title))
                {
                    form.Text = ui.Owner.Text;
                }
                else
                {
                    form.Text = title;
                }

                form.Icon = ui.Owner.Icon;

                if (!fields.IsArray())
                {
                    throw new JavaScriptException("fields must be an array");
                }

                var controls = new List <Field>();

                fields.AsArray().ForEach((index, value) =>
                {
                    var container = form._container;

                    while (container.RowStyles.Count <= index)
                    {
                        container.RowCount++;
                        container.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                    }

                    var field          = value.AsObject();
                    string name        = field.Get("name").ConvertToString();
                    string label       = field.Get("label").ConvertToString();
                    var type           = ParseType(field.Get("type").ConvertToString());
                    ArrayInstance list = null;
                    if (field.HasOwnProperty("list"))
                    {
                        list = field.Get("list").AsArray();
                    }

                    Field control;
                    switch (type)
                    {
                    case FieldType.Text:
                        control = new TextField(name, label);
                        break;

                    case FieldType.CheckBox:
                        control = new CheckBoxField(name, label);
                        break;

                    case FieldType.Numeric:
                        control = new NumericField(name, label);
                        break;

                    case FieldType.Date:
                        control = new DateField(name, label);
                        break;

                    case FieldType.DateTime:
                        control = new DateTimeField(name, label);
                        break;

                    case FieldType.ComboBox:
                        control = new ComboBoxField(name, label, list);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    controls.Add(control);

                    if (field.HasOwnProperty("value"))
                    {
                        control.SetValue(field.Get("value"));
                    }

                    if (control.ShowLabel)
                    {
                        var labelControl = new Label
                        {
                            AutoSize  = true,
                            Text      = label,
                            Dock      = DockStyle.Fill,
                            TextAlign = ContentAlignment.MiddleLeft
                        };

                        container.SetRow(labelControl, index);
                        container.Controls.Add(labelControl);
                    }

                    control.Control.Dock     = DockStyle.Fill;
                    control.Control.AutoSize = true;
                    container.SetRow(control.Control, index);
                    container.SetColumn(control.Control, 1);
                    container.Controls.Add(control.Control);
                });

                form._acceptButton.Click += (s, e) =>
                {
                    try
                    {
                        if (validate.IsObject())
                        {
                            var values = BuildValues(ui.Engine, controls);
                            var result = validate.Invoke(values);
                            if (!result.ConvertToBoolean().GetValueOrDefault())
                            {
                                return;
                            }
                        }
                        form.DialogResult = DialogResult.OK;
                    }
                    catch (JavaScriptException exception)
                    {
                        JintDebugger.ExceptionForm.Show(form, exception);
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(
                            form,
                            new StringBuilder()
                            .AppendLine("An exception occurred while executing the script:")
                            .AppendLine()
                            .Append(exception.Message).Append(" (").Append(exception.GetType().FullName).AppendLine(")")
                            .AppendLine()
                            .AppendLine(exception.StackTrace)
                            .ToString(),
                            "Error",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error
                            );
                    }
                };

                var owner = ui.Owner;

                using (ui.PushOwner(form))
                {
                    if (form.ShowDialog(owner) == DialogResult.OK)
                    {
                        return(BuildValues(ui.Engine, controls));
                    }
                }
            }

            return(JsValue.Null);
        }