Exemplo n.º 1
0
        /// <summary>
        /// Attempts to create an instance of an object using the specified constructor.
        /// Checks each constructor parameter to make sure that it can be resolved.
        /// </summary>
        /// <param name="constructor">The constructor that we are attempting to invoke</param>
        /// <returns>An object created by the constructor, or null if the dependencies could not be satisfied</returns>
        private static object CreateInstanceWithConstructor(System.Reflection.ConstructorInfo constructor)
        {
            object instance = null;

            var parameters      = constructor.GetParameters();
            var parameterValues = new List <object>();

            // Loop through each parameter and see if we can resolve it
            foreach (var parameter in parameters)
            {
                object instanceOfParameter = Get(parameter.ParameterType, CachePolicy.Cached);
                if (instanceOfParameter == null)
                {
                    break;
                }

                parameterValues.Add(instanceOfParameter);
            }

            // If we were able to resolve each parameter, create the instance
            if (parameterValues.Count == parameters.Count())
            {
                instance = Activator.CreateInstance(constructor.DeclaringType, parameterValues.ToArray());
            }

            return(instance);
        }
        public IReadOnlyList <IParameterInfo> GetParameters([NotNull] System.Reflection.ConstructorInfo constructor)
        {
            var parameters = new List <IParameterInfo>();

            var ownerType = constructor.ReflectedType;

            ThrowIf.Variable.IsNull(ownerType, nameof(ownerType));

            foreach (var parameter in constructor.GetParameters())
            {
                var parameterType = parameter.ParameterType;

                if (parameterType.IsGenericType && parameterType.GetGenericTypeDefinition() == typeof(IReadOnlyList <>))
                {
                    var itemType = parameterType.GetGenericArguments().First();
                    ThrowIf.Variable.IsNull(itemType, nameof(itemType));

                    parameters.Add(new ListParameterInfo(ownerType, itemType));
                }
                else
                {
                    parameters.Add(new SingleParameterInfo(ownerType, parameterType));
                }
            }

            return(parameters);
        }
Exemplo n.º 3
0
        static bool ConstructorMatch(object[] constructorParameters, System.Reflection.ConstructorInfo constructorInfo)
        {
            var constructorMatch   = false;
            var parameterInfos     = constructorInfo.GetParameters();
            var numberOfParameters = parameterInfos.Length;

            if (numberOfParameters == constructorParameters.Length)
            {
                for (int i = 0; i < numberOfParameters; i++)
                {
                    var constructorParameterType = parameterInfos[i].ParameterType;
                    var givenParameterType       = constructorParameters[i].GetType();
                    if ((givenParameterType == constructorParameterType) || constructorParameterType.IsAssignableFrom(givenParameterType))
                    {
                        constructorMatch = true;
                    }
                    else
                    {
                        constructorMatch = false;
                        break;
                    }
                }
            }

            return(constructorMatch);
        }
Exemplo n.º 4
0
        private object Create(Type type)
        {
            if (implementations.ContainsKey(type))
            {
                return(implementations[type]);
            }

            var availableTypes = types[type];

            System.Reflection.ConstructorInfo defConstructor = availableTypes.GetConstructors()[0];
            System.Reflection.ParameterInfo[] defParams      = defConstructor.GetParameters();

            var parameters = defParams.Select(param => {
                if (implementations.ContainsKey(param.GetType()))
                {
                    return(implementations[param.GetType()]);
                }
                else
                {
                    return(Create(param.ParameterType));
                }
            }).ToArray();

            return(defConstructor.Invoke(parameters));
        }
        public static TypeCache[] ForConstructor(System.Reflection.ConstructorInfo constructor)
        {
            if (cache.ContainsKey(constructor))
            {
                return(cache[constructor]);
            }

            var parameters = constructor.GetParameters();

            if (parameters == null || parameters.Length == 0)
            {
                cache[constructor] = new TypeCache[0];
                return(cache[constructor]);
            }

            var result = new TypeCache[parameters.Length];

            var ix = 0;

            foreach (var par in parameters)
            {
                result[ix] = TypeCache.ForParameter(par, null);
                if (result[ix].RequirePluginContext)
                {
                    throw new Exceptions.InvalidConstructorServiceArgumentException(constructor, par);
                }
                ix++;
            }
            cache[constructor] = result;
            return(result);
        }
Exemplo n.º 6
0
        static BaseView()
        {
            var ctors = typeof(TPainter).GetConstructors().Where(c => c.GetParameters().All(param => param.IsOptional));

            if (ctors.IsEmpty())
            {
                throw new ArgumentException($"The supplied generic type parameter for {nameof(TPainter)}, which is {typeof(TPainter)}, does not have any constructors with no parameters nor all optional parameters.");
            }
            painterCtor = ctors.First();
            ctorParams  = Enumerable.Repeat(Type.Missing, painterCtor.GetParameters().Length).ToArray();
            var painter          = (TPainter)painterCtor.Invoke(ctorParams);
            var thisType         = typeof(BaseView <TPainter, TSource>);
            var drawMethodParams = typeof(TPainter).GetMethod(nameof(ICanvasPainter <SKCanvas, TSource, SKColor> .Draw), new[] { typeof(SKCanvas), typeof(TextAlignment), typeof(Thickness), typeof(float), typeof(float) }).GetParameters();

            TPainter p(BindableObject b) => ((BaseView <TPainter, TSource>)b).Painter;

            SourceProperty             = BindableProperty.Create(nameof(Source), typeof(TSource), thisType, painter.Source, BindingMode.TwoWay, null, (b, o, n) => { p(b).Source = (TSource)n; ((BaseView <TPainter, TSource>)b).ErrorMessage = p(b).ErrorMessage; });
            DisplayErrorInlineProperty = BindableProperty.Create(nameof(DisplayErrorInline), typeof(bool), thisType, painter.DisplayErrorInline, propertyChanged: (b, o, n) => p(b).DisplayErrorInline = (bool)n);
            FontSizeProperty           = BindableProperty.Create(nameof(FontSize), typeof(float), thisType, painter.FontSize, propertyChanged: (b, o, n) => p(b).FontSize = (float)n);
            ErrorFontSizeProperty      = BindableProperty.Create(nameof(ErrorFontSize), typeof(float?), thisType, painter.ErrorFontSize, propertyChanged: (b, o, n) => p(b).ErrorFontSize = (float)n);
            TextColorProperty          = BindableProperty.Create(nameof(TextColor), typeof(Color), thisType, painter.TextColor.ToFormsColor(), propertyChanged: (b, o, n) => p(b).TextColor = ((Color)n).ToSKColor());
            HighlightColorProperty     = BindableProperty.Create(nameof(HighlightColor), typeof(Color), thisType, painter.HighlightColor.ToFormsColor(), propertyChanged: (b, o, n) => p(b).HighlightColor = ((Color)n).ToSKColor());
            ErrorColorProperty         = BindableProperty.Create(nameof(ErrorColor), typeof(Color), thisType, painter.ErrorColor.ToFormsColor(), propertyChanged: (b, o, n) => p(b).ErrorColor = ((Color)n).ToSKColor());
            TextAlignmentProperty      = BindableProperty.Create(nameof(TextAlignment), typeof(TextAlignment), thisType, drawMethodParams[1].DefaultValue is DBNull ? default(TextAlignment) : drawMethodParams[1].DefaultValue ?? default(TextAlignment));
            DisplacementXProperty      = BindableProperty.Create(nameof(DisplacementX), typeof(float), thisType, drawMethodParams[3].DefaultValue, BindingMode.TwoWay);
            DisplacementYProperty      = BindableProperty.Create(nameof(DisplacementY), typeof(float), thisType, drawMethodParams[4].DefaultValue, BindingMode.TwoWay);
            MagnificationProperty      = BindableProperty.Create(nameof(Magnification), typeof(float), thisType, painter.Magnification, propertyChanged: (b, o, n) => p(b).Magnification = (float)n);
            PaintStyleProperty         = BindableProperty.Create(nameof(PaintStyle), typeof(PaintStyle), thisType, painter.PaintStyle, propertyChanged: (b, o, n) => p(b).PaintStyle = (PaintStyle)n);
            LineStyleProperty          = BindableProperty.Create(nameof(LineStyle), typeof(Enumerations.LineStyle), thisType, painter.LineStyle, propertyChanged: (b, o, n) => p(b).LineStyle = (Enumerations.LineStyle)n);
            PaddingProperty            = BindableProperty.Create(nameof(Padding), typeof(Thickness), thisType, drawMethodParams[2].DefaultValue ?? default(Thickness));
            ErrorMessagePropertyKey    = BindableProperty.CreateReadOnly(nameof(ErrorMessage), typeof(string), thisType, painter.ErrorMessage, BindingMode.OneWayToSource);
            ErrorMessageProperty       = ErrorMessagePropertyKey.BindableProperty;
        }
Exemplo n.º 7
0
 /// <summary>
 /// Construtor padrão.
 /// </summary>
 /// <param name="validatorType">Tipo do validador associado.</param>
 /// <param name="cultureInfo"></param>
 public ValidatorCreator(Type validatorType, System.Globalization.CultureInfo cultureInfo)
 {
     validatorType.Require("validatorType").NotNull();
     _validatorType  = validatorType;
     _cultureInfo    = cultureInfo;
     _constructor    = validatorType.GetConstructors().FirstOrDefault();
     _parameters     = _constructor.GetParameters();
     _parameterNames = _parameters.Select(f => char.ToUpper(f.Name[0]) + f.Name.Substring(1)).ToArray();
 }
Exemplo n.º 8
0
 public ConstructorValueData(System.Reflection.ConstructorInfo ctor)
 {
     serializedType = new MemberData(ctor.DeclaringType);
     System.Reflection.ParameterInfo[] param = ctor.GetParameters();
     parameters = new ParameterValueData[param.Length];
     for (int i = 0; i < param.Length; i++)
     {
         parameters[i] = new ParameterValueData()
         {
             name     = param[i].Name,
             typeData = MemberData.CreateFromType(param[i].ParameterType)
         };
     }
 }
Exemplo n.º 9
0
        protected void OutputCtorSig(System.Text.StringBuilder sb,
                                     System.Reflection.ConstructorInfo ci)
        {
            System.Reflection.ParameterInfo[] ps = ci.GetParameters();
            int i;

            for (i = 0; i < ps.Length; i++)
            {
                OutputHaskellType(sb, ps[i].ParameterType, i);
                sb.Append(" -> ");
            }
            sb.AppendFormat("IO ({0} ())", ci.DeclaringType.Name);
            sb.Append(System.Environment.NewLine);
        }
Exemplo n.º 10
0
        public ConstructorsInfo(System.Reflection.ConstructorInfo constructor)
        {
            Name = $"Constructor : {Namer.GetName(constructor.DeclaringType)} (";

            var parametrs = constructor.GetParameters();

            List <string> temp = new List <string>();

            foreach (var parameter in parametrs)
            {
                temp.Add($"{Namer.GetName(parameter.ParameterType)} {parameter.Name} ");
            }

            Name += $"{string.Join(", ", temp.ToArray())})";
        }
Exemplo n.º 11
0
        public static MethodName FromConstructorInfo(System.Reflection.ConstructorInfo constructor)
        {
            if (constructor == null)
            {
                throw new ArgumentNullException("constructor");
            }

            return(new DefaultMethodName(
                       TypeName.FromType(constructor.DeclaringType),
                       constructor.Name,
                       DefaultMethodName.SetGenericMangle(0),
                       DefaultMethodName.SetParameters(
                           ParameterData.ConvertAll(constructor.GetParameters())
                           )
                       ));
        }
Exemplo n.º 12
0
 public void SetName(System.Reflection.ConstructorInfo constructor)
 {
     Name = $"Constructor: {constructor.DeclaringType.Name}(";
     foreach (var param in constructor.GetParameters())
     {
         if (param.ParameterType.IsGenericType)
         {
             Name += $"{PrettyName(param.ParameterType)}";
         }
         else
         {
             Name += param.Name;
         }
     }
     Name += ")";
 }
        public static string GetSignature(this System.Reflection.ConstructorInfo constructor, bool isConstructor = false)
        {
            string result     = "";
            var    parameters = constructor.GetParameters();
            bool   first      = true;

            foreach (var parameter in parameters)
            {
                if (!first)
                {
                    result += ", ";
                }
                result += parameter.ParameterType.ToParameterTypeName() + (parameter.ParameterType == constructor.DeclaringType ? "&" : "") + parameter.GetName();
                first   = false;
            }
            return(result);
        }
Exemplo n.º 14
0
        public static Method ReverseEngineer(System.Reflection.ConstructorInfo _constructor)
        {
            Method constructor = new Method();

            //decompile method body
            if (!_constructor.IsAbstract)
            {
                Mono.Cecil.AssemblyDefinition ass = Decompiler.LoadAssembly(_constructor.DeclaringType.Module.Assembly.Location);
                MethodDefinition md = ass.MainModule.GetType(_constructor.DeclaringType.FullName).Methods.Where(md2 => md2.Name == _constructor.Name).Select(md2 => md2).First();
                constructor.MethodCode = Decompiler.GetSourceCode(md);
            }

            constructor.Type = constructor.ReturnType = ReverseEngineer(_constructor.DeclaringType);
            constructor.Name = constructor.Type.Name;

            constructor.IsStatic   = _constructor.IsStatic;
            constructor.IsAbstract = _constructor.IsAbstract;
            constructor.IsVirtual  = _constructor.IsVirtual;
            constructor.Access     = _constructor.GetAccessModifier();

            foreach (System.Reflection.ParameterInfo _param in _constructor.GetParameters())
            {
                MethodArgument ma = new MethodArgument();
                ma.Method = constructor;
                ma.Name   = _param.Name;
                ma.Type   = ReverseEngineer(_param.ParameterType);

                DataBase.Current.Set <MethodArgument>().Add(ma);
            }

            if (_constructor.IsGenericMethod || _constructor.IsGenericMethodDefinition || _constructor.ContainsGenericParameters)
            {
                foreach (System.Type _genericArg in _constructor.GetGenericArguments())
                {
                    MethodGenericArgument genericArg = new MethodGenericArgument();

                    genericArg.ArgumentType = ReverseEngineer(_genericArg);
                    genericArg.Position     = _genericArg.GenericParameterPosition;
                    genericArg.AppliedTo    = constructor;

                    DataBase.Current.Set <MethodGenericArgument>().Add(genericArg);
                }
            }

            DataBase.Current.Set <Method>().Add(constructor);
        }
Exemplo n.º 15
0
        public void Register <T>()
        {
            if (registeredTypes.HasRegisteredType(typeof(T)))
            {
                throw new AlreadyRegisteredDependencyException();
            }

            Type type = typeof(T);
            DependencyCollection collection = registeredTypes.GetOrAddCollection(type, true);

            System.Reflection.ConstructorInfo constructor = type.GetConstructors()[0];
            foreach (System.Reflection.ParameterInfo t in constructor.GetParameters())
            {
                DependencyCollection typeCollection = registeredTypes.GetOrAddCollection(t.ParameterType, false);
                collection.AddNode(t.ParameterType, typeCollection);
            }
        }
Exemplo n.º 16
0
        private static MiniCustomAttributeInfo ParseCustomAttribute(byte[] caBlob, Type caReflectedType)
        {
            uint b = 2;  //skip prolog

            System.Reflection.BindingFlags         visibility = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public;
            List <MiniCustomAttributeFixedArgInfo> fixedArgs  = new List <MiniCustomAttributeFixedArgInfo>();

            // to support multiple constructors we would need to look up the exact one in the method table
            System.Reflection.ConstructorInfo[] ctors = caReflectedType.GetConstructors(visibility);
            if (ctors.Length > 1)
            {
                throw new NotImplementedException();
            }

            System.Reflection.ConstructorInfo ctor = ctors[0];
            foreach (System.Reflection.ParameterInfo parameterInfo in ctor.GetParameters())
            {
                if (parameterInfo.ParameterType == typeof(String))
                {
                    String fixedParamString = ReadSerString(caBlob, ref b);
                    fixedArgs.Add(new MiniCustomAttributeFixedArgInfo(fixedParamString));
                }
                else
                {
                    throw new NotImplementedException();
                }
            }

            byte low  = caBlob[b++];
            byte high = caBlob[b++];

            int numNamed = (high * 0x100) | low;

            List <MiniCustomAttributeNamedArgInfo> namedArgs = new List <MiniCustomAttributeNamedArgInfo>();

            for (int j = 0; j < numNamed; j++)
            {
                String propName, value;
                ReadNamedArg(caBlob, ref b, out propName, out value);

                namedArgs.Add(new MiniCustomAttributeNamedArgInfo(CorElementType.String, propName, value));
            }

            return(new MiniCustomAttributeInfo(caReflectedType.Name, fixedArgs.ToArray(), namedArgs.ToArray()));
        }
Exemplo n.º 17
0
        public void System_ConstructorInfo_GetParameters_is_wrapped_by_Routine_MethodInfo()
        {
            constructorInfo = typeof(TestClass_Members).GetConstructor(new[] { typeof(string), typeof(int) });
            testing         = type.of <TestClass_Members>().GetConstructor(type.of <string>(), type.of <int>());

            var expected = constructorInfo.GetParameters();
            var actual   = testing.GetParameters();

            foreach (var parameter in actual)
            {
                Assert.IsTrue(expected.Any(p => p.ParameterType == parameter.ParameterType.GetActualType()), parameter.Name + " was not expected in parameters of " + constructorInfo);
            }

            foreach (var parameter in expected)
            {
                Assert.IsTrue(actual.Any(p => p.ParameterType.GetActualType() == parameter.ParameterType), parameter.Name + " was expected in index parameters of " + constructorInfo);
            }
        }
        public void DisplayConstructorProperties(System.Reflection.ConstructorInfo constructorInfo)
        {
            ThisConstructor = constructorInfo;//store the constructor information

            Label2.Text = ThisConstructor.Name;//display constructor name
            //calling convention output to textbox
            Label4.Text = "0x" + ThisConstructor.CallingConvention.ToString("x") + " = " + ThisConstructor.CallingConvention.ToString();
            //standard attributes to textbox
            Label6.Text = "0x" + ThisConstructor.Attributes.ToString("x") + " = " + ThisConstructor.Attributes.ToString();
            //constructor parameters
            foreach (System.Reflection.ParameterInfo parm in ThisConstructor.GetParameters())
            {
                ListBox1.Items.Add(parm);
            }
            //display custom attributes
            foreach (object attr in ThisConstructor.GetCustomAttributes(true))
            {
                ListBox2.Items.Add(attr);
            }
        }
Exemplo n.º 19
0
        private static void TestDtoEquality <T>(Expression <Func <T> > constructor)
            where T : IEquatable <T>
        {
            Assert.Equal(ExpressionType.New, constructor.Body.NodeType);
            var newExpression = (NewExpression)constructor.Body;

            ParameterExpression p1  = Expression.Parameter(typeof(T), "p1");
            ParameterExpression p2  = Expression.Parameter(typeof(T), "p2");
            Func <T, T, bool>   eq  = Expression.Lambda <Func <T, T, bool> >(Expression.Equal(p1, p2), p1, p2).Compile();
            Func <T, T, bool>   neq = Expression.Lambda <Func <T, T, bool> >(Expression.NotEqual(p1, p2), p1, p2).Compile();

            System.Reflection.ConstructorInfo ctor = newExpression.Constructor;
            System.Collections.ObjectModel.ReadOnlyCollection <Expression> constructorArguments = newExpression.Arguments;
            System.Reflection.ParameterInfo[] ctorParams = ctor.GetParameters();

            var param     = new Expression[ctorParams.Length];
            T   allValues = constructor.Compile()();
            var hs        = new HashSet <T>();

            for (var i = -1; i < constructorArguments.Count; i++)
            {
                for (var j = 0; j < constructorArguments.Count; j++)
                {
                    param[j] = i != j
                        ? ExtractActualArg(constructorArguments[j])
                        : Expression.Default(ctorParams[j].ParameterType);
                }

                NewExpression nw     = Expression.New(ctor, param);
                Func <T>      lambda = Expression.Lambda <Func <T> >(nw).Compile();

                T current = lambda();
                hs.Add(current);
                if (i == -1)
                {
                    Assert.Equal(allValues, current);
                    Assert.NotEqual(default, current);
Exemplo n.º 20
0
        public override void OnClick(Node source, PortCommandData data, Vector2 mousePosition)
        {
            if (source.owner)
            {
                Undo.SetCurrentGroupName("Assign to contructor node");
                Undo.RegisterFullObjectHierarchyUndo(source.owner, "Assign to contructor node");
            }
            var member = data.member;

            NodeEditorUtility.AddNewNode <MultipurposeNode>(graph.editorData, null, null, new Vector2(source.editorRect.x - 100, source.editorRect.y), (node) => {
                var type  = filter.GetActualType();
                var ctors = type.GetConstructors();
                if (ctors != null && ctors.Length > 0)
                {
                    System.Reflection.ConstructorInfo ctor = null;
                    foreach (var c in ctors)
                    {
                        if (ctor == null)
                        {
                            ctor = c;
                        }
                        else if (ctor.GetParameters().Length < c.GetParameters().Length)
                        {
                            ctor = c;
                        }
                    }
                    node.target.target = new MemberData(ctor);
                }
                else
                {
                    node.target.target = new MemberData(type.Name + ".ctor", type, MemberData.TargetType.Constructor);
                }
                MemberDataUtility.UpdateMultipurposeMember(node.target);
                member.CopyFrom(new MemberData(node, MemberData.TargetType.ValueNode));
            });
            graph.Refresh();
        }
            public SerializeTypeInfo(ImmutablePropertyInfo idProperty, ImmutablePropertyInfo[] properties,
                                     Dictionary <string, string> refProperties,
                                     Dictionary <string, PushInfo[]> pushes,
                                     System.Reflection.ConstructorInfo constructor)
            {
                this.IdProperty       = idProperty;
                this.Properties       = properties;
                this.Properties_Wo_Id = properties.Where(property => property != idProperty).ToArray();
                this.RefProperties    = refProperties;
                this.Pushes           = pushes;
                this.Constructor      = constructor;

                if (constructor != null)
                {
                    var parameters = constructor.GetParameters();

                    this.Parameters = parameters
                                      .Select(parameter =>
                    {
                        var pName = ToUpper(parameter.Name);
                        return(new SerializeParameterInfo(pName, parameter.ParameterType,
                                                          IdProperty?.Name == pName, refProperties.Find(pName), pushes.Find(pName)));
                    }
                                              )
                                      .ToArray();
                    this.ParameterIndexByName =
                        this.Parameters.Select((p, i) => new { p.Name, i })
                        .ToDictionary(pair => pair.Name, pair => pair.i);

                    this.Construct = constructor.ToFunc(parameters);
                }
                //if (idProperty != null && idProperty.Field != null && idProperty.Field.DeclaringType == typeof(Planet))
                //{
                //  Construct = values => new Planet((long)values[0], (int)values[1], (int)values[2], (int)values[3], (int)values[4], (int)values[5], (int)values[6]);
                //}
            }
Exemplo n.º 22
0
        private static Dictionary <string, BaseUtils.ObjectActivator.Activator <JournalEntry> > GetClassActivators()
        {
            var actlist = new Dictionary <string, BaseUtils.ObjectActivator.Activator <JournalEntry> > ();

            var asm   = System.Reflection.Assembly.GetExecutingAssembly();
            var types = asm.GetTypes().Where(t => typeof(JournalEntry).IsAssignableFrom(t) && !t.IsAbstract).ToList();

            foreach (Type type in types)
            {
                JournalEntryTypeAttribute typeattrib = type.GetCustomAttributes(false).OfType <JournalEntryTypeAttribute>().FirstOrDefault();
                if (typeattrib != null)
                {
                    System.Reflection.ConstructorInfo ctor = type.GetConstructors().First();        // this is freaking deep c# here.
                    var r = ctor.GetParameters();
                    System.Diagnostics.Debug.Assert(r.Count() == 1);
                    var r0t = r[0].GetType();
                    System.Diagnostics.Debug.Assert(r[0].ParameterType.Name == "JObject");      // checking we are picking the correct ctor
                    actlist[typeattrib.EntryType.ToString()] = BaseUtils.ObjectActivator.GetActivator <JournalEntry>(ctor);
                    //   System.Diagnostics.Debug.WriteLine("Activator " + typeattrib.EntryType.ToString());
                }
            }

            return(actlist);
        }
Exemplo n.º 23
0
        //TODO: Возможно объеденить с compiled_function_node
		private compiled_constructor_node(System.Reflection.ConstructorInfo con_info)
		{
			_con_info=con_info;
            compiled_constructors[con_info] = this;
            //type_node ret_val=null;
			System.Reflection.ParameterInfo[] pinf=_con_info.GetParameters();
			parameter_list pal=new parameter_list();
			foreach(System.Reflection.ParameterInfo pi in pinf)
			{
				Type t=null;
				type_node par_type=null;
				SemanticTree.parameter_type pt=SemanticTree.parameter_type.value;
				if (pi.ParameterType.IsByRef) 
				{
					t=pi.ParameterType.GetElementType();
					par_type=compiled_type_node.get_type_node(t);
					pt=SemanticTree.parameter_type.var;
				}
				else
				{
					par_type=compiled_type_node.get_type_node(pi.ParameterType);
				}
				string name=pi.Name;
				compiled_parameter crpar=new compiled_parameter(pi);
				crpar.SetParameterType(pt);
				pal.AddElement(crpar);
                if (pi.IsOptional && pi.DefaultValue != null)
                    _num_of_default_parameters++;
			}
			this.return_value_type=compiled_type_node.get_type_node(_con_info.DeclaringType);
			this.parameters.AddRange(pal);
		}
        public string GetCode()
        {
            System.Reflection.ParameterInfo[] paras;
            if (constructor != null)
            {
                paras = constructor.GetParameters();
            }
            else
            {
                paras = new System.Reflection.ParameterInfo[0];
            }

            string funccode = Properties.Resources.CreateInstance;

            funccode = funccode.Replace("[classname]", classname);
            funccode = funccode.Replace("[paracount]", paras.Length.ToString());

            string pushparas = string.Empty;

            for (int i = 0; i < paras.Length; i++)
            {
                var para = paras[i];

                pushparas = pushparas + "\t\t\t\t" + string.Format("para.Add({0});\n", GetAS3RuntimeTypeString(para.ParameterType));
            }

            funccode = funccode.Replace("[pushparas]", pushparas);


            string loadargs = string.Empty;

            for (int i = 0; i < paras.Length; i++)
            {
                var argement = paras[i];

                loadargs = loadargs + GetLoadArgementString(argement);
                loadargs = loadargs + "\n";
            }

            funccode = funccode.Replace("[loadargement]", loadargs);



            string newobj = "new ";

            newobj += NativeCodeCreatorBase.GetTypeFullName(type);
            newobj += "(";

            for (int i = 0; i < paras.Length; i++)
            {
                newobj += string.Format("({0})arg{1}", GetTypeFullName(paras[i].ParameterType), i);
                if (i < paras.Length - 1)
                {
                    newobj += ",";
                }
            }

            newobj += ")";



            funccode = funccode.Replace("[newinstance]", newobj);
            return(funccode);
        }
Exemplo n.º 25
0
        private dynamic ParseCollection(Type t, STEPParser.CollectionContext value)
        {
            // Ex: #25 = IFCDIRECTION((1., 0., 0.));
            // IfcDirection takes a List<double> as its input parameters, so we get the type argument - double - and
            // do the coercion for all the items.

            // Ex: #31 = IFCSITE('3BoQ8L5UXBEOT1kW0PLzej', #2, 'Default Site', 'Description of Default Site', $, #32, $, $, .ELEMENT., (24, 28, 0), (54, 25, 0), 10., $, $);
            // IfcSite takes two IfcCompoundPlaneMeasure objects. It seems that some IFC exporters will not specify a type's constructor, they'll just
            // specify the arguments as a collection.

            Type collectionType;

            System.Reflection.ConstructorInfo ctor = null;
            var ctorChain = new List <System.Reflection.ConstructorInfo>();

            if (t.IsGenericType)
            {
                collectionType = t.GetGenericArguments()[0];
            }
            else
            {
                ctor           = GetConstructorForType(t, ref ctorChain);
                collectionType = ctor.GetParameters()[0].ParameterType.GetGenericArguments()[0];
            }

            var result = new List <object>();

            foreach (var cv in value.collectionValue())
            {
                if (cv.Id() != null)
                {
                    result.Add(ParseId(cv.Id().GetText()));
                }
                else if (cv.AnyString() != null)
                {
                    result.Add(ParseString(collectionType, cv.AnyString().GetText()));
                }
                else if (cv.StringLiteral() != null)
                {
                    result.Add(ParseString(collectionType, cv.StringLiteral().GetText()));
                }
                else if (cv.IntegerLiteral() != null)
                {
                    result.Add(ParseInt(collectionType, cv.IntegerLiteral().GetText()));
                }
                else if (cv.RealLiteral() != null)
                {
                    result.Add(ParseReal(collectionType, cv.RealLiteral().GetText()));
                }
                else if (cv.constructor() != null)
                {
                    result.Add(ParseConstructor(currId, cv.constructor()));
                }
            }

            if (ctor != null)
            {
                return(new InstanceData(-1, t, new List <object>()
                {
                    result
                }, ctor, ctorChain));
            }

            return(result);
        }
Exemplo n.º 26
0
        public string GetCode()
        {
            System.Reflection.ParameterInfo[] paras;
            if (constructor != null)
            {
                paras = constructor.GetParameters();
            }
            else
            {
                paras = new System.Reflection.ParameterInfo[0];
            }

            string funccode = Properties.Resources.CtorFunc;

            funccode = funccode.Replace("[classname]", classname);
            funccode = funccode.Replace("[paracount]", paras.Length.ToString());

            string pushparas = string.Empty;

            for (int i = 0; i < paras.Length; i++)
            {
                var para = paras[i];

                pushparas = pushparas + "\t\t\t\t" + string.Format("para.Add({0});\n", GetAS3RuntimeTypeString(para.ParameterType));
            }

            funccode = funccode.Replace("[pushparas]", pushparas);


            string loadargs = string.Empty;

            for (int i = 0; i < paras.Length; i++)
            {
                var argement = paras[i];

                loadargs = loadargs + GetLoadArgementString(argement);
                loadargs = loadargs + "\n";
            }

            funccode = funccode.Replace("[loadargement]", loadargs);


            string setnativeinstance = string.Empty;

            if (type.IsValueType)
            {
                //((LinkObj<UInt64>)((ASBinCode.rtData.rtObjectBase)thisObj).value).value = (UInt64)value;
                setnativeinstance = "((LinkObj<" + GetTypeFullName(type) + ">)((ASBinCode.rtData.rtObjectBase)thisObj).value).value = ";
            }
            else
            {
                setnativeinstance = "((LinkObj<object>)((ASBinCode.rtData.rtObjectBase)thisObj).value).value = ";
            }



            string newobj = "new ";

            newobj += NativeCodeCreatorBase.GetTypeFullName(type);
            newobj += "(";

            for (int i = 0; i < paras.Length; i++)
            {
                newobj += string.Format("({0})arg{1}", GetTypeFullName(paras[i].ParameterType), i);
                if (i < paras.Length - 1)
                {
                    newobj += ",";
                }
            }

            newobj += ");";

            setnativeinstance += newobj;

            funccode = funccode.Replace("[setnativeinstance]", setnativeinstance);
            return(funccode);
        }
        public UsedRsDataSets(string RdlPath)
        {
            //all this code is just to call VBExpressionParser.ParseExpression which is a private class
            //that method required all sorts of other objects, not many of which we know what in the world they are for
            System.Reflection.Assembly assembly = System.Reflection.Assembly.Load("Microsoft.ReportingServices.ProcessingCore");
#if !YUKON
            Type type = BIDSHelper.SSIS.ExpressionHighlighterPlugin.GetPrivateType(assembly.GetTypes()[0], "Microsoft.ReportingServices.RdlExpressions.VBExpressionParser");
#else
            Type type = BIDSHelper.SSIS.ExpressionHighlighterPlugin.GetPrivateType(assembly.GetTypes()[0], "Microsoft.ReportingServices.ReportProcessing.VBExpressionParser");
#endif
            System.Reflection.ConstructorInfo constructor = type.GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)[0];

            //create PublishingErrorContext
            Type typeErrorContext = BIDSHelper.SSIS.ExpressionHighlighterPlugin.GetPrivateType(assembly.GetTypes()[0], "Microsoft.ReportingServices.ReportProcessing.PublishingErrorContext");
            System.Reflection.ConstructorInfo constructorErrorContext = typeErrorContext.GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)[0];
            object oErrorContext = constructorErrorContext.Invoke(new object[] { });

            //get ExpressionContext type and constructor
#if !YUKON
            Type typeExpressionContext = BIDSHelper.SSIS.ExpressionHighlighterPlugin.GetPrivateType(assembly.GetTypes()[0], "Microsoft.ReportingServices.RdlExpressions.ExpressionParser+ExpressionContext");
#else
            Type typeExpressionContext = BIDSHelper.SSIS.ExpressionHighlighterPlugin.GetPrivateType(assembly.GetTypes()[0], "Microsoft.ReportingServices.ReportProcessing.ExpressionParser+ExpressionContext");
#endif
            System.Reflection.ConstructorInfo constructorExpressionContext = typeExpressionContext.GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)[0];

#if DENALI || SQL2014
            //get InternalPublishingContext constructor
            Type typeInternalPublishingContext = BIDSHelper.SSIS.ExpressionHighlighterPlugin.GetPrivateType(assembly.GetTypes()[0], "Microsoft.ReportingServices.ReportPublishing.InternalPublishingContext");
            System.Reflection.ConstructorInfo constructorInternalPublishingContext = null;
            foreach (System.Reflection.ConstructorInfo c in typeInternalPublishingContext.GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public))
            {
                if (c.GetParameters().Length == 8)
                {
                    constructorInternalPublishingContext = c;
                    break;
                }
            }
            if (constructorInternalPublishingContext == null)
            {
                throw new Exception("Couldn't find InternalPublishingContext constructor");
            }
#endif

            //get PreviewItemContext
            System.Reflection.Assembly assemblyReportPreview = System.Reflection.Assembly.Load("Microsoft.ReportingServices.ReportPreview");
            Type typeItemContext = BIDSHelper.SSIS.ExpressionHighlighterPlugin.GetPrivateType(assemblyReportPreview.GetTypes()[0], "Microsoft.Reporting.PreviewItemContext");

            ////////////////////////////////////////
            //now run the main code to parse the RDL
            XmlDocument doc = new XmlDocument();
            doc.Load(RdlPath);

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace("rs", doc.DocumentElement.NamespaceURI);

            //build list of all DataSets in report
            foreach (XmlNode nodeDataSet in doc.SelectNodes("/rs:Report/rs:DataSets/rs:DataSet", nsmgr))
            {
                RsDataSet ds = new RsDataSet();
                ds.ReportName  = System.IO.Path.GetFileNameWithoutExtension(RdlPath);
                ds.DataSetName = nodeDataSet.Attributes["Name"].Value;
                _dataSets.Add(ds.DataSetName, ds);
            }

            //build list of all objects such as tables that use the dataset
            foreach (XmlNode nodeDataSetRef in doc.SelectNodes("//rs:DataSetName", nsmgr))
            {
                if (_dataSets.ContainsKey(nodeDataSetRef.InnerText))
                {
                    if (!_dataSets[nodeDataSetRef.InnerText].Usages.Contains(GetPathForXmlNode(nodeDataSetRef)))
                    {
                        _dataSets[nodeDataSetRef.InnerText].Usages.Add(GetPathForXmlNode(nodeDataSetRef));
                    }
                }
            }

            //loop through all expressions and parse them
            foreach (XmlNode nodeExpression in doc.SelectNodes("//*[starts-with(text(),'=')]", nsmgr))
            {
                try
                {
                    //see if the surrounding table, for example, has already said it uses a particular DataSet. If so, we won't report it again
                    string  sDataSetUsedByParent = string.Empty;
                    XmlNode parentNode           = nodeExpression.SelectSingleNode("ancestor-or-self::*/rs:DataSetName", nsmgr);
                    if (parentNode != null)
                    {
                        sDataSetUsedByParent = parentNode.InnerText;
                    }

                    //create VBExpressionParser
                    object vbparser = constructor.Invoke(new object[] { oErrorContext });

                    //create PreviewItemContext
                    object itemContext = typeItemContext.GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public)[0].Invoke(null);

#if DENALI || SQL2014
                    //signature of this function call is: public InternalPublishingContext(ICatalogItemContext catalogContext, Microsoft.ReportingServices.ReportProcessing.ReportProcessing.CheckSharedDataSource checkDataSourceCallback, Microsoft.ReportingServices.ReportProcessing.ReportProcessing.ResolveTemporaryDataSource resolveTemporaryDataSourceCallback, DataSourceInfoCollection originalDataSources, IConfiguration configuration, IDataProtection dataProtection, bool traceAtomicScopes, bool isPackagedReportArchive)
                    object oInternalPublishingContext = constructorInternalPublishingContext.Invoke(new object[] { itemContext, null, null, null, null, null, false, false });

                    //create ExpressionContext
                    //signature of this function call is: internal ExpressionContext(ExpressionParser.ExpressionType expressionType, DataType constantType, LocationFlags location, ObjectType objectType, string objectName, string propertyName, string dataSetName, int maxExpressionLength, InternalPublishingContext publishingContext);
                    object expressionContext = constructorExpressionContext.Invoke(new object[] { ExpressionInfo.ExpressionType.General, 0x12, ExpressionInfo.LocationFlags.None, ExpressionInfo.ObjectType.Field, string.Empty, "Text", "DSN", int.MaxValue, oInternalPublishingContext });
#elif KATMAI
                    //create ExpressionContext
                    object expressionContext = null;
                    if (constructorExpressionContext.GetParameters().Length == 8)
                    {
                        //SSRS2008 R2
                        //signature of this function call is: internal ExpressionContext(ExpressionParser.ExpressionType expressionType, DataType constantType, LocationFlags location, ObjectType objectType, string objectName, string propertyName, string dataSetName, int maxExpressionLength);
                        expressionContext = constructorExpressionContext.Invoke(new object[] { ExpressionInfo.ExpressionType.General, 0x12, ExpressionInfo.LocationFlags.None, ExpressionInfo.ObjectType.Field, string.Empty, "Text", "DSN", int.MaxValue });
                    }
                    else
                    {
                        //SSRS2008
                        //signature of this function call is: internal ExpressionContext(ExpressionParser.ExpressionType expressionType, DataType constantType, LocationFlags location, ObjectType objectType, string objectName, string propertyName, string dataSetName)
                        expressionContext = constructorExpressionContext.Invoke(new object[] { ExpressionInfo.ExpressionType.General, 0x12, ExpressionInfo.LocationFlags.None, ExpressionInfo.ObjectType.Field, string.Empty, "Text", "DSN" });
                    }
#elif YUKON
                    //create ExpressionContext
                    //signature of this function call is: internal ExpressionContext(ExpressionParser.ExpressionType expressionType, ExpressionParser.ConstantType constantType, LocationFlags location, ObjectType objectType, string objectName, string propertyName, string dataSetName, bool parseExtended)
                    object expressionContext = constructorExpressionContext.Invoke(new object[] { ExpressionInfo.ExpressionType.General, 0, ExpressionInfo.LocationFlags.None, ExpressionInfo.ObjectType.Field, string.Empty, "Text", "DSN", false });
#endif

                    //find and invoke ParseExpression method
#if !YUKON
                    int      iParseExpressionParamCount = 3;
                    object[] arrParseExpressionParams   = new object[] { nodeExpression.InnerText, expressionContext, 0 };
#else
                    int      iParseExpressionParamCount = 2;
                    object[] arrParseExpressionParams   = new object[] { nodeExpression.InnerText, expressionContext };
#endif
                    System.Reflection.MethodInfo methodParseExpression = null;
                    foreach (System.Reflection.MethodInfo method in type.GetMethods(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
                    {
                        if (method.Name == "ParseExpression" && method.GetParameters().Length == iParseExpressionParamCount)
                        {
                            methodParseExpression = method;
                            break;
                        }
                    }
                    if (methodParseExpression == null)
                    {
                        throw new Exception("Couldn't find VBExpressionParser.ParseExpression method");
                    }
                    object expressionInfo = methodParseExpression.Invoke(vbparser, arrParseExpressionParams);

                    //create a wrapper for the SSRS object then examine it recursively
                    ExpressionInfo info = new ExpressionInfo(expressionInfo);
                    RecurseExpressionInfo(info, nodeExpression, sDataSetUsedByParent);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error while scanning...\r\nReport: " + RdlPath + "\r\nExpression: " + nodeExpression.InnerText, ex);
                }
            }
        }
        public string GetCode()
        {
            System.Reflection.ParameterInfo[] paras;
            if (constructor != null)
            {
                paras = constructor.GetParameters();
            }
            else
            {
                paras = new System.Reflection.ParameterInfo[0];
            }

            string funccode = Properties.Resources.AdapterCtorFunc;

            funccode = funccode.Replace("[adapterclass]", adapterclassname);

            funccode = funccode.Replace("[classname]", classname);
            funccode = funccode.Replace("[paracount]", paras.Length.ToString());

            string pushparas = string.Empty;

            for (int i = 0; i < paras.Length; i++)
            {
                var para = paras[i];

                pushparas = pushparas + "\t\t\t\t" + string.Format("para.Add({0});\n", GetAS3RuntimeTypeString(para.ParameterType));
            }

            funccode = funccode.Replace("[pushparas]", pushparas);


            string loadargs = string.Empty;

            for (int i = 0; i < paras.Length; i++)
            {
                var argement = paras[i];

                loadargs = loadargs + GetLoadArgementString(argement);
                loadargs = loadargs + "\n";
            }

            funccode = funccode.Replace("[loadargement]", loadargs);


            string setnativeinstance = string.Empty;


            setnativeinstance = "((LinkObj<object>)((ASBinCode.rtData.rtObjectBase)thisObj).value).value = ";



            string newobj = "new ";

            newobj += adapterclassname;
            newobj += "(";

            for (int i = 0; i < paras.Length; i++)
            {
                newobj += string.Format("({0})arg{1}", GetTypeFullName(paras[i].ParameterType), i);
                if (i < paras.Length - 1)
                {
                    newobj += ",";
                }
            }

            newobj += ");";

            setnativeinstance += newobj;


            setnativeinstance += "\n";
            setnativeinstance += @"
					((ICrossExtendAdapter)((LinkObj<object>)((ASBinCode.rtData.rtObjectBase)thisObj).value).value)
						.SetAS3RuntimeEnvironment(stackframe.player, ((ASBinCode.rtData.rtObjectBase)thisObj).value._class, (ASBinCode.rtData.rtObjectBase)thisObj);

";

            funccode = funccode.Replace("[setnativeinstance]", setnativeinstance);
            return(funccode);
        }
Exemplo n.º 29
0
        public ConstructorInfo(System.Reflection.ConstructorInfo constructorInfo, XElement xmlDocs)
        {
            Constructor = constructorInfo;

            Parameters = constructorInfo.GetParameters().ToList();
        }
Exemplo n.º 30
0
        private IMVCController CreateNewViewContent_Unsynchronized(IProjectItem document)
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            // make sure that the item is already contained in the project
            if (!Current.Project.ContainsItem(document))
            {
                Current.Project.AddItemWithThisOrModifiedName(document);
            }

            var types = Altaxo.Main.Services.ReflectionService.GetNonAbstractSubclassesOf(typeof(AbstractViewContent));

            System.Reflection.ConstructorInfo cinfo = null;
            object viewContent = null;

            foreach (Type type in types)
            {
                if (null != (cinfo = type.GetConstructor(new Type[] { document.GetType() })))
                {
                    var par = cinfo.GetParameters()[0];
                    if (par.ParameterType != typeof(object)) // ignore view content which takes the most generic type
                    {
                        viewContent = cinfo.Invoke(new object[] { document });
                        break;
                    }
                }
            }

            if (null == viewContent)
            {
                foreach (IProjectItemDisplayBindingDescriptor descriptor in AddInTree.BuildItems <IProjectItemDisplayBindingDescriptor>("/Altaxo/Workbench/ProjectItemDisplayBindings", this, false))
                {
                    if (descriptor.ProjectItemType == document.GetType())
                    {
                        if (null != (cinfo = descriptor.ViewContentType.GetConstructor(new Type[] { document.GetType() })))
                        {
                            var par = cinfo.GetParameters()[0];
                            if (par.ParameterType != typeof(object)) // ignore view content which takes the most generic type
                            {
                                viewContent = cinfo.Invoke(new object[] { document });
                                break;
                            }
                        }
                    }
                }
            }

            var controller = viewContent as IMVCController;

            if (controller.ViewObject == null)
            {
                Current.Gui.FindAndAttachControlTo(controller);
            }

            if (null != Current.Workbench)
            {
                Current.Workbench.ShowView(viewContent, true);
            }

            return(controller);
        }
Exemplo n.º 31
0
 public bool Is <T>() where T : class
 {
     System.Reflection.ConstructorInfo ctor = typeof(T).GetConstructors()[0];
     System.Type paramType = ctor.GetParameters()[0].ParameterType;
     return(paramType.IsInstanceOfType(this.WrappedObject));
 }
Exemplo n.º 32
0
        public override void ModifyImplementation(CodeNamespace cns, CodeTypeDeclaration ctd, Type type)
        {
            if (implementation == NullableImplementation.Default || implementation == NullableImplementation.Abstract)
            {
                ctd.BaseTypes.Add(new CodeTypeReference("INullable"));
                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name       = "IsNull";
                prop.Type       = new CodeTypeReference(typeof(bool));
                prop.Attributes = MemberAttributes.Public;
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(false)));
                ctd.Members.Add(prop);
            }
            if (implementation != NullableImplementation.Abstract)
            {
                CodeTypeDeclaration newType = new CodeTypeDeclaration("Null" + ctd.Name);
                newType.BaseTypes.Add(new CodeTypeReference(ctd.Name));
                cns.Types.Add(newType);

                System.Reflection.ConstructorInfo baseCtor = MainClass.GetBaseCtor(type);
                CodeConstructor ctor = new CodeConstructor();
                ctor.Attributes = MemberAttributes.Private;
                if (baseCtor != null)
                {
                    foreach (object o in baseCtor.GetParameters())
                    {
                        ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(null));
                    }
                }
                newType.Members.Add(ctor);

                CodeMemberField field = new CodeMemberField(newType.Name, "instance");
                field.Attributes     = MemberAttributes.Static;
                field.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference(newType.Name));
                newType.Members.Add(field);

                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name       = "Instance";
                prop.Type       = new CodeTypeReference(newType.Name);
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("instance")));
                newType.Members.Add(prop);

                prop            = new CodeMemberProperty();
                prop.Name       = "IsNull";
                prop.Type       = new CodeTypeReference(typeof(bool));
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Override;
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(true)));
                newType.Members.Add(prop);

                CodeMemberMethod method = new CodeMemberMethod();
                method.Name       = "AcceptVisitor";
                method.Attributes = MemberAttributes.Public | MemberAttributes.Override;
                method.Parameters.Add(new CodeParameterDeclarationExpression("IAstVisitor", "visitor"));
                method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "data"));
                method.ReturnType = new CodeTypeReference(typeof(object));
                method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
                newType.Members.Add(method);

                method            = new CodeMemberMethod();
                method.Name       = "ToString";
                method.Attributes = MemberAttributes.Public | MemberAttributes.Override;
                method.ReturnType = new CodeTypeReference(typeof(string));
                method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("[" + newType.Name + "]")));
                newType.Members.Add(method);

                prop            = new CodeMemberProperty();
                prop.Name       = "Null";
                prop.Type       = new CodeTypeReference(ctd.Name);
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                if (implementation == NullableImplementation.Shadow)
                {
                    prop.Attributes |= MemberAttributes.New;
                }
                CodeExpression ex = new CodeTypeReferenceExpression(newType.Name);
                ex = new CodePropertyReferenceExpression(ex, "Instance");
                prop.GetStatements.Add(new CodeMethodReturnStatement(ex));
                ctd.Members.Add(prop);
            }
        }