Пример #1
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));
        }
Пример #2
0
        public double ProcessEvent(string evtJson)
        {
            // Should we accumulate this metric for the current period, or should
            // we reset the accumulator for the new period.

            var currentPeriod = _period.StandardizeDate(DateTime.UtcNow);

            if (currentPeriod != _currentPeriod)
            {
                if (_currentPeriod != DateTime.MinValue)
                {
                    // Get the terminated value for this period
                    JsValue terminationJsValue = _context.ExecuteFunction("terminate");
                    var     terminationValue   = terminationJsValue.AsNumber();
                    // Store it in the database for this period / TimePeriod
                    StoreResultValue(_currentPeriod, terminationValue);

                    // Reset the current value
                    _context.ExecuteFunction("reset");
                }
                _currentPeriod = currentPeriod;
            }

            JsValue v     = _context.ExecuteFunction("accumulate", new string[] { evtJson });
            var     value = v.AsNumber();


            // Update the "current" context we have for this value, so if the process
            // restarts, it can restore its state.
            StoreResultContext();

            return(value);
        }
Пример #3
0
        internal static ObjectInstance ToBooleanOrObject(this JsValue x, out bool boolVal)
        {
            if (x.IsObject())
            {
                boolVal = false;
                return(x.AsObject());
            }

            switch (x.Type)
            {
            case Types.Boolean:
                boolVal = x.AsBoolean();
                break;

            case Types.Number:
                boolVal = x.AsNumber() != 0;
                break;

            default:
                boolVal = !x.IsNull() && !x.IsUndefined();
                break;
            }

            return(null);
        }
Пример #4
0
        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();
            }
        }
Пример #5
0
        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());
        }
Пример #6
0
        public static JsValue PostDecrement(ref JsValue val)
        {
            var prev = val.AsNumber();

            val = new JsNumber(prev.Value - 1);
            return(prev);
        }
Пример #7
0
        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);
        }
Пример #8
0
        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));
            }
        }
 public int AsNativeInt(JsValue value)
 {
     if (value.IsNull() || value.IsUndefined())
     {
         return(0);
     }
     return((int)Math.Round(value.AsNumber()));
 }
Пример #10
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);
        }
Пример #11
0
        public static object GetItem(this Jint.Native.Array.ArrayInstance a, int index)
        {
            JsValue l = a.Get(index.ToString());

            if (l.IsNull())
            {
                return(null);
            }
            if (l.IsNumber())
            {
                return(l.AsNumber());
            }
            if (l.IsBoolean())
            {
                return(l.AsBoolean());
            }
            if (l.IsString())
            {
                return(l.AsString());
            }
            if (l.IsNumber())
            {
                return(l.AsNumber());
            }
            if (l.IsUndefined())
            {
                return("undefined");
            }
            if (l.IsObject())
            {
                return(l.AsObject());
            }
            if (l.IsRegExp())
            {
                return(l.AsObject());
            }

            throw new ArgumentException(string.Format("Cannot deal with JsValue {0}", l));
        }
Пример #12
0
        /// <summary>
        /// Management Web-Interface: Monitoring / Port Statistics
        /// </summary>
        /// <returns></returns>
        public IReadOnlyList <PortStateInfo> GetPortStatistics()
        {
            string html = _client.DownloadString("PortStatisticsRpm.htm");

            if (html.Contains("id=\"logon\""))
            {
                // not logged in!
                throw new Exception("login failed");
            }

            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(html);
            List <HtmlNode> scriptNodes = doc.DocumentNode.Descendants("script").ToList();

            if (!scriptNodes.Any())
            {
                throw new Exception("no script nodes found");
            }
            HtmlNode script     = scriptNodes.First();
            string   scriptText = script.InnerText;

            Engine  scriptingEngine = new Engine();
            Engine  result          = scriptingEngine.Execute(scriptText);
            JsValue r1           = result.GetValue("max_port_num");
            JsValue r2           = result.GetValue("all_info");
            int     max_port_num = (int)r1.AsNumber();

            long[] linkStatusArray  = AsLongArray(r2.AsObject().GetProperty("link_status").Value);
            long[] stateArray       = AsLongArray(r2.AsObject().GetProperty("state").Value);
            long[] packetCountArray = AsLongArray(r2.AsObject().GetProperty("pkts").Value);

            List <PortStateInfo> ports = new List <PortStateInfo>();

            for (int i = 0; i < max_port_num; i++)
            {
                var psi = new PortStateInfo()
                {
                    PortNumber = (byte)(i + 1),
                    IsEnabled  = stateArray[i] == 1,
                    LinkStatus = (byte)linkStatusArray[i],
                    TxGoodPkt  = packetCountArray[i * 4 + 0],
                    TxBadPkt   = packetCountArray[i * 4 + 1],
                    RxGoodPkt  = packetCountArray[i * 4 + 2],
                    RxBadPkt   = packetCountArray[i * 4 + 3],
                };
                ports.Add(psi);
            }
            return(ports);
        }
Пример #13
0
        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);
        }
Пример #14
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());
 }
Пример #15
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);
        }
Пример #16
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());
        }
Пример #17
0
        public Class1()
        {
            int    x1       = 1;
            int    x2       = 3;
            Engine jsEngine = new Engine();

            jsEngine.SetValue("val1", x1);
            jsEngine.SetValue("val2", x2);
            jsEngine.Execute("function test() { return val1+val2; }");
            var qaz  = jsEngine.Execute("(function test() { return val1*val2; })()").GetCompletionValue().AsNumber();
            var qaz2 = jsEngine.Execute("(function test() { return {Val1:2,Val2:\"df\"}; })()").GetCompletionValue()
                       .TryCast <Data>();
            JsValue fnVal  = jsEngine.GetValue("test");
            JsValue result = fnVal.Invoke();
            Double  obj    = result.AsNumber();
        }
Пример #18
0
        /// <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;
        }
Пример #19
0
        /// <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);
        }
Пример #20
0
        public IReadOnlyList <PortSpeedInfo> GetPortSpeeds()
        {
            string html = _client.DownloadString("QosBandWidthControlRpm.htm");

            if (html.Contains("id=\"logon\""))
            {
                // not logged in!
                throw new Exception("login failed");
            }

            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(html);
            List <HtmlNode> scriptNodes = doc.DocumentNode.Descendants("script").ToList();

            if (!scriptNodes.Any())
            {
                throw new Exception("no script nodes found");
            }
            HtmlNode script     = scriptNodes.First();
            string   scriptText = script.InnerText;

            Engine  scriptingEngine = new Engine();
            Engine  result          = scriptingEngine.Execute(scriptText);
            JsValue r1           = result.GetValue("portNumber");
            JsValue r2           = result.GetValue("bcInfo");
            int     max_port_num = (int)r1.AsNumber();

            long[] speedRateArray = AsLongArray(r2);

            List <PortSpeedInfo> ports = new List <PortSpeedInfo>();

            for (int i = 0; i < max_port_num; i++)
            {
                var psi = new PortSpeedInfo()
                {
                    PortNumber      = (byte)(i + 1),
                    IngressRateKbps = speedRateArray[i * 3 + 0],
                    EgressRateKbps  = speedRateArray[i * 3 + 1],
                };
                ports.Add(psi);
            }
            return(ports);
        }
Пример #21
0
        /// <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 == null)
            {
                return(null);
            }
            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)));
        }
Пример #22
0
        public virtual string PutDocument(string key, JsValue document, JsValue metadata, JsValue etagJs, Engine engine)
        {
            if (document.IsObject() == false)
            {
                throw new InvalidOperationException(
                          $"Created document must be a valid object which is not null or empty. Document key: '{key}'.");
            }

            long?etag = null;

            if (etagJs.IsNumber())
            {
                etag = (long)etagJs.AsNumber();
            }
            else if (etagJs.IsNull() == false && etagJs.IsUndefined() == false && etagJs.ToString() != "None")
            {
                throw new InvalidOperationException($"Invalid ETag value for document '{key}'");
            }

            var data = ToBlittable(document.AsObject());

            if (metadata.IsObject())
            {
                data["@metadata"] = ToBlittable(metadata.AsObject());
            }

            if (DebugMode)
            {
                DebugActions.PutDocument.Add(new DynamicJsonValue
                {
                    ["Key"]  = key,
                    ["Etag"] = etag,
                    ["Data"] = data,
                });
            }

            var dataReader = _context.ReadObject(data, key, BlittableJsonDocumentBuilder.UsageMode.ToDisk);
            var put        = _database.DocumentsStorage.Put(_context, key, etag, dataReader);

            return(put.Key);
        }
Пример #23
0
        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);
        }
Пример #24
0
        public object UncastJsValue(JsValue value)
        {
            if (value.IsBoolean())
            {
                return(value.AsBoolean());
            }
            if (value.IsNumber())
            {
                return(value.AsNumber());
            }
            if (value.IsObject())
            {
                return(value.AsObject());
            }
            if (value.IsString())
            {
                return(value.AsString());
            }

            return(null);
        }
Пример #25
0
        public void SetValue(JsValue arg)
        {
            switch (arg.Type)
            {
            case Types.Boolean:
                Cell.SetCellValue(arg.AsBoolean());
                break;

            case Types.String:
                Cell.SetCellValue(arg.AsString());
                break;

            case Types.Number:
                Cell.SetCellValue(arg.AsNumber());
                break;

            case Types.Object:
                if (arg.IsDate())
                {
                    Cell.SetCellValue(arg.AsDate().ToDateTime());
                }
                else
                {
                    double?value = arg.ConvertToDouble();
                    if (value.HasValue)
                    {
                        Cell.SetCellValue(value.Value);
                    }
                    else
                    {
                        Cell.SetCellValue((string)null);
                    }
                }
                break;

            default:
                Cell.SetCellValue((string)null);
                break;
            }
        }
Пример #26
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);
        }
Пример #27
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));
        }
Пример #28
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());
        }
Пример #29
0
        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);
        }
Пример #30
0
        /// 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);
            }
        }
Пример #31
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);
        }
Пример #32
0
        /// <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));
        }
Пример #33
0
        /// <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));
        }
Пример #34
0
        /// <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 = StringPrototype.TrimEx(o.AsString());

                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)));
        }
Пример #35
0
        public static bool StrictlyEqual(JsValue x, JsValue y)
        {
            var typea = x.Type;
            var typeb = y.Type;

            if (typea != typeb)
            {
                return(false);
            }

            if (typea == Types.Undefined || typea == Types.Null)
            {
                return(true);
            }

            if (typea == Types.None)
            {
                return(true);
            }

            if (typea == Types.Number)
            {
                var nx = x.AsNumber();
                var ny = y.AsNumber();

                if (double.IsNaN(nx) || double.IsNaN(ny))
                {
                    return(false);
                }

                if (nx.Equals(ny))
                {
                    return(true);
                }

                return(false);
            }

            if (typea == Types.String)
            {
                return(x.AsString() == y.AsString());
            }

            if (typea == Types.Boolean)
            {
                return(x.AsBoolean() == y.AsBoolean());
            }

            if (typea == Types.Object)
            {
                var xw = x.AsObject() as IObjectWrapper;

                if (xw != null)
                {
                    var yw = y.AsObject() as IObjectWrapper;
                    return(Object.Equals(xw.Target, yw.Target));
                }
            }

            return(x == y);
        }
Пример #36
0
        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);
        }