Inheritance: IRequireResolving, IReflectionVisitable
 public virtual DialogResult ShowDialog(CustomAttribute attribute, CustomAttributeNamedArgument? argument, bool usefields)
 {
     m_selectedargument = argument;
     m_selectedattribute = attribute;
     m_usefields = usefields;
     return base.ShowDialog();
 }
Example #2
0
        private CecilCustomAttribute CreateCecilCustomAttribute(ModuleDefinition module)
        {
            var ctorRef = Constructor.Import(module);
            var cca     = new CecilCustomAttribute(ctorRef);

            foreach (var value in Arguments)
            {
                cca.ConstructorArguments.Add(CreateCecilTypedArgument(
                                                 module, value));
            }

            for (var i = 0; i < PropertiesInitialized.Length; ++i)
            {
                var clrProp = PropertiesInitialized[i];
                var value   = PropertyValues[i];
                cca.Properties.Add(CreateCecilNamedArgument(
                                       clrProp.Name, module, value));
            }

            for (var i = 0; i < FieldsInitialized.Length; ++i)
            {
                var clrField = FieldsInitialized[i];
                var value    = FieldValues[i];
                cca.Fields.Add(CreateCecilNamedArgument(
                                   clrField.Name, module, value));
            }
            return(cca);
        }
		/*CustomAttribute customAttribute;
		
		public CustomAttribute CustomAttribute {
			get {
				return customAttribute;
			}
		}*/
		
		public DomCecilAttribute (CustomAttribute customAttribute)
		{
			//this.customAttribute = customAttribute;
			base.AttributeType = DomCecilMethod.GetReturnType (customAttribute.Constructor);
			base.Name          = customAttribute.Constructor.DeclaringType.FullName;
			
			try {
				foreach (var argument in customAttribute.ConstructorArguments)
					AddPositionalArgument (CreateExpressionFor (argument));
			} catch (Exception e) {
				LoggingService.LogError ("Error reading attributes", e);
			}
			
			try {
				foreach (var namedArgument in customAttribute.Properties)
					AddNamedArgument (namedArgument.Name, CreateExpressionFor (namedArgument.Argument));
			} catch (Exception e) {
				LoggingService.LogError ("Error reading attributes", e);
			}
			
			try {
				foreach (var namedArgument in customAttribute.Fields)
					AddNamedArgument (namedArgument.Name, CreateExpressionFor (namedArgument.Argument));
			} catch (Exception e) {
				LoggingService.LogError ("Error reading attributes", e);
			}
		}
		public void Run()
		{
			// Retrieve the target method onto which we want to add the attribute
			var targetType = _module.Types.Single(t => t.Name == "Target");
			var targetMethod = targetType.Methods.Single(m => m.Name == "TargetMethod");

			// Retrieve the type of the attribute
			var decorationAttributeType = _module.Types.Single(t => t.Name == "DecorationAttribute");

			// Create the equivalent of [Decoration("WOW")]
			// All custom attributes are created from a constructor
			var decorationAttributeConstructor = decorationAttributeType
				.Methods
				.Single(m => m.IsConstructor
					&& m.Parameters.Count == 1
					&& m.Parameters[0].ParameterType.MetadataType == MetadataType.String);

			var decorationAttribute = new CustomAttribute(decorationAttributeConstructor);

			decorationAttribute.ConstructorArguments.Add(
				new CustomAttributeArgument(
					type: _module.TypeSystem.String,
					value: "WOW"));

			// Add the custom attribute to the method
			targetMethod.CustomAttributes.Add(decorationAttribute);

			// Write the module with default parameters
			_module.Write(_targetFileName);
		}
Example #5
0
        public void Visit(IBehaviorDefinition method, CustomAttribute attribute)
        {
            ILProcessor processor = method.Body.GetILProcessor();
            string description = attribute.Properties.Where(argument => (argument.Name == "Description")).First().Argument.Value as string;
            Instruction exitInstruction = processor.Create(OpCodes.Callvirt, method.Module.Import(broadcastType.GetMethod("Run", new[] {typeof(object), typeof(string)})));
            var returnValue = new VariableDefinition("retVal", method.Module.Import(typeof(object)));
            var enclosingObject = new VariableDefinition("enclosing", method.Module.Import(typeof(object)));
            method.Body.Variables.Add(enclosingObject);
            method.Body.Variables.Add(returnValue);
            Instruction store = processor.Create(OpCodes.Stloc, returnValue);
            Instruction reload = processor.Create(OpCodes.Ldloc, returnValue);
            var instructions = new List<Instruction>();
            if (!ReturnsVoid(method))
            {
                instructions.Add(store);
            }
            instructions.Add(processor.Create(OpCodes.Newobj, method.Module.Import(broadcastType.GetConstructor(new Type[] { }))));
            instructions.Add(processor.Create(OpCodes.Ldarg_0));
            instructions.Add(processor.Create(OpCodes.Ldstr, description));
            instructions.Add(exitInstruction);
            if (!ReturnsVoid(method))
            {
                instructions.Add(reload);
            }

            new InsertionAtEnd(processor, method).Run(instructions);
        }
Example #6
0
        /// <summary>
        /// Runs the specified cloaking task.
        /// </summary>
        /// <param name="context">The running context of this cloak job.</param>
        public void RunTask(ICloakContext context)
        {
            Dictionary<string, AssemblyDefinition> assemblyCache = context.GetAssemblyDefinitions();
            foreach (string assembly in assemblyCache.Keys)
            {
                AssemblyDefinition def = assemblyCache[assembly];
                Type si = typeof (SuppressIldasmAttribute);
                CustomAttribute found = null;
                foreach (CustomAttribute attr in def.CustomAttributes)
                {
                    if (attr.Constructor.DeclaringType.FullName == si.FullName)
                    {
                        found = attr;
                        break;
                    }
                }

                //Only add if it's not there already
                if (found == null)
                {
                    //Add one
                    MethodReference constructor = def.MainModule.Import(typeof (SuppressIldasmAttribute).GetConstructor(Type.EmptyTypes));
                    CustomAttribute attr = new CustomAttribute(constructor);
                    def.CustomAttributes.Add(attr);
                }
            }

        }
 protected override bool IsRemovedAttribute(CustomAttribute attribute)
 {
     // note: this also avoid calling FullName (which allocates a string)
     var attr_type = attribute.Constructor.DeclaringType;
     switch (attr_type.Name) {
     case "AdviceAttribute":
     case "FieldAttribute":
     case "PreserveAttribute":	// the ApplyPreserveAttribute substep is executed before this
     case "LinkerSafeAttribute":
         return attr_type.Namespace == Namespaces.Foundation;
     // used for documentation, not at runtime
     case "AvailabilityAttribute":
     case "AvailabilityBaseAttribute":
     case "DeprecatedAttribute":
     case "IntroducedAttribute":
     case "iOSAttribute":
     case "MacAttribute":
     case "LionAttribute":
     case "MountainLionAttribute":
     case "MavericksAttribute":
     case "ObsoletedAttribute":
     case "SinceAttribute":
     case "ThreadSafeAttribute":
     case "UnavailableAttribute":
     case "LinkWithAttribute":
     case "DesignatedInitializerAttribute":
         return attr_type.Namespace == Namespaces.ObjCRuntime;
     default:
         return base.IsRemovedAttribute (attribute);
     }
 }
        protected override void WillRemoveAttribute(ICustomAttributeProvider provider, CustomAttribute attribute)
        {
            var attr_type = attribute.Constructor.DeclaringType;
            if (attr_type.Namespace == Namespaces.ObjCRuntime) {
                switch (attr_type.Name) {
                case "AvailabilityAttribute":
                case "AvailabilityBaseAttribute":
                case "DeprecatedAttribute":
                case "IntroducedAttribute":
                    var dict = context.Annotations.GetCustomAnnotations ("Availability");
                    List<CustomAttribute> attribs;
                    object attribObjects;
                    if (!dict.TryGetValue (provider, out attribObjects)) {
                        attribs = new List<CustomAttribute> ();
                        dict [provider] = attribs;
                    } else {
                        attribs = (List<CustomAttribute>) attribObjects;
                    }
                    // Make sure the attribute is resolved, since after removing the attribute
                    // it won't be able to do it. The 'CustomAttribute.Resolve' method is private, but fetching
                    // any property will cause it to be called.
                    var dummy = attribute.HasConstructorArguments;
                    attribs.Add (attribute);
                    break;
                }
            }

            base.WillRemoveAttribute (provider, attribute);
        }
Example #9
0
        private bool AddXmlSchemaProviderAttribute(CatelType catelType)
        {
            var catelTypeDefinition = catelType.TypeDefinition;

            var methodName = GetXmlSchemaMethodName(catelType);

            var existingCustomAttribute = (from attribute in catelTypeDefinition.CustomAttributes
                                           where string.Equals(attribute.AttributeType.Name, "XmlSchemaProviderAttribute")
                                           select attribute).FirstOrDefault();
            if (existingCustomAttribute != null)
            {
                var constructorArgument = existingCustomAttribute.ConstructorArguments[0];
                if (string.Equals(constructorArgument.Value, methodName))
                {
                    return false;
                }
            }

            var xmlSchemaProviderAttribute = catelTypeDefinition.Module.FindType("System.Xml", "System.Xml.Serialization.XmlSchemaProviderAttribute");

            var attributeConstructor = catelTypeDefinition.Module.Import(xmlSchemaProviderAttribute.Resolve().Constructor(false));
            var customAttribute = new CustomAttribute(attributeConstructor);
            customAttribute.ConstructorArguments.Add(new CustomAttributeArgument(catelTypeDefinition.Module.TypeSystem.String, methodName));

            catelTypeDefinition.CustomAttributes.Add(customAttribute);

            return true;
        }
 public static CustomAttribute Clone(CustomAttribute custattr, ModuleDefinition context,
     IImportMapper mapper)
 {
     var ca = new CustomAttribute(context.Import(custattr.Constructor, mapper));
     custattr.CopyTo(ca, context, mapper);
     return ca;
 }
Example #11
0
        public void Visit(IBehaviorDefinition behaviorDefinition, CustomAttribute attribute)
        {
            ILProcessor processor = behaviorDefinition.Body.GetILProcessor();
            var pingerDefinition = new VariableDefinition("pinger",
                                                          behaviorDefinition.Module.Import(breakpointType));
            behaviorDefinition.Body.Variables.Add(pingerDefinition);
            var sequencedInstructions =
                behaviorDefinition.Body.Instructions.Where(instruction => instruction.SequencePoint != null).ToList();

            Console.Out.WriteLine(sequencedInstructions.Count);
            //            var extractedInstructions = Specific(sequencedInstructions, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 20, 21);
            var extractedInstructions = Filtered(sequencedInstructions);
            foreach (var instruction in extractedInstructions)
            {
                Type intType = typeof(int);
                var breakPointInstructions = new List<Instruction>
                                       {
                                           processor.Create(OpCodes.Newobj, behaviorDefinition.Module.Import(
                                                                                breakpointType.GetConstructor(new Type[]{}))),
                                           processor.Create(OpCodes.Ldc_I4, instruction.SequencePoint.StartLine),
                                           processor.Create(OpCodes.Ldc_I4, instruction.SequencePoint.StartColumn),
                                           processor.Create(OpCodes.Ldc_I4, instruction.SequencePoint.EndLine),
                                           processor.Create(OpCodes.Ldc_I4, instruction.SequencePoint.EndColumn),
                                           processor.Create(OpCodes.Ldstr, instruction.SequencePoint.Document.Url),
                                           processor.Create(OpCodes.Call,
                                                            behaviorDefinition.Module.Import(breakpointType.GetMethod("Activate",
                                                                                                                      new[] {intType, intType, intType, intType, typeof(string)})))
                                       };
                breakPointInstructions.ForEach(bpr => processor.InsertBefore(instruction, bpr));
                foreach (var i in behaviorDefinition.Body.Instructions)
                {
                    Console.Out.WriteLine("{0}/[{1}]: {2} {3}", i.Offset, Sequence(i.SequencePoint), i.OpCode, i.Operand);
                }
            }
        }
Example #12
0
        public void Visit(IBehaviorDefinition method, CustomAttribute attribute)
        {
            ILProcessor processor = method.Body.GetILProcessor();
            string description = attribute.Properties.Where(argument => (argument.Name == "Description")).First().Argument.Value as string;
            var listType = typeof(List<object>);
            var listVariable = new VariableDefinition("argumentz", method.Module.Import(listType));
            method.Body.Variables.Add(listVariable);
            var instructions = new List<Instruction>();
            instructions.Add(processor.Create(OpCodes.Newobj, method.Module.Import(listType.GetConstructor(new Type[] { }))));
            instructions.Add(processor.Create(OpCodes.Stloc, listVariable));

            int parameterIndex = 1;
            foreach (var parameter in method.Parameters)
            {
                instructions.Add(processor.Create(OpCodes.Ldloc, listVariable));
                instructions.Add(processor.Create(OpCodes.Ldarg, parameterIndex));
                if (parameter.ParameterType.IsPrimitive || parameter.ParameterType.IsValueType)
                    instructions.Add(processor.Create(OpCodes.Box, parameter.ParameterType));
                instructions.Add(processor.Create(OpCodes.Callvirt, method.Module.Import(listType.GetMethod("Add", new[] { typeof(object) }))));
                ++parameterIndex;
            }
            instructions.Add(processor.Create(OpCodes.Newobj, method.Module.Import(broadcastType.GetConstructor(new Type[] {}))));
            instructions.Add(processor.Create(OpCodes.Ldloc, listVariable));
            instructions.Add(processor.Create(OpCodes.Ldstr, description));
            instructions.Add(processor.Create(OpCodes.Callvirt, method.Module.Import(broadcastType.GetMethod("Run", new[] {listType, typeof(string)}))));

            new InsertionAtStart(processor, method).Run(instructions);
        }
Example #13
0
        MethodReference FindConstructor(CustomAttribute att)
        {
            // The constructor provided by CustomAttribute.Constructor is lacking some information, such as the parameter
            // name and custom attributes. Since we need the full info, we have to look it up in the declaring type.

            TypeDefinition atd = FindTypeDefinition(att.Constructor.DeclaringType.Module.Assembly, att.Constructor.DeclaringType);

            foreach (MethodReference met in atd.Methods)
            {
                if (met.Name != ".ctor")
                {
                    continue;
                }

                if (met.Parameters.Count == att.Constructor.Parameters.Count)
                {
                    for (int n = met.Parameters.Count - 1; n >= 0; n--)
                    {
                        if (met.Parameters[n].ParameterType.FullName != att.Constructor.Parameters[n].ParameterType.FullName)
                        {
                            break;
                        }
                        if (n == 0)
                        {
                            return(met);
                        }
                    }
                }
            }
            return(null);
        }
        public static CustomAttribute InjectCustomAttribute(this ICustomAttributeProvider provider, CustomAttribute attribute, ReferenceResolver resolver)
        {
            if (attribute == null)
                throw new ArgumentNullException("attribute");
            if (resolver == null)
                throw new ArgumentNullException("resolver");

            TypeReference attributeType = resolver.ReferenceType(attribute.AttributeType);

            // no context required as attributes cannot be generic
            MethodReference constructor = resolver.ReferenceMethod(attribute.Constructor);

            CustomAttribute newAttribute;
            if ((newAttribute = Helper.GetCustomAttribute(provider.CustomAttributes, attribute)) != null)
                return newAttribute;

            newAttribute = new CustomAttribute(constructor);//, attr.GetBlob());
            provider.CustomAttributes.Add(newAttribute);

            MetadataBuilderHelper.CopyCustomAttributeArguments(attribute.ConstructorArguments, newAttribute.ConstructorArguments, resolver);

            MetadataBuilderHelper.CopyCustomAttributeNamedArguments(attribute.Fields, newAttribute.Fields, resolver);

            MetadataBuilderHelper.CopyCustomAttributeNamedArguments(attribute.Properties, newAttribute.Properties, resolver);

            return newAttribute;
        }
Example #15
0
        public AppliedPatchInfo(CustomAttribute cecilCustomAttribute)
        {
            _cecilCustomAttribute = cecilCustomAttribute;
            Name =  cecilCustomAttribute.Fields.Single(f => f.Name == "Name").Argument.Value.ToString();

            Version = int.Parse(
                cecilCustomAttribute.Fields.Single(f => f.Name == "Version").Argument.Value.ToString()
                );

            var catStr = PatchCategory.Unknown.ToString();
            var catField = cecilCustomAttribute.Fields.SingleOrDefault(f => f.Name == "Category");
            if (catField.Name == "Category")
            {
                catStr = catField.Argument.Value.ToString();
            }

            PatchCategory catTemp = PatchCategory.Unknown;
            Enum.TryParse(catStr, true, out catTemp);
            Category = catTemp;

            var codeBlocksObj = cecilCustomAttribute.Fields.SingleOrDefault(f => f.Name == "CodeBlocks");

            if (codeBlocksObj.Name == "CodeBlocks")
            {
                AppliedCodeBlocks = AppliedCodeBlock.Deserialise(codeBlocksObj.Argument.Value.ToString());
            }
            else
            {
                AppliedCodeBlocks = new List<AppliedCodeBlock>();
            }
        }
Example #16
0
        /// <summary>
        /// Public translation interface.
        /// Translates the given method to GLSL
        /// </summary>
        /// <param name="s">Shader type definition.</param>
        /// <param name="m">A method representing a shader to translate.</param>
        /// <param name="attr">The shader type as attribute (either FragmentShaderAttribute or VertexShaderAttribute</param>
        /// <param name="type">The shader type as ShaderType</param>
        /// <returns>The translated GLSL shader source</returns>
        public FunctionDescription Transform(TypeDefinition s, MethodDefinition m, CustomAttribute attr,
            ShaderType type)
        {
            if (s == null)
                throw new ArgumentNullException("s");

            if (m == null)
                throw new ArgumentNullException("m");

            if (attr == null)
                throw new ArgumentNullException("attr");

            var ctx = new DecompilerContext(s.Module)
            {
                CurrentType = s,
                CurrentMethod = m,
                CancellationToken = CancellationToken.None
            };

            var d = AstMethodBodyBuilder.CreateMethodBody(m, ctx);

            var glsl = new GlslVisitor(d, attr, ctx);

            _functions.UnionWith(glsl.Functions);

            var entry = (bool)attr.ConstructorArguments.FirstOrDefault().Value;
            var sig = entry ? "void main()" : GlslVisitor.GetSignature(m);

            var code = glsl.Result;
            var desc = new FunctionDescription(entry ? "main" : Shader.GetMethodName(m), sig + code, entry, type);

            _dependencies.UnionWith(glsl.Dependencies);

            return desc;
        }
Example #17
0
        public void Visit(IBehaviorDefinition behaviorDefinition, CustomAttribute attribute)
        {
            ILProcessor processor = behaviorDefinition.Body.GetILProcessor();
            var pingerDefinition = new VariableDefinition("pinger",
                                                         behaviorDefinition.Module.Import(pingType));
            behaviorDefinition.Body.Variables.Add(pingerDefinition);

            var start = new List<Instruction>
                            {
                                processor.Create(OpCodes.Ldstr, behaviorDefinition.Name),
                                processor.Create(OpCodes.Newobj,
                                                 behaviorDefinition.Module.Import(
                                                     pingType.GetConstructor(new[]{typeof(string)}))),
                                processor.Create(OpCodes.Stloc, pingerDefinition),
                                processor.Create(OpCodes.Ldloc, pingerDefinition),
                                processor.Create(OpCodes.Callvirt,
                                               behaviorDefinition.Module.Import(pingType.GetMethod("Start",
                                                                                                      new Type[] {}))),

                            };
            var end = new List<Instruction>
                          {
                              processor.Create(OpCodes.Ldloc, pingerDefinition),
                              processor.Create(OpCodes.Callvirt,
                                               behaviorDefinition.Module.Import(pingType.GetMethod("End",
                                                                                                      new Type[] {})))
                          };

            new InsertionAtStart(processor, behaviorDefinition).Run(start);
            new InsertionAtEnd(processor, behaviorDefinition).Run(end);
            foreach (var instruction in behaviorDefinition.Body.Instructions)
            {
                Console.Out.WriteLine("{0}/[{1}]: {2} {3}", instruction.Offset, Sequence(instruction.SequencePoint), instruction.OpCode, instruction.Operand);
            }
        }
Example #18
0
        public CustomAttribute InjectCustomAttribute(Mono.Cecil.ICustomAttributeProvider target, CustomAttribute attribute)
        {
            if(module == null)
                throw new ArgumentNullException("module");
            if(target == null)
                throw new ArgumentNullException("target");
            if(attribute == null)
                throw new ArgumentNullException("attribute");

            TypeReference attributeType = ReferenceOrInjectType(attribute.AttributeType);

            // no context required as attributes cannot be generic
            MethodReference constructor = ReferenceOrInjectMethod(attribute.Constructor);

            CustomAttribute newAttribute;

            if((newAttribute = Helper.GetCustomAttribute(target.CustomAttributes, attribute)) != null)
                return newAttribute;

            newAttribute = new CustomAttribute(constructor);//, attr.GetBlob());

            target.CustomAttributes.Add(newAttribute);

            CopyCustomAttributeArguments(attribute.ConstructorArguments, newAttribute.ConstructorArguments);

            CopyCustomAttributeNamedArguments(attribute.Fields, newAttribute.Fields);

            CopyCustomAttributeNamedArguments(attribute.Properties, newAttribute.Properties);

            return newAttribute;
        }
 protected override bool IsRemovedAttribute(CustomAttribute attribute)
 {
     // note: this also avoid calling FullName (which allocates a string)
     var attr_type = attribute.Constructor.DeclaringType;
     switch (attr_type.Name) {
     case "ObsoleteAttribute":
     // System.Mono*Attribute from mono/mcs/build/common/MonoTODOAttribute.cs
     case "MonoDocumentationNoteAttribute":
     case "MonoExtensionAttribute":
     case "MonoInternalNoteAttribute":
     case "MonoLimitationAttribute":
     case "MonoNotSupportedAttribute":
     case "MonoTODOAttribute":
         return attr_type.Namespace == "System";
     case "MonoFIXAttribute":
         return attr_type.Namespace == "System.Xml";
     // remove debugging-related attributes if we're not linking symbols (i.e. we're building release builds)
     case "DebuggableAttribute":
     case "DebuggerBrowsableAttribute":
     case "DebuggerDisplayAttribute":
     case "DebuggerHiddenAttribute":
     case "DebuggerNonUserCodeAttribute":
     case "DebuggerStepperBoundaryAttribute":
     case "DebuggerStepThroughAttribute":
     case "DebuggerTypeProxyAttribute":
     case "DebuggerVisualizerAttribute":
         return !DebugBuild && attr_type.Namespace == "System.Diagnostics";
     default:
         return false;
     }
 }
 /// <summary>
 /// Default ctor
 /// </summary>
 internal DexImport(string className, TypeDefinition firstType, CustomAttribute attr, string scope)
 {
     this.className = className;
     this.attr = attr;
     this.scope = scope;
     types = new List<TypeDefinition> { firstType };
 }
Example #21
0
        /// <summary>
        /// Create app widget provider xml file.
        /// </summary>
        private void CreateAppWidgetProviderFile(string tempFolder, int index, CustomAttribute attr)
        {
            var resourceName = AppWidgetProviderResource.GetResourceName(index);
            var path = Path.Combine(Path.Combine(tempFolder, @"res\xml"), resourceName + ".xml");

            var doc = new XDocument();
            var root = new XElement("appwidget-provider");
            doc.Add(root);

            root.AddAttrIfNotEmpty("minWidth", Namespace, attr.GetValue<string>("MinWidth"));
            root.AddAttrIfNotEmpty("minHeight", Namespace, attr.GetValue<string>("MinHeight"));
            root.AddAttrIfNotDefault("updatePeriodMillis", Namespace, attr.GetValue<long>("UpdatePeriod"), 0L);
            root.AddAttrIfNotEmpty("previewImage", Namespace, attr.GetValue<string>("PreviewImage"), FormatDrawable);
            root.AddAttrIfNotEmpty("initialLayout", Namespace, attr.GetValue<string>("InitialLayout"), FormatLayout);
            var configureActivityType = attr.GetValue<TypeReference>("ConfigureActivity");
            if (configureActivityType != null)
            {
                var configureActivityTypeDef = configureActivityType.Resolve();
                if (configureActivityTypeDef == null)
                    throw new ArgumentException("Cannot resolve " + configureActivityType.FullName);
                root.AddAttr("configure", Namespace, FormatClassName(XBuilder.AsTypeDefinition(module, configureActivityTypeDef)));
            }
            root.AddAttrIfNotDefault("resizeMode", Namespace, attr.GetValue<int>("ResizeMode"), 0, widgetResizeModesOptions.Format);
            root.AddAttrIfNotDefault("widgetCategory", Namespace, attr.GetValue<int>("Category"), 0, widgetCategoriesOptions.Format);
            root.AddAttrIfNotEmpty("initialKeyguardLayout", Namespace, attr.GetValue<string>("InitialKeyguardLayout"), FormatLayout);

            Directory.CreateDirectory(Path.GetDirectoryName(path));
            doc.Save(path);
        }
Example #22
0
 private void AddDataAttr(List<Tuple<string, string>> data, CustomAttribute attr, string attrName)
 {
     string propertyName = "Data" + char.ToUpperInvariant(attrName[0]) + attrName.Substring(1);
     string value = attr.GetValue<string>(-1, propertyName);
     if (value == null)
         return;
     data.Add(Tuple.Create(attrName, value));
 }
		public virtual DialogResult ShowDialog(CustomAttribute attribute, CustomAttributeNamedArgument? argument,
			bool usefields)
		{
			SelectedArgument = argument;
			SelectedAttribute = attribute;
			_useFields = usefields;
			return ShowDialog();
		}
Example #24
0
		void MarkMethod (MethodDefinition method, CustomAttribute preserve_attribute)
		{
			if (method == null)
				return;

			Mark (method, preserve_attribute);
			Annotations.SetAction (method, MethodAction.Parse);
		}
Example #25
0
		protected virtual bool IsPreservedAttribute (CustomAttribute attribute)
		{
			// [assembly: Preserve (type)] does not preserve all the code in the assembly, in fact it might
			// not preserve anything in _this_ assembly, but something in a separate assembly (reference)
			if (attribute.HasConstructorArguments)
				return false;
			return (attribute.AttributeType.Name == "PreserveAttribute");
		}
Example #26
0
        public static void VisibileInReport(this TypeDefinition t, bool visible)
        {
            var mod  = t.Module;
            var ctor = mod.ImportReference(typeof(VisibleInReportsAttribute).GetConstructor(new[] { typeof(bool) }));
            var cb   = new Mono.Cecil.CustomAttribute(ctor);

            cb.ConstructorArguments.Add(new CustomAttributeArgument(mod.ImportReference(typeof(bool)), visible));
            t.CustomAttributes.Add(cb);
        }
		void Mark (IMetadataTokenProvider provider, CustomAttribute preserve_attribute)
		{
			if (IsConditionalAttribute (preserve_attribute)) {
				PreserveConditional (provider);
				return;
			}

			PreserveUnconditional (provider);
		}
Example #28
0
        public static object GetLeadingConstructorArgument(CustomAttribute customAttribute)
        {
            if (customAttribute.ConstructorParameters.Count < 1)
            {
                throw new CompilerException("Expected custom attribute to have at least 1 constructor parameter: " + customAttribute);
            }

            return customAttribute.ConstructorParameters[0];
        }
Example #29
0
 /// <summary>
 /// Adds the specified attribute to the specified field.
 /// </summary>
 /// <param name="field">The field to add the attribute to.</param>
 /// <param name="attribute">The attribute to add.</param>
 /// <param name="module">The module the field is defined in.</param>
 public static CustomAttribute AddAttribute(FieldDefinition field, Type attribute, ModuleDefinition module)
 {
     TypeDefinition tr = module.Import(attribute).Resolve();
     MethodDefinition mr = tr.Methods.First(value => value.IsConstructor);
     MethodReference rf = module.Import(mr);
     var customAttribute = new CustomAttribute(rf);
     field.CustomAttributes.Add(customAttribute);
     return customAttribute;
 }
Example #30
0
        /// <summary>
        /// Contracts for <see cref="IWeave.Weave"/>
        /// </summary>
        /// <param name="weavingContext">Context data for weaving.</param>
        /// <param name="target">The type to which the weave will be applied/</param>
        /// <param name="weaveAttribute">Attribute that may contain arguments for the weave invocation.</param>
        public void Weave(IWeavingContext weavingContext, TypeDefinition target, CustomAttribute weaveAttribute)
        {
            Contract.Requires(weavingContext != null);
            Contract.Requires(target != null);
            Contract.Requires(weaveAttribute != null);
            Contract.Requires(this.IsInitialized);

            throw new NotSupportedException();
        }
Example #31
0
        /// <summary>
        /// CopyMethod copies a method definition into a new copy which can be added
        /// to another module.
        /// </summary>
        /// <param name="method">The MethodDefinition to copy</param>
        /// <returns>A copy of the MethodDefinition</returns>
        public static MethodDefinition CopyMethod(MethodDefinition method)
        {
            MethodDefinition newMethod = new MethodDefinition(method.Name, method.Attributes, method.ReturnType);
            foreach (ParameterDefinition param in method.Parameters)
            {
                ParameterDefinition newParam = new ParameterDefinition(param.Name, param.Attributes, param.ParameterType);
                newMethod.Parameters.Add(newParam);
            }

            foreach (CustomAttribute attr in method.CustomAttributes)
            {
                CustomAttribute newAttr = new CustomAttribute(attr.Constructor);
                foreach (CustomAttributeArgument arg in attr.ConstructorArguments)
                {
                    CustomAttributeArgument newArg = new CustomAttributeArgument(arg.Type, arg.Value);
                    newAttr.ConstructorArguments.Add(newArg);
                }
                foreach (CustomAttributeNamedArgument arg in attr.Fields)
                {
                    CustomAttributeNamedArgument newArg = new CustomAttributeNamedArgument(arg.Name, new CustomAttributeArgument(arg.Argument.Type, arg.Argument.Value));
                    newAttr.Fields.Add(newArg);
                }
                newMethod.CustomAttributes.Add(newAttr);
            }

            if (method.Body != null)
            {
                if (newMethod.Body == null)
                    newMethod.Body = new MethodBody(newMethod);
                foreach (Instruction inst in method.Body.Instructions)
                {
                    newMethod.Body.Instructions.Add(inst);
                }

                foreach (VariableDefinition var in method.Body.Variables)
                {
                    VariableDefinition newVar = new VariableDefinition(var.Name, var.VariableType);
                    newMethod.Body.Variables.Add(newVar);
                }

                foreach (ExceptionHandler handler in method.Body.ExceptionHandlers)
                {
                    ExceptionHandler newHandler = new ExceptionHandler(handler.HandlerType);
                    newHandler.HandlerStart = handler.HandlerStart;
                    newHandler.HandlerEnd = handler.HandlerEnd;
                    newHandler.TryStart = handler.TryStart;
                    newHandler.TryEnd = handler.TryEnd;
                    newHandler.FilterStart = handler.FilterStart;
                    newHandler.CatchType = handler.CatchType;
                    newMethod.Body.ExceptionHandlers.Add(newHandler);
                }

                newMethod.Body.InitLocals = method.Body.InitLocals;
            }
            return newMethod;
        }
Example #32
0
 /// <summary>
 /// Compile the given XML file to a binary XML file in the given output folder.
 /// </summary>
 private void CreateUsesSdk(XElement manifest, CustomAttribute packageAttribute)
 {
     // Create uses-sdk
     var usesSdk = new XElement("uses-sdk", new XAttribute(XName.Get("minSdkVersion", Namespace), FindMinSdkLevel().ToString()));
     if (!string.IsNullOrEmpty(targetSdkVersion))
     {
         usesSdk.Add(new XAttribute(XName.Get("targetSdkVersion", Namespace), FormatTargetSdkVersion(targetSdkVersion)));
     }
     manifest.Add(usesSdk);
 }
        private static void AddCustomAttributeArgument(Collection<CustomAttribute> customAttributes)
        {
            var version = typeof (ModuleWeaver).Assembly.GetName().Version.ToString();
            var name = typeof (ModuleWeaver).Assembly.GetName().Name;

            var generatedAttribute = new CustomAttribute(ReferenceFinder.GeneratedCodeAttribute.ConstructorStringString);
            generatedAttribute.ConstructorArguments.Add(new CustomAttributeArgument(ReferenceFinder.String.TypeReference, name));
            generatedAttribute.ConstructorArguments.Add(new CustomAttributeArgument(ReferenceFinder.String.TypeReference, version));
            customAttributes.Add(generatedAttribute);
        }
Example #34
0
 protected static IList GetArgumentsToBaseConstructor(MC.CustomAttribute att, MC.TypeReference baseType)
 {
     if (att.AttributeType.FullName == baseType.FullName)
     {
         return(att.ConstructorArguments.Select(arg => arg.Value).ToList());
     }
     else
     {
         //FIXME: Implement
         throw new NotImplementedException();
     }
 }
Example #35
0
 protected static IList GetArgumentsToBaseConstructor(MC.CustomAttribute att, MC.TypeReference baseType)
 {
     if (att.Constructor.DeclaringType.FullName == baseType.FullName)
     {
         return(att.ConstructorParameters);
     }
     else
     {
         //FIXME: Implement
         throw new NotImplementedException();
     }
 }
Example #36
0
        private static Mono.Cecil.CustomAttribute GetModelDefaultCustomAttribute(string name, string value,
                                                                                 ModuleDefinition mod)
        {
            var ctor =
                mod.ImportReference(
                    typeof(ModelDefaultAttribute).GetConstructor(new[] { typeof(string), typeof(string) }));
            var cb = new Mono.Cecil.CustomAttribute(ctor);
            var tr = mod.ImportReference(typeof(string));

            cb.ConstructorArguments.Add(new CustomAttributeArgument(tr, name));
            cb.ConstructorArguments.Add(new CustomAttributeArgument(tr, value));
            return(cb);
        }
Example #37
0
        public static void AddNonPersistentDc(this TypeDefinition type)
        {
            var modf = type.Module;
            var ctor = modf.ImportReference(typeof(NonPersistentAttribute).GetConstructor(Type.EmptyTypes));

            if (ctor == null)
            {
                throw new Exception("没有找到合适的构造函数!");
            }

            var att = new Mono.Cecil.CustomAttribute(ctor);

            type.CustomAttributes.Add(att);
        }
Example #38
0
        public static void Size(this PropertyDefinition p, int size)
        {
            var modf = p.PropertyType.Module;
            var ctor = modf.ImportReference(typeof(SizeAttribute).GetConstructor(new[] { typeof(int) }));

            if (ctor == null)
            {
                throw new Exception("没有找到合适的构造函数!");
            }

            var att = new Mono.Cecil.CustomAttribute(ctor);

            att.ConstructorArguments.Add(new CustomAttributeArgument(modf.ImportReference(typeof(int)), size));
            p.CustomAttributes.Add(att);
        }
Example #39
0
        public static void Aggregate(this PropertyDefinition self)
        {
            var mod = self.DeclaringType.Module;

            var clrctor = typeof(AggregatedAttribute).GetConstructor(Type.EmptyTypes);

            var ctor = self.DeclaringType.Module.ImportReference(clrctor);

            if (ctor == null)
            {
                throw new Exception("没有找到合适的构造函数!");
            }

            var att = new Mono.Cecil.CustomAttribute(ctor);

            self.CustomAttributes.Add(att);
        }
Example #40
0
        public static void Assocication(this PropertyDefinition self, string name)
        {
            var mod = self.DeclaringType.Module;

            var clrctor = typeof(AssociationAttribute).GetConstructor(new Type[] { typeof(string) });

            var ctor = self.DeclaringType.Module.ImportReference(clrctor);

            if (ctor == null)
            {
                throw new Exception("没有找到合适的构造函数!");
            }

            var att = new Mono.Cecil.CustomAttribute(ctor);

            att.ConstructorArguments.Add(new CustomAttributeArgument(mod.ImportReference(typeof(string)), name));
            self.CustomAttributes.Add(att);
        }
Example #41
0
 protected virtual void Visit(Mono.Cecil.CustomAttribute customAttribute, Context context)
 {
     if (customAttribute.Constructor != null)
     {
         this.Visit(customAttribute.Constructor, context.AttributeConstructor(customAttribute));
     }
     if (customAttribute.AttributeType != null)
     {
         this.VisitTypeReference(customAttribute.AttributeType, context.AttributeType(customAttribute));
     }
     foreach (CustomAttributeArgument argument in customAttribute.ConstructorArguments)
     {
         this.Visit(argument, context.AttributeArgument(customAttribute));
     }
     foreach (Mono.Cecil.CustomAttributeNamedArgument argument2 in customAttribute.Fields)
     {
         this.Visit(argument2, context.AttributeArgument(customAttribute));
     }
     foreach (Mono.Cecil.CustomAttributeNamedArgument argument3 in customAttribute.Properties)
     {
         this.Visit(argument3, context.AttributeArgument(customAttribute));
     }
 }
Example #42
0
        protected void SetCustomAttributes(ICollection <AnalysisNet.Types.CustomAttribute> ourAttributes, ICollection <Cecil.CustomAttribute> cecilAttributes)
        {
            foreach (AnalysisNet.Types.CustomAttribute analysisNetAttr in ourAttributes)
            {
                Cecil.MethodReference ctor = ReferenceGenerator.MethodReference(analysisNetAttr.Constructor);
                Cecil.TypeReference   type = ReferenceGenerator.TypeReference(analysisNetAttr.Type);

                Cecil.CustomAttribute cecilAttr = new Cecil.CustomAttribute(ctor);
                foreach (AnalysisNet.ThreeAddressCode.Values.Constant constant in analysisNetAttr.Arguments)
                {
                    // todo: cci is not working correctly
                    if (constant == null)
                    {
                        continue;
                    }

                    Cecil.CustomAttributeArgument cecilArg = new Cecil.CustomAttributeArgument(ReferenceGenerator.TypeReference(constant.Type), constant.Value);
                    cecilAttr.ConstructorArguments.Add(cecilArg);
                }

                cecilAttributes.Add(cecilAttr);
            }
        }
Example #43
0
        object ConvertAttribute(CustomAttribute att, Type expectedType)
        {
            Type attype = typeof(IAssemblyReflector).Assembly.GetType(att.Constructor.DeclaringType.FullName);

            if (attype == null || !expectedType.IsAssignableFrom(attype))
            {
                return(null);
            }

            object ob;

            if (att.ConstructorArguments.Count > 0)
            {
                object[]   cargs          = new object [att.ConstructorArguments.Count];
                List <int> typeParameters = null;

                // Constructor parameters of type System.Type can't be set because types from the assembly
                // can't be loaded. The parameter value will be set later using a type name property.
                for (int n = 0; n < cargs.Length; n++)
                {
                    var atype = Type.GetType(att.Constructor.Parameters[n].ParameterType.FullName);
                    if (atype == null)
                    {
                        atype = typeof(IAssemblyReflector).Assembly.GetType(att.Constructor.Parameters[n].ParameterType.FullName);
                    }

                    if (atype.IsEnum)
                    {
                        cargs [n] = Enum.ToObject(atype, att.ConstructorArguments [n].Value);
                    }
                    else
                    {
                        cargs [n] = att.ConstructorArguments [n].Value;
                    }

                    if (typeof(System.Type).IsAssignableFrom(atype))
                    {
                        if (typeParameters == null)
                        {
                            typeParameters = new List <int> ();
                        }
                        cargs [n] = typeof(object);
                        typeParameters.Add(n);
                    }
                }
                ob = Activator.CreateInstance(attype, cargs);

                // If there are arguments of type System.Type, set them using the property
                if (typeParameters != null)
                {
                    Type[] ptypes = new Type [cargs.Length];
                    for (int n = 0; n < cargs.Length; n++)
                    {
                        ptypes [n] = cargs [n].GetType();
                    }
                    ConstructorInfo ci       = attype.GetConstructor(ptypes);
                    ParameterInfo[] ciParams = ci.GetParameters();

                    for (int n = 0; n < typeParameters.Count; n++)
                    {
                        int    ip       = typeParameters [n];
                        string propName = ciParams[ip].Name;
                        propName = char.ToUpper(propName [0]) + propName.Substring(1);

                        SetTypeNameAndAssemblyName(propName, attype, ob, (TypeReference)att.ConstructorArguments[ip].Value);
                    }
                }
            }
            else
            {
                ob = Activator.CreateInstance(attype);
            }

            foreach (Mono.Cecil.CustomAttributeNamedArgument namedArgument in att.Properties)
            {
                string       pname = namedArgument.Name;
                PropertyInfo prop  = attype.GetProperty(pname);
                if (prop != null)
                {
                    if (prop.PropertyType == typeof(System.Type))
                    {
                        SetTypeNameAndAssemblyName(pname, attype, ob, (TypeReference)namedArgument.Argument.Value);
                    }
                    else
                    {
                        prop.SetValue(ob, namedArgument.Argument.Value, null);
                    }
                }
            }
            return(ob);
        }
Example #44
0
        internal static MethodDefinition Clone(MethodDefinition meth, ImportContext context)
        {
            MethodDefinition nm = new MethodDefinition(
                meth.Name,
                RVA.Zero,
                meth.Attributes,
                meth.ImplAttributes,
                meth.HasThis,
                meth.ExplicitThis,
                meth.CallingConvention);

            MethodReference contextMethod = context.GenericContext.Method;

            context.GenericContext.Method = nm;

            GenericParameter.CloneInto(meth, nm, context);

            nm.ReturnType.ReturnType = context.Import(meth.ReturnType.ReturnType);

            if (meth.ReturnType.Parameter != null)
            {
                nm.ReturnType.Parameter        = ParameterDefinition.Clone(meth.ReturnType.Parameter, context);
                nm.ReturnType.Parameter.Method = nm;
            }

            if (meth.PInvokeInfo != null)
            {
                nm.PInvokeInfo = meth.PInvokeInfo;                 // TODO: import module ?
            }
            if (meth.HasParameters)
            {
                foreach (ParameterDefinition param in meth.Parameters)
                {
                    nm.Parameters.Add(ParameterDefinition.Clone(param, context));
                }
            }
            if (meth.HasOverrides)
            {
                foreach (MethodReference ov in meth.Overrides)
                {
                    nm.Overrides.Add(context.Import(ov));
                }
            }
            if (meth.HasCustomAttributes)
            {
                foreach (CustomAttribute ca in meth.CustomAttributes)
                {
                    nm.CustomAttributes.Add(CustomAttribute.Clone(ca, context));
                }
            }
            if (meth.HasSecurityDeclarations)
            {
                foreach (SecurityDeclaration sec in meth.SecurityDeclarations)
                {
                    nm.SecurityDeclarations.Add(SecurityDeclaration.Clone(sec));
                }
            }

            if (meth.Body != null)
            {
                nm.Body = MethodBody.Clone(meth.Body, nm, context);
            }

            context.GenericContext.Method = contextMethod;

            return(nm);
        }
Example #45
0
        void ReadCustomAttributes()
        {
            if (!m_tHeap.HasTable(CustomAttributeTable.RId))
            {
                return;
            }

            CustomAttributeTable caTable = m_tableReader.GetCustomAttributeTable();

            for (int i = 0; i < caTable.Rows.Count; i++)
            {
                CustomAttributeRow caRow = caTable [i];
                MethodReference    ctor;
                if (caRow.Type.TokenType == TokenType.Method)
                {
                    ctor = GetMethodDefAt(caRow.Type.RID);
                }
                else
                {
                    ctor = GetMemberRefAt(caRow.Type.RID, new GenericContext()) as MethodReference;
                }

                CustomAttrib    ca = m_sigReader.GetCustomAttrib(caRow.Value, ctor);
                CustomAttribute cattr;
                if (!ca.Read)
                {
                    cattr            = new CustomAttribute(ctor);
                    cattr.IsReadable = false;
                    cattr.Blob       = m_root.Streams.BlobHeap.Read(caRow.Value);
                }
                else
                {
                    cattr = BuildCustomAttribute(ctor, ca);
                }

                ICustomAttributeProvider owner = null;
                switch (caRow.Parent.TokenType)
                {
                case TokenType.Assembly:
                    owner = this.Module.Assembly;
                    break;

                case TokenType.Module:
                    owner = this.Module;
                    break;

                case TokenType.TypeDef:
                    owner = GetTypeDefAt(caRow.Parent.RID);
                    break;

                case TokenType.TypeRef:
                    owner = GetTypeRefAt(caRow.Parent.RID);
                    break;

                case TokenType.Field:
                    owner = GetFieldDefAt(caRow.Parent.RID);
                    break;

                case TokenType.Method:
                    owner = GetMethodDefAt(caRow.Parent.RID);
                    break;

                case TokenType.Property:
                    owner = GetPropertyDefAt(caRow.Parent.RID);
                    break;

                case TokenType.Event:
                    owner = GetEventDefAt(caRow.Parent.RID);
                    break;

                case TokenType.Param:
                    owner = GetParamDefAt(caRow.Parent.RID);
                    break;

                case TokenType.GenericParam:
                    owner = GetGenericParameterAt(caRow.Parent.RID);
                    break;

                default:
                    //TODO: support other ?
                    break;
                }

                if (owner != null)
                {
                    owner.CustomAttributes.Add(cattr);
                }
            }
        }
 public void Add(CustomAttribute value)
 {
     List.Add(value);
 }
 public CustomAttributeEventArgs(CustomAttribute item)
 {
     m_item = item;
 }
 public void Insert(int index, CustomAttribute value)
 {
     List.Insert(index, value);
 }
 public void Remove(CustomAttribute value)
 {
     List.Remove(value);
 }
 public virtual void VisitCustomAttribute(CustomAttribute customAttr)
 {
 }
        private void GenerateModuleAssembly()
        {
            #region GetVersion

            Version ver = BusinessBuilder.GetVersion(AdmiralEnvironment.UserDefineBusinessFile);

            if (ver != null)
            {
                ver = new Version(ver.Major + 1, ver.Minor, ver.Build, ver.Revision);
            }
            else
            {
                ver = new Version(1, 0, 0, 0);
            }

            #endregion

            var assemblyName = "AdmiralDynamicDC";
            var newFileName  = AdmiralEnvironment.UserDefineBusinessTempFile.FullName;

            #region 定义程序集

            var asmName = new AssemblyNameDefinition(assemblyName, ver);
            //[assembly: AssemblyFileVersionAttribute("1.0.0.12")]
            var assembly =
                AssemblyDefinition.CreateAssembly(
                    asmName,
                    "MainModule",
                    ModuleKind.Dll
                    );
            //AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Save, AdmiralEnvironment.UserDefineBusinessDirectoryInfo.FullName);

            #region 定义模块

            var module = assembly.MainModule;

            #endregion

            #endregion

            #region 设置文件版本

            var asmFileVerCtor = typeof(SR.AssemblyFileVersionAttribute).GetConstructor(new[] { typeof(string) });

            var asmFileVerCtorRef = assembly.MainModule.ImportReference(asmFileVerCtor);
            var ca = new Mono.Cecil.CustomAttribute(asmFileVerCtorRef);
            ca.ConstructorArguments.Add(new CustomAttributeArgument(
                                            assembly.MainModule.ImportReference(typeof(string)), ver.ToString()));
            assembly.CustomAttributes.Add(ca);

            #endregion

            #region XafModule

            var xafModule = new TypeDefinition("", "RuntimeModule",
                                               TypeAttributes.Public | TypeAttributes.Class,
                                               assembly.MainModule.ImportReference(typeof(RuntimeModuleBase)));

            //module.DefineType("RuntimeModule", TypeAttributes.Public | TypeAttributes.Class, typeof(RuntimeModuleBase));
            var ctor = new MethodDefinition(".ctor",
                                            MethodAttributes.Public
                                            | MethodAttributes.HideBySig
                                            | MethodAttributes.SpecialName
                                            | MethodAttributes.RTSpecialName,
                                            module.ImportReference(typeof(void))
                                            );
            //.method public hidebysig specialname rtspecialname instance void .ctor() cil managed

            //xafModule.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard | CallingConventions.HasThis, Type.EmptyTypes);
            var baseCtor = typeof(RuntimeModuleBase).GetConstructor(Type.EmptyTypes);

            var il = ctor.Body.Instructions;

            //.maxstack 8
            //L_0000: ldarg.0
            //L_0001: call instance void Admiral.ERP.Module.RuntimeModuleBase::.ctor()
            //L_0006: ret
            il.Add(Instruction.Create(OpCodes.Ldarg_0));
            il.Add(Instruction.Create(OpCodes.Call, module.ImportReference(baseCtor)));
            il.Add(Instruction.Create(OpCodes.Ret));
            xafModule.Methods.Add(ctor);
            module.Types.Add(xafModule);

            #endregion

            #region 创建业务对象
            var ObjectSpace = this.Application.CreateObjectSpace();
            var allTypes    = ObjectSpace.GetObjects <BusinessObjectBase>();

            var userDefinedBos = allTypes.OfType <BusinessObject>().Where(x => x.IsRuntimeDefine).ToList(); //ObjectSpace.GetObjects<BusinessObject>(new BinaryOperator("IsRuntimeDefine", true)).OrderBy(x => x.CreateIndex).ToArray();
            var dllTypes       = allTypes.Except(userDefinedBos);                                           //ObjectSpace.GetObjects<BusinessObject>(new BinaryOperator("IsRuntimeDefine", false));
            module.InitializeTypeReferences(dllTypes);



            //第一步只生成类型定义,是因为可能有交叉使用类型,如,基类是未定义的类型,则无法使用
            #region 定义类型生成的代码,包含属性修饰:-->[NonPersistent]pubic class {    }
            foreach (var bo in userDefinedBos)
            {
                var typeAtt = TypeAttributes.Class | TypeAttributes.Public;
                if (bo.IsAbstract)
                {
                    typeAtt |= TypeAttributes.Abstract;
                }
                else if (!bo.CanInherits)
                {
                    typeAtt |= TypeAttributes.Sealed;
                }

                var type = new TypeDefinition(bo.Category.FullName, bo.称, typeAtt);
                module.Types.Add(type);

                if (!bo.IsPersistent)
                {
                    type.AddNonPersistentDc();
                }

                if (bo.IsCloneable.HasValue)
                {
                    type.ModelDefault("IsCloneable", bo.IsCloneable.Value.ToString().ToLower());
                }

                if (bo.IsCreatableItem.HasValue)
                {
                    type.ModelDefault("IsCreatableItem", bo.IsCreatableItem.Value.ToString().ToLower());
                }

                if (bo.IsVisibileInReports.HasValue)
                {
                    type.VisibileInReport(bo.IsVisibileInReports.Value);
                }
                type.AddToTypeReferences(bo);
            }
            #endregion

            #region 生成剩下的内容
            foreach (var bo in userDefinedBos)
            {
                var type = bo.GetTypeDefintion();
                if (type == null)
                {
                    throw new Exception("错误!");
                }

                #region 处理基类

                var             boBaseType = bo.Base.GetTypeReference() ?? module.ImportReference(typeof(SimpleObject));
                MethodReference boBaseCtor;

                if (boBaseType.HasGenericParameters)
                {
                    type.BaseType = boBaseType.MakeGenericType(bo.GenericParameters.Select(gp => gp.ParameterValue.GetTypeReference()).ToArray());

                    //var tb = boBaseType.Resolve().MakeGenericType(bo.GenericParameters.Select(gp => gp.ParameterValue.FindType(typeReferences)).ToArray());

                    boBaseCtor =
                        //(tb as TypeDefinition).Methods.Single(x => x.Name == ".ctor" && x.Parameters.First().ParameterType.FullName == typeof(Session).FullName);
                        module.ImportReference(
                            type.BaseType.Resolve()
                            .Methods.Single(
                                x => x.Name == ".ctor" && x.Parameters.First().ParameterType.FullName == typeof(Session).FullName)
                            );
                    boBaseCtor = boBaseCtor.MakeGeneric(bo.GenericParameters.Select(gp => gp.ParameterValue.GetTypeReference()).ToArray());
                }
                else
                {
                    type.BaseType = boBaseType;
                    boBaseCtor    = module.ImportReference(
                        boBaseType.Resolve().Methods.Single(x => x.Name == ".ctor" && x.Parameters.Count == 1 && x.Parameters.Single().ParameterType.FullName == typeof(Session).FullName)
                        );
                }

                if (boBaseCtor != null)
                {
                    var boctor = new MethodDefinition(".ctor",
                                                      MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName,
                                                      //CallingConventions.Standard | CallingConventions.HasThis,
                                                      module.ImportReference(typeof(void))
                                                      );
                    // type.DefineConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName, CallingConventions.Standard | CallingConventions.HasThis, new Type[] { typeof(Session) });
                    var p = new ParameterDefinition("session", ParameterAttributes.None, module.ImportReference(typeof(Session)));
                    boctor.Parameters.Add(p);
                    var boil = boctor.Body.GetILProcessor();
                    //.GetILGenerator();

                    boil.Emit(OpCodes.Ldarg_0);
                    boil.Emit(OpCodes.Ldarg_1);
                    boil.Emit(OpCodes.Call, boBaseCtor);
                    boil.Emit(OpCodes.Nop);
                    boil.Emit(OpCodes.Nop);
                    boil.Emit(OpCodes.Ret);

                    //L_0000: ldarg.0
                    //L_0001: ldarg.1
                    //L_0002: call instance void IMatrix.ERP.Module.BusinessObjects.订单`1 <class IMatrix.ERP.Module.BusinessObjects.PMS.采购订单明细>::.ctor(class [DevExpress.Xpo.v15.2]
                    //DevExpress.Xpo.Session)
                    //L_0007: nop
                    //L_0008: nop
                    //L_0009: ret

                    //.method public hidebysig specialname rtspecialname
                    //instance void  .ctor(class ['DevExpress.Xpo.v15.2']DevExpress.Xpo.Session session) cil managed
                    //{
                    //// 代码大小       10 (0xa)
                    //.maxstack  8
                    //IL_0000:  ldarg.0
                    //IL_0001:  ldarg.1
                    //IL_0002:  call       instance void [IMatrix.ERP.Module]IMatrix.ERP.Module.BusinessObjects.'订单`1'::.ctor<class '业务'.'采购计划明细'>(class ['DevExpress.Xpo.v15.2']DevExpress.Xpo.Session)
                    //IL_0007:  nop
                    //IL_0008:  nop
                    //IL_0009:  ret
                    //} // end of method '采购计划'::.ctor

                    type.Methods.Add(boctor);
                }

                #endregion

                #region 填加属性

                foreach (var p in bo.Properties)
                {
                    BuildPropertyCore(p, type);
                }

                #endregion

                #region 填加集合属性
                foreach (var item in bo.CollectionProperties)
                {
                    BuildCollectionProperty(item, type);
                }
                #endregion
            }
            #endregion

            #endregion

            #region 保存生成的程序集
            assembly.Write(newFileName);
            #endregion

            #region  除模块信息,让系统执行更新表结构动作

            var moduleInfo = ObjectSpace.FindObject <ModuleInfo>(new BinaryOperator("Name", "RuntimeModule"));
            if (moduleInfo != null)
            {
                ObjectSpace.Delete(moduleInfo);
                ObjectSpace.CommitChanges();
            }
            var restart = Application as IRestartApplication;
            if (restart != null)
            {
                restart.RestartApplication();
            }
            #endregion
        }
 public static void SetConstructorArgumentValue(Mono.Cecil.CustomAttribute ca, int index, object value)
 {
     Mono.Cecil.CustomAttributeArgument[] items = GetCaaItems(ca.ConstructorArguments);
     items[index].Value = value;
 }
 public static void SetPropertyName(Mono.Cecil.CustomAttribute ca, int index, string name)
 {
     Mono.Cecil.CustomAttributeNamedArgument[] items = GetCanaItems(ca.Properties);
     items[index].Name = name;
 }
Example #54
0
        MA.CustomAttribute ConvertToRawAttribute(CustomAttribute att, string expectedType)
        {
            TypeDefinition attType = FindTypeDefinition(att.Constructor.DeclaringType.Module.Assembly, att.Constructor.DeclaringType);

            if (attType == null || !TypeIsAssignableFrom(expectedType, attType))
            {
                return(null);
            }

            MA.CustomAttribute mat = new MA.CustomAttribute();
            mat.TypeName = att.Constructor.DeclaringType.FullName;

            if (att.ConstructorArguments.Count > 0)
            {
                var arguments = att.ConstructorArguments;

                MethodReference constructor = FindConstructor(att);
                if (constructor == null)
                {
                    throw new InvalidOperationException("Custom attribute constructor not found");
                }

                for (int n = 0; n < arguments.Count; n++)
                {
                    ParameterDefinition par = constructor.Parameters[n];
                    object val = arguments [n].Value;
                    if (val != null)
                    {
                        string name = par.Name;
                        NodeAttributeAttribute bat = (NodeAttributeAttribute)GetCustomAttribute(par, typeof(NodeAttributeAttribute), false);
                        if (bat != null)
                        {
                            name = bat.Name;
                        }
                        mat.Add(name, Convert.ToString(val, System.Globalization.CultureInfo.InvariantCulture));
                    }
                }
            }

            foreach (Mono.Cecil.CustomAttributeNamedArgument namedArgument in att.Properties)
            {
                string pname = namedArgument.Name;
                object val   = namedArgument.Argument.Value;
                if (val == null)
                {
                    continue;
                }

                foreach (TypeDefinition td in GetInheritanceChain(attType))
                {
                    PropertyDefinition prop = GetMember(td.Properties, pname);
                    if (prop == null)
                    {
                        continue;
                    }

                    NodeAttributeAttribute bat = (NodeAttributeAttribute)GetCustomAttribute(prop, typeof(NodeAttributeAttribute), false);
                    if (bat != null)
                    {
                        string name = string.IsNullOrEmpty(bat.Name) ? prop.Name : bat.Name;
                        mat.Add(name, Convert.ToString(val, System.Globalization.CultureInfo.InvariantCulture));
                    }
                }
            }

            foreach (Mono.Cecil.CustomAttributeNamedArgument namedArgument in att.Fields)
            {
                string pname = namedArgument.Name;
                object val   = namedArgument.Argument.Value;
                if (val == null)
                {
                    continue;
                }

                foreach (TypeDefinition td in GetInheritanceChain(attType))
                {
                    FieldDefinition field = GetMember(td.Fields, pname);
                    if (field != null)
                    {
                        NodeAttributeAttribute bat = (NodeAttributeAttribute)GetCustomAttribute(field, typeof(NodeAttributeAttribute), false);
                        if (bat != null)
                        {
                            string name = string.IsNullOrEmpty(bat.Name) ? field.Name : bat.Name;
                            mat.Add(name, Convert.ToString(val, System.Globalization.CultureInfo.InvariantCulture));
                        }
                    }
                }
            }

            return(mat);
        }
 public int IndexOf(CustomAttribute value)
 {
     return(List.IndexOf(value));
 }
Example #56
0
        object ConvertAttribute(CustomAttribute att, Type expectedType)
        {
            Type attype = typeof(IAssemblyReflector).Assembly.GetType(att.Constructor.DeclaringType.FullName);

            if (attype == null || !expectedType.IsAssignableFrom(attype))
            {
                return(null);
            }

            object ob;

            if (att.ConstructorArguments.Count > 0)
            {
                object[]  cargs          = new object [att.ConstructorArguments.Count];
                ArrayList typeParameters = null;

                // Constructor parameters of type System.Type can't be set because types from the assembly
                // can't be loaded. The parameter value will be set later using a type name property.
                for (int n = 0; n < cargs.Length; n++)
                {
                    cargs [n] = att.ConstructorArguments [n].Value;
                    string atype = att.Constructor.Parameters[n].ParameterType.FullName;
                    if (atype == "System.Type")
                    {
                        if (typeParameters == null)
                        {
                            typeParameters = new ArrayList();
                        }
                        cargs [n] = typeof(object);
                        typeParameters.Add(n);
                    }
                }
                ob = Activator.CreateInstance(attype, cargs);

                // If there are arguments of type System.Type, set them using the property
                if (typeParameters != null)
                {
                    Type[] ptypes = new Type [cargs.Length];
                    for (int n = 0; n < cargs.Length; n++)
                    {
                        ptypes [n] = cargs [n].GetType();
                    }
                    ConstructorInfo ci       = attype.GetConstructor(ptypes);
                    ParameterInfo[] ciParams = ci.GetParameters();

                    for (int n = 0; n < typeParameters.Count; n++)
                    {
                        int    ip       = (int)typeParameters [n];
                        string propName = ciParams[ip].Name;
                        propName = char.ToUpper(propName [0]) + propName.Substring(1) + "Name";
                        PropertyInfo pi = attype.GetProperty(propName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

                        if (pi == null)
                        {
                            throw new InvalidOperationException("Property '" + propName + "' not found in type '" + attype + "'.");
                        }

                        pi.SetValue(ob, ((TypeReference)att.ConstructorArguments [ip].Value).FullName, null);
                    }
                }
            }
            else
            {
                ob = Activator.CreateInstance(attype);
            }

            foreach (Mono.Cecil.CustomAttributeNamedArgument namedArgument in att.Properties)
            {
                string       pname = namedArgument.Name;
                PropertyInfo prop  = attype.GetProperty(pname);
                if (prop != null)
                {
                    if (prop.PropertyType == typeof(System.Type))
                    {
                        // We can't load the type. We have to use the typeName property instead.
                        pname += "Name";
                        prop   = attype.GetProperty(pname, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

                        if (prop == null)
                        {
                            throw new InvalidOperationException("Property '" + pname + "' not found in type '" + attype + "'.");
                        }

                        prop.SetValue(ob, ((TypeReference)namedArgument.Argument.Value).FullName, null);
                    }
                    else
                    {
                        prop.SetValue(ob, namedArgument.Argument.Value, null);
                    }
                }
            }
            return(ob);
        }
 public bool Contains(CustomAttribute value)
 {
     return(List.Contains(value));
 }