Пример #1
0
        private static bool CheckExtensionMethods(Type[] types, AutoWrap autoWrap, string methodName, object[] parameters,
                                                  out object result)
        {
            result = null;
            if (types.Length == 0)
            {
                return(false);
            }

            var args = new object[parameters.Length + 1];

            Array.Copy(parameters, 0, args, 1, parameters.Length);
            args[0] = autoWrap.Object;
            foreach (var type in types)
            {
                try
                {
                    var method = InformationOnTheTypes.FindMethod(type, true, methodName, args);
                    if (method != null)
                    {
                        result = method.ExecuteMethod(null, args);
                        Array.Copy(args, 1, parameters, 0, parameters.Length);

                        return(true);
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            return(false);
        }
Пример #2
0
        public static bool ExecuteGenericMethod(object obj, Type type, string methodName, bool isStatic, Type[] arguments, Type[] variableType, object[] parameters, out object result)
        {
            result = null;

            var res = InformationOnTheTypes.FindGenericMethodsWithGenericArguments(type, isStatic, methodName, arguments, variableType);

            if (res == null)
            {
                return(false);
            }

            try
            {
                result = res.Invoke(obj, parameters);

                if (result != null && res.ReturnType.GetTypeInfo().IsInterface)
                {
                    result = new AutoWrap(result, res.ReturnType);
                }
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
Пример #3
0
        public bool TryInvokeMember(string name, object[] argsOrig, out object result, List <int> changedParameters, out string error)
        {
            error = null;
            if (IndexInStorage == 0 && name == "ОчиститьСсылку")
            {
                if (argsOrig[0] is AutoWrap temp)
                {
                    ObjectsList.RemoveKey(temp.IndexInStorage);
                }
                result = null;
                return(true);
            }

            result = null;
            object[] args = GetArrayRealObjects(argsOrig);

            try
            {
                object obj;
                if (IsDynamic)
                {
                    obj = DynamicInvoker.InvokeMember(Object, name, args);
                }
                else
                {
                    var method = InformationOnTheTypes.FindMethod(Type, IsType, name, args);

                    if (method == null)
                    {
                        if (name == "_as")
                        {
                            obj = NetObjectToNative.GetInterface(Object, args[0]);
                        }
                        else if (!ExtensionMethod.ExecuteExtensionMethod(this, name, args, out obj) &&
                                 !ExecuteInterfaceMethodAsObject(name, args, out obj, ref error))
                        {
                            error += " Не найден метод " + name;
                            return(false);
                        }
                    }
                    else
                    {
                        obj = method.ExecuteMethod(IsType ? null : Object, args);
                    }
                }
                SetChangeInArgs(argsOrig, args, changedParameters);
                result = obj;
            }
            catch (Exception e)
            {
                error = GetExceptionString("методе", name, e);

                return(false);
            }

            // Так как параметры могут изменяться (OUT) и передаются по ссылке
            // нужно обратно обернуть параметры

            return(true);
        }
Пример #4
0
        public bool TrySetMember(string name, object valueOrig, out string error)
        {
            error = null;
            object value = GetRalObject(valueOrig);

            try
            {
                if (IsDynamic)
                {
                    DynamicInvoker.SetValue(Object, name, value);
                    return(true);
                }

                var property = InformationOnTheTypes.FindProperty(Type, name);
                if (property == null)
                {
                    if (!FindInterfacePropertyAsObject(name, out property))
                    {
                        error = "Не найдено Свойство " + name;
                        return(false);
                    }
                }

                property.SetValue(Object, value);

                return(true);
            }
            catch (Exception e)
            {
                error = GetExceptionString("установки свойства", name, e);
            }
            return(false);
        }
Пример #5
0
        private bool ExecuteInterfaceMethodAsObject(string name, object[] args, out object result, ref string Error)
        {
            result = null;
            Error  = null;
            if (!(IsType || Type.GetTypeInfo().IsInterface))
            {
                return(false);
            }

            RpcMethodInfo method = InformationOnTheTypes.FindMethod(Object.GetType(), false, name, args);

            if (method == null)
            {
                return(false);
            }

            try
            {
                result = method.ExecuteMethod(Object, args);
                return(true);
            }
            catch (Exception e)
            {
                Error += GetExceptionString("методе", name, e);
            }
            return(false);
        }
Пример #6
0
        public RpcMethodInfo(RpcMethodInfo methodInfo, int parametersCount)
        {
            Method          = methodInfo.Method;
            ParametersCount = parametersCount;
            ParamsCount     = methodInfo.ParametersCount;
            ReturnType      = methodInfo.ReturnType;

            Parameters = new RpcTypeInfo[parametersCount];

            var count = methodInfo.HasDefaultValue ? parametersCount : ParamsCount - 1;

            for (int i = 0; i < count; i++)
            {
                Parameters[i] = methodInfo.Parameters[i];
            }

            if (methodInfo.HasDefaultValue)
            {
                HasDefaultValue    = true;
                FirstDefaultParams = methodInfo.FirstDefaultParams;
                return;
            }

            HasParams   = true;
            TypeParams  = methodInfo.TypeParams;
            ElementType = methodInfo.ElementType;

            var rpcTypeInfo = InformationOnTheTypes.GetTypeInformation(methodInfo.TypeParams);

            for (int i = ParamsCount - 1; i < parametersCount; i++)
            {
                Parameters[i] = rpcTypeInfo;
            }
        }
        // Ищет Дженерик метод по дженерик аргументам и типам параметров
        // Пример использования
        //ТипыПараметров=ъ(Врап.ТипМассив(IParentNode.ПолучитьСсылку(),String.ПолучитьСсылку()));
        // ТипыАргументов=ъ(Врап.ТипМассив(IHtmlAnchorElement.ПолучитьСсылку()));
        ////public static TElement QuerySelector<TElement>(this IParentNode parent, string selectors) where TElement : class, IElement;
        //стр=Врап.FindGenericMethod(ApiExtensions.ПолучитьСсылку(),true,"QuerySelector",ТипыАргументов.ПолучитьСсылку(),ТипыПараметров.ПолучитьСсылку());
        //QuerySelector_AnchorElement = ъ(стр);

        public static RpcMethodInfo FindGenericMethod(Type type, bool isStatic, string methodName, Type[] genericParameters, Type[] methodParameters)
        {
            var res = InformationOnTheTypes.FindGenericMethodsWithGenericArguments(type, isStatic, methodName, genericParameters, methodParameters);

            if (res == null)
            {
                //  AutoWrap.СообщитьОбОшибке("Не найден метод "+ methodName);
                throw new Exception("Не найден метод " + methodName);
            }
            return(res);
        }
        // Возвращает делегат для вызова внешнего события в 1С
        // Пример использования
        //Делегат=Ъ(Врап.ПолучитьДелегатВнешнегоСобытия1C());
        // У объекта Тест есть поле
        //  public Action<string, string, string> ВнешнееСобытие1С;
        // Которое мы установим
        //Тест.ВнешнееСобытие1С=Делегат.ПолучитьСсылку();
        // И ктоторое может быть вызвано при возникновении события
        // ВнешнееСобытие1С?.DynamicInvoke("Тестовый", "ТестовоеСообщение", значение);

        private static IPropertyOrFieldInfo FindProperty(object obj, string delegateName)
        {
            var T        = obj.GetType();
            var property = InformationOnTheTypes.FindProperty(T, delegateName);

            if (property == null)
            {
                throw new Exception("Не найдено Делегат  " + delegateName);
            }

            return(property);
        }
Пример #9
0
        private static Type[] FindType(Type[] types, Type extendedType, string methodName, Func <MethodInfo, bool> filter = null)
        {
            var query = from type in types
                        let typeInfo = type.GetTypeInfo()
                                       where typeInfo.IsSealed && typeInfo.IsAbstract
                                       let synonym = InformationOnTheTypes.GetMethodNameBySynonym(type, methodName)
                                                     from method in typeInfo.GetMethods()
                                                     where method.IsStatic && method.IsDefined(typeof(ExtensionAttribute), false) &&
                                                     method.Name == synonym && (filter?.Invoke(method) ?? true)
                                                     let parameterType = method.GetParameters()[0].ParameterType
                                                                         where (parameterType.IsAssignableFrom(extendedType) ||
                                                                                GenericMethodData.IsSuit(parameterType, extendedType))
                                                                         select type;

            return(query.Distinct().ToArray());
        }
Пример #10
0
        private bool FindInterfacePropertyAsObject(string name, out IPropertyOrFieldInfo result)
        {
            result = null;

            if (!(IsType || Type.GetTypeInfo().IsInterface))
            {
                return(false);
            }

            result = InformationOnTheTypes.FindProperty(Object.GetType(), name);

            if (result == null)
            {
                return(false);
            }

            return(true);
        }
Пример #11
0
        public RpcMethodInfo(MethodInfo methodInfo)
        {
            Method = methodInfo;

            ParameterInfo[] parameters = Method.GetParameters();
            HasParams       = false;
            ParametersCount = parameters.Length;
            ParamsCount     = 0;
            if (ParametersCount > 0)
            {
                HasParams = parameters[parameters.Length - 1].GetCustomAttributes(typeof(ParamArrayAttribute), false).GetEnumerator().MoveNext();
            }

            if (HasParams)
            {
                TypeParams  = parameters[parameters.Length - 1].ParameterType.GetElementType();
                ElementType = InformationOnTheTypes.GetTypeInformation(TypeParams);
            }

            Parameters = new RpcTypeInfo[ParametersCount];

            for (int i = 0; i < parameters.Length; i++)
            {
                var param = parameters[i];
                Parameters[i] = InformationOnTheTypes.GetTypeInformation(param.ParameterType);

                if (!HasDefaultValue && param.HasDefaultValue)
                {
                    HasDefaultValue = true;

                    FirstDefaultParams = i;
                }
            }

            IsGeneric = methodInfo.IsGenericMethod && methodInfo.IsGenericMethodDefinition;

            if (IsGeneric)
            {
                GenericMethod = new GenericMethodData(Method, Parameters);
            }
            ReturnType = methodInfo.ReturnType.GetTypeInfo().IsInterface ? methodInfo.ReturnType : null;
        }
Пример #12
0
        public static void CallAsyncFunc(BinaryReader br, BinaryWriter bw, IPAddress address)
        {
            if (!CallAsFuncAll(br, bw, out var result, false))
            {
                return;
            }
            try
            {
                var taskId   = new Guid(br.ReadBytes(16));
                var port     = br.ReadInt32();
                var typeInfo = result.GetType().GetTypeInfo();

                var asyncCallBack = new TcpAsyncCallBack(taskId, address, port);
                var callBack      = new Action <bool, object>(asyncCallBack.SendAsyncMessage);
                if (!typeInfo.IsGenericType)
                {
                    AsyncRunner.TaskExecute((Task)result, callBack);
                    return;
                }

                var args   = new[] { result, callBack };
                var method = InformationOnTheTypes.FindMethod(typeof(AsyncRunner), true, "Execute", args);

                if (method == null)
                {
                    SetError("Неверный результат", bw);
                    return;
                }

                method.ExecuteMethod(null, args);
            }
            catch (Exception e)
            {
                SetError(AutoWrap.GetExceptionString("Ошибка вызова делегата", "", e), bw);
                return;
            }

            bw.Write(true);
            WorkWithVariant.WriteObject(null, bw);
        }
Пример #13
0
        // получение свойства
        public bool TryGetMember(string name, out object result, out string error)
        {
            result = null;
            error  = null;
            try
            {
                if (IsDynamic)
                {
                    result = DynamicInvoker.GetValue(Object, name);
                    return(true);
                }

                if (IsEnum)
                {
                    result = Enum.Parse(Type, name);
                    return(true);
                }

                var property = InformationOnTheTypes.FindProperty(Type, name);
                if (property == null)
                {
                    if (!FindInterfacePropertyAsObject(name, out property))
                    {
                        error = "Не найдено Свойство " + name;
                        return(false);
                    }
                }

                result = property.GetValue(Object);

                return(true);
            }
            catch (Exception e)
            {
                error = GetExceptionString("получения свойства", name, e);
            }
            result = null;
            return(false);
        }
Пример #14
0
        private static void CallStaticMethod(BinaryWriter bw, Type T, string methodName, object[] args)
        {
            try
            {
                var method = InformationOnTheTypes.FindMethod(T, true, methodName, args);

                if (method == null)
                {
                    SetError($"Нет найден метод  {method} для типа {T}", bw);
                    return;
                }

                var obj = method.ExecuteMethod(null, args);

                bw.Write(true);
                WorkWithVariant.WriteObject(AutoWrap.WrapObject(obj), bw);
                bw.Write((int)0);
            }
            catch (Exception e)
            {
                SetError(AutoWrap.GetExceptionString("Ошибка бинарной операции ", "", e), bw);
            }
        }
Пример #15
0
        public static bool CallAsGenericFuncAll(BinaryReader br, BinaryWriter bw, out object result, bool writeResult)
        {
            result = null;;
            if (!GetAW(br, bw, out var autoWrap))
            {
                return(false);
            }

            string methodName = br.ReadString();
            var    arguments  = GetArrayParams(br);
            var    Params     = GetArrayParams(br);

            // Можно параметры передавать ввиде типов и строк
            var genericArguments = new Type[arguments.Length];

            for (int i = 0; i < genericArguments.Length; i++)
            {
                genericArguments[i] = NetObjectToNative.FindTypeForCreateObject(arguments[i]);
            }

            result = null;
            var typesOfParameters = AllMethodsForName.GetTypesParameters(Params);
            var res = InformationOnTheTypes.FindGenericMethodsWithGenericArguments(
                autoWrap.Type,
                autoWrap.IsType,
                methodName,
                genericArguments,
                typesOfParameters);

            if (res == null)
            {
                SetError("Не найден дженерик метод " + methodName, bw);
                return(false);
            }

            try
            {
                var copyParams = new object[Params.Length];
                Params.CopyTo(copyParams, 0);

                var obj = autoWrap.IsType ? null : autoWrap.Object;
                result = res.ExecuteMethod(obj, copyParams);

                var returnType = res.Method.ReturnType;

                if (result != null && returnType.GetTypeInfo().IsInterface)
                {
                    result = new AutoWrap(result, returnType);
                }

                if (writeResult)
                {
                    bw.Write(true);
                    WorkWithVariant.WriteObject(AutoWrap.WrapObject(result), bw);
                    WriteChangeParams(bw, copyParams, AutoWrap.GetChangeParams(Params, copyParams));
                }
            }
            catch (Exception e)
            {
                SetError(AutoWrap.GetExceptionString($"Ошибка вызова Дженерик метода {methodName}", "", e), bw);
                return(false);
            }

            return(true);
        }
        // Добавляет синоним дле метода
        //Assembly=ъ(СборкаHttpClient.GetType());
        // Врап.AddSynonym(Assembly.ПолучитьСсылку(),"type","GetType");
        // Теперь вмето GetType можно использовать type
        //HttpClient=ъ(СборкаHttpClient.type("System.Net.Http.HttpClient"));

        public static void AddSynonym(object type, string synonym, string methodName) =>
        InformationOnTheTypes.SetSynonym(FindTypeForCreateObject(type), synonym, methodName);