public static T Duplicate <T>(this T origin) where T : IDataObject, new()
        {
            if (origin == null)
            {
                return(default(T));
            }
            var t           = typeof(T);
            var ridCol      = FiTechBDadosExtensions.RidColumnOf[t];
            var idCol       = FiTechBDadosExtensions.IdColumnOf[t];
            T   destination = new T();

            ObjectReflector.Open(origin, (objA) => {
                ObjectReflector.Open(destination, (objB) => {
                    foreach (var field in objB)
                    {
                        if (field.Key.Name == ridCol)
                        {
                            continue;
                        }
                        if (objA.ContainsKey(field.Key.Name))
                        {
                            objB[field.Key] = objA[field.Key.Name];
                        }
                    }
                });
            });

            return(destination);
        }
Пример #2
0
        public SqlCommand ProcedureFunction(object provider, string commandText)
        {
            SqlCommand command = new SqlCommand();

            this.ConnectionOpen();
            command.Connection = Connection;
            this.BeginTransaction(true);
            command.Transaction = this.Transaction;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = commandText;
            ObjectReflector objectReflector = new ObjectReflector();
            var             propertyList    = objectReflector.GetPropertyList(provider);

            foreach (KeyValuePair <string, ObjectReflector.ProviderPropertyInfo> providerPropertyInfo in propertyList)
            {
                if (providerPropertyInfo.Key.ToUpper() == "EntryDate".ToUpper() ||
                    providerPropertyInfo.Key.ToUpper() == "TS" ||
                    providerPropertyInfo.Key.ToUpper() == "UpdateDate".ToUpper())
                {
                    continue;
                }
                AddParam(command, providerPropertyInfo.Key, providerPropertyInfo.Value.Value, providerPropertyInfo.Value.SqlDbType);
            }

            return(command);
        }
Пример #3
0
        public void SetConfiguration(IDictionary <string, object> settings)
        {
            Config = new PgSQLPluginConfiguration();
            ObjectReflector o = new ObjectReflector(Config);

            foreach (var a in settings)
            {
                o[a.Key] = a.Value;
            }
        }
Пример #4
0
        public static void CopyFromAndMergeLists(this Object me, object other)
        {
            if (me == null)
            {
                throw new NullReferenceException("Figlotech CopyFrom Extension method called on a null value, this is a natural NullReferenceException");
            }

            if (other == null)
            {
                me = null;
                return;
            }
            ObjectReflector.Open(other, (objA) => {
                ObjectReflector.Open(me, (objB) => {
                    foreach (var field in objB)
                    {
                        if (objA.ContainsKey(field.Key.Name))
                        {
                            var valA = objA[field.Key.Name];
                            var valB = objB[field.Key.Name];
                            if (
                                valA.GetType().IsGenericType&& valA.GetType().Implements(typeof(List <>)) &&
                                valB.GetType().IsGenericType&& valB.GetType().Implements(typeof(List <>))
                                )
                            {
                                var addMethod   = valB.GetType().GetMethods().FirstOrDefault(m => m.Name == "Add" && m.GetParameters().Length == 1);
                                var enny        = (IEnumerator)valA.GetType().GetMethods().FirstOrDefault(e => e.Name == "GetEnumerator")?.Invoke(valA, new object[0]);
                                var fodefMethod = valB.GetType().GetMethods().FirstOrDefault(m => m.Name == "FirstOrDefault" && m.GetParameters().Length == 1);
                                while (enny.MoveNext())
                                {
                                    var paramEx = Expression.Parameter(valB.GetType().GetGenericArguments().First(), "a");
                                    var lambda  = Expression.Lambda(Expression.Equal(paramEx, Expression.Constant(enny.Current)), paramEx);
                                    var fodef   = fodefMethod?.Invoke(valB, new object[] { lambda });
                                    if (fodef != null)
                                    {
                                        if (!fodef.Equals(enny.Current))
                                        {
                                            addMethod.Invoke(valB, new object[] { enny.Current });
                                        }
                                        else
                                        {
                                            CopyFromAndMergeLists(fodef, enny.Current);
                                        }
                                    }
                                }
                            }
                            objB[field.Key] = objA[field.Key.Name];
                        }
                    }
                });
            });
        }
        public List <T> GetObjectList <T>(BDadosTransaction transaction, IDbCommand command) where T : new()
        {
            var refl = new ObjectReflector();

            transaction?.Benchmarker.Mark("Enter lock command");
            lock (command) {
                transaction?.Benchmarker.Mark("- Starting Execute Query");
                using (var reader = command.ExecuteReader(CommandBehavior.SingleResult | CommandBehavior.SequentialAccess | CommandBehavior.KeyInfo)) {
                    transaction?.Benchmarker.Mark("- Starting build");
                    return(Fi.Tech.MapFromReader <T>(reader).ToList());
                }
            }
        }
Пример #6
0
        public override void SetUp()
        {
            base.SetUp();
            var cache = new ImmutableInMemorySpecCache();

            ObjectReflectorConfiguration.NoValidate = true;

            var reflectorConfiguration = new ObjectReflectorConfiguration(new Type[] { }, new Type[] { });

            facetFactory = new RemoveIgnoredMethodsFacetFactory(GetOrder <RemoveIgnoredMethodsFacetFactory>(), LoggerFactory);
            var objectFactFactorySet = new ObjectFacetFactorySet(new IObjectFacetFactoryProcessor[] { facetFactory });
            var classStrategy        = new ObjectClassStrategy(reflectorConfiguration);
            var metamodel            = new Metamodel(cache, null);
            var mockLogger           = new Mock <ILogger <AbstractParallelReflector> >().Object;
            var mockLoggerFactory    = new Mock <ILoggerFactory>().Object;

            Reflector = new ObjectReflector(objectFactFactorySet, classStrategy, metamodel, reflectorConfiguration, new IFacetDecorator[] { }, mockLoggerFactory, mockLogger);
        }
Пример #7
0
        /// <summary>
        /// <para>
        /// This function scans input object and resolves all fields and properties
        /// that are Interface type with null value and resolves them. The scanner considers
        /// EVERY public interface field or property that is null as a "non-satisfied" dependency
        /// and tries to resolve it.
        /// </para>
        /// <para>
        /// It's shitty, I think the programmer community will hate on me for this, but I don't care
        /// I'm lazy, that's what I am.
        /// </para>
        /// </summary>
        /// <param name="input">The object to be scanned and have its dependencies resolved</param>
        public void SmartResolve(object input, bool ignoreErrors = false)
        {
            ObjectReflector rflx    = new ObjectReflector(input);
            var             t       = input.GetType();
            var             members = ReflectionTool.FieldsAndPropertiesOf(t);

            foreach (var member in members)
            {
                var type = ReflectionTool.GetTypeOf(member);
                if (type.IsInterface)
                {
                    var resolution = Resolve(type, ignoreErrors);
                    if (resolution != null)
                    {
                        rflx[member] = resolution;
                    }
                }
            }
        }
Пример #8
0
        public static List<dynamic> ExecuteQuery(string sql, string filename = "default.xls")
        {
            var ls = new List<dynamic>();

            var r = new ObjectReflector();
            using (var conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=Yes'"))
            {
                conn.Open();
                var cmd = new OleDbCommand(sql, conn);
                var reader = cmd.ExecuteReader();
                while (reader != null && reader.Read())
                {
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        r.Add(reader.GetName(i), reader.GetValue(i));
                    }
                    ls.Add(r.CreateObject());
                }
            }

            return ls;
        }
Пример #9
0
        public static void ApplyToCommand(this IQueryBuilder query, IDbCommand command, Func <object, object> ProcessParameterValue = null)
        {
            String QueryText = query.GetCommandText();

            command.CommandText = QueryText;
            // Adiciona os parametros
            var paramRefl = new ObjectReflector();

            foreach (KeyValuePair <String, Object> param in query.GetParameters())
            {
                var cmdParam = command.CreateParameter();
                cmdParam.ParameterName = param.Key;

                var usableValue = param.Value;
                if (ProcessParameterValue != null)
                {
                    usableValue = ProcessParameterValue.Invoke(param.Value);
                }
                if (usableValue == null)
                {
                    cmdParam.Value = DBNull.Value;
                }
                else
                if (usableValue is String str)
                {
                    cmdParam.Value  = str;
                    cmdParam.DbType = DbType.String;
                    //paramRefl.Slot(cmdParam);
                    //paramRefl["Encoding"] = Fi.StandardEncoding;
                }
                else
                {
                    cmdParam.Value = usableValue;
                }
                cmdParam.Direction = ParameterDirection.Input;

                command.Parameters.Add(cmdParam);
            }
        }
Пример #10
0
        //        private static Lazy<WorkQueuer> _globalQueuer = new Lazy<WorkQueuer>(()=> new WorkQueuer("FIGLOTECH_GLOBAL_QUEUER", Environment.ProcessorCount, true));
        //        public static WorkQueuer GlobalQueuer { get => _globalQueuer.Value; }

        //        public static int currentBDadosConnections = 0;

        //        public static List<string> RanChecks = new List<string>();

        //        public static string DefaultLogRepository = "Logs\\Fi.TechLogs";

        //        public static String DefaultBackupStore { get; set; } = "../Backups/";

        //        public static String Version {
        //            get {
        //                return Assembly.GetExecutingAssembly().GetName().Version.ToString();
        //            }
        //        }

        //        public static void As<T>(this Fi _selfie, object input, Action<T> act) {
        //            if (
        //                (typeof(T).IsInterface && input.GetType().GetInterfaces().Contains(typeof(T))) ||
        //                input.GetType().IsAssignableFrom(typeof(T))
        //            ) {
        //                act((T)input);
        //            }

        //        }

        //        public static void RecursiveGiveRids(this Fi _selfie, IDataObject obj) {
        //            if(obj.RID == null) {
        //                obj.RID = Fi.Tech.GenerateIdString(obj.GetType().Name, 64);
        //                var props = ReflectionTool.FieldsAndPropertiesOf(obj.GetType());

        //                for(int i = 0; i < props.Count; i++) {
        //                    var t = ReflectionTool.GetTypeOf(props[i]);
        //                    if (t.GetInterfaces().Contains(typeof(IDataObject))) {
        //                        Fi.Tech.RecursiveGiveRids((IDataObject) ReflectionTool.GetValue(obj, props[i].Name));
        //                    }
        //                }
        //            }
        //        }

        //        public static T Deserialize<T>(this Fi _selfie, String txt) where T: IDataObject, new() {
        //            var v = JsonConvert.DeserializeObject<T>(txt);
        //            Fi.Tech.RecursiveGiveRids(v);
        //            return v;
        //        }

        /// <summary>
        /// deprecated
        /// this gimmick should barely be used by the data accessors
        /// provided by the rdbms language providers
        /// But it's a contravention, must be avoided whenever possible.
        /// </summary>
        /// <param name="valor"></param>
        /// <returns></returns>
        public static IEnumerable <T> MapFromReader <T>(this Fi _selfie, IDataReader reader, bool ignoreCase = false) where T : new()
        {
            var refl         = new ObjectReflector();
            var existingKeys = new string[reader.FieldCount];

            for (int i = 0; i < reader.FieldCount; i++)
            {
                var name = reader.GetName(i);
                if (name != null)
                {
                    if (ReflectionTool.DoesTypeHaveFieldOrProperty(typeof(T), name))
                    {
                        existingKeys[i] = name;
                    }
                }
            }
            while (reader.Read())
            {
                T obj = new T();
                refl.Slot(obj);
                for (int i = 0; i < existingKeys.Length; i++)
                {
                    if (existingKeys[i] != null)
                    {
                        try {
                            var o = reader.GetValue(i);
                            refl[existingKeys[i]] = Fi.Tech.ProperMapValue(o);
                        } catch (Exception x) {
                            Debugger.Break();
                            throw x;
                        }
                    }
                }
                yield return((T)refl.Retrieve());
            }
            yield break;
        }
Пример #11
0
        private JavaScriptProjection InitializeProjectionForType(Type t)
        {
            var eng = GetEngineAndClaimContext();

            ObjectReflector      reflector          = ObjectReflector.Create(t);
            JavaScriptProjection baseTypeProjection = null;

            if (reflector.HasBaseType)
            {
                Type baseType = reflector.GetBaseType();
                if (!projectionTypes_.TryGetValue(baseType, out baseTypeProjection))
                {
                    baseTypeProjection           = InitializeProjectionForType(baseType);
                    baseTypeProjection.RefCount += 1;
                    projectionTypes_[baseType]   = baseTypeProjection;
                }
            }

            var publicConstructors       = reflector.GetConstructors();
            var publicInstanceProperties = reflector.GetProperties(instance: true);
            var publicStaticProperties   = reflector.GetProperties(instance: false);
            var publicInstanceMethods    = reflector.GetMethods(instance: true);
            var publicStaticMethods      = reflector.GetMethods(instance: false);
            var publicInstanceEvents     = reflector.GetEvents(instance: true);
            var publicStaticEvents       = reflector.GetEvents(instance: false);

            if (AnyHaveSameArity(out var duplicateName, publicConstructors, publicInstanceMethods, publicStaticMethods, publicInstanceProperties, publicStaticProperties))
            {
                throw new InvalidOperationException("The specified type cannot be marshaled; some publicly accessible members have the same arity.  Projected methods can't differentiate only by type (e.g., Add(int, int) and Add(float, float) would cause this error): " + t.FullName + "::" + duplicateName);
            }

            JavaScriptFunction ctor;

            if (publicConstructors.Any())
            {
                // e.g. var MyObject = function() { [native code] };
                ctor = eng.CreateFunction((engine, constr, thisObj, args) =>
                {
                    // todo
                    return(FromObject(publicConstructors.First().Invoke(new object[] { })));
                }, t.FullName);
            }
            else
            {
                ctor = eng.CreateFunction((engine, constr, thisObj, args) =>
                {
                    return(eng.UndefinedValue);
                }, t.FullName);
            }

            // MyObject.prototype = Object.create(baseTypeProjection.PrototypeObject);
            var prototypeObj = CreateObjectFor(eng, baseTypeProjection);

            ctor.SetPropertyByName("prototype", prototypeObj);
            // MyObject.prototype.constructor = MyObject;
            prototypeObj.SetPropertyByName("constructor", ctor);

            // MyObject.CreateMyObject = function() { [native code] };
            ProjectMethods(t.FullName, ctor, eng, publicStaticMethods);
            // Object.defineProperty(MyObject, 'Foo', { get: function() { [native code] } });
            ProjectProperties(t.FullName, ctor, eng, publicStaticProperties);
            // MyObject.addEventListener = function() { [native code] };
            if ((baseTypeProjection?.HasStaticEvents ?? false) || publicStaticEvents.Any())
            {
                ProjectEvents(t.FullName, ctor, eng, publicStaticEvents, baseTypeProjection, instance: false);
            }

            // MyObject.prototype.ToString = function() { [native code] };
            ProjectMethods(t.FullName + ".prototype", prototypeObj, eng, publicInstanceMethods);
            // Object.defineProperty(MyObject.prototype, 'baz', { get: function() { [native code] }, set: function() { [native code] } });
            ProjectProperties(t.FullName + ".prototype", prototypeObj, eng, publicInstanceProperties);
            // MyObject.prototype.addEventListener = function() { [native code] };
            if ((baseTypeProjection?.HasInstanceEvents ?? false) || publicInstanceEvents.Any())
            {
                ProjectEvents(t.FullName + ".prototype", prototypeObj, eng, publicInstanceEvents, baseTypeProjection, instance: true);
            }

            prototypeObj.Freeze();

            return(new JavaScriptProjection
            {
                RefCount = 0,
                Constructor = ctor,
                Prototype = prototypeObj,
                HasInstanceEvents = (baseTypeProjection?.HasInstanceEvents ?? false) || publicInstanceEvents.Any(),
                HasStaticEvents = (baseTypeProjection?.HasStaticEvents ?? false) || publicStaticEvents.Any(),
            });
        }
Пример #12
0
        /// <summary>
        /// Projects the [[iterator]] protocol on IEnumerable objects.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="targetObject"></param>
        /// <param name="reflector"></param>
        private void ProjectIEnumerable(BaristaContext context, JsObject targetObject, ObjectReflector reflector)
        {
            if (typeof(IEnumerable).IsAssignableFrom(reflector.Type))
            {
                var fnIterator = context.CreateFunction(new Func <JsObject, JsValue>((thisObj) => {
                    IEnumerable targetObj = null;

                    if (thisObj == null)
                    {
                        context.CurrentScope.SetException(context.CreateTypeError($"Could not retrieve iterator on object {targetObject.ToString()}: Invalid 'this' context."));
                        return(context.Undefined);
                    }

                    if (thisObj.TryGetBean(out JsExternalObject xoObj))
                    {
                        targetObj = xoObj.Target as IEnumerable;
                    }

                    return(context.CreateIterator(targetObj.GetEnumerator()));
                }));

                var iteratorDescriptor = context.CreateObject();
                iteratorDescriptor.SetProperty("value", fnIterator);
                targetObject.SetProperty(context.Symbol.Iterator, iteratorDescriptor);
            }
        }
Пример #13
0
        private void ProjectEvents(BaristaContext context, JsObject targetObject, ObjectReflector reflector, IDictionary <string, EventInfo> eventsTable)
        {
            if (eventsTable.Count == 0)
            {
                return;
            }

            var fnAddEventListener = context.CreateFunction(new Func <JsObject, string, JsFunction, JsValue>((thisObj, eventName, fnCallback) => {
                if (String.IsNullOrWhiteSpace(eventName))
                {
                    context.CurrentScope.SetException(context.CreateTypeError($"The name of the event listener to register must be specified."));
                    return(context.Undefined);
                }

                object targetObj = null;

                if (thisObj == null)
                {
                    context.CurrentScope.SetException(context.CreateTypeError($"Could not register event listener '{eventName}': Invalid 'this' context."));
                    return(context.Undefined);
                }

                if (thisObj.TryGetBean(out JsExternalObject xoObj))
                {
                    targetObj = xoObj.Target;
                }

                if (!eventsTable.TryGetValue(eventName, out EventInfo targetEvent))
                {
                    return(context.False);
                }

                Action <object[]> invokeListener = (args) =>
                {
                    //TODO: Object conversion.
                    fnCallback.Call(thisObj, null);
                };

                var targetEventMethod     = targetEvent.EventHandlerType.GetMethod("Invoke");
                var targetEventParameters = targetEventMethod.GetParameters().Select(p => Expression.Parameter(p.ParameterType, p.Name)).ToArray();

                var exprInvokeListener = Expression.Lambda(targetEvent.EventHandlerType, Expression.Block(
                                                               Expression.Call(
                                                                   Expression.Constant(invokeListener.Target),
                                                                   invokeListener.Method,
                                                                   Expression.NewArrayInit(typeof(object), targetEventParameters))
                                                               ), targetEventParameters);

                var invokeListenerDelegate = exprInvokeListener.Compile();

                IDictionary <string, IList <Tuple <JsFunction, Delegate> > > eventListeners;
                if (thisObj.HasProperty(BaristaEventListenersPropertyName))
                {
                    var xoListeners = thisObj.GetProperty <JsExternalObject>(BaristaEventListenersPropertyName);
                    eventListeners  = xoListeners.Target as IDictionary <string, IList <Tuple <JsFunction, Delegate> > >;
                }
                else
                {
                    eventListeners = new Dictionary <string, IList <Tuple <JsFunction, Delegate> > >();

                    //Set the listeners as a non-configurable, non-enumerable, non-writable property
                    var xoListeners = context.CreateExternalObject(eventListeners);

                    var baristaEventListenersPropertyDescriptor = context.CreateObject();
                    baristaEventListenersPropertyDescriptor.SetProperty("value", xoListeners);
                    context.Object.DefineProperty(thisObj, context.CreateString(BaristaEventListenersPropertyName), baristaEventListenersPropertyDescriptor);
                }

                if (eventListeners != null)
                {
                    if (eventListeners.ContainsKey(eventName))
                    {
                        eventListeners[eventName].Add(new Tuple <JsFunction, Delegate>(fnCallback, invokeListenerDelegate));
                    }
                    else
                    {
                        eventListeners.Add(eventName, new List <Tuple <JsFunction, Delegate> >()
                        {
                            new Tuple <JsFunction, Delegate>(fnCallback, invokeListenerDelegate)
                        });
                    }
                }

                targetEvent.AddMethod.Invoke(targetObj, new object[] { invokeListenerDelegate });

                return(context.True);
            }), "addEventListener");

            var fnRemoveEventListener = context.CreateFunction(new Func <JsObject, string, JsFunction, JsValue>((thisObj, eventName, eventListener) =>
            {
                if (String.IsNullOrWhiteSpace(eventName))
                {
                    context.CurrentScope.SetException(context.CreateTypeError($"The name of the event listener to remove must be specified."));
                    return(context.Undefined);
                }

                if (eventListener == null)
                {
                    context.CurrentScope.SetException(context.CreateTypeError($"The event listener to remove must be specified."));
                    return(context.Undefined);
                }

                object targetObj = null;

                if (thisObj == null)
                {
                    context.CurrentScope.SetException(context.CreateTypeError($"Could not unregister event listener '{eventName}': Invalid 'this' context."));
                    return(context.Undefined);
                }

                if (thisObj.TryGetBean(out JsExternalObject xoObj))
                {
                    targetObj = xoObj.Target;
                }

                if (!eventsTable.TryGetValue(eventName, out EventInfo targetEvent))
                {
                    return(context.False);
                }

                //Get the event listeners.
                IDictionary <string, IList <Tuple <JsFunction, Delegate> > > eventListeners = null;
                if (thisObj.HasProperty(BaristaEventListenersPropertyName))
                {
                    var xoListeners = thisObj.GetProperty <JsExternalObject>(BaristaEventListenersPropertyName);
                    eventListeners  = xoListeners.Target as IDictionary <string, IList <Tuple <JsFunction, Delegate> > >;
                }

                if (eventListeners == null)
                {
                    return(context.False);
                }

                var hasRemoved = false;
                if (eventListeners.ContainsKey(eventName))
                {
                    var listeners = eventListeners[eventName];
                    var toRemove  = new List <Tuple <JsFunction, Delegate> >();
                    foreach (var listener in listeners)
                    {
                        if (listener.Item1 == eventListener)
                        {
                            targetEvent.RemoveMethod.Invoke(targetObj, new object[] { listener.Item2 });
                            toRemove.Add(listener);
                            hasRemoved = true;
                        }
                    }

                    eventListeners[eventName] = listeners.Where(l => toRemove.Any(tl => tl == l)).ToList();
                }

                return(hasRemoved ? context.True : context.False);
            }), "removeEventListener");

            var fnRemoveAllEventListeners = context.CreateFunction(new Func <JsObject, string, JsValue>((thisObj, eventName) => {
                if (String.IsNullOrWhiteSpace(eventName))
                {
                    context.CurrentScope.SetException(context.CreateTypeError($"The name of the event listener to remove must be specified."));
                    return(context.Undefined);
                }

                object targetObj = null;

                if (thisObj == null)
                {
                    context.CurrentScope.SetException(context.CreateTypeError($"Could not unregister event listener '{eventName}': Invalid 'this' context."));
                    return(context.Undefined);
                }

                if (thisObj.TryGetBean(out JsExternalObject xoObj))
                {
                    targetObj = xoObj.Target;
                }

                if (!eventsTable.TryGetValue(eventName, out EventInfo targetEvent))
                {
                    return(context.False);
                }

                //Get the event listeners.
                IDictionary <string, IList <Tuple <JsFunction, Delegate> > > eventListeners = null;
                if (thisObj.HasProperty(BaristaEventListenersPropertyName))
                {
                    var xoListeners = thisObj.GetProperty <JsExternalObject>(BaristaEventListenersPropertyName);
                    eventListeners  = xoListeners.Target as IDictionary <string, IList <Tuple <JsFunction, Delegate> > >;
                }

                if (eventListeners == null)
                {
                    return(context.False);
                }

                if (eventListeners.ContainsKey(eventName))
                {
                    foreach (var listener in eventListeners[eventName])
                    {
                        targetEvent.RemoveMethod.Invoke(targetObj, new object[] { listener.Item2 });
                    }

                    eventListeners.Remove(eventName);
                }

                return(context.True);
            }), "removeAllEventListeners");

            var addEventListenerFunctionDescriptor = context.CreateObject();

            addEventListenerFunctionDescriptor.SetProperty("enumerable", context.True);
            addEventListenerFunctionDescriptor.SetProperty("value", fnAddEventListener);
            targetObject.SetProperty(context.CreateString("addEventListener"), addEventListenerFunctionDescriptor);

            var removeEventListenerFunctionDescriptor = context.CreateObject();

            removeEventListenerFunctionDescriptor.SetProperty("enumerable", context.True);
            removeEventListenerFunctionDescriptor.SetProperty("value", fnRemoveEventListener);
            targetObject.SetProperty(context.CreateString("removeEventListener"), removeEventListenerFunctionDescriptor);

            var removeAllEventListenersFunctionDescriptor = context.CreateObject();

            removeAllEventListenersFunctionDescriptor.SetProperty("enumerable", context.True);
            removeAllEventListenersFunctionDescriptor.SetProperty("value", fnRemoveAllEventListeners);
            targetObject.SetProperty(context.CreateString("removeAllEventListeners"), removeAllEventListenersFunctionDescriptor);
        }
Пример #14
0
        private void ProjectMethods(BaristaContext context, JsObject targetObject, ObjectReflector reflector, IDictionary <string, IList <MethodInfo> > methods)
        {
            foreach (var method in methods)
            {
                var methodName  = method.Key;
                var methodInfos = method.Value;

                var fn = context.CreateFunction(new BaristaFunctionDelegate((calleeObj, isConstructCall, thisObj, args) =>
                {
                    object targetObj = null;

                    if (thisObj == null)
                    {
                        context.CurrentScope.SetException(context.CreateTypeError($"Could not call function '{methodName}': Invalid 'this' context."));
                        return(context.Undefined);
                    }

                    if (thisObj.TryGetBean(out JsExternalObject xoObj))
                    {
                        targetObj = xoObj.Target;
                    }

                    try
                    {
                        var bestMethod = reflector.GetMethodBestMatch(methodInfos, args);
                        if (bestMethod == null)
                        {
                            var ex = context.CreateTypeError($"Failed to call function '{methodName}': Could not find a matching function for the provided arguments.");
                            context.CurrentScope.SetException(ex);
                            return(context.Undefined);
                        }

                        //Convert the args into the native args of the method.
                        var methodParams  = bestMethod.GetParameters();
                        var convertedArgs = ConvertArgsToParamTypes(context, args, methodParams);

                        var result = bestMethod.Invoke(targetObj, convertedArgs);
                        if (context.Converter.TryFromObject(context, result, out JsValue resultValue))
                        {
                            return(resultValue);
                        }
                        else
                        {
                            context.CurrentScope.SetException(context.CreateTypeError($"The call to '{methodName}' was successful, but the result could not be converted into a JavaScript object."));
                            return(context.Undefined);
                        }
                    }
                    catch (Exception ex)
                    {
                        context.CurrentScope.SetException(context.CreateError(ex.Message));
                        return(context.Undefined);
                    }
                }));

                var functionDescriptor = context.CreateObject();

                if (methodInfos.All(mi => BaristaPropertyAttribute.GetAttribute(mi).Configurable))
                {
                    functionDescriptor.SetProperty("configurable", context.True);
                }
                if (methodInfos.All(mi => BaristaPropertyAttribute.GetAttribute(mi).Enumerable))
                {
                    functionDescriptor.SetProperty("enumerable", context.True);
                }
                if (methodInfos.All(mi => BaristaPropertyAttribute.GetAttribute(mi).Writable))
                {
                    functionDescriptor.SetProperty("writable", context.True);
                }

                functionDescriptor.SetProperty("value", fn);

                targetObject.SetProperty(context.CreateString(methodName), functionDescriptor);
            }
        }
Пример #15
0
        public bool TryCreatePrototypeFunction(BaristaContext context, Type typeToConvert, out JsFunction ctor)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (typeToConvert == null)
            {
                throw new ArgumentNullException(nameof(typeToConvert));
            }

            if (m_prototypes.ContainsKey(typeToConvert))
            {
                ctor = m_prototypes[typeToConvert];
                return(true);
            }

            var reflector = new ObjectReflector(typeToConvert);

            JsFunction superCtor = null;
            var        baseType  = reflector.GetBaseType();

            if (baseType != null && !baseType.IsSameOrSubclass(typeof(JsValue)) && TryCreatePrototypeFunction(context, baseType, out JsFunction fnSuper))
            {
                superCtor = fnSuper;
            }

            var objectName = BaristaObjectAttribute.GetBaristaObjectNameFromType(typeToConvert);

            //Get all the property descriptors for the specified type.
            var staticPropertyDescriptors   = context.CreateObject();
            var instancePropertyDescriptors = context.CreateObject();

            //Get static and instance properties.
            ProjectProperties(context, staticPropertyDescriptors, reflector.GetProperties(false));
            ProjectProperties(context, instancePropertyDescriptors, reflector.GetProperties(true));

            //Get static and instance indexer properties.
            ProjectIndexerProperties(context, staticPropertyDescriptors, reflector.GetIndexerProperties(false));
            ProjectIndexerProperties(context, instancePropertyDescriptors, reflector.GetIndexerProperties(true));

            //Get static and instance methods.
            ProjectMethods(context, staticPropertyDescriptors, reflector, reflector.GetUniqueMethodsByName(false));
            ProjectMethods(context, instancePropertyDescriptors, reflector, reflector.GetUniqueMethodsByName(true));

            //Get static and instance events.
            ProjectEvents(context, staticPropertyDescriptors, reflector, reflector.GetEventTable(false));
            ProjectEvents(context, instancePropertyDescriptors, reflector, reflector.GetEventTable(true));

            //Get the [[iterator]] property.
            ProjectIEnumerable(context, instancePropertyDescriptors, reflector);

            JsFunction fnCtor;
            var        publicConstructors = reflector.GetConstructors();

            if (publicConstructors.Any())
            {
                fnCtor = context.CreateFunction(new BaristaFunctionDelegate((calleeObj, isConstructCall, thisObj, args) =>
                {
                    if (thisObj == null)
                    {
                        var ex = context.CreateTypeError($"Failed to construct '{objectName}': 'this' must be specified.");
                        context.CurrentScope.SetException(ex);
                        return(context.Undefined);
                    }

                    if (superCtor != null)
                    {
                        superCtor.Call(thisObj);
                    }

                    context.Object.DefineProperties(thisObj, instancePropertyDescriptors);

                    //If this isn't a construct call, don't attempt to set the bean
                    if (!isConstructCall)
                    {
                        return(thisObj);
                    }

                    //Set our native object.
                    JsExternalObject externalObject = null;

                    //!!Special condition -- if there's exactly one argument, and if it matches the enclosing type,
                    //don't invoke the type's constructor, rather, just wrap the object with the JsObject.
                    if (args.Length == 1 && args[0].GetType() == typeToConvert)
                    {
                        externalObject = context.CreateExternalObject(args[0]);
                    }
                    else
                    {
                        try
                        {
                            var bestConstructor = reflector.GetConstructorBestMatch(args);
                            if (bestConstructor == null)
                            {
                                var ex = context.CreateTypeError($"Failed to construct '{objectName}': Could not find a matching constructor for the provided arguments.");
                                context.CurrentScope.SetException(ex);
                                return(context.Undefined);
                            }

                            //Convert the args into the native args of the constructor.
                            var constructorParams = bestConstructor.GetParameters();
                            var convertedArgs     = ConvertArgsToParamTypes(context, args, constructorParams);

                            var newObj     = bestConstructor.Invoke(convertedArgs);
                            externalObject = context.CreateExternalObject(newObj);
                        }
                        catch (Exception ex)
                        {
                            context.CurrentScope.SetException(context.CreateError(ex.Message));
                            return(context.Undefined);
                        }
                    }

                    thisObj.SetBean(externalObject);

                    return(thisObj);
                }), objectName);
            }
            else
            {
                fnCtor = context.CreateFunction(new BaristaFunctionDelegate((calleeObj, isConstructCall, thisObj, args) =>
                {
                    var ex = context.CreateTypeError($"Failed to construct '{objectName}': This object cannot be constructed.");
                    context.CurrentScope.SetException(ex);
                    return(context.Undefined);
                }), objectName);
            }

            //We've got everything we need.
            fnCtor.Prototype = context.Object.Create(superCtor == null ? context.Object.Prototype : superCtor.Prototype);

            context.Object.DefineProperties(fnCtor, staticPropertyDescriptors);

            m_prototypes.Add(typeToConvert, fnCtor);
            ctor = fnCtor;
            return(true);
        }
Пример #16
0
        public static bool NotIn <T>(object input, string column, List <T> o, Func <T, object> fn)
        {
            var refl = new ObjectReflector(input);

            return(o.Any(item => fn(item) == refl[column]));
        }
 public void BuildAggregateObject(BDadosTransaction transaction,
                                  Type t, IDataReader reader, ObjectReflector refl,
                                  object obj, Dictionary <string, (int[], string[])> fieldNamesDict, JoiningTable[] joinTables, IDictionary <int, Relation[]> joinRelations,