public void AttachConstructors(ObjectInstance obj)
        {
            var constructors = GetType().GetProperties();

            foreach (var constructor in constructors)
                obj.FastAddProperty(constructor.Name, constructor.GetValue(this) as FunctionInstance, true, false, true);
        }
Пример #2
0
 /// <summary>
 /// Copies and translates the contents of the specified config file into the specified object
 /// </summary>
 /// <param name="config"></param>
 /// <param name="engine"></param>
 /// <returns></returns>
 public static ObjectInstance ObjectFromConfig(DynamicConfigFile config, Engine engine)
 {
     var objInst = new ObjectInstance(engine) {Extensible = true};
     foreach (var pair in config)
     {
         objInst.FastAddProperty(pair.Key, JsValueFromObject(pair.Value, engine), true, true, true);
     }
     return objInst;
 }
Пример #3
0
 /// <summary>
 /// Copies and translates the contents of the specified table into the specified config file
 /// </summary>
 /// <param name="config"></param>
 /// <param name="objectInstance"></param>
 public static void SetConfigFromObject(DynamicConfigFile config, ObjectInstance objectInstance)
 {
     config.Clear();
     foreach (var property in objectInstance.GetOwnProperties())
     {
         var value = property.Value.Value?.ToObject();
         if (value != null) config[property.Key] = value;
     }
 }
Пример #4
0
        public static Jint.Native.Object.ObjectInstance MakeObjectInstance(IDictionary <string, object> dic, Jint.Engine engine)
        {
            var o = new Jint.Native.Object.ObjectInstance(engine);

            foreach (var i in dic)
            {
                o.FastAddProperty(i.Key, MakeJsValue(i.Value, engine), true, true, true);
            }
            return(o);
        }
Пример #5
0
 public static JsValue JsValueFromObject(object obj, Engine engine)
 {
     var values = obj as List<object>;
     if (values != null)
     {
         var array = (ArrayInstance) engine.Array.Construct(values.Select(v => JsValueFromObject(v, engine)).ToArray());
         array.Extensible = true;
         return array;
     }
     var dict = obj as Dictionary<string, object>;
     if (dict != null)
     {
         var objInst = new ObjectInstance(engine) { Extensible = true };
         foreach (var pair in dict)
         {
             objInst.FastAddProperty(pair.Key, JsValueFromObject(pair.Value, engine), true, true, true);
         }
         return objInst;
     }
     return JsValue.FromObject(engine, obj);
 }
Пример #6
0
        public void Initialize(string javascript)
        {
            lock (_sync) {
                try {
                    // Define the aggregator
                    mng = _engine.Execute(javascript).GetCompletionValue().AsObject();

                } catch (Exception ex) {
                    var details = string.Format(@"Error, unable to execute initial script:
            Javascript
            ------
            {0}
            ------
            Message: {1}
            In: {2}

            The script needs to follow the pattern:

            E.g. `(function () { return this; })();`
            ",
                                javascript,
                                ex.Message,
                                _errorMessageContext + ":" + "Initialize"
                        );
                    throw new JavascriptException(details, ex);
                }
            }
        }
Пример #7
0
        private string SerializeObject(ObjectInstance value)
        {
            string final;

            EnsureNonCyclicity(value);
            _stack.Push(value);
            var stepback = _indent;
            _indent += _gap;
            
            var k = _propertyList ?? value.GetOwnProperties()
                .Where(x => x.Value.Enumerable.HasValue && x.Value.Enumerable.Value == true)
                .Select(x => x.Key)
                .ToList();

            var partial = new List<string>();
            foreach (var p in k)
            {
                var strP = Str(p, value);
                if (strP != JsValue.Undefined)
                {
                    var member = Quote(p) + ":";
                    if (_gap != "")
                    {
                        member += " ";
                    }
                    member += strP.AsString(); // TODO:This could be undefined
                    partial.Add(member);
                }
            }
            if (partial.Count == 0)
            {
                final = "{}";
            }
            else
            {
                if (_gap == "")
                {
                    var separator = ",";
                    var properties = System.String.Join(separator, partial.ToArray());
                    final = "{" + properties + "}";
                }
                else
                {
                    var separator = ",\n" + _indent;
                    var properties = System.String.Join(separator, partial.ToArray());
                    final = "{\n" + _indent + properties + "\n" + stepback + "}";
                }                
            }
            _stack.Pop();
            _indent = stepback;
            return final;
        }
Пример #8
0
        private JsValue Str(string key, ObjectInstance holder)
        {
            
            var value = holder.Get(key);
            if (value.IsObject())
            {
                var toJson = value.AsObject().Get("toJSON");
                if (toJson.IsObject())
                {
                    var callableToJson = toJson.AsObject() as ICallable;
                    if (callableToJson != null)
                    {
                        value = callableToJson.Call(value, Arguments.From(key));
                    }
                }
            }
            
            if (_replacerFunction != Undefined.Instance)
            {
                var replacerFunctionCallable = (ICallable)_replacerFunction.AsObject();
                value = replacerFunctionCallable.Call(holder, Arguments.From(key, value));
            }

            
            if (value.IsObject())
            {
                var valueObj = value.AsObject();
                switch (valueObj.Class)
                {
                    case "Number":
                        value = TypeConverter.ToNumber(value);
                        break;
                    case "String":
                        value = TypeConverter.ToString(value);
                        break;
                    case "Boolean":
                        value = TypeConverter.ToPrimitive(value);
                        break;
                    case "Array": 
                        value = SerializeArray(value.As<ArrayInstance>());
                        return value;
                    case "Object":
                        value = SerializeObject(value.AsObject());
                        return value;
                }
            }
           
            if (value == Null.Instance)
            {
                return "null";
            }

            if (value.IsBoolean() && value.AsBoolean())
            {
                return "true";
            }

            if (value.IsBoolean() && !value.AsBoolean())
            {
                return "false";
            }

            if (value.IsString())
            {
                return Quote(value.AsString());
            }

            if (value.IsNumber())
            {
                if (GlobalObject.IsFinite(Undefined.Instance, Arguments.From(value)).AsBoolean())
                {
                    return TypeConverter.ToString(value);
                }
                
                return "null";
            }

            var isCallable = value.IsObject() && value.AsObject() is ICallable;

            if (value.IsObject() && isCallable == false)
            {
                if (value.AsObject().Class == "Array")
                {
                    return SerializeArray(value.As<ArrayInstance>());
                }

                return SerializeObject(value.AsObject());
            }

            return JsValue.Undefined;
        }
Пример #9
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.2.1
        /// </summary>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public ObjectInstance Construct(JsValue[] arguments)
        {
            if (arguments.Length > 0)
            {
                var value = arguments[0];
                var valueObj = value.TryCast<ObjectInstance>();
                if (valueObj != null)
                {
                    return valueObj;
                }
                var type = value.Type;
                if (type == Types.String || type == Types.Number || type == Types.Boolean)
                {
                    return TypeConverter.ToObject(_engine, value);
                }
            }

            var obj = new ObjectInstance(_engine)
                {
                    Extensible = true,
                    Prototype = Engine.Object.PrototypeObject
                };

            return obj;
        }
Пример #10
0
        //public JiraHistory[] GetIssueHistory(int issueId)
        //{
        //    var parameters = new Dictionary<string, string>
        //    {
        //        { "expand", "changelog" }
        //    };
        //    dynamic response = Request(
        //        String.Format("/rest/api/2/issue/{0}", issueId),
        //        parameters
        //    );
        //    var result = new List<JiraHistory>();
        //    foreach (var history in response.changelog.histories)
        //    {
        //        result.Add(new JiraHistory(history));
        //    }
        //    return result.ToArray();
        //}
        //public JiraStatus[] GetStatuses()
        //{
        //    dynamic response = Request("/rest/api/2/status");
        //    var result = new List<JiraStatus>();
        //    foreach (var status in response)
        //    {
        //        result.Add(new JiraStatus(status));
        //    }
        //    return result.ToArray();
        //}
        //public JiraTransition[] GetTransitions(int issueId, int? transitionId = null)
        //{
        //    var parameters = new Dictionary<string, string>();
        //    if (transitionId.HasValue)
        //        parameters.Add("transitionId", transitionId.Value.ToString());
        //    dynamic response = Request(
        //        String.Format("/rest/api/2/issue/{0}/transitions", issueId),
        //        parameters
        //    );
        //    var result = new List<JiraTransition>();
        //    foreach (var transition in response.transitions)
        //    {
        //        result.Add(new JiraTransition(transition));
        //    }
        //    return result.ToArray();
        //}
        //public void Transition(int issueId, int transitionId)
        //{
        //    Request(
        //        String.Format(
        //            "/rest/api/2/issue/{0}/transitions", issueId
        //        ),
        //        null,
        //        new JObject(
        //            new JProperty(
        //                "transition",
        //                new JObject(
        //                    new JProperty(
        //                        "id", transitionId
        //                    )
        //                )
        //            )
        //        )
        //    );
        //}
        //public void Comment(int issueId, string comment)
        //{
        //    Request(
        //        String.Format("/rest/api/2/issue/{0}/comment", issueId),
        //        null,
        //        new JObject(
        //            new JProperty("body", comment)
        //        )
        //    );
        //}
        //public void LogWork(int issueId, string timeSpent, DateTime dateStarted, AdjustRemainingMode adjustRemaining, string adjustRemainingBy, string workDescription)
        //{
        //    var parameters = new Dictionary<string, string>();
        //    switch (adjustRemaining)
        //    {
        //        case AdjustRemainingMode.AdjustAutomatically:
        //            parameters.Add("adjustEstimate", "auto");
        //            break;
        //        case AdjustRemainingMode.DonNotChange:
        //            parameters.Add("adjustEstimate", "leave");
        //            break;
        //        case AdjustRemainingMode.ReduceBy:
        //            parameters.Add("adjustEstimate", "manual");
        //            parameters.Add("reduceBy", adjustRemainingBy);
        //            break;
        //        case AdjustRemainingMode.SetTo:
        //            parameters.Add("adjustEstimate", "new");
        //            parameters.Add("newEstimate", adjustRemainingBy);
        //            break;
        //    }
        //    var obj = new JObject(
        //        new JProperty(
        //            "timeSpent", timeSpent
        //        )
        //    );
        //    if (workDescription != null)
        //        obj.Add(new JProperty("comment", workDescription));
        //    Request(
        //        String.Format(
        //            "/rest/api/2/issue/{0}/worklog", issueId
        //        ),
        //        parameters,
        //        obj
        //    );
        //}
        public string Request(string url, ObjectInstance parameters, string payload)
        {
            Dictionary<string, string> dictionary = null;

            if (parameters != null)
            {
                dictionary = new Dictionary<string, string>();

                foreach (var parameter in parameters.GetOwnProperties())
                {
                    dictionary[parameter.Key] = parameter.Value?.ToString();
                }
            }

            return Request(url, dictionary, payload);
        }
Пример #11
0
        public void PocosCanReturnObjectInstanceDirectly()
        {
            var x = new ObjectInstance(_engine) { Extensible = true};
            x.Put("foo", new JsValue("bar"), false);

            var o = new
            {
                x
            };

            _engine.SetValue("o", o);

            RunTest(@"
                assert(o.x.foo === 'bar');
            ");
        }
Пример #12
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-13.2.2
        /// </summary>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public ObjectInstance Construct(JsValue[] arguments)
        {
            var proto = Get("prototype").TryCast<ObjectInstance>();
            var obj = new ObjectInstance(Engine);
            obj.Extensible = true;
            obj.Prototype = proto ?? Engine.Object.PrototypeObject;

            var result = Call(obj, arguments).TryCast<ObjectInstance>();
            if (result != null)
            {
                return result;
            }

            return obj;
        }
Пример #13
0
 public ObjectEnvironmentRecord(Engine engine, ObjectInstance bindingObject, bool provideThis) : base(engine)
 {
     _engine = engine;
     _bindingObject = bindingObject;
     _provideThis = provideThis;
 }
Пример #14
0
 private static Func<object, object> GetFunc(string funcName, ObjectInstance exports)
 {
     var func = exports.Get(funcName);
     if (func.IsUndefined() || func.IsNull())
     {
         return null;
     }
     if (func.Is<ICallable>())
     {
         return s =>
         {
             var model = JintProcessorHelper.ConvertStrongTypeToJsValue(s);
             return func.Invoke(model).ToObject();
         };
     }
     else
     {
         throw new InvalidPreprocessorException($"Invalid '{funcName}' variable definition. '{funcName} MUST be a function");
     }
 }
        public static void AddConstructor(this EngineInstance engine, ObjectInstance obj, Type type)
        {
            var info = type.GetConstructors().FirstOrDefault(m => 
                m.GetCustomAttributes<DomConstructorAttribute>().Any());

            if (info != null)
            {
                var name = type.GetOfficialName();
                var constructor = new DomConstructorInstance(engine, info);
                obj.FastSetProperty(name, new PropertyDescriptor(constructor, false, true, false));
            }
        }
 public static void AddConstructors(this EngineInstance engine, ObjectInstance obj, Type type)
 {
     foreach (var exportedType in type.Assembly.ExportedTypes)
         engine.AddConstructor(obj, exportedType);
 }
Пример #17
0
 public static LexicalEnvironment NewObjectEnvironment(Engine engine, ObjectInstance objectInstance, LexicalEnvironment outer, bool provideThis)
 {
     return new LexicalEnvironment(new ObjectEnvironmentRecord(engine, objectInstance, provideThis), outer);
 }
Пример #18
0
		public JsValue ToJsObject(Engine engine, RavenJObject doc, string propertyName = null)
        {
            var jsObject = new ObjectInstance(engine)
                           {
                               Extensible = true
                           };

            foreach (var prop in doc)
            {
	            var propertyKey = CreatePropertyKey(prop.Key, propertyName);
				var jsValue = ToJsInstance(engine, prop.Value, propertyKey);

                var value = prop.Value as RavenJValue;
                if (value != null)
					propertiesByValue[propertyKey] = new KeyValuePair<RavenJValue, JsValue>(value, jsValue);

                jsObject.Put(prop.Key, jsValue, true);
            }
            return jsObject;
        }
Пример #19
0
        /// <summary>
        /// Loads this plugin
        /// </summary>
        public override void Load()
        {
            // Load the plugin
            LoadSource();
            if (JavaScriptEngine.GetValue(Name).TryCast<ObjectInstance>() == null) throw new Exception("Plugin is missing main object");
            Class = JavaScriptEngine.GetValue(Name).AsObject();
            if (!Class.HasProperty("Name"))
                Class.FastAddProperty("Name", Name, true, false, true);
            else
                Class.Put("Name", Name, true);

            // Read plugin attributes
            if (!Class.HasProperty("Title") || string.IsNullOrEmpty(Class.Get("Title").AsString())) throw new Exception("Plugin is missing title");
            if (!Class.HasProperty("Author") || string.IsNullOrEmpty(Class.Get("Author").AsString())) throw new Exception("Plugin is missing author");
            if (!Class.HasProperty("Version") || Class.Get("Version").ToObject() == null) throw new Exception("Plugin is missing version");
            Title = Class.Get("Title").AsString();
            Author = Class.Get("Author").AsString();
            Version = (VersionNumber) Class.Get("Version").ToObject();
            if (Class.HasProperty("Description")) Description = Class.Get("Description").AsString();
            if (Class.HasProperty("ResourceId")) ResourceId = (int)Class.Get("ResourceId").AsNumber();
            HasConfig = Class.HasProperty("HasConfig") && Class.Get("HasConfig").AsBoolean();

            // Set attributes
            Class.FastAddProperty("Plugin", JsValue.FromObject(JavaScriptEngine, this), true, false, true);

            Globals = new Dictionary<string, ICallable>();
            foreach (var property in Class.GetOwnProperties())
            {
                var callable = property.Value.Value?.TryCast<ICallable>();
                if (callable != null) Globals.Add(property.Key, callable);
            }
            foreach (var property in Class.Prototype.GetOwnProperties())
            {
                var callable = property.Value.Value?.TryCast<ICallable>();
                if (callable != null) Globals.Add(property.Key, callable);
            }
            if (!HasConfig) HasConfig = Globals.ContainsKey("LoadDefaultConfig");

            // Bind any base methods (we do it here because we don't want them to be hooked)
            BindBaseMethods();
        }