public void Ctor_Default()
		{
			var declaration = new CodeAttributeDeclaration();
			Assert.Empty(declaration.Name);
			Assert.Empty(declaration.Arguments);
			Assert.Null(declaration.AttributeType);
		}
		public void Ctor_String(string name, CodeAttributeArgument[] arguments)
		{
			if (arguments.Length == 0)
			{
				var declaration1 = new CodeAttributeDeclaration(name);
				Assert.Equal(name ?? string.Empty, declaration1.Name);
				Assert.Empty(declaration1.Arguments);
				Assert.Equal(new CodeTypeReference(name).BaseType, declaration1.AttributeType.BaseType);
			}
			var declaration2 = new CodeAttributeDeclaration(name, arguments);
			Assert.Equal(name ?? string.Empty, declaration2.Name);
			Assert.Equal(arguments, declaration2.Arguments.Cast<CodeAttributeArgument>());
			Assert.Equal(new CodeTypeReference(name).BaseType, declaration2.AttributeType.BaseType);
		}
		public void Ctor_CodeTypeReference(CodeTypeReference attributeType, CodeAttributeArgument[] arguments)
		{
			if (arguments == null || arguments.Length == 0)
			{
				var declaration1 = new CodeAttributeDeclaration(attributeType);
				Assert.Equal(attributeType?.BaseType ?? string.Empty, declaration1.Name);
				Assert.Equal(attributeType, declaration1.AttributeType);
				Assert.Empty(declaration1.Arguments);
			}
			var declaration2 = new CodeAttributeDeclaration(attributeType, arguments);
			Assert.Equal(attributeType?.BaseType ?? string.Empty, declaration2.Name);
			Assert.Equal(attributeType, declaration2.AttributeType);
			Assert.Equal(arguments ?? new CodeAttributeArgument[0], declaration2.Arguments.Cast<CodeAttributeArgument>());
		}
Example #4
0
    static void Main()
    {
        // Declare a new type called Class1.
        CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");

        // Declare a new code attribute
        CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration(
            "System.CLSCompliantAttribute",
            new CodeAttributeArgument(new CodePrimitiveExpression(false)));

        class1.CustomAttributes.Add(codeAttrDecl);

        // Create a C# code provider
        CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

        // Generate code and send the output to the console
        provider.GenerateCodeFromType(class1, Console.Out, new CodeGeneratorOptions());
    }
Example #5
0
        CodeTypeDeclaration CreateResourceClass()
        {
            var decl = new CodeTypeDeclaration("Resource")
            {
                IsPartial = true,
            };
            var asm          = Assembly.GetExecutingAssembly().GetName();
            var codeAttrDecl =
                new CodeAttributeDeclaration("System.CodeDom.Compiler.GeneratedCodeAttribute",
                                             new CodeAttributeArgument(
                                                 new CodePrimitiveExpression(asm.Name)),
                                             new CodeAttributeArgument(
                                                 new CodePrimitiveExpression(asm.Version.ToString()))
                                             );

            decl.CustomAttributes.Add(codeAttrDecl);
            return(decl);
        }
Example #6
0
        private void AddElementMetadata(CodeAttributeDeclarationCollection metadata, string elementName, TypeDesc typeDesc, bool isNullable)
        {
            CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(typeof(SoapElementAttribute).FullName);

            if (elementName != null)
            {
                declaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(elementName)));
            }
            if ((typeDesc != null) && typeDesc.IsAmbiguousDataType)
            {
                declaration.Arguments.Add(new CodeAttributeArgument("DataType", new CodePrimitiveExpression(typeDesc.DataType.Name)));
            }
            if (isNullable)
            {
                declaration.Arguments.Add(new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(true)));
            }
            metadata.Add(declaration);
        }
Example #7
0
        private static CodeAttributeDeclaration GenerateCodeAttributeDeclaration(Func <CodeTypeReference, CodeTypeReference> codeTypeModifier, CustomAttribute customAttribute)
        {
            var attribute = new CodeAttributeDeclaration(codeTypeModifier(CreateCodeTypeReference(customAttribute.AttributeType)));

            foreach (var arg in customAttribute.ConstructorArguments)
            {
                attribute.Arguments.Add(new CodeAttributeArgument(CreateInitialiserExpression(arg)));
            }
            foreach (var field in customAttribute.Fields.OrderBy(f => f.Name, StringComparer.InvariantCulture))
            {
                attribute.Arguments.Add(new CodeAttributeArgument(field.Name, CreateInitialiserExpression(field.Argument)));
            }
            foreach (var property in customAttribute.Properties.OrderBy(p => p.Name, StringComparer.InvariantCulture))
            {
                attribute.Arguments.Add(new CodeAttributeArgument(property.Name, CreateInitialiserExpression(property.Argument)));
            }
            return(attribute);
        }
Example #8
0
        public CodeAttributeDeclaration[] GetValidationAttributes()
        {
            ArrayList list = GetValidatorsAsArrayList();

            if (list != null && list.Count > 0)
            {
                CodeAttributeDeclaration[] result = new CodeAttributeDeclaration[list.Count];

                for (int i = 0; i < list.Count; i++)
                {
                    result[i] = ((AbstractValidation)list[i]).GetAttributeDeclaration();
                }

                return(result);
            }

            return(null);
        }
        internal CodeTypeMemberCollection GenerateParameterProperty(IDiscoveryParameter parameter,
                                                                    IMethod method,
                                                                    CodeTypeDeclaration resourceClass,
                                                                    IEnumerable <string> usedNames)
        {
            // Get the name and return type of this parameter.
            string            name       = parameter.Name;
            CodeTypeReference returnType = ResourceBaseGenerator.GetParameterTypeReference(
                resourceClass, parameter);

            // Generate the property and field.
            CodeTypeMemberCollection newMembers = DecoratorUtil.CreateAutoProperty(
                name, parameter.Description, returnType, usedNames, parameter.IsRequired, null);

            // Add the KeyAttribute to the property.
            foreach (CodeTypeMember member in newMembers)
            {
                CodeMemberProperty property = member as CodeMemberProperty;
                if (property == null)
                {
                    continue;
                }

                RequestParameterType requestParameterType =
                    parameter.ParameterType == PathParameter ? RequestParameterType.Path : RequestParameterType.Query;

                // Declare the RequestParameter attribute.
                CodeTypeReference attributeType = new CodeTypeReference(typeof(RequestParameterAttribute));

                // Generates something like..
                // [Google.Apis.Util.RequestParameterAttribute("prettyPrint",
                //   Google.Apis.Util.RequestParameterType.Query)]
                CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(attributeType);
                attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(parameter.Name)));
                attribute.Arguments.Add(
                    new CodeAttributeArgument(
                        new CodeFieldReferenceExpression(
                            new CodeTypeReferenceExpression(typeof(RequestParameterType)),
                            Enum.GetName(typeof(RequestParameterType), requestParameterType))));
                property.CustomAttributes.Add(attribute);
            }

            return(newMembers);
        }
            public void AddMemberAttributes(XmlName messageName, MessagePartDescription part, CodeAttributeDeclarationCollection attributesImported, CodeAttributeDeclarationCollection typeAttributes, CodeAttributeDeclarationCollection fieldAttributes)
            {
                CodeAttributeDeclaration dataContractAttributeDecl = null;

                foreach (CodeAttributeDeclaration attr in typeAttributes)
                {
                    if (attr.AttributeType.BaseType == dataContractAttributeTypeRef.BaseType)
                    {
                        dataContractAttributeDecl = attr;
                        break;
                    }
                }

                if (dataContractAttributeDecl == null)
                {
                    Fx.Assert(String.Format(CultureInfo.InvariantCulture, "Cannot find DataContract attribute for  {0}", messageName));

                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, "Cannot find DataContract attribute for  {0}", messageName)));
                }
                bool nsAttrFound = false;

                foreach (CodeAttributeArgument attrArg in dataContractAttributeDecl.Arguments)
                {
                    if (attrArg.Name == "Namespace")
                    {
                        nsAttrFound = true;
                        string nsValue = ((CodePrimitiveExpression)attrArg.Value).Value.ToString();
                        if (nsValue != part.Namespace)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxWrapperTypeHasMultipleNamespaces, messageName)));
                        }
                    }
                }
                if (!nsAttrFound)
                {
                    dataContractAttributeDecl.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(part.Namespace)));
                }

                DataMemberAttribute dataMemberAttribute = new DataMemberAttribute();

                dataMemberAttribute.Order            = memberCount++;
                dataMemberAttribute.EmitDefaultValue = !IsNonNillableReferenceType(part);
                fieldAttributes.Add(OperationGenerator.GenerateAttributeDeclaration(context.Contract.ServiceContractGenerator, dataMemberAttribute));
            }
Example #11
0
        public override void Execute(CodeNamespace codeNamespace)
        {
            // for each type
            foreach (CodeTypeDeclaration type in codeNamespace.Types)
            {
                if (type.IsEnum)
                {
                    continue;
                }

                // add the "ProtoContract" attribute to the class
                type.CustomAttributes.Add(new CodeAttributeDeclaration("ProtoContract"));

                int number = 1;

                // for each member
                foreach (CodeTypeMember member in type.Members)
                {
                    // if the member is a property
                    CodeMemberProperty codeProperty = member as CodeMemberProperty;
                    if (codeProperty == null)
                    {
                        continue;
                    }

                    // if the member is XmlElement
                    if (codeProperty.Type.BaseType == "System.Xml.XmlElement")
                    {
                        return;
                    }

                    // add the custom type editor attribute
                    CodeAttributeDeclaration attr = new CodeAttributeDeclaration("ProtoMember");
                    attr.Arguments.Add(new CodeAttributeArgument(
                                           new CodePrimitiveExpression(number)));
                    codeProperty.CustomAttributes.Add(attr);

                    number++;
                }
            }

            // add an include for "ProtoBuf" which is th namespace of the ProtoContract and ProtoMember attributes
            codeNamespace.Imports.Add(new CodeNamespaceImport("ProtoBuf"));
        }
Example #12
0
 private void PopulateKeyPropertyAttribute(CodeAttributeDeclaration attribute)
 {
     if (!string.IsNullOrEmpty(Column))
     {
         attribute.Arguments.Add(AttributeHelper.GetNamedAttributeArgument("Column", Column));
     }
     attribute.Arguments.Add(AttributeHelper.GetNamedAttributeArgument("ColumnType", ColumnType.ToString()));
     if (Access != PropertyAccess.Property)
     {
         attribute.Arguments.Add(AttributeHelper.GetNamedEnumAttributeArgument("Access", "PropertyAccess", Access));
     }
     if (!string.IsNullOrEmpty(CustomAccess))
     {
         attribute.Arguments.Add(AttributeHelper.GetNamedAttributeArgument("CustomAccess", CustomAccess));
     }
     if (!string.IsNullOrEmpty(Formula))
     {
         attribute.Arguments.Add(AttributeHelper.GetNamedAttributeArgument("Formula", Formula));
     }
     if (!Insert)
     {
         attribute.Arguments.Add(AttributeHelper.GetNamedAttributeArgument("Insert", Insert));
     }
     if (Length > 0)
     {
         attribute.Arguments.Add(AttributeHelper.GetNamedAttributeArgument("Length", Length));
     }
     if (NotNull)
     {
         attribute.Arguments.Add(AttributeHelper.GetNamedAttributeArgument("NotNull", NotNull));
     }
     if (Unique)
     {
         attribute.Arguments.Add(AttributeHelper.GetNamedAttributeArgument("Unique", Unique));
     }
     if (!string.IsNullOrEmpty(UnsavedValue))
     {
         attribute.Arguments.Add(AttributeHelper.GetNamedAttributeArgument("UnsavedValue", UnsavedValue));
     }
     if (!Update)
     {
         attribute.Arguments.Add(AttributeHelper.GetNamedAttributeArgument("Update", Update));
     }
 }
Example #13
0
        private CodeAssignStatement AddProperty(string name, string typeName, string description, CodeTypeDeclaration parent)
        {
            string          fieldName = name.ToFirstCharUpper();
            CodeMemberField field     = new CodeMemberField(typeName, fieldName)
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            };

            if (!string.IsNullOrEmpty(description))
            {
                field.Comments.Add(new CodeCommentStatement(description));
            }
            parent.Members.Add(field);

            if (IsProtobuf)
            {
                const string kFieldCount = "FieldCount";
                int          count;
                if (parent.UserData.Contains(kFieldCount))
                {
                    count = (int)parent.UserData[kFieldCount];
                    ++count;
                    parent.UserData[kFieldCount] = count;
                }
                else
                {
                    count = 1;
                    parent.UserData.Add(kFieldCount, count);
                }
                CodeAttributeArgument    codeAttr             = new CodeAttributeArgument(new CodePrimitiveExpression(count));
                CodeAttributeDeclaration protoMemberAttribute = new CodeAttributeDeclaration("ProtoMember", codeAttr);
                field.CustomAttributes.Add(protoMemberAttribute);
            }
            else
            {
                field.Name += kPropertieSign; //使字段,变成自动属性
            }

            CodeAssignStatement assign = new CodeAssignStatement(
                new CodeVariableReferenceExpression("this." + fieldName),
                new CodeVariableReferenceExpression(string.Format("{0}.Get(element, \"{1}\", {2})", kGeneratorUtility, name, "this." + fieldName)));

            return(assign);
        }
Example #14
0
        private void AddConstructorToSource(ConstructorInfo ctor)
        {
            Debug.Assert(ctor != null);
            Debug.Assert(ctor.GetParameters().Length > 0);

            var ctorCode = new CodeConstructor();

            AddDebuggerNonUserCodeAttribute(ctorCode);
            ctorCode.Attributes &= ~MemberAttributes.AccessMask;
            ctorCode.Attributes |= MemberAttributes.Public;

            // copy all the attributes of the contrustor parameters
            foreach (var p in ctor.GetParameters())
            {
                var parameterExpr = new CodeParameterDeclarationExpression(p.ParameterType, p.Name);
                foreach (var attr in p.CustomAttributes)
                {
                    var attrArgs = new List <CodeAttributeArgument>();
                    foreach (var arg in attr.ConstructorArguments)
                    {
                        attrArgs.Add(new CodeAttributeArgument(new CodePrimitiveExpression(arg.Value)));
                    }

                    foreach (var arg in attr.NamedArguments)
                    {
                        attrArgs.Add(new CodeAttributeArgument(arg.MemberName, new CodePrimitiveExpression(arg.TypedValue.Value)));
                    }

                    var customAttrExpr = new CodeAttributeDeclaration(new CodeTypeReference(attr.AttributeType), attrArgs.ToArray());
                    parameterExpr.CustomAttributes.Add(customAttrExpr);
                }
                if (p.HasDefaultValue)
                {
                    var defaultValAttrExpr = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultParameterValueAttribute)),
                                                                          new CodeAttributeArgument(new CodePrimitiveExpression(p.DefaultValue)));
                    parameterExpr.CustomAttributes.Add(defaultValAttrExpr);
                }
                ctorCode.Parameters.Add(parameterExpr);
                ctorCode.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(p.Name));
            }

            ctorCode.Statements.Add(CreateInitInvoke());
            _sourceDataClass.Members.Add(ctorCode);
        }
        protected string GenerateMethodReturnTypeAttributes(CodeGeneratorOptions options)
        {
            TypeDeclaration.Name = "Test1";

            CodeMemberMethod method = new CodeMemberMethod();

            method.Name       = "Execute";
            method.Attributes = MemberAttributes.Public;
            method.ReturnType = new CodeTypeReference(typeof(int));
            TypeDeclaration.Members.Add(method);

            // method custom attributes
            CodeAttributeDeclaration attrDec = new CodeAttributeDeclaration();

            attrDec.Name = "A";
            method.CustomAttributes.Add(attrDec);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = "B";
            method.CustomAttributes.Add(attrDec);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = typeof(ParamArrayAttribute).FullName;
            method.CustomAttributes.Add(attrDec);

            // return TypeDeclaration custom attributes
            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = "C";
            attrDec.Arguments.Add(new CodeAttributeArgument("A1",
                                                            new CodePrimitiveExpression(false)));
            attrDec.Arguments.Add(new CodeAttributeArgument("A2",
                                                            new CodePrimitiveExpression(true)));
            method.ReturnTypeCustomAttributes.Add(attrDec);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = typeof(ParamArrayAttribute).FullName;
            method.ReturnTypeCustomAttributes.Add(attrDec);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = "D";
            method.ReturnTypeCustomAttributes.Add(attrDec);

            return(GenerateCodeFromType(TypeDeclaration, options));
        }
        protected string GenerateFieldMembersAttributes(CodeGeneratorOptions options)
        {
            TypeDeclaration.Name = "Test1";

            CodeMemberField fld = new CodeMemberField();

            CodeAttributeDeclaration attrDec = new CodeAttributeDeclaration();

            attrDec.Name = "A";
            fld.CustomAttributes.Add(attrDec);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = "B";
            fld.CustomAttributes.Add(attrDec);

            TypeDeclaration.Members.Add(fld);

            return(GenerateCodeFromType(TypeDeclaration, options));
        }
Example #17
0
        /// <summary>
        /// Creates a new class for the tag group and returns a MutationCodeCreator who's root namespace is the new class.
        /// </summary>
        /// <param name="className">Name of the class definition.</param>
        /// <param name="blockAttribute">Tag block definition attribute for the block.</param>
        /// <param name="baseType">Name of the base type if this class inherits another type.</param>
        /// <returns>A new MutationCodeCreator for the child namespace.</returns>
        public MutationCodeCreator CreateTagGroupClass(string className, CodeAttributeDeclaration blockAttribute, string baseType = TagBlockDefinitionBaseType)
        {
            // Create a new code creator instance.
            MutationCodeCreator codeCreator = new MutationCodeCreator();

            // Create the class code type declaration.
            codeCreator.CodeClass         = new CodeTypeDeclaration(className);
            codeCreator.CodeClass.IsClass = true;
            codeCreator.CodeClass.BaseTypes.Add(new CodeTypeReference(baseType));

            // Add the block attribute to the class declaration.
            codeCreator.CodeClass.CustomAttributes.Add(blockAttribute);

            // Add the new tag group class to our namespace.
            this.CodeNamespace.Types.Add(codeCreator.CodeClass);

            // Return the new code creator.
            return(codeCreator);
        }
Example #18
0
        static CodeAttributeDeclaration GenerateCodeAttributeDeclaration(Func <CodeTypeReference, CodeTypeReference> codeTypeModifier, CustomAttribute customAttribute)
        {
            var attribute = new CodeAttributeDeclaration(codeTypeModifier(customAttribute.AttributeType.CreateCodeTypeReference(mode: NullableMode.Disable)));

            attribute.Name = AttributeNameBuilder.Get(attribute.Name);
            foreach (var arg in customAttribute.ConstructorArguments)
            {
                attribute.Arguments.Add(new CodeAttributeArgument(CreateInitialiserExpression(arg)));
            }
            foreach (var field in customAttribute.Fields.OrderBy(f => f.Name, StringComparer.Ordinal))
            {
                attribute.Arguments.Add(new CodeAttributeArgument(field.Name, CreateInitialiserExpression(field.Argument)));
            }
            foreach (var property in customAttribute.Properties.OrderBy(p => p.Name, StringComparer.Ordinal))
            {
                attribute.Arguments.Add(new CodeAttributeArgument(property.Name, CreateInitialiserExpression(property.Argument)));
            }
            return(attribute);
        }
 public static CodeAttributeArgument TryGetAttributeProperty(CodeAttributeDeclaration attribute, string propertyName)
 {
     if (attribute == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("attribute");
     }
     if (propertyName == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("propertyName");
     }
     foreach (CodeAttributeArgument argument in attribute.Arguments)
     {
         if (argument.Name == propertyName)
         {
             return(argument);
         }
     }
     return(null);
 }
        protected string GeneratePropertyMembersAttributes(CodeGeneratorOptions options)
        {
            TypeDeclaration.Name = "Test1";

            CodeMemberProperty property = new CodeMemberProperty();

            TypeDeclaration.Members.Add(property);

            CodeAttributeDeclaration attrDec = new CodeAttributeDeclaration();

            attrDec.Name = "A";
            property.CustomAttributes.Add(attrDec);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = "B";
            property.CustomAttributes.Add(attrDec);

            return(GenerateCodeFromType(TypeDeclaration, options));
        }
        protected string GenerateMethodMembersType1(CodeGeneratorOptions options)
        {
            TypeDeclaration.Name = "Test1";

            CodeMemberMethod method = new CodeMemberMethod();

            CodeAttributeDeclaration attrDec = new CodeAttributeDeclaration();

            attrDec.Name = "A";
            method.CustomAttributes.Add(attrDec);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = "B";
            method.CustomAttributes.Add(attrDec);

            TypeDeclaration.Members.Add(method);

            return(GenerateCodeFromType(TypeDeclaration, options));
        }
        protected string GenerateConstructorAttributes(CodeGeneratorOptions options)
        {
            TypeDeclaration.Name = "Test1";

            CodeConstructor ctor = new CodeConstructor();

            CodeAttributeDeclaration attrDec = new CodeAttributeDeclaration();

            attrDec.Name = "A";
            ctor.CustomAttributes.Add(attrDec);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = "B";
            ctor.CustomAttributes.Add(attrDec);

            TypeDeclaration.Members.Add(ctor);

            return(GenerateCodeFromType(TypeDeclaration, options));
        }
        protected string GenerateMethodParamArrayAttribute(CodeGeneratorOptions options)
        {
            TypeDeclaration.Name = "Test1";

            CodeMemberMethod method = new CodeMemberMethod();

            method.Name       = "Something";
            method.Attributes = MemberAttributes.Public;
            method.ReturnType = new CodeTypeReference(typeof(int));

            // first parameter
            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(
                typeof(object), "value");

            param.Direction = FieldDirection.Out;
            method.Parameters.Add(param);

            CodeAttributeDeclaration attrDec = new CodeAttributeDeclaration();

            attrDec.Name = "A";
            param.CustomAttributes.Add(attrDec);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = typeof(ParamArrayAttribute).FullName;
            param.CustomAttributes.Add(attrDec);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = "B";
            param.CustomAttributes.Add(attrDec);

            // second parameter
            param           = new CodeParameterDeclarationExpression(typeof(int), null);
            param.Direction = FieldDirection.Ref;
            method.Parameters.Add(param);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = "C";
            param.CustomAttributes.Add(attrDec);

            TypeDeclaration.Members.Add(method);

            return(GenerateCodeFromType(TypeDeclaration, options));
        }
        public static void AddAttribute(ITypeDefinition cls, string name, params object[] parameters)
        {
            bool   isOpen;
            string fileName = cls.Region.FileName;
            var    buffer   = TextFileProvider.Instance.GetTextEditorData(fileName, out isOpen);

            var attr = new CodeAttributeDeclaration(name);

            foreach (var parameter in parameters)
            {
                attr.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(parameter)));
            }

            var type = new CodeTypeDeclaration("temp");

            type.CustomAttributes.Add(attr);
            Project project;

            if (!cls.TryGetSourceProject(out project))
            {
                LoggingService.LogError("Error can't get source project for:" + cls.FullName);
            }

            var provider = ((DotNetProject)project).LanguageBinding.GetCodeDomProvider();
            var sw       = new StringWriter();

            provider.GenerateCodeFromType(type, sw, new CodeGeneratorOptions());
            string code  = sw.ToString();
            int    start = code.IndexOf('[');
            int    end   = code.LastIndexOf(']');

            code = code.Substring(start, end - start + 1) + Environment.NewLine;

            int pos = buffer.LocationToOffset(cls.Region.BeginLine, cls.Region.BeginColumn);

            code = buffer.GetLineIndent(cls.Region.BeginLine) + code;
            buffer.Insert(pos, code);
            if (!isOpen)
            {
                File.WriteAllText(fileName, buffer.Text);
                buffer.Dispose();
            }
        }
        private void AddKnownTypesForPart(OperationContractGenerationContext context, MessagePartDescription part, Dictionary <CodeTypeReference, object> operationKnownTypes)
        {
            ICollection <CodeTypeReference> is2;

            if (this.knownTypes.TryGetValue(part, out is2))
            {
                foreach (CodeTypeReference reference in is2)
                {
                    object obj2;
                    if (!operationKnownTypes.TryGetValue(reference, out obj2))
                    {
                        operationKnownTypes.Add(reference, null);
                        CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(typeof(ServiceKnownTypeAttribute).FullName);
                        declaration.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(reference)));
                        context.SyncMethod.CustomAttributes.Add(declaration);
                    }
                }
            }
        }
Example #26
0
 private static void RemoveAttributes(CodeNamespace codeNamespace)
 {
     foreach (CodeTypeDeclaration codeType in codeNamespace.Types)
     {
         CodeAttributeDeclaration xmlTypeAttribute = null;
         foreach (CodeAttributeDeclaration codeAttribute in codeType.CustomAttributes)
         {
             if (codeAttribute.Name == "System.Xml.Serialization.XmlTypeAttribute")
             {
                 xmlTypeAttribute = codeAttribute;
             }
         }
         codeType.CustomAttributes.Clear();
         if (xmlTypeAttribute != null)
         {
             codeType.CustomAttributes.Add(xmlTypeAttribute);
         }
     }
 }
Example #27
0
        //[WebServiceBinding(ConformsTo=WsiClaims.BP10,EmitConformanceClaims = true)]
        //public class <WorkflowTypeName>_WebService : System.Workflow.Runtime.Hosting.WorkflowWebService
        //{
        //  public <WorkflowTypeName>_WebService():base(typeof(<WorkflowTypeName>)) {}
        //}
        private CodeTypeDeclaration GetWebserviceCodeTypeDeclaration(string workflowTypeName)
        {
            CodeTypeDeclaration typeDeclaration = new CodeTypeDeclaration(workflowTypeName + "_WebService");

            typeDeclaration.BaseTypes.Add(new CodeTypeReference("WorkflowWebService"));

            CodeAttributeDeclaration attributeDeclaration = new CodeAttributeDeclaration("WebServiceBinding", new CodeAttributeArgument("ConformsTo", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("WsiProfiles"), "BasicProfile1_1")), new CodeAttributeArgument("EmitConformanceClaims", new CodePrimitiveExpression(true)));

            typeDeclaration.CustomAttributes.Add(attributeDeclaration);

            //Emit Constructor
            CodeConstructor constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;
            constructor.BaseConstructorArgs.Add(new CodeTypeOfExpression(workflowTypeName));
            typeDeclaration.Members.Add(constructor);

            return(typeDeclaration);
        }
        private void AddOrderAttribute(CodeMemberProperty codeMemberProperty, int order)
        {
            // Get the XmlElementAttribute or create one
            var xmlAttributeOrder = codeMemberProperty.CustomAttributes.OfType <CodeAttributeDeclaration>().FirstOrDefault(m => m.Name == xmlElementAttributeString || m.Name == xmlArrayAttributeString);

            if (xmlAttributeOrder == null)
            {
                var xmlAttributeString = xmlElementAttributeString;
                if (codeMemberProperty.Type.ArrayRank > 0)
                {
                    xmlAttributeString = xmlArrayAttributeString;
                }

                xmlAttributeOrder = new CodeAttributeDeclaration(xmlAttributeString);
                codeMemberProperty.CustomAttributes.Insert(0, xmlAttributeOrder);
            }

            AddOrderArgument(xmlAttributeOrder, order);
        }
        internal static CodeTypeDeclaration GenerateEnum(CodeTypeDeclaration typeDeclaration,
                                                         string proposedName,
                                                         string description,
                                                         IEnumerable <KeyValuePair <string, string> > entries)
        {
            typeDeclaration.ThrowIfNull("typeDeclaration");
            proposedName.ThrowIfNullOrEmpty("proposedName");
            entries.ThrowIfNull("entries");

            // Create a safe enum name by avoiding the names of all members which are already in this type.
            IEnumerable <string> memberNames = from CodeTypeMember m in typeDeclaration.Members select m.Name;
            string name = GeneratorUtils.GetEnumName(proposedName, memberNames);

            // Create the enum type.
            var decl = new CodeTypeDeclaration(name);

            decl.IsEnum = true;

            foreach (KeyValuePair <string, string> enumEntry in entries)
            {
                // Consider the names of all members in the current type as used words.
                IEnumerable <string> usedNames = from CodeTypeMember m in decl.Members select m.Name;
                string safeName = GeneratorUtils.GetEnumValueName(enumEntry.Key, usedNames);
                var    member   = new CodeMemberField(typeof(int), safeName);

                // Attribute:
                var valueAttribute = new CodeAttributeDeclaration();
                valueAttribute.Name = typeof(StringValueAttribute).FullName;
                valueAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(enumEntry.Key)));
                member.CustomAttributes.Add(valueAttribute);

                // Comments:
                member.Comments.AddRange(DecoratorUtil.CreateSummaryComment(enumEntry.Value));

                // Add member to enum.
                decl.Members.Add(member);
            }

            // Class comment:
            decl.Comments.AddRange(DecoratorUtil.CreateSummaryComment(description));

            return(decl);
        }
Example #30
0
        void AddTypeAttributes(CodeTypeDeclaration td, XmlSchemaType type, params XmlSchemaElement [] collectionArgs)
        {
            var name = type.QualifiedName;

            // [GeneratedCode (assembly_name, assembly_version)]
            td.CustomAttributes.Add(new CodeAttributeDeclaration(
                                        new CodeTypeReference(typeof(GeneratedCodeAttribute)),
                                        new CodeAttributeArgument(new CodePrimitiveExpression(ass_name)),
                                        new CodeAttributeArgument(new CodePrimitiveExpression(ass_version))));

            var ct = type as XmlSchemaComplexType;

            // [DataContract(Name="foobar",Namespace="urn:foobar")] (optionally IsReference=true),
            // or [CollectionDataContract(ditto, ItemType/KeyType/ValueType)]
            var dca = new CodeAttributeDeclaration(
                collectionArgs != null && collectionArgs.Length > 0 ? typeref_coll_contract : typeref_data_contract,
                new CodeAttributeArgument("Name", new CodePrimitiveExpression(name.Name)),
                new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(name.Namespace)));

            if (collectionArgs != null)
            {
                if (collectionArgs.Length > 0)
                {
                    dca.Arguments.Add(new CodeAttributeArgument("ItemName", new CodePrimitiveExpression(CodeIdentifier.MakeValid(collectionArgs [0].QualifiedName.Name))));
                }
                if (collectionArgs.Length > 2)
                {
                    dca.Arguments.Add(new CodeAttributeArgument("KeyName", new CodePrimitiveExpression(CodeIdentifier.MakeValid(collectionArgs [1].QualifiedName.Name))));
                    dca.Arguments.Add(new CodeAttributeArgument("ValueName", new CodePrimitiveExpression(CodeIdentifier.MakeValid(collectionArgs [2].QualifiedName.Name))));
                }
            }
            if (ct != null && ct.AttributeUses [new XmlQualifiedName("Ref", KnownTypeCollection.MSSimpleNamespace)] != null)
            {
                dca.Arguments.Add(new CodeAttributeArgument("IsReference", new CodePrimitiveExpression(true)));
            }
            td.CustomAttributes.Add(dca);

            // optional [Serializable]
            if (Options != null && Options.GenerateSerializable)
            {
                td.CustomAttributes.Add(new CodeAttributeDeclaration("System.SerializableAttribute"));
            }
        }
Example #31
0
        /// <summary>
        /// The method to be called to create the type level attributes for the ItemTypeEmitter
        /// </summary>
        /// <param name="emitter">The strongly typed emitter</param>
        /// <param name="typeDecl">The type declaration to add the attribues to.</param>
        public void EmitTypeAttributes(EntityTypeEmitter emitter, CodeTypeDeclaration typeDecl)
        {
            Debug.Assert(emitter != null, "emitter should not be null");
            Debug.Assert(typeDecl != null, "typeDecl should not be null");

            EmitSchemaTypeAttribute(FQAdoFrameworkDataClassesName("EdmEntityTypeAttribute"), emitter, typeDecl);

            CodeAttributeDeclaration attribute2 = EmitSimpleAttribute("System.Runtime.Serialization.DataContractAttribute");

            AttributeEmitter.AddNamedAttributeArguments(attribute2,
                                                        "IsReference", true);
            typeDecl.CustomAttributes.Add(attribute2);

            CodeAttributeDeclaration attribute3 = EmitSimpleAttribute("System.Serializable");

            typeDecl.CustomAttributes.Add(attribute3);

            EmitKnownTypeAttributes(emitter.Item, emitter.Generator, typeDecl);
        }
        public void AttributeAndSimpleNamespaceTest()
        {
            CodeNamespace ns = new CodeNamespace("A");

            codeUnit.Namespaces.Add(ns);

            CodeAttributeDeclaration attrDec = new CodeAttributeDeclaration();

            attrDec.Name = "A";
            codeUnit.AssemblyCustomAttributes.Add(attrDec);

            attrDec      = new CodeAttributeDeclaration();
            attrDec.Name = "B";
            codeUnit.AssemblyCustomAttributes.Add(attrDec);

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "<Assembly: A(),  _{0} Assembly: B()> {0}{0}Namespace A{0}End "
                                          + "Namespace{0}", NewLine), Generate());
        }
        private void AddGeneratedMethod(CodeTypeDeclaration generatedClass, MultiDirectionTestMethod testMethod)
        {
            foreach (var transferDirection in testMethod.GetTransferDirections())
            {
                string generatedMethodName = this.GetGeneratedMethodName(testMethod, transferDirection);

                CodeMemberMethod generatedMethod = new CodeMemberMethod();
                generatedMethod.Name       = generatedMethodName;
                generatedMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;

                // Add TestCategoryAttribute to the generated method
                this.AddTestCategoryAttributes(generatedMethod, testMethod);
                this.AddTestCategoryAttribute(generatedMethod, MultiDirectionTag.MultiDirection);
                foreach (var tag in transferDirection.GetTags())
                {
                    this.AddTestCategoryAttribute(generatedMethod, tag);
                }

                CodeAttributeDeclaration testMethodAttribute = null;

                testMethodAttribute = new CodeAttributeDeclaration(
                    new CodeTypeReference(typeof(MSUnittest.TestMethodAttribute)));

                generatedMethod.CustomAttributes.Add(testMethodAttribute);

                if (Program.FrameWorkType == FrameworkType.DNetCore)
                {
                    // add TestStartEndAttribute to ensure Test.Start and Test.End will be called as expected
                    generatedMethod.CustomAttributes.Add(new CodeAttributeDeclaration("TestStartEnd"));
                }

                foreach (var statement in TransferDirectionExtensions.EnumerateUpdateContextStatements(transferDirection as DMLibTransferDirection))
                {
                    generatedMethod.Statements.Add(statement);
                }

                CodeMethodReferenceExpression callee = new CodeMethodReferenceExpression(
                    new CodeBaseReferenceExpression(), testMethod.MethodInfoObj.Name);
                CodeMethodInvokeExpression invokeExp = new CodeMethodInvokeExpression(callee);
                generatedMethod.Statements.Add(invokeExp);
                generatedClass.Members.Add(generatedMethod);
            }
        }
	public void AddRange(CodeAttributeDeclaration[] value) {}
Example #35
0
    public void PostMembersHook(Smoke* smoke, Smoke.Class* klass, CodeTypeDeclaration type)
    {
        if (Util.IsQObject(klass))
        {
            CodeMemberProperty emit = new CodeMemberProperty();
            emit.Name = "Emit";
            emit.Attributes = MemberAttributes.Family | MemberAttributes.New | MemberAttributes.Final;
            emit.HasGet = true;
            emit.HasSet = false;

            string signalsIfaceName = "I" + type.Name + "Signals";
            CodeTypeReference returnType = new CodeTypeReference(signalsIfaceName);
            emit.Type = returnType;

            emit.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(
                returnType,
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Q_EMIT")
            )));

            type.Members.Add(emit);

            string className = ByteArrayManager.GetString(klass->className);
            int colon = className.LastIndexOf("::", StringComparison.Ordinal);
            string prefix = (colon != -1) ? className.Substring(0, colon) : string.Empty;

            IList typeCollection = Data.GetTypeCollection(prefix);
            CodeTypeDeclaration ifaceDecl = new CodeTypeDeclaration(signalsIfaceName);
            ifaceDecl.IsInterface = true;

            if (className != "QObject")
            {
                string parentClassName = ByteArrayManager.GetString(smoke->classes[smoke->inheritanceList[klass->parents]].className);
                colon = parentClassName.LastIndexOf("::", StringComparison.Ordinal);
                prefix = (colon != -1) ? parentClassName.Substring(0, colon) : string.Empty;
                if (colon != -1)
                {
                    parentClassName = parentClassName.Substring(colon + 2);
                }

                string parentInterface = (prefix != string.Empty) ? prefix.Replace("::", ".") + "." : string.Empty;
                parentInterface += "I" + parentClassName + "Signals";

                ifaceDecl.BaseTypes.Add(new CodeTypeReference(parentInterface));
            }
            Dictionary<CodeSnippetTypeMember, CodeMemberMethod> signalEvents = new Dictionary<CodeSnippetTypeMember, CodeMemberMethod>();
            GetSignals(smoke, klass, delegate(string signature, string name, string typeName, IntPtr metaMethod)
            {
                CodeMemberMethod signal = new CodeMemberMethod();
                signal.Attributes = MemberAttributes.Abstract;

                // capitalize the first letter
                StringBuilder builder = new StringBuilder(name);
                builder[0] = char.ToUpper(builder[0]);
                string tmp = builder.ToString();

                signal.Name = tmp;
                bool isRef;
                try
                {
                    if (typeName == string.Empty)
                        signal.ReturnType = new CodeTypeReference(typeof(void));
                    else
                        signal.ReturnType = Translator.CppToCSharp(typeName, out isRef);
                }
                catch (NotSupportedException)
                {
                    Debug.Print("  |--Won't wrap signal {0}::{1}", className, signature);
                    return;
                }

                CodeAttributeDeclaration attr = new CodeAttributeDeclaration("Q_SIGNAL",
                    new CodeAttributeArgument(new CodePrimitiveExpression(signature)));
                signal.CustomAttributes.Add(attr);

                int argNum = 1;
                StringBuilder fullNameBuilder = new StringBuilder("Slot");
                GetMetaMethodParameters(metaMethod, delegate(string paramType, string paramName)
                {
                    if (paramName == string.Empty)
                    {
                        paramName = "arg" + argNum.ToString();
                    }
                    argNum++;

                    CodeParameterDeclarationExpression param;
                    try
                    {
                        short id = smoke->IDType(paramType);
                        CodeTypeReference paramTypeRef;
                        if (id > 0)
                        {
                            paramTypeRef = Translator.CppToCSharp(smoke->types + id, out isRef);
                        }
                        else
                        {
                            if (!paramType.Contains("::"))
                            {
                                id = smoke->IDType(className + "::" + paramType);
                                if (id > 0)
                                {
                                    paramTypeRef = Translator.CppToCSharp(smoke->types + id, out isRef);
                                }
                                else
                                {
                                    paramTypeRef = Translator.CppToCSharp(paramType, out isRef);
                                }
                            }
                            else
                            {
                                paramTypeRef = Translator.CppToCSharp(paramType, out isRef);
                            }
                        }
                        param = new CodeParameterDeclarationExpression(paramTypeRef, paramName);
                    }
                    catch (NotSupportedException)
                    {
                        Debug.Print("  |--Won't wrap signal {0}::{1}", className, signature);
                        return;
                    }
                    if (isRef)
                    {
                        param.Direction = FieldDirection.Ref;
                    }
                    signal.Parameters.Add(param);
                    if (argNum == 2)
                    {
                        fullNameBuilder.Append('<');
                    }
                    fullNameBuilder.Append(param.Type.BaseType);
                    fullNameBuilder.Append(',');
                });
                if (fullNameBuilder[fullNameBuilder.Length - 1] == ',')
                {
                    fullNameBuilder[fullNameBuilder.Length - 1] = '>';
                }
                ifaceDecl.Members.Add(signal);
                CodeSnippetTypeMember signalEvent = new CodeSnippetTypeMember();
                signalEvent.Name = signal.Name;
                CodeSnippetTypeMember existing = signalEvents.Keys.FirstOrDefault(m => m.Name == signal.Name);
                if (existing != null)
                {
                    CodeSnippetTypeMember signalEventToUse;
                    CodeMemberMethod signalToUse;
                    if (signal.Parameters.Count == 0)
                    {
                        signalEventToUse = existing;
                        signalToUse = signalEvents[existing];
                    }
                    else
                    {
                        signalEventToUse = signalEvent;
                        signalToUse = signal;
                    }
                    string suffix = signalToUse.Parameters.Cast<CodeParameterDeclarationExpression>().Last().Name;
                    if (suffix.StartsWith("arg") && suffix.Length > 3 && char.IsDigit(suffix[3]))
                    {
                        string lastType = signalToUse.Parameters.Cast<CodeParameterDeclarationExpression>().Last().Type.BaseType;
                        suffix = lastType.Substring(lastType.LastIndexOf('.') + 1);
                    }
                    else
                    {
                        StringBuilder lastParamBuilder = new StringBuilder(suffix);
                        lastParamBuilder[0] = char.ToUpper(lastParamBuilder[0]);
                        suffix = lastParamBuilder.ToString();
                    }
                    signalEventToUse.Text = signalEventToUse.Text.Replace(signalEventToUse.Name, signalEventToUse.Name += suffix);
                }
                signalEvent.Text = string.Format(@"
        public event {0} {1}
        {{
            add
            {{
                QObject.Connect(this, Qt.SIGNAL(""{2}""), (QObject) value.Target, Qt.SLOT(value.Method.Name + ""{3}""));
            }}
            remove
            {{
                QObject.Disconnect(this, Qt.SIGNAL(""{2}""), (QObject) value.Target, Qt.SLOT(value.Method.Name + ""{3}""));
            }}
        }}", fullNameBuilder, signalEvent.Name, signature, signature.Substring(signature.IndexOf('(')));
                signalEvents.Add(signalEvent, signal);
            });

            typeCollection.Add(ifaceDecl);
            foreach (KeyValuePair<CodeSnippetTypeMember, CodeMemberMethod> signalEvent in signalEvents)
            {
                CodeSnippetTypeMember implementation = signalEvent.Key;
                CodeCommentStatementCollection comments = new CodeCommentStatementCollection();
                foreach (CodeTypeMember current in from CodeTypeMember member in type.Members
                                                   where member.Name == implementation.Name
                                                   select member)
                {
                    if (comments.Count == 0)
                    {
                        comments.AddRange(current.Comments);
                    }
                    current.Name = "On" + current.Name;
                }
                signalEvent.Value.Comments.AddRange(comments);
                signalEvent.Key.Comments.AddRange(comments);
                type.Members.Add(signalEvent.Key);
            }
        }
    }
 private void AddServiceContractAttribute(ServiceContractGenerationContext context)
 {
     CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(context.ServiceContractGenerator.GetCodeTypeReference(typeof(ServiceContractAttribute)));
     if (context.ContractType.Name != context.Contract.CodeName)
     {
         string str = (NamingHelper.XmlName(context.Contract.CodeName) == context.Contract.Name)  context.Contract.CodeName  context.Contract.Name;
         declaration.Arguments.Add(new CodeAttributeArgument(Name, new CodePrimitiveExpression(str)));
     }
     if (httptempuri.org != context.Contract.Namespace)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(Namespace, new CodePrimitiveExpression(context.Contract.Namespace)));
     }
     declaration.Arguments.Add(new CodeAttributeArgument(ConfigurationName, new CodePrimitiveExpression(ServiceContractGenerator.NamespaceHelper.GetCodeTypeReference(context.Namespace, context.ContractType).BaseType)));
     if (context.Contract.HasProtectionLevel)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(ProtectionLevel, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(ProtectionLevel)), context.Contract.ProtectionLevel.ToString())));
     }
     if (context.DuplexCallbackType != null)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(CallbackContract, new CodeTypeOfExpression(context.DuplexCallbackTypeReference)));
     }
     if (context.Contract.SessionMode != SessionMode.Allowed)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(SessionMode, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(SessionMode)), context.Contract.SessionMode.ToString())));
     }
     context.ContractType.CustomAttributes.Add(declaration);
 }
	public void Remove(CodeAttributeDeclaration value) {}
	public int IndexOf(CodeAttributeDeclaration value) {}
		public void Arguments_AddMultiple_ReturnsExpected()
		{
			var declaration = new CodeAttributeDeclaration();

			CodeAttributeArgument argument1 = new CodeAttributeArgument(new CodePrimitiveExpression("Value1"));
			declaration.Arguments.Add(argument1);
			Assert.Equal(new CodeAttributeArgument[] { argument1 }, declaration.Arguments.Cast<CodeAttributeArgument>());

			CodeAttributeArgument argument2 = new CodeAttributeArgument(new CodePrimitiveExpression("Value2"));
			declaration.Arguments.Add(argument2);
			Assert.Equal(new CodeAttributeArgument[] { argument1, argument2 }, declaration.Arguments.Cast<CodeAttributeArgument>());
		}
		public void Name_Set_Get_ReturnsExpected(string value)
		{
			var declaration = new CodeAttributeDeclaration();
			declaration.Name = value;
			Assert.Equal(value ?? string.Empty, declaration.Name);
		}
 private static CodeAttributeDeclaration CreateAttrDecl(OperationContractGenerationContext context, TransactionFlowAttribute attr)
 {
     CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(context.Contract.ServiceContractGenerator.GetCodeTypeReference(typeof(TransactionFlowAttribute)));
     declaration.Arguments.Add(new CodeAttributeArgument(ServiceContractGenerator.GetEnumReferenceTransactionFlowOption(attr.Transactions)));
     return declaration;
 }
 private void AddGeneratedCodeAttribute(CodeTypeDeclaration codeType)
 {
     CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(this.parent.GetCodeTypeReference(typeof(GeneratedCodeAttribute)));
     AssemblyName name = Assembly.GetExecutingAssembly().GetName();
     declaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(name.Name)));
     declaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(name.Version.ToString())));
     codeType.CustomAttributes.Add(declaration);
 }
	public bool Contains(CodeAttributeDeclaration value) {}
Example #44
0
    public CodeMemberMethod GenerateMethod(Smoke* smoke, Smoke.Method* method, string mungedName, CodeTypeReference iface)
    {
        string cppSignature = smoke->GetMethodSignature(method);
        CodeMemberMethod cmm = GenerateBasicMethodDefinition(smoke, method, cppSignature, iface);
        if (cmm == null)
        {
            return null;
        }

        // put the method into the correct type
        CodeTypeDeclaration containingType = type;
        if (cmm.Name.StartsWith("operator") || cmm.Name.StartsWith("explicit "))
        {
            if (!data.CSharpTypeMap.TryGetValue(cmm.Parameters[0].Type.GetStringRepresentation(), out containingType))
            {
                if (cmm.Parameters.Count < 2 ||
                    !data.CSharpTypeMap.TryGetValue(cmm.Parameters[1].Type.GetStringRepresentation(), out containingType))
                {
                    Debug.Print("  |--Can't find containing type for {0} - skipping", cppSignature);
                }
                return null;
            }
        }

        // already implemented?
        if (containingType.HasMethod(cmm))
        {
            if (iface == null || (method->flags & (uint) Smoke.MethodFlags.mf_protected) > 0)
            {
                // protected methods are not available in interfaces
                Debug.Print("  |--Skipping already implemented method {0}", cppSignature);
                return null;
            }
            else
            {
                cmm.PrivateImplementationType = iface;
            }
        }

        if (PreMethodBodyHooks != null)
        {
            PreMethodBodyHooks(smoke, method, cmm, containingType);
        }

        // do we have pass-by-ref parameters?
        bool generateInvokeForRefParams = cmm.Parameters.Cast<CodeParameterDeclarationExpression>().Any(expr => expr.Direction == FieldDirection.Ref);

        // generate the SmokeMethod attribute
        CodeAttributeDeclaration attr = new CodeAttributeDeclaration("SmokeMethod",
                                                                     new CodeAttributeArgument(
                                                                     	new CodePrimitiveExpression(cppSignature)));
        cmm.CustomAttributes.Add(attr);

        // choose the correct 'interceptor'
        CodeMethodInvokeExpression invoke;
        if ((cmm.Attributes & MemberAttributes.Static) == MemberAttributes.Static)
        {
            invoke = new CodeMethodInvokeExpression(SmokeSupport.staticInterceptor_Invoke);
        }
        else
        {
            invoke = new CodeMethodInvokeExpression(SmokeSupport.interceptor_Invoke);
        }

        // first pass the munged name, then the C++ signature
        invoke.Parameters.Add(new CodePrimitiveExpression(mungedName));
        invoke.Parameters.Add(new CodePrimitiveExpression(cppSignature));

        // retrieve the return type
        CodeTypeReference returnType;
        if ((method->flags & (uint) Smoke.MethodFlags.mf_dtor) > 0)
        {
            // destructor
            returnType = new CodeTypeReference(typeof(void));
        }
        else if (cmm.Name.StartsWith("explicit operator "))
        {
            // strip 'explicit operator' from the name to get the return type
            returnType = new CodeTypeReference(cmm.Name.Substring(18));
        }
        else
        {
            returnType = cmm.ReturnType;
        }

        // add the return type
        invoke.Parameters.Add(new CodeTypeOfExpression(returnType));
        invoke.Parameters.Add(new CodePrimitiveExpression(generateInvokeForRefParams));
        invoke.Parameters.Add(new CodeVariableReferenceExpression("smokeArgs"));

        ProcessEqualityOperators(cmm);

        CodeArrayCreateExpression argsInitializer = new CodeArrayCreateExpression(typeof(object[]));

        // add the parameters
        foreach (CodeParameterDeclarationExpression param in cmm.Parameters)
        {
            argsInitializer.Initializers.Add(new CodeTypeOfExpression(param.Type));
            string argReference = param.Name;
            int indexOfSpace = argReference.IndexOf(' ');
            if (indexOfSpace > 0)
            {
                argReference = argReference.Substring(0, indexOfSpace);
            }
            argsInitializer.Initializers.Add(new CodeArgumentReferenceExpression(argReference));
        }

        CodeStatement argsStatement = new CodeVariableDeclarationStatement(typeof(object[]), "smokeArgs", argsInitializer);
        cmm.Statements.Add(argsStatement);

        // we have to call "CreateProxy()" in constructors
        if (cmm is CodeConstructor)
        {
            cmm.Statements.Add(
                new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "CreateProxy")));
        }

        // add the method call statement
        CodeStatement statement;

        if (!generateInvokeForRefParams)
        {
            if (method->ret > 0 && (method->flags & (uint) Smoke.MethodFlags.mf_ctor) == 0)
            {
                statement = new CodeMethodReturnStatement(new CodeCastExpression(returnType, invoke));
            }
            else
            {
                statement = new CodeExpressionStatement(invoke);
            }
            cmm.Statements.Add(statement);
        }
        else
        {
            if (method->ret > 0 && (method->flags & (uint) Smoke.MethodFlags.mf_ctor) == 0)
            {
                statement = new CodeVariableDeclarationStatement(returnType, "smokeRetval",
                                                                 new CodeCastExpression(returnType, invoke));
                cmm.Statements.Add(statement);
            }
            else
            {
                statement = new CodeExpressionStatement(invoke);
                cmm.Statements.Add(statement);
            }

            int i = 0;
            foreach (CodeParameterDeclarationExpression param in cmm.Parameters)
            {
                ++i;
                if (param.Direction != FieldDirection.Ref)
                {
                    continue;
                }
                cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(param.Name),
                                                           new CodeCastExpression(param.Type.BaseType,
                                                                                  new CodeArrayIndexerExpression(
                                                                                  	new CodeVariableReferenceExpression("smokeArgs"),
                                                                                  	new CodePrimitiveExpression(i*2 - 1)
                                                                                  	)
                                                           	)
                                   	));
            }

            if (method->ret > 0 && (method->flags & (uint) Smoke.MethodFlags.mf_ctor) == 0)
            {
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("smokeRetval")));
            }
        }
        containingType.Members.Add(cmm);

        if ((method->flags & (uint) Smoke.MethodFlags.mf_dtor) != 0)
        {
            containingType.BaseTypes.Add(new CodeTypeReference(typeof(IDisposable)));
            CodeMemberMethod dispose = new CodeMemberMethod();
            dispose.Name = "Dispose";
            dispose.Attributes = MemberAttributes.Public | MemberAttributes.New | MemberAttributes.Final;
            dispose.Statements.AddRange(cmm.Statements);
            dispose.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(
                                                               	new CodeTypeReferenceExpression("GC"), "SuppressFinalize",
                                                               	new CodeThisReferenceExpression()
                                                               	)));
            containingType.Members.Add(dispose);
        }
        return cmm;
    }
	public void CopyTo(CodeAttributeDeclaration[] array, int index) {}
	// Methods
	public int Add(CodeAttributeDeclaration value) {}
	public void Insert(int index, CodeAttributeDeclaration value) {}
 private CodeAttributeDeclaration CreateOperationContractAttributeDeclaration(OperationDescription operationDescription, bool asyncPattern)
 {
     CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(this.context.ServiceContractGenerator.GetCodeTypeReference(typeof(OperationContractAttribute)));
     if (operationDescription.IsOneWay)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(IsOneWay, new CodePrimitiveExpression(true)));
     }
     if ((operationDescription.DeclaringContract.SessionMode == SessionMode.Required) && operationDescription.IsTerminating)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(IsTerminating, new CodePrimitiveExpression(true)));
     }
     if ((operationDescription.DeclaringContract.SessionMode == SessionMode.Required) && !operationDescription.IsInitiating)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(IsInitiating, new CodePrimitiveExpression(false)));
     }
     if (asyncPattern)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(AsyncPattern, new CodePrimitiveExpression(true)));
     }
     if (operationDescription.HasProtectionLevel)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(ProtectionLevel, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(ProtectionLevel)), operationDescription.ProtectionLevel.ToString())));
     }
     return declaration;
 }
	public CodeAttributeDeclarationCollection(CodeAttributeDeclaration[] value) {}
        public void MetadataAttributes()
        {
            var cu = new CodeCompileUnit();

            var ns = new CodeNamespace();
            ns.Name = "MyNamespace";
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
            ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            cu.Namespaces.Add(ns);

            var attrs = cu.AssemblyCustomAttributes;
            attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
            attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
            attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));

            var class1 = new CodeTypeDeclaration() { Name = "MyClass" };
            class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
            class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class"))));
            ns.Types.Add(class1);

            var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic };
            nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
            class1.Members.Add(nestedClass);

            var method1 = new CodeMemberMethod() { Name = "MyMethod" };
            method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method"))));
            method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That"))));
            var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
            param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
                            new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                            new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
            method1.Parameters.Add(param1);
            var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit");
            param2.CustomAttributes.Add(
                        new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
                            new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                            new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
            method1.Parameters.Add(param2);
            class1.Members.Add(method1);

            var function1 = new CodeMemberMethod();
            function1.Name = "MyFunction";
            function1.ReturnType = new CodeTypeReference(typeof(string));
            function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
            function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
            function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
                CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
                CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
            function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
            class1.Members.Add(function1);

            CodeMemberMethod function2 = new CodeMemberMethod();
            function2.Name = "GlobalKeywordFunction";
            function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new
                CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
            CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference);
            CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef);
            function2.ReturnTypeCustomAttributes.Add(codeAttrib);
            class1.Members.Add(function2);

            CodeMemberField field1 = new CodeMemberField();
            field1.Name = "myField";
            field1.Type = new CodeTypeReference(typeof(string));
            field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute"));
            field1.InitExpression = new CodePrimitiveExpression("hi!");
            class1.Members.Add(field1);

            CodeMemberProperty prop1 = new CodeMemberProperty();
            prop1.Name = "MyProperty";
            prop1.Type = new CodeTypeReference(typeof(string));
            prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property"))));
            prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField")));
            class1.Members.Add(prop1);

            CodeConstructor const1 = new CodeConstructor();
            const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor"))));
            class1.Members.Add(const1);

            class1 = new CodeTypeDeclaration("Test");
            class1.IsClass = true;
            class1.BaseTypes.Add(new CodeTypeReference("Form"));
            ns.Types.Add(class1);

            CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
            mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
            class1.Members.Add(mfield);

            CodeConstructor ctor = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                                "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
                                new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "Text"), new CodePrimitiveExpression("Test")));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "TabIndex"), new CodePrimitiveExpression(0)));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
                                new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
            ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
                CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
                , new CodeThisReferenceExpression(), "b_Click")));
            class1.Members.Add(ctor);

            CodeMemberEvent evt = new CodeMemberEvent();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference("System.EventHandler");
            evt.Attributes = MemberAttributes.Public;
            evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
            class1.Members.Add(evt);

            var cmm = new CodeMemberMethod();
            cmm.Name = "b_Click";
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
            class1.Members.Add(cmm);

            AssertEqual(cu,
                @"//------------------------------------------------------------------------------
                  // <auto-generated>
                  //     This code was generated by a tool.
                  //     Runtime Version:4.0.30319.42000
                  //
                  //     Changes to this file may cause incorrect behavior and will be lost if
                  //     the code is regenerated.
                  // </auto-generated>
                  //------------------------------------------------------------------------------

                  [assembly: System.Reflection.AssemblyTitle(""MyAssembly"")]
                  [assembly: System.Reflection.AssemblyVersion(""1.0.6.2"")]
                  [assembly: System.CLSCompliantAttribute(false)]

                  namespace MyNamespace
                  {
                      using System;
                      using System.Drawing;
                      using System.Windows.Forms;
                      using System.ComponentModel;
                  
                      [System.Serializable()]
                      [System.Obsolete(""Don\'t use this Class"")]
                      public class MyClass
                      {
                          [System.Xml.Serialization.XmlElementAttribute()]
                          private string myField = ""hi!"";
              
                          [System.Obsolete(""Don\'t use this Constructor"")]
                          private MyClass()
                          {
                          }
              
                          [System.Obsolete(""Don\'t use this Property"")]
                          private string MyProperty
                          {
                              get
                              {
                                  return this.myField;
                              }
                          }
              
                          [System.Obsolete(""Don\'t use this Method"")]
                          [System.ComponentModel.Editor(""This"", ""That"")]
                          private void MyMethod([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] string blah, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] int[] arrayit)
                          {
                          }
              
                          [System.Obsolete(""Don\'t use this Function"")]
                          [return: System.Xml.Serialization.XmlIgnoreAttribute()]
                          [return: System.Xml.Serialization.XmlRootAttribute(Namespace=""Namespace Value"", ElementName=""Root, hehehe"")]
                          private string MyFunction()
                          {
                              return ""Return"";
                          }
              
                          [global::System.ObsoleteAttribute(""Don\'t use this Function"")]
                          [return: global::System.Xml.Serialization.XmlIgnoreAttribute()]
                          private void GlobalKeywordFunction()
                          {
                          }
              
                          [System.Serializable()]
                          public class NestedClass
                          {
                          }
                      }
              
                      public class Test : Form
                      {
                          private Button b = new Button();
              
                          public Test()
                          {
                              this.Size = new Size(600, 600);
                              b.Text = ""Test"";
                              b.TabIndex = 0;
                              b.Location = new Point(400, 525);
                              this.MyEvent += new EventHandler(this.b_Click);
                          }
              
                          [System.CLSCompliantAttribute(false)]
                          public event System.EventHandler MyEvent;
              
                          private void b_Click(object sender, System.EventArgs e)
                          {
                          }
                      }
                  }");
        }
        public void MetadataAttributes()
        {
            var cu = new CodeCompileUnit();

            var ns = new CodeNamespace();
            ns.Name = "MyNamespace";
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
            ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            cu.Namespaces.Add(ns);

            var attrs = cu.AssemblyCustomAttributes;
            attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
            attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
            attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));

            var class1 = new CodeTypeDeclaration() { Name = "MyClass" };
            class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
            class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class"))));
            ns.Types.Add(class1);

            var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic };
            nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
            class1.Members.Add(nestedClass);

            var method1 = new CodeMemberMethod() { Name = "MyMethod" };
            method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method"))));
            method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That"))));
            var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
            param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
                            new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                            new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
            method1.Parameters.Add(param1);
            var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit");
            param2.CustomAttributes.Add(
                        new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
                            new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                            new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
            method1.Parameters.Add(param2);
            class1.Members.Add(method1);

            var function1 = new CodeMemberMethod();
            function1.Name = "MyFunction";
            function1.ReturnType = new CodeTypeReference(typeof(string));
            function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
            function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
            function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
                CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
                CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
            function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
            class1.Members.Add(function1);

            CodeMemberMethod function2 = new CodeMemberMethod();
            function2.Name = "GlobalKeywordFunction";
            function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new
                CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
            CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference);
            CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef);
            function2.ReturnTypeCustomAttributes.Add(codeAttrib);
            class1.Members.Add(function2);

            CodeMemberField field1 = new CodeMemberField();
            field1.Name = "myField";
            field1.Type = new CodeTypeReference(typeof(string));
            field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute"));
            field1.InitExpression = new CodePrimitiveExpression("hi!");
            class1.Members.Add(field1);

            CodeMemberProperty prop1 = new CodeMemberProperty();
            prop1.Name = "MyProperty";
            prop1.Type = new CodeTypeReference(typeof(string));
            prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property"))));
            prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField")));
            class1.Members.Add(prop1);

            CodeConstructor const1 = new CodeConstructor();
            const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor"))));
            class1.Members.Add(const1);

            class1 = new CodeTypeDeclaration("Test");
            class1.IsClass = true;
            class1.BaseTypes.Add(new CodeTypeReference("Form"));
            ns.Types.Add(class1);

            CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
            mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
            class1.Members.Add(mfield);

            CodeConstructor ctor = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                                "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
                                new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "Text"), new CodePrimitiveExpression("Test")));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "TabIndex"), new CodePrimitiveExpression(0)));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
                                new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
            ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
                CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
                , new CodeThisReferenceExpression(), "b_Click")));
            class1.Members.Add(ctor);

            CodeMemberEvent evt = new CodeMemberEvent();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference("System.EventHandler");
            evt.Attributes = MemberAttributes.Public;
            evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
            class1.Members.Add(evt);

            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "b_Click";
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
            class1.Members.Add(cmm);

            AssertEqual(cu,
                @"'------------------------------------------------------------------------------
                  ' <auto-generated>
                  '     This code was generated by a tool.
                  '     Runtime Version:4.0.30319.42000
                  '
                  '     Changes to this file may cause incorrect behavior and will be lost if
                  '     the code is regenerated.
                  ' </auto-generated>
                  '------------------------------------------------------------------------------

                  Option Strict Off
                  Option Explicit On

                  Imports System
                  Imports System.ComponentModel
                  Imports System.Drawing
                  Imports System.Windows.Forms
                  <Assembly: System.Reflection.AssemblyTitle(""MyAssembly""),  _
                   Assembly: System.Reflection.AssemblyVersion(""1.0.6.2""),  _
                   Assembly: System.CLSCompliantAttribute(false)>

                  Namespace MyNamespace

                      <System.Serializable(),  _
                       System.Obsolete(""Don't use this Class"")>  _
                      Public Class [MyClass]

                          <System.Xml.Serialization.XmlElementAttribute()>  _
                          Private myField As String = ""hi!""

                          <System.Obsolete(""Don't use this Constructor"")>  _
                          Private Sub New()
                              MyBase.New
                          End Sub

                          <System.Obsolete(""Don't use this Property"")>  _
                          Private ReadOnly Property MyProperty() As String
                              Get
                                  Return Me.myField
                              End Get
                          End Property

                          <System.Obsolete(""Don't use this Method""),  _
                           System.ComponentModel.Editor(""This"", ""That"")>  _
                          Private Sub MyMethod(<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal blah As String, <System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal arrayit() As Integer)
                          End Sub

                          <System.Obsolete(""Don't use this Function"")>  _
                          Private Function MyFunction() As <System.Xml.Serialization.XmlIgnoreAttribute(), System.Xml.Serialization.XmlRootAttribute([Namespace]:=""Namespace Value"", ElementName:=""Root, hehehe"")> String
                              Return ""Return""
                          End Function

                          <Global.System.ObsoleteAttribute(""Don't use this Function"")>  _
                          Private Sub GlobalKeywordFunction()
                          End Sub

                          <System.Serializable()>  _
                          Public Class NestedClass
                          End Class
                      End Class

                      Public Class Test
                          Inherits Form

                          Private b As Button = New Button()

                          Public Sub New()
                              MyBase.New
                              Me.Size = New Size(600, 600)
                              b.Text = ""Test""
                              b.TabIndex = 0
                              b.Location = New Point(400, 525)
                              AddHandler MyEvent, AddressOf Me.b_Click
                          End Sub

                          <System.CLSCompliantAttribute(false)>  _
                          Public Event MyEvent As System.EventHandler

                          Private Sub b_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                          End Sub
                      End Class
                  End Namespace");
        }
 private static CodeAttributeDeclaration CreateEditorBrowsableAttribute(EditorBrowsableState editorBrowsableState)
 {
     CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(EditorBrowsableAttribute)));
     CodeTypeReferenceExpression targetObject = new CodeTypeReferenceExpression(typeof(EditorBrowsableState));
     CodeAttributeArgument argument = new CodeAttributeArgument(new CodeFieldReferenceExpression(targetObject, editorBrowsableState.ToString()));
     declaration.Arguments.Add(argument);
     return declaration;
 }
 private static CodeAttributeDeclaration CreateAttrDecl(OperationContractGenerationContext context, FaultDescription fault)
 {
     CodeTypeReference type = (fault.DetailType != null)  context.Contract.ServiceContractGenerator.GetCodeTypeReference(fault.DetailType)  fault.DetailTypeReference;
     if ((type == null)  (type == voidTypeReference))
     {
         return null;
     }
     CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(context.ServiceContractGenerator.GetCodeTypeReference(typeof(FaultContractAttribute)));
     declaration.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(type)));
     if (fault.Action != null)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(Action, new CodePrimitiveExpression(fault.Action)));
     }
     if (fault.HasProtectionLevel)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(ProtectionLevel, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(ProtectionLevel)), fault.ProtectionLevel.ToString())));
     }
     if (!XmlName.IsNullOrEmpty(fault.ElementName))
     {
         declaration.Arguments.Add(new CodeAttributeArgument(Name, new CodePrimitiveExpression(fault.ElementName.EncodedName)));
     }
     if (fault.Namespace != context.Contract.Contract.Namespace)
     {
         declaration.Arguments.Add(new CodeAttributeArgument(Namespace, new CodePrimitiveExpression(fault.Namespace)));
     }
     return declaration;
 }
Example #54
0
    /*
     * Create a .NET class from a smoke class.
     * A class Namespace::Foo is mapped to Namespace.Foo. Classes that are not in any namespace go into the default namespace.
     * For namespaces that contain functions, a Namespace.Global class is created which holds the functions as methods.
     */
    private void DefineClass(short classId)
    {
        Smoke.Class* smokeClass = data.Smoke->classes + classId;
        string smokeName = ByteArrayManager.GetString(smokeClass->className);
        string mapName = smokeName;
        string name;
        string prefix = string.Empty;
        if (smokeClass->size == 0 && !translator.NamespacesAsClasses.Contains(smokeName))
        {
            if (smokeName == "QGlobalSpace")
            {
                // global space
                name = data.GlobalSpaceClassName;
                mapName = name;
            }
            else
            {
                // namespace
                prefix = smokeName;
                name = "Global";
                mapName = prefix + "::Global";
            }
        }
        else
        {
            int colon = smokeName.LastIndexOf("::", StringComparison.Ordinal);
            prefix = (colon != -1) ? smokeName.Substring(0, colon) : string.Empty;
            name = (colon != -1) ? smokeName.Substring(colon + 2) : smokeName;
        }

        // define the .NET class
        CodeTypeDeclaration type;
        bool alreadyDefined;
        if (!(alreadyDefined = data.CSharpTypeMap.TryGetValue(mapName, out type)))
        {
            type = new CodeTypeDeclaration(name);
            CodeAttributeDeclaration attr = new CodeAttributeDeclaration("SmokeClass",
                                                                         new CodeAttributeArgument(
                                                                             new CodePrimitiveExpression(smokeName)));
            type.CustomAttributes.Add(attr);
            type.IsPartial = true;
        }
        else
        {
            int toBeRemoved = -1;

            for (int i = 0; i < type.CustomAttributes.Count; i++)
            {
                CodeAttributeDeclaration attr = type.CustomAttributes[i];
                if (attr.Name == "SmokeClass" && attr.Arguments.Count == 1 &&
                    ((string) ((CodePrimitiveExpression) attr.Arguments[0].Value).Value) == "QGlobalSpace")
                {
                    toBeRemoved = i;
                    break;
                }
            }

            if (toBeRemoved > -1)
            {
                type.CustomAttributes.RemoveAt(toBeRemoved);
                CodeAttributeDeclaration attr = new CodeAttributeDeclaration("SmokeClass",
                                                                             new CodeAttributeArgument(
                                                                                 new CodePrimitiveExpression(smokeName)));
                type.CustomAttributes.Add(attr);
            }
        }

        if (smokeClass->parents != 0)
        {
            short* parent = data.Smoke->inheritanceList + smokeClass->parents;
            if (*parent > 0)
            {
                type.BaseTypes.Add(
                    new CodeTypeReference(ByteArrayManager.GetString((data.Smoke->classes + *parent)->className).Replace("::", ".")));
            }
        }

        if (Util.IsClassAbstract(data.Smoke, classId))
        {
            type.TypeAttributes |= TypeAttributes.Abstract;
        }

        if (PreMembersHooks != null)
        {
            PreMembersHooks(data.Smoke, smokeClass, type);
        }

        if (!alreadyDefined)
        {
            DefineWrapperClassFieldsAndMethods(smokeClass, type);
            data.CSharpTypeMap[mapName] = type;
            IList collection = data.GetTypeCollection(prefix);
            collection.Add(type);
            type.UserData.Add("parent", prefix);

            // add the internal implementation type for abstract classes
            if ((type.TypeAttributes & TypeAttributes.Abstract) == TypeAttributes.Abstract)
            {
                CodeTypeDeclaration implType = new CodeTypeDeclaration();
                implType.Name = type.Name + "Internal";
                implType.BaseTypes.Add(new CodeTypeReference(type.Name));
                implType.IsPartial = true;
                implType.TypeAttributes = TypeAttributes.NotPublic;

                CodeConstructor dummyCtor = new CodeConstructor();
                dummyCtor.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(Type)), "dummy"));
                dummyCtor.BaseConstructorArgs.Add(new CodeSnippetExpression("(System.Type) null"));
                dummyCtor.Attributes = MemberAttributes.Family;
                implType.Members.Add(dummyCtor);

                data.InternalTypeMap[type] = implType;

                collection.Add(implType);
            }
        }

        data.SmokeTypeMap[(IntPtr) smokeClass] = type;
    }
            private void CodeDomProducer_CodeDomProduction(object sender, CodeDomProductionEventArgs e)
            {
                if (e.EventType == CodeDomProductionEventType.UnitsProducing)
                {
                    if (e.Argument == null)
                        return;

                    foreach (var entity in Project.Entities)
                    {
                        if (!entity.GetAttributeValue("enabled", NamespaceUri, true))
                            continue;

                        CodeTypeDeclaration typeDeclaration = _codeDomProducer.GetType(entity);
                        if (typeDeclaration == null)
                            continue;

                        // Class
                        var jsonObjectAttribute = new CodeAttributeDeclaration("Newtonsoft.Json.JsonObjectAttribute");
                        string optMode = entity.GetAttributeValue("optMode", NamespaceUri, "OptIn");
                        if (optMode != null)
                        {
                            var memberSerialization = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("Newtonsoft.Json.MemberSerialization"), optMode);
                            jsonObjectAttribute.Arguments.Add(new CodeAttributeArgument("MemberSerialization", memberSerialization));
                        }
                        CodeDomUtilities.EnsureAttribute(typeDeclaration, jsonObjectAttribute, true);

                        // Properties
                        foreach (CodeTypeMember member in typeDeclaration.Members)
                        {
                            PropertyDefinition propertyDefinition = null;

                            CodeMemberProperty memberProperty = member as CodeMemberProperty;
                            if (memberProperty != null)
                            {
                                propertyDefinition = UserData.GetPropertyDefinition(memberProperty);
                            }

                            Property property = null;
                            if (propertyDefinition != null && propertyDefinition.Property != null)
                            {
                                property = propertyDefinition.Property;
                                if (!property.GetAttributeValue("enabled", NamespaceUri, true))
                                    continue;
                            }
                            else
                            {
                                if (!entity.GetAttributeValue("enabledForNonModelProperties", NamespaceUri, true))
                                    continue;
                            }

                            bool? serialized = null;
                            if (property != null)
                            {
                                serialized = property.GetAttributeValue("includeInSerialization", NamespaceUri, (bool?)null);
                            }

                            if (serialized == null)
                            {
                                //[System.NonSerializedAttribute()] => false
                                //[System.Xml.Serialization.XmlIgnoreAttribute()] => false
                                //[System.Runtime.Serialization.DataMemberAttribute()] => true

                                if (CodeDomUtilities.GetAttribute(member, typeof(NonSerializedAttribute)) != null)
                                {
                                    serialized = false;
                                }
                                else if (CodeDomUtilities.GetAttribute(member, typeof(XmlIgnoreAttribute)) != null)
                                {
                                    serialized = false;
                                }
                                else if (CodeDomUtilities.GetAttribute(member, typeof(DataMemberAttribute)) != null)
                                {
                                    serialized = true;
                                }
                                else if (CodeDomUtilities.GetAttribute(member, typeof(XmlAttribute)) != null)
                                {
                                    serialized = true;
                                }
                                else if (CodeDomUtilities.GetAttribute(member, typeof(XmlElementAttribute)) != null)
                                {
                                    serialized = true;
                                }
                                else if (property != null)
                                {
                                    serialized = property.IsIncludedInSerialization;
                                }
                            }

                            // [JsonIgnore] or [JsonProperty]
                            if (serialized != null)
                            {
                                var jsonPropertyAttribute = new CodeAttributeDeclaration();
                                jsonPropertyAttribute.Name = serialized == true ? "Newtonsoft.Json.JsonPropertyAttribute" : "Newtonsoft.Json.JsonIgnoreAttribute";
                                CodeDomUtilities.EnsureAttribute(member, jsonPropertyAttribute, true);
                            }

                        }
                    }
                }
            }
    public void Run()
    {
        HashSet<short> interfaceClasses = GetClassList();

        // Make the interfaces known first, otherwise Translator won't work correctly.
        foreach (short idx in interfaceClasses)
        {
            Smoke.Class* klass = data.Smoke->classes + idx;
            string className = ByteArrayManager.GetString(klass->className);
            int colon = className.LastIndexOf("::", StringComparison.Ordinal);
            string prefix = (colon != -1) ? className.Substring(0, colon) : string.Empty;
            string name = (colon != -1) ? className.Substring(colon + 2) : className;

            CodeTypeDeclaration ifaceDecl = new CodeTypeDeclaration('I' + name);
            ifaceDecl.IsInterface = true;
            CodeAttributeDeclaration attr = new CodeAttributeDeclaration("SmokeClass",
                                                                         new CodeAttributeArgument(
                                                                             new CodePrimitiveExpression(className)));
            ifaceDecl.CustomAttributes.Add(attr);

            data.GetTypeCollection(prefix).Add(ifaceDecl);
            data.InterfaceTypeMap[className] = ifaceDecl;
        }

        // Now generate the methods.
        foreach (short idx in interfaceClasses)
        {
            Smoke.Class* klass = data.Smoke->classes + idx;
            string className = ByteArrayManager.GetString(klass->className);
            CodeTypeDeclaration ifaceDecl = data.InterfaceTypeMap[className];

            short* parent = data.Smoke->inheritanceList + klass->parents;
            while (*parent > 0)
            {
                ifaceDecl.BaseTypes.Add(translator.CppToCSharp(data.Smoke->classes + *parent, ifaceDecl));
                parent++;
            }

            MethodsGenerator mg = new MethodsGenerator(data, translator, ifaceDecl, klass);
            AttributeGenerator ag = new AttributeGenerator(data, translator, ifaceDecl);

            List<IntPtr> methods = new List<IntPtr>();
            ///TODO: replace this algorithm, it's highly inefficient
            for (short i = 0; i <= data.Smoke->numMethods && data.Smoke->methods[i].classId <= idx; i++)
            {
                Smoke.Method* meth = data.Smoke->methods + i;
                if (meth->classId != idx)
                    continue;
                string methName = ByteArrayManager.GetString(data.Smoke->methodNames[meth->name]);

                // we don't want anything except protected, const or empty flags
                if ((meth->flags & (ushort) Smoke.MethodFlags.mf_enum) > 0
                    || (meth->flags & (ushort) Smoke.MethodFlags.mf_ctor) > 0
                    || (meth->flags & (ushort) Smoke.MethodFlags.mf_copyctor) > 0
                    || (meth->flags & (ushort) Smoke.MethodFlags.mf_dtor) > 0
                    || (meth->flags & (ushort) Smoke.MethodFlags.mf_static) > 0
                    || (meth->flags & (ushort) Smoke.MethodFlags.mf_internal) > 0
                    || (meth->flags & (ushort) Smoke.MethodFlags.mf_protected) > 0
                    || methName.StartsWith("operator"))
                {
                    continue;
                }
                if ((meth->flags & (ushort) Smoke.MethodFlags.mf_attribute) > 0)
                {
                    ag.ScheduleAttributeAccessor(meth);
                    continue;
                }

                methods.Add((IntPtr) meth);
            }
            methods.Sort(CompareSmokeMethods);
            foreach (Smoke.Method* method in methods)
            {
                CodeMemberMethod cmm = mg.GenerateBasicMethodDefinition(data.Smoke, method);
                if (cmm != null && !ifaceDecl.HasMethod(cmm))
                {
                    ifaceDecl.Members.Add(cmm);
                }
            }
            mg.GenerateProperties();

            foreach (CodeMemberProperty prop in ag.GenerateBasicAttributeDefinitions())
            {
                ifaceDecl.Members.Add(prop);
            }
        }
    }