예제 #1
0
 protected async Task DeregisterMethod <TParam, TResult>(MethodProvider <TParam, TResult> method)
 {
     await CallControlMethod <Deregister, Empty>("method.deregister", new Deregister()
     {
         EndPoint = method.Endpoint.ToString()
     });
 }
예제 #2
0
        /// <summary>Any types derived from a type with a custom initializer must itself have a custom initialzier.</summary>
        public static void CheckForDerivedCustomInitializers(MethodProvider initializerMethods,
                                                             HashSet <Type> referenceTypes, StreamWriter errors)
        {
            foreach (var type in referenceTypes)
            {
                Debug.Assert(!type.IsValueType);
                Debug.Assert(!type.IsInterface);

                if (initializerMethods.GetMethodForType(type) != null)
                {
                    continue;                     // Type has a custom initializer
                }
                var baseType = type.BaseType;
                while (baseType != null && baseType != typeof(object))
                {
                    if (initializerMethods.GetMethodForType(baseType) != null)
                    {
                        errors.WriteLine("ERROR: Type " + type + " is drived from type " + baseType +
                                         " with a custom initializer!");
                        errors.WriteLine("  Add a [CustomInitializer] for " + type);
                        errors.WriteLine();
                        goto nextType;
                    }

                    baseType = baseType.BaseType;                     // <- walk up inheritance hierarchy
                }

                nextType :;
            }
        }
예제 #3
0
 public ILGenContext(Direction direction, MethodProvider fieldSerializeMethods,
                     MethodProvider referenceTypeSerializeMethods)
 {
     this.direction                    = direction;
     fieldSerializationMethods         = fieldSerializeMethods;
     referenceTypeSerializationMethods = referenceTypeSerializeMethods;
 }
예제 #4
0
        private static Expression CreateAnyAllExpression(
            Expression left,
            Expression right,
            ParameterExpression sourceParameter,
            IEnumerable <ParameterExpression> lambdaParameters,
            MethodInfo anyAllMethod)
        {
            var genericFunc = typeof(Func <,>)
                              .MakeGenericType(
                MethodProvider.GetIEnumerableImpl(left.Type).GetGenericArguments()[0],
                typeof(bool));

            var filteredParameters = new ParameterVisitor()
                                     .GetParameters(right)
                                     .Where(p => p.Name != sourceParameter.Name)
                                     .ToArray();

            if (!filteredParameters.Any())
            {
                filteredParameters = lambdaParameters.ToArray();
            }

            return(Expression.Call(
                       anyAllMethod,
                       left,
                       Expression.Lambda(genericFunc, right, filteredParameters)));
        }
예제 #5
0
        public void TestInitialize()
        {
            ExpressionEqualityComparer = new ExpressionEqualityComparer();

            var methods = typeof(SqlFunctions).GetMethods().Where(x => x.Name == "StringConvert").ToArray();

            MethodProvider.UserFunctions.Clear();

            MethodProvider.RegisterFunction("StringConvert", methods);
        }
예제 #6
0
        public ActionResult IndexAll([Bind(Include = "yacimiento,campo, yacimientos,campos,procesados,metodo")] PozosView datamodel, int page = 0, int checkpozoid = 0, int metodo = 0, int?flow = 0)
        {
            int pageindex = page;
            var pagesize  = 12;

            if (flow == 5)
            {
                if (datamodel.metodo == 1)
                {
                    return(RedirectToAction("SorGraph2", "Pozos", datamodel));
                }
                else
                {
                    return(RedirectToAction("SorGraph", "Pozos", datamodel));
                }
            }

            datamodel.procesados = true;
            var campos_Qry = db.cat_campo.ToList().OrderBy(o => o.campo);

            datamodel.campos = new SelectList(campos_Qry, "id_campo", "campo", datamodel.campo);
            if (datamodel.campo == 0)
            {
                datamodel.campo = campos_Qry.FirstOrDefault().id_campo;
            }
            if (datamodel.yacimiento == 0)
            {
                datamodel.yacimiento = db.cat_yacimiento.Where(y => y.id_campo == datamodel.campo).FirstOrDefault().id_yacimiento;
            }

            var yacimientos_Qry = db.cat_yacimiento.Where(w => w.id_campo == datamodel.campo).ToList().OrderBy(o => o.yacimiento);

            if (yacimientos_Qry.Where(y => y.id_yacimiento == datamodel.yacimiento).Count() == 0)
            {
                datamodel.yacimiento = yacimientos_Qry.FirstOrDefault().id_yacimiento;
            }
            datamodel.yacimientos = new SelectList(yacimientos_Qry, "id_yacimiento", "yacimiento", datamodel.yacimiento);
            var detalles = new List <PozosViewDetail>();

            Services.Set(MethodProvider.Get(datamodel.metodo));
            detalles = GetDetalles(datamodel.campo, datamodel.yacimiento, datamodel.procesados).ToList();

            if (pageindex == 0)
            {
                pageindex = 1;
            }
            if ((datamodel.yacimiento != (int?)Session["yacimiento"]) || (datamodel.procesados != (bool?)Session["procesado"]))
            {
                pageindex = 1;
            }
            datamodel.Preguntas = Preguntas.Where(w => w.Metodo == metodo).ToList();
            datamodel.Detalle   = detalles.ToPagedList(pageindex, pagesize);
            ViewBag.SubTitle    = "Inferencia del Método";
            return(View(datamodel));
        }
예제 #7
0
        private Expression GetAnyAllFunctionExpression <T>(string filter, ParameterExpression sourceParameter,
                                                           ICollection <ParameterExpression> lambdaParameters,
                                                           IFormatProvider formatProvider)
        {
            if (filter == null)
            {
                throw new ArgumentNullException("filter");
            }

            if (sourceParameter == null)
            {
                throw new ArgumentNullException("sourceParameter");
            }

            if (lambdaParameters == null)
            {
                throw new ArgumentNullException("lambdaParameters");
            }

            var functionTokens = filter.GetAnyAllFunctionTokens();

            if (functionTokens == null)
            {
                return(null);
            }

            var propertyExpression = GetPropertyExpression <T>(functionTokens.Left, sourceParameter, lambdaParameters);
            var leftType           = propertyExpression.Type;
            var left = CreateExpression <T>(
                functionTokens.Left,
                sourceParameter,
                lambdaParameters,
                leftType,
                formatProvider);

            // Create a new ParameterExpression from the lambda parameter and add to a collection to pass around
            var parameterName =
                functionTokens.Right.Substring(0, functionTokens.Right.IndexOf(":", System.StringComparison.Ordinal)).Trim();
            var lambdaParameter =
                Expression.Parameter(MethodProvider.GetIEnumerableImpl(leftType).GetGenericArguments()[0], parameterName);

            lambdaParameters.Add(lambdaParameter);
            var lambdaFilter =
                functionTokens.Right.Substring(functionTokens.Right.IndexOf(":", System.StringComparison.Ordinal) + 1).Trim();
            var lambdaType = GetFunctionParameterType(functionTokens.Operation) ?? left.Type;

            var isLambdaAnyAllFunction = lambdaFilter.GetAnyAllFunctionTokens() != null;
            var right = isLambdaAnyAllFunction
                    ? GetAnyAllFunctionExpression <T>(lambdaFilter, lambdaParameter, lambdaParameters, formatProvider)
                    : CreateExpression <T>(lambdaFilter, sourceParameter, lambdaParameters, lambdaType, formatProvider);

            return(left == null
               ? null
               : GetFunction(functionTokens.Operation, left, right, sourceParameter, lambdaParameters));
        }
예제 #8
0
        public override Expression Output(OneToManyQueryDetailWalkInfo walkInfo)
        {
            var expression = BuildWhereExpression(walkInfo);

            expression = BuildOrderExpression(expression, walkInfo);
            expression = BuildSelectExpression(expression, walkInfo);

            var toListMethod = MethodProvider.MakeGenericMethod(typeof(Enumerable), "ToList",
                                                                new Type[] { typeof(IEnumerable <>) },
                                                                new Type[] { walkInfo.Type });

            return(Expression.Call(toListMethod, expression));
        }
예제 #9
0
        private Expression BuildSelectExpression(Expression expression, OneToManyQueryDetailWalkInfo walkInfo)
        {
            var memberInitializationExpression = Expression.Lambda(
                typeof(Func <,>).MakeGenericType(walkInfo.Type, walkInfo.Type),
                BuildMemberInitExpression(),
                walkInfo.Member as ParameterExpression);

            var selectMethod = MethodProvider.MakeGenericMethod(typeof(Enumerable), "Select",
                                                                new Type[] { typeof(IEnumerable <>), typeof(Func <,>) },
                                                                new Type[] { walkInfo.Type, walkInfo.Type });

            return(Expression.Call(
                       selectMethod,
                       expression ?? walkInfo.DetailMember,
                       memberInitializationExpression));
        }
 public SerializationMethodProviders(
     MethodProvider valueTypeSerializeMethods,
     MethodProvider valueTypeDeserializeMethods,
     MethodProvider referenceTypeSerializeMethods,
     MethodProvider referenceTypeDeserializeMethods,
     MethodProvider referenceFieldSerializeMethods,
     MethodProvider referenceFieldDeserializeMethods,
     MethodProvider referenceTypeInitializeMethods)
 {
     ValueTypeSerializeMethods        = valueTypeSerializeMethods;
     ValueTypeDeserializeMethods      = valueTypeDeserializeMethods;
     ReferenceTypeSerializeMethods    = referenceTypeSerializeMethods;
     ReferenceTypeDeserializeMethods  = referenceTypeDeserializeMethods;
     ReferenceFieldSerializeMethods   = referenceFieldSerializeMethods;
     ReferenceFieldDeserializeMethods = referenceFieldDeserializeMethods;
     ReferenceTypeInitializeMethods   = referenceTypeInitializeMethods;
 }
예제 #11
0
        private Expression BuildWhereExpression(OneToManyQueryDetailWalkInfo walkInfo)
        {
            var filterExpression = BuildFilterExpression(walkInfo);

            if (filterExpression != null)
            {
                var whereMethod = MethodProvider.MakeGenericMethod(typeof(Enumerable), "Where",
                                                                   new Type[] { typeof(IEnumerable <>), typeof(Func <,>) },
                                                                   new Type[] { walkInfo.Type });

                return(Expression.Call(
                           whereMethod,
                           walkInfo.DetailMember,
                           filterExpression));
            }

            return(null);
        }
예제 #12
0
        private void updateRecord(int?metodo, ResultadoCuestionario newrecord, action actionUpd)
        {
            decimal sor = MethodProvider.Get(metodo.Value).getSor(newrecord.IdPozo);

            newrecord.GetType().GetProperty("sor" + (metodo).ToString()).SetValue(newrecord, sor);

            if (actionUpd == action.Add)
            {
                newrecord.included = true;
                db.ResultadoCuestionarios.Add(newrecord);
            }
            if (actionUpd == action.Update)
            {
                db.ResultadoCuestionarios.Attach(newrecord);
                db.Entry(newrecord).State = System.Data.Entity.EntityState.Modified;
            }

            db.SaveChanges();
        }
        private Expression GetAnyAllFunctionExpression <T>(string filter, ParameterExpression sourceParameter, ICollection <ParameterExpression> lambdaParameters, IFormatProvider formatProvider)
        {
            CustomContract.Requires(filter != null);
            CustomContract.Requires(sourceParameter != null);
            CustomContract.Requires(lambdaParameters != null);

            var functionTokens = filter.GetAnyAllFunctionTokens();

            if (functionTokens == null)
            {
                return(null);
            }

            var propertyExpression = GetPropertyExpression <T>(functionTokens.Left, sourceParameter, lambdaParameters);
            var leftType           = propertyExpression.Type;
            var left = CreateExpression <T>(
                functionTokens.Left,
                sourceParameter,
                lambdaParameters,
                leftType,
                formatProvider);

            // Create a new ParameterExpression from the lambda parameter and add to a collection to pass around
            var parameterName   = functionTokens.Right.Substring(0, functionTokens.Right.IndexOf(":", StringComparison.CurrentCultureIgnoreCase)).Trim();
            var lambdaParameter =
                Expression.Parameter(MethodProvider.GetIEnumerableImpl(leftType).GetGenericArguments()[0], parameterName);

            lambdaParameters.Add(lambdaParameter);
            var lambdaFilter = functionTokens.Right.Substring(functionTokens.Right.IndexOf(":", StringComparison.CurrentCultureIgnoreCase) + 1).Trim();
            var lambdaType   = GetFunctionParameterType(functionTokens.Operation)
                               ?? (left != null ? left.Type : null);

            var isLambdaAnyAllFunction = lambdaFilter.GetAnyAllFunctionTokens() != null;
            var right = isLambdaAnyAllFunction
                                ? GetAnyAllFunctionExpression <T>(lambdaFilter, lambdaParameter, lambdaParameters, formatProvider)
                                : CreateExpression <T>(lambdaFilter, sourceParameter, lambdaParameters, lambdaType, formatProvider);

            return(left == null
                                ? null
                                : GetFunction(functionTokens.Operation, left, right, sourceParameter, lambdaParameters));
        }
예제 #14
0
        private static Expression CreateAnyAllExpression(
            Expression left,
            Expression right,
            ParameterExpression sourceParameter,
            IEnumerable <ParameterExpression> lambdaParameters,
            MethodInfo anyAllMethod)
        {
            if (left == null)
            {
                throw new ArgumentNullException("left");
            }

            if (right == null)
            {
                throw new ArgumentNullException("right");
            }

            var genericFunc = typeof(Func <,>)
                              .MakeGenericType(
                MethodProvider.GetIEnumerableImpl(left.Type).GetGenericArguments()[0],
                typeof(bool));

            var filteredParameters = new ParameterVisitor()
                                     .GetParameters(right)
                                     .Where(p => p.Name != sourceParameter.Name)
                                     .ToArray();

            if (filteredParameters.Length > 0)
            {
                return(Expression.Call(
                           anyAllMethod,
                           left,
                           Expression.Lambda(genericFunc, right, filteredParameters)));
            }

            return(Expression.Call(
                       MethodProvider.GetAnyAllMethod("All", left.Type),
                       left,
                       Expression.Lambda(genericFunc, right, lambdaParameters)));
        }
예제 #15
0
        private static Expression GetFunction(string function, Expression left, Expression right,
                                              ParameterExpression sourceParameter,
                                              IEnumerable <ParameterExpression> lambdaParameters)
        {
            if (function == null)
            {
                throw new ArgumentNullException("function");
            }

            if (left == null)
            {
                throw new ArgumentNullException("left");
            }

            switch (function.ToLowerInvariant())
            {
            case "substringof":
                return(Expression.Call(right, MethodProvider.ContainsMethod, new[] { left }));

            case "endswith":
                return(Expression.Call(left, MethodProvider.EndsWithMethod, new[] { right, MethodProvider.IgnoreCaseExpression }));

            case "startswith":
                return(Expression.Call(left, MethodProvider.StartsWithMethod,
                                       new[] { right, MethodProvider.IgnoreCaseExpression }));

            case "length":
                return(Expression.Property(left, MethodProvider.LengthProperty));

            case "indexof":
                return(Expression.Call(left, MethodProvider.IndexOfMethod, new[] { right, MethodProvider.IgnoreCaseExpression }));

            case "substring":
                return(Expression.Call(left, MethodProvider.SubstringMethod, new[] { right }));

            case "tolower":
                return(Expression.Call(left, MethodProvider.ToLowerMethod));

            case "toupper":
                return(Expression.Call(left, MethodProvider.ToUpperMethod));

            case "trim":
                return(Expression.Call(left, MethodProvider.TrimMethod));

            case "hour":
                return(Expression.Property(left, MethodProvider.HourProperty));

            case "minute":
                return(Expression.Property(left, MethodProvider.MinuteProperty));

            case "second":
                return(Expression.Property(left, MethodProvider.SecondProperty));

            case "day":
                return(Expression.Property(left, MethodProvider.DayProperty));

            case "month":
                return(Expression.Property(left, MethodProvider.MonthProperty));

            case "year":
                return(Expression.Property(left, MethodProvider.YearProperty));

            case "round":
                return
                    (Expression.Call(
                         left.Type == typeof(double) ? MethodProvider.DoubleRoundMethod : MethodProvider.DecimalRoundMethod, left));

            case "floor":
                return
                    (Expression.Call(
                         left.Type == typeof(double) ? MethodProvider.DoubleFloorMethod : MethodProvider.DecimalFloorMethod, left));

            case "ceiling":
                return
                    (Expression.Call(
                         left.Type == typeof(double) ? MethodProvider.DoubleCeilingMethod : MethodProvider.DecimalCeilingMethod,
                         left));

            case "any":
            case "all":
            {
                return(CreateAnyAllExpression(
                           left,
                           right,
                           sourceParameter,
                           lambdaParameters,
                           MethodProvider.GetAnyAllMethod(function.Capitalize(), left.Type)));
            }

            default:
                return(null);
            }
        }
        private static Expression GetFunction(string function, Expression left, Expression right, ParameterExpression sourceParameter, ICollection <ParameterExpression> lambdaParameters)
        {
            CustomContract.Requires(function != null);
            CustomContract.Requires(left != null);

            switch (function.ToLowerInvariant())
            {
            case "substringof":
                return(Expression.Call(right, MethodProvider.ContainsMethod, new[] { left }));

            case "endswith":
                return(Expression.Call(left, MethodProvider.EndsWithMethod, new[] { right }));

            case "startswith":
                return(Expression.Call(left, MethodProvider.StartsWithMethod, new[] { right }));

            case "length":
                return(Expression.Property(left, MethodProvider.LengthProperty));

            case "indexof":
                return(Expression.Call(left, MethodProvider.IndexOfMethod, new[] { right }));

            case "substring":
                return(Expression.Call(left, MethodProvider.SubstringMethod, new[] { right }));

            case "tolower":
                return(Expression.Call(left, MethodProvider.ToLowerMethod));

            case "toupper":
                return(Expression.Call(left, MethodProvider.ToUpperMethod));

            case "trim":
                return(Expression.Call(left, MethodProvider.TrimMethod));

            case "hour":
                return(Expression.Property(left, MethodProvider.HourProperty));

            case "minute":
                return(Expression.Property(left, MethodProvider.MinuteProperty));

            case "second":
                return(Expression.Property(left, MethodProvider.SecondProperty));

            case "day":
                return(Expression.Property(left, MethodProvider.DayProperty));

            case "month":
                return(Expression.Property(left, MethodProvider.MonthProperty));

            case "year":
                return(Expression.Property(left, MethodProvider.YearProperty));

            case "round":
                return(Expression.Call(left.Type == typeof(double) ? MethodProvider.DoubleRoundMethod : MethodProvider.DecimalRoundMethod, left));

            case "floor":
                return(Expression.Call(left.Type == typeof(double) ? MethodProvider.DoubleFloorMethod : MethodProvider.DecimalFloorMethod, left));

            case "ceiling":
                return(Expression.Call(left.Type == typeof(double) ? MethodProvider.DoubleCeilingMethod : MethodProvider.DecimalCeilingMethod, left));

            case "any":
            case "all":
            {
                CustomContract.Assume(right != null);
                CustomContract.Assume(!string.IsNullOrEmpty(function));

                return(CreateAnyAllExpression(
                           left,
                           right,
                           sourceParameter,
                           lambdaParameters,
                           MethodProvider.GetAnyAllMethod(function.Capitalize(), left.Type)));
            }

            default:
                return(null);
            }
        }
예제 #17
0
파일: Services.cs 프로젝트: hugoaraujor/IMP
 public static string GetMethodName(int metodo)
 {
     Services.Set(MethodProvider.Get(metodo));
     return(db.Cuestionarios.Where(m => m.Metodo == metodo).SingleOrDefault().Cuestionario_name);
 }
예제 #18
0
        public virtual void  runTest()
        {
            MethodProvider mp = new MethodProvider();

            try {
                // Test boolean primitive.
                System.Object[] booleanParams = new System.Object[] { true };
                type   = "boolean";
                method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", booleanParams);
                result = (System.String)method.Invoke(mp, (System.Object[])booleanParams);

                if (!result.Equals(type))
                {
                    failures.add(type + "Method could not be found!");
                }

                // Test byte primitive.
                System.Object[] byteParams = new System.Object[] { System.Byte.Parse("1") };
                type   = "byte";
                method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", byteParams);
                result = (System.String)method.Invoke(mp, (System.Object[])byteParams);

                if (!result.Equals(type))
                {
                    failures.add(type + "Method could not be found!");
                }

                // Test char primitive.
                System.Object[] characterParams = new System.Object[] { 'a' };
                type   = "character";
                method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", characterParams);
                result = (System.String)method.Invoke(mp, (System.Object[])characterParams);

                if (!result.Equals(type))
                {
                    failures.add(type + "Method could not be found!");
                }

                // Test double primitive.
                System.Object[] doubleParams = new System.Object[] { (double)1 };
                type   = "double";
                method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", doubleParams);
                result = (System.String)method.Invoke(mp, (System.Object[])doubleParams);

                if (!result.Equals(type))
                {
                    failures.add(type + "Method could not be found!");
                }

                // Test float primitive.
                System.Object[] floatParams = new System.Object[] { (float)1 };
                type   = "float";
                method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", floatParams);
                result = (System.String)method.Invoke(mp, (System.Object[])floatParams);

                if (!result.Equals(type))
                {
                    failures.add(type + "Method could not be found!");
                }

                // Test integer primitive.
                System.Object[] integerParams = new System.Object[] { (int)1 };
                type   = "integer";
                method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", integerParams);
                result = (System.String)method.Invoke(mp, (System.Object[])integerParams);

                if (!result.Equals(type))
                {
                    failures.add(type + "Method could not be found!");
                }

                // Test long primitive.
                System.Object[] longParams = new System.Object[] { (long)1 };
                type   = "long";
                method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", longParams);
                result = (System.String)method.Invoke(mp, (System.Object[])longParams);

                if (!result.Equals(type))
                {
                    failures.add(type + "Method could not be found!");
                }

                // Test short primitive.
                System.Object[] shortParams = new System.Object[] { (short)1 };
                type   = "short";
                method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", shortParams);
                result = (System.String)method.Invoke(mp, (System.Object[])shortParams);

                if (!result.Equals(type))
                {
                    failures.add(type + "Method could not be found!");
                }

                // Test untouchable

                System.Object[] params_Renamed = new System.Object[] {};

                method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), "untouchable", params_Renamed);

                if (method != null)
                {
                    failures.add(type + "able to access a private-access method.");
                }

                // Test really untouchable

                method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), "reallyuntouchable", params_Renamed);

                if (method != null)
                {
                    failures.add(type + "able to access a default-access method.");
                }

                // There were any failures then show all the
                // errors that occured.

                int totalFailures = failures.size();
                if (totalFailures > 0)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder("\nIntrospection Errors:\n");
                    for (int i = 0; i < totalFailures; i++)
                    {
                        sb.Append((System.String)failures.get(i)).Append("\n");
                    }

                    fail(sb.ToString());
                }
            } catch (System.Exception e) {
                fail(e.ToString());
            }
        }
예제 #19
0
 public WeakDelegateBase()
 {
     provider = new MethodProvider <T>();
 }
예제 #20
0
        public GeneratorResult Generate(MethodCreatorCreator methodCreatorCreator)
        {
            #region Declare Value Type Serializer Methods

            var valueTypeSerializerType   = methodCreatorCreator.Create("ValueTypeSerializer");
            var valueTypeDeserializerType = methodCreatorCreator.Create("ValueTypeDeserializer");

            var generatedValueTypeSerializeMethods   = new Dictionary <Type, MethodInfo>();
            var generatedValueTypeDeserializeMethods = new Dictionary <Type, MethodInfo>();

            foreach (var valueType in typeClassifier.ValueTypes)
            {
                if (customMethods.HasTypeSerializer(valueType))
                {
                    continue;                     // Don't generate serializers where custom methods exist
                }
                var serializeMethod = valueTypeSerializerType.CreateMethod(valueType, "ValueTypeSerialize",
                                                                           typeof(void), new[] { typeof(SerializeContext), typeof(BinaryWriter), valueType.MakeByRefType() });
                generatedValueTypeSerializeMethods.Add(valueType, serializeMethod);

                var deserializeMethod = valueTypeDeserializerType.CreateMethod(valueType, "ValueTypeDeserialize",
                                                                               typeof(void), new[] { typeof(DeserializeContext), typeof(BinaryReader), valueType.MakeByRefType() });
                generatedValueTypeDeserializeMethods.Add(valueType, deserializeMethod);
            }

            #endregion


            #region Declare Reference Type Serializer Methods

            // Note: These methods have no type check/dispatch - fields that could reference derived types must go through the field methods instead of these!

            var referenceTypeSerializerType   = methodCreatorCreator.Create("ReferenceTypeSerializer");
            var referenceTypeDeserializerType = methodCreatorCreator.Create("ReferenceTypeDeserializer");

            var generatedReferenceTypeSerializeMethods   = new Dictionary <Type, MethodInfo>();
            var generatedReferenceTypeDeserializeMethods = new Dictionary <Type, MethodInfo>();

            foreach (var referenceType in typeClassifier.ReferenceTypes)
            {
                Debug.Assert(!referenceType.IsArray);
                if (customMethods.HasTypeSerializer(referenceType))
                {
                    continue;                     // Don't generate serializers where custom methods exist
                }
                var serializeMethod = referenceTypeSerializerType.CreateMethod(referenceType, "ReferenceTypeSerialize",
                                                                               typeof(void), new[] { typeof(SerializeContext), typeof(BinaryWriter), referenceType });
                generatedReferenceTypeSerializeMethods.Add(referenceType, serializeMethod);

                var deserializeMethod = referenceTypeDeserializerType.CreateMethod(referenceType,
                                                                                   "ReferenceTypeDeserialize", typeof(void),
                                                                                   new[] { typeof(DeserializeContext), typeof(BinaryReader), referenceType });
                generatedReferenceTypeDeserializeMethods.Add(referenceType, deserializeMethod);
            }

            #endregion


            #region Declare Field Serializer Methods

            var fieldSerializerType   = methodCreatorCreator.Create("FieldSerializer");
            var fieldDeserializerType = methodCreatorCreator.Create("FieldDeserializer");

            var generatedReferenceFieldSerializeMethods   = new Dictionary <Type, MethodInfo>();
            var generatedReferenceFieldDeserializeMethods = new Dictionary <Type, MethodInfo>();

            foreach (var fieldType in typeClassifier.fieldSerializerDispatchLookup.Keys)
            {
                if (customMethods.HasFieldSerializer(fieldType))
                {
                    continue;                     // Don't create field serializers where custom ones exist
                }
                var serializeMethod = fieldSerializerType.CreateMethod(fieldType, "FieldSerialize", typeof(void),
                                                                       new[] { typeof(SerializeContext), typeof(BinaryWriter), fieldType });
                generatedReferenceFieldSerializeMethods.Add(fieldType, serializeMethod);

                var deserializeMethod = fieldDeserializerType.CreateMethod(fieldType, "FieldDeserialize", typeof(void),
                                                                           new[] { typeof(DeserializeContext), typeof(BinaryReader), fieldType.MakeByRefType() });
                generatedReferenceFieldDeserializeMethods.Add(fieldType, deserializeMethod);
            }

            #endregion


            #region Declare Dispatch Methods

            var serializerDispatchType   = methodCreatorCreator.Create("SerializerDispatch");
            var deserializerDispatchType = methodCreatorCreator.Create("DeserializerDispatch");

            // These are dispatched by ID#, so this is a lookup by that ID#
            var dynamicDispatchMethods = new List <SerializationMethods>(typeClassifier.dispatchableTypes.Count);

            // Dispatch to types that require actual dispatch (from type classification) as well as any suplemental types
            // (Suplemental types come from delegates, at the moment, a few of which require dynamic dispatch (see DelegateSerialization.SerializeDelegate)
            // and I haven't written a direct-dispatch path yet)
            HashSet <Type> dispatchTypes;
            if (suplementalDispatchTypes == null)
            {
                dispatchTypes = typeClassifier.dispatchableTypes;
            }
            else
            {
                dispatchTypes = new HashSet <Type>(typeClassifier.dispatchableTypes.Concat(suplementalDispatchTypes));
            }


            foreach (var type in dispatchTypes.NetworkOrder(t => t.Module.Name + t.FullName))
            {
                var idString = dynamicDispatchMethods.Count.ToString("0000");
                SerializationMethods sm;
                sm.type = type;

                sm.serializer = serializerDispatchType.CreateMethod(type, "SerializeWithId_" + idString, typeof(void),
                                                                    new[] { typeof(SerializeContext), typeof(BinaryWriter), typeof(object) });
                sm.deserializer = deserializerDispatchType.CreateMethod(type, "DeserializeFromId_" + idString, type,
                                                                        new[] { typeof(DeserializeContext), typeof(BinaryReader) });
                dynamicDispatchMethods.Add(sm);                 // Defines the ID#
            }

            // Deserialization dispatch method (this could reasonably use a table like serialization, but it was original a giant switch statement - so let's keep it that way)
            deserializationDispatcherMethod = deserializerDispatchType.CreateMethod(null, "DeserializationDispatcher",
                                                                                    typeof(object), new[] { typeof(DeserializeContext), typeof(BinaryReader) });

            #endregion


            #region Lookup Hookup

            // These are all used to do lookup during IL generation (should probably be switched to a SerializationMethodProviders)

            fieldSerializeMethods = FallbackMethodProvider.Combine(customMethods.ValueTypeSerializeMethods,
                                                                   customMethods.ReferenceFieldSerializeMethods,
                                                                   new LookupMethodProvider(generatedValueTypeSerializeMethods),
                                                                   new LookupMethodProvider(generatedReferenceFieldSerializeMethods));

            fieldDeserializeMethods = FallbackMethodProvider.Combine(
                customMethods.ValueTypeDeserializeMethods,
                customMethods.ReferenceFieldDeserializeMethods,
                new LookupMethodProvider(generatedValueTypeDeserializeMethods),
                new LookupMethodProvider(generatedReferenceFieldDeserializeMethods));

            referenceTypeSerializeMethods = FallbackMethodProvider.Combine(
                customMethods.ReferenceTypeSerializeMethods,
                new LookupMethodProvider(generatedReferenceTypeSerializeMethods));

            referenceTypeDeserializeMethods = FallbackMethodProvider.Combine(
                customMethods.ReferenceTypeDeserializeMethods,
                new LookupMethodProvider(generatedReferenceTypeDeserializeMethods));

            var serializeContext =
                new ILGenContext(Direction.Serialize, fieldSerializeMethods, referenceTypeSerializeMethods);
            var deserializeContext = new ILGenContext(Direction.Deserialize, fieldDeserializeMethods,
                                                      referenceTypeDeserializeMethods);

            #endregion


            #region Generate Dynamic Dispatch Method IL

            for (var i = 0; i < dynamicDispatchMethods.Count; i++)
            {
                // SerializeWithId Method:

                #region Generate IL

                {
                    var il = dynamicDispatchMethods[i].serializer.GetILGenerator();

                    // br.Write('i');
                    il.Emit(OpCodes.Ldarg_1);
                    il.Emit(OpCodes.Ldc_I4, i);
                    il.Emit(OpCodes.Callvirt, Methods.BinaryWriter_WriteInt32);

                    // ReferenceTypeSerializer.Serialize(context, bw, (Class)obj);
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldarg_1);
                    il.Emit(OpCodes.Ldarg_2);
                    il.Emit(OpCodes.Castclass, dynamicDispatchMethods[i].type);
                    il.Emit(OpCodes.Call, referenceTypeSerializeMethods[dynamicDispatchMethods[i].type]);

                    il.Emit(OpCodes.Ret);
                }

                #endregion


                // DeserializeFromId Method:

                #region Generate IL

                {
                    var il = dynamicDispatchMethods[i].deserializer.GetILGenerator();
                    il.DeclareLocal(dynamicDispatchMethods[i].type);                     // Class obj

                    // Class obj = /* create object */
                    GenerateTypeCreation(il, dynamicDispatchMethods[i].type);
                    il.Emit(OpCodes.Stloc_0);

                    // ReferenceTypeDeserializer.Deserialize(context, br, (Class)obj);
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldarg_1);
                    il.Emit(OpCodes.Ldloc_0);
                    il.Emit(OpCodes.Call, referenceTypeDeserializeMethods[dynamicDispatchMethods[i].type]);

                    // return obj;
                    il.Emit(OpCodes.Ldloc_0);
                    il.Emit(OpCodes.Ret);
                }

                #endregion
            }

            #endregion


            #region Generate Reference Field Serializer Method IL

            foreach (var fieldDispatch in typeClassifier.fieldSerializerDispatchLookup)
            {
                var fieldType       = fieldDispatch.Key;
                var dispatchToTypes = fieldDispatch.Value;

                var serializeMethod   = generatedReferenceFieldSerializeMethods[fieldType];
                var deserializeMethod = generatedReferenceFieldDeserializeMethods[fieldType];

                GenerateReferenceFieldSerializer(serializeMethod.GetILGenerator(), fieldType, dispatchToTypes);
                GenerateReferenceFieldDeserializer(deserializeMethod.GetILGenerator(), fieldType, dispatchToTypes);
            }

            #endregion


            #region Generate Reference and Value Type Serializers

            foreach (var sm in generatedValueTypeSerializeMethods)
            {
                TypeSerializeILGeneration.GenerateValueTypeSerializationMethod(sm.Key, sm.Value.GetILGenerator(),
                                                                               serializeContext);
            }
            foreach (var sm in generatedValueTypeDeserializeMethods)
            {
                TypeSerializeILGeneration.GenerateValueTypeSerializationMethod(sm.Key, sm.Value.GetILGenerator(),
                                                                               deserializeContext);
            }
            foreach (var sm in generatedReferenceTypeSerializeMethods)
            {
                TypeSerializeILGeneration.GenerateReferenceTypeSerializationMethod(sm.Key, sm.Value.GetILGenerator(),
                                                                                   serializeContext);
            }
            foreach (var sm in generatedReferenceTypeDeserializeMethods)
            {
                TypeSerializeILGeneration.GenerateReferenceTypeSerializationMethod(sm.Key, sm.Value.GetILGenerator(),
                                                                                   deserializeContext);
            }

            #endregion


            #region Generate Deserialization Dispatcher (IL)

            {
                var il = deserializationDispatcherMethod.GetILGenerator();

                var dispatchLabels = new Label[dynamicDispatchMethods.Count];
                for (var i = 0; i < dispatchLabels.Length; i++)
                {
                    dispatchLabels[i] = il.DefineLabel();
                }
                var failLabel = il.DefineLabel();

                // br.ReadInt32()
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Callvirt,
                        typeof(BinaryReader)
                        .GetMethod("ReadInt32"));                         // NOTE: C# compiler loads this into two locals for no reason

                // switch(...)
                il.Emit(OpCodes.Switch, dispatchLabels);
                il.Emit(OpCodes.Br,
                        failLabel);                 // default case // NOTE: C# compiler emits br.s, but I bet it's not short with our huge table!

                for (var i = 0; i < dynamicDispatchMethods.Count; i++)
                {
                    // case 'i':
                    il.MarkLabel(dispatchLabels[i]);
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldarg_1);
                    il.Emit(OpCodes.Call, dynamicDispatchMethods[i].deserializer);
                    il.Emit(OpCodes.Ret);
                }

                // throw new Exception("...");
                il.MarkLabel(failLabel);
                il.Emit(OpCodes.Ldstr, "Unknown Type");
                il.Emit(OpCodes.Newobj, typeof(Exception).GetConstructor(new[] { typeof(string) }));
                il.Emit(OpCodes.Throw);
            }

            #endregion


            #region Fill Serialization Dispatch Table

            // We used to generate a table with IL in the serializer assembly (fancy). Now we can just do it directly.
            // (But we do have to do it last, so the methods are actually ready to convert to delegates)

            var dispatchTable = new Dictionary <Type, SerializeDispatchDelegate>();

            // Only dynamic methods can be converted to delegates (because the dynamic assembly we create in assembly-generating mode is save-only)
            if (methodCreatorCreator is DynamicMethodCreatorCreator)
            {
                for (var i = 0; i < dynamicDispatchMethods.Count; i++)
                {
                    var serializerMethod = dynamicDispatchMethods[i].serializer as DynamicMethod;
                    Debug.Assert(serializerMethod != null);
                    var serializerDelegate =
                        (SerializeDispatchDelegate)serializerMethod.CreateDelegate(typeof(SerializeDispatchDelegate));
                    dispatchTable.Add(dynamicDispatchMethods[i].type, serializerDelegate);
                }
            }

            #endregion


            #region Return

            var generatedMethodProviders = new SerializationMethodProviders(
                new LookupMethodProvider(generatedValueTypeSerializeMethods),
                new LookupMethodProvider(generatedValueTypeDeserializeMethods),
                new LookupMethodProvider(generatedReferenceTypeSerializeMethods),
                new LookupMethodProvider(generatedReferenceTypeDeserializeMethods),
                new LookupMethodProvider(generatedReferenceFieldSerializeMethods),
                new LookupMethodProvider(generatedReferenceFieldDeserializeMethods),
                new EmptyMethodProvider());


            // Note: custom methods come before generated methods:
            var combinedMethodProviders = SerializationMethodProviders
                                          .Combine(customMethods, generatedMethodProviders);


            DeserializeDispatchDelegate deserializeDispatchDelegate = null;
            if (methodCreatorCreator is DynamicMethodCreatorCreator
                )         // Only dynamic methods can be converted to delegates (our dynamic assembly is save-only)
            {
                deserializeDispatchDelegate =
                    (DeserializeDispatchDelegate)(deserializationDispatcherMethod as DynamicMethod).CreateDelegate(
                        typeof(DeserializeDispatchDelegate));
            }


            return(new GeneratorResult(combinedMethodProviders, dispatchTable, deserializeDispatchDelegate,
                                       null)); // module table gets filled later

            #endregion
        }
예제 #21
0
        public virtual void runTest()
        {
            MethodProvider mp = new MethodProvider();

            try {
            // Test boolean primitive.
            System.Object[] booleanParams = new System.Object[]{true};
            type = "boolean";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", booleanParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) booleanParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test byte primitive.
            System.Object[] byteParams = new System.Object[]{System.Byte.Parse("1")};
            type = "byte";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", byteParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) byteParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test char primitive.
            System.Object[] characterParams = new System.Object[]{'a'};
            type = "character";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", characterParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) characterParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test double primitive.
            System.Object[] doubleParams = new System.Object[]{(double) 1};
            type = "double";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", doubleParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) doubleParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test float primitive.
            System.Object[] floatParams = new System.Object[]{(float) 1};
            type = "float";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", floatParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) floatParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test integer primitive.
            System.Object[] integerParams = new System.Object[]{(int) 1};
            type = "integer";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", integerParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) integerParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test long primitive.
            System.Object[] longParams = new System.Object[]{(long) 1};
            type = "long";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", longParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) longParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test short primitive.
            System.Object[] shortParams = new System.Object[]{(short) 1};
            type = "short";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", shortParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) shortParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test untouchable

            System.Object[] params_Renamed = new System.Object[]{};

            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), "untouchable", params_Renamed);

            if (method != null)
            failures.add(type + "able to access a private-access method.");

            // Test really untouchable

            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), "reallyuntouchable", params_Renamed);

            if (method != null)
            failures.add(type + "able to access a default-access method.");

            // There were any failures then show all the
            // errors that occured.

            int totalFailures = failures.size();
            if (totalFailures > 0) {
            System.Text.StringBuilder sb = new System.Text.StringBuilder("\nIntrospection Errors:\n");
            for (int i = 0; i < totalFailures; i++)
            sb.Append((System.String) failures.get(i)).Append("\n");

            fail(sb.ToString());
            }
            } catch (System.Exception e) {
            fail(e.ToString());
            }
        }
예제 #22
0
        /// <summary>
        /// Method used to convert value to target type. Should be used for any conversion during script execution.
        ///
        /// This method should be used by derived class for performance instead of ConvertTo
        /// </summary>
        /// <param name="value">value to convert or null</param>
        /// <param name="targetType">target type</param>
        /// <returns>Converted value or NoResult constant if conversion impossible</returns>
        protected static object ConvertToStatic(object value, Type targetType)
        {
            //TODO: Cache conversion method

            if (value == null)
            {
                return(value);
            }
            if (targetType == typeof(object))
            {
                return(value);
            }

            Type valueType = value.GetType();

            //Interface
            if (targetType.IsInterface)
            {
                if (valueType
                    .GetInterfaces()
                    .Where(i => i.FullName == targetType.FullName)
                    .Count() != 0)
                {
                    return(value);
                }
                //return new ExplicitInterface(value, targetType);
            }

            //Type Match
            if (targetType.IsAssignableFrom(valueType))
            {
                return(value);
            }

            //Conversion operators
            var mi = MethodProvider.GetConversionMethod(valueType, targetType);

            if (mi != null)
            {
                return(mi.Invoke(value, new[] { value }));
            }

            //NOTE: ref, out
            if (targetType.IsByRef)
            {
                return(targetType.GetElementType() == valueType ? value : ConvertToStatic(value, targetType.GetElementType()));
            }

            //Convertible
            if (value is IConvertible)
            {
                try
                {
                    return(Convert.ChangeType(value, targetType, System.Globalization.CultureInfo.CurrentCulture));
                }
                catch (InvalidCastException)
                {
                    return(NoResult);
                }
            }

            //TODO: Improve
            Scripting.SSharp.Parser.Ast.ScriptFunctionDefinition f = value as Scripting.SSharp.Parser.Ast.ScriptFunctionDefinition;
            if (f != null)
            {
                try {
                    return(f.AsDelegate(targetType));
                }
                catch (InvalidCastException) {
                    return(NoResult);
                }
            }

            return(NoResult);
        }