Inheritance: CodeTypeMember
Esempio n. 1
0
        public ClassCreator AddProperties(string propertyName, Type propertyType)
        {
            var backingField = new CodeMemberField(propertyType, "_" + propertyName);
            _targetClass.Members.Add(backingField);

            // Declare the read-only Width property.
            var memberProperty = new CodeMemberProperty
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                Name = propertyName,
                HasGet = true,
                HasSet = true,
                Type = new CodeTypeReference(propertyType)
            };

            memberProperty.GetStatements.Add(new CodeMethodReturnStatement(
                new CodeFieldReferenceExpression(
                    new CodeThisReferenceExpression(), "_" + propertyName)));

            memberProperty.SetStatements.Add(
                new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_" + propertyName),
                    new CodePropertySetValueReferenceExpression())
                );

            _targetClass.Members.Add(memberProperty);

            return this;
        }
        private static void CreateAttributeConstForProperty(CodeTypeDeclaration type, CodeMemberProperty prop, HashSet<string> attributes)
        {
            
            var attributeLogicalName = (from CodeAttributeDeclaration att in prop.CustomAttributes
                                        where att.AttributeType.BaseType == XrmAttributeLogicalName || HasAttributeAndRelationship(prop, att)
                                        select new 
                                        {
                                            FieldName = ((CodePrimitiveExpression)att.Arguments[0].Value).Value.ToString(),
                                            Order = att.AttributeType.BaseType == XrmRelationshipSchemaName ? 0 : 1
                                        }).
                                        OrderBy(a => a.Order).
                                        FirstOrDefault()?.FieldName;

            if (attributes.Contains(prop.Name) || attributeLogicalName == null) return;

            attributes.Add(prop.Name);
            type.Members.Add(new CodeMemberField
            {
                // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
                Attributes = System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.Const,
                Name = prop.Name,
                Type = new CodeTypeReference(typeof (string)),
                InitExpression = new CodePrimitiveExpression(attributeLogicalName)
            });
        }
        protected override void ProcessProperty(CodeTypeDeclaration type, CodeMemberField field, CodeMemberProperty property)
        {
            if (property.Type.ArrayElementType == null) return; // Is array?

            if (property.Name == "Items" || property.Name == "ItemsElementName") return;

            CodeTypeReference genericType = new CodeTypeReference("System.Collections.Generic.List", new CodeTypeReference(property.Type.BaseType));

            property.Type = genericType;
            if (field != null) {
                field.Type = genericType;

                property.GetStatements.Insert(0,
                    // if
                    new CodeConditionStatement(
                        // field == null
                        new CodeBinaryOperatorExpression(
                            new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name),
                            CodeBinaryOperatorType.IdentityEquality,
                            new CodePrimitiveExpression(null)),
                        // field = new List<T>();
                        new CodeAssignStatement(
                            new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name),
                            new CodeObjectCreateExpression(genericType))));
            }
        }
        public static CodeMemberProperty GenerateProperty(string propertyName, string propertyType, List<CodeStatement> getStatements = null, List<CodeStatement> setStatements = null)
        {
            CodeMemberProperty property = new CodeMemberProperty
            {

                Attributes = MemberAttributes.Family | MemberAttributes.Final,
                Name = propertyName,
                Type = GetTypeReferenceFromName(propertyType),
                HasGet = (getStatements != null && getStatements.Any()),
                HasSet = (setStatements != null && setStatements.Any())
            };

            if (property.HasGet && getStatements != null)
            {
                foreach (CodeStatement statement in getStatements)
                {
                    property.GetStatements.Add(statement);
                }
            }

            if (property.HasSet && setStatements != null)
            {
                foreach (CodeStatement statement in setStatements)
                {
                    property.SetStatements.Add(statement);
                }
            }

            return property;
        }
Esempio n. 5
0
	public void EmitImplementationCode (CodeTypeDeclaration ctd) 
	{
	    byte[] bytes = Hash;
	    int hash = 0;
	    
	    for (int i = 0; bytes.Length - i > 3; i += 4)
		hash ^= BitConverter.ToInt32 (bytes, i);
	    
	    // Insane Clown Property
	    
	    CodeMemberProperty icp = new CodeMemberProperty ();
	    icp.Name = "ImplementationCode";
	    icp.Attributes = MemberAttributes.Family | MemberAttributes.Override;
	    icp.Type = new CodeTypeReference (typeof (int));
	    icp.HasGet = true;
	    icp.HasSet = false;
	    
	    // get { return base.ImplementationCode ^ [number] } 
	    // becomes:
	    // get { return LameCodeDomXor (base.ImplementationCode, [number]); }
	    
	    CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
	    invoke.Method = new CodeMethodReferenceExpression (CDH.This, "LameCodeDomXor");
	    invoke.Parameters.Add (new CodePropertyReferenceExpression (CDH.Base, "ImplementationCode"));
	    invoke.Parameters.Add (new CodePrimitiveExpression (hash));
	    
	    icp.GetStatements.Add (new CodeMethodReturnStatement (invoke));

	    ctd.Members.Add (icp);
	}
		protected internal override void CreateMethods ()
		{
			CodeMemberField fld;
			CodeMemberProperty prop;

			/* override the following abstract PageTheme properties:
			   protected abstract string AppRelativeTemplateSourceDirectory { get; }
			   protected abstract IDictionary ControlSkins { get; }
			   protected abstract string[] LinkedStyleSheets { get; }
			*/

			/* ControlSkins */
			fld = new CodeMemberField (typeof (HybridDictionary), "__controlSkins");
			fld.Attributes = MemberAttributes.Private;
			fld.InitExpression = new CodeObjectCreateExpression (typeof (HybridDictionary));
			mainClass.Members.Add (fld);

			prop = new CodeMemberProperty ();
			prop.Name = "ControlSkins";
			prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
			prop.Type = new CodeTypeReference (typeof (IDictionary));
			prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("__controlSkins")));
			mainClass.Members.Add (prop);

			/* LinkedStyleSheets */
			fld = new CodeMemberField (typeof (string[]), "__linkedStyleSheets");
			fld.Attributes = MemberAttributes.Private;
			fld.InitExpression = CreateLinkedStyleSheets ();
			mainClass.Members.Add (fld);

			prop = new CodeMemberProperty ();
			prop.Name = "LinkedStyleSheets";
			prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
			prop.Type = new CodeTypeReference (typeof (string[]));
			prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("__linkedStyleSheets")));
			mainClass.Members.Add (prop);

			/* AppRelativeTemplateSourceDirectory */
			prop = new CodeMemberProperty ();
			prop.Name = "AppRelativeTemplateSourceDirectory";
			prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
			prop.Type = new CodeTypeReference (typeof (string));
			prop.GetStatements.Add (new CodeMethodReturnStatement (
							new CodePrimitiveExpression (
								VirtualPathUtility.ToAbsolute (parser.BaseVirtualDir))));
			mainClass.Members.Add (prop);

			ControlBuilder builder = parser.RootBuilder;
			if (builder.Children != null) {
				foreach (object o in builder.Children) {
					if (! (o is ControlBuilder))
						continue;
					if (o is CodeRenderBuilder)
						continue;
					
					ControlBuilder b = (ControlBuilder) o;
					CreateControlSkinMethod (b);
				}
			}
		}
 private static void AddCommentsToFieldProperty(CodeMemberProperty property, ITemplateFieldInfo field)
 {
     if (!string.IsNullOrEmpty(field.HelpText))
         property.Comments.Add(new CodeCommentStatement("<summary>" + field.HelpText + "</summary>", true));
     else
         property.Comments.Add(new CodeCommentStatement(string.Format("<summary>Represents the {0} field</summary>", field.DisplayName), true));
 }
 private void AddPropertyGroup(AssemblyBuilder assemblyBuilder, string groupName, string propertyNames, Hashtable properties, CodeTypeDeclaration type, CodeNamespace ns)
 {
     CodeMemberProperty property = new CodeMemberProperty {
         Name = groupName,
         Attributes = MemberAttributes.Public,
         HasGet = true,
         Type = new CodeTypeReference("ProfileGroup" + groupName)
     };
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression {
         Method = { TargetObject = new CodeThisReferenceExpression(), MethodName = "GetProfileGroup" }
     };
     expression.Parameters.Add(new CodePrimitiveExpression(property.Name));
     CodeMethodReturnStatement statement = new CodeMethodReturnStatement(new CodeCastExpression(property.Type, expression));
     property.GetStatements.Add(statement);
     type.Members.Add(property);
     CodeTypeDeclaration declaration = new CodeTypeDeclaration {
         Name = "ProfileGroup" + groupName
     };
     declaration.BaseTypes.Add(new CodeTypeReference(typeof(ProfileGroupBase)));
     foreach (string str in propertyNames.Split(new char[] { ';' }))
     {
         this.CreateCodeForProperty(assemblyBuilder, declaration, (ProfileNameTypeStruct) properties[str]);
     }
     ns.Types.Add(declaration);
 }
 // If using the Xrm Client, OptionSets are converted to nullable Ints
 private static bool IsNullableIntPropery(CodeMemberProperty property)
 {
     return property.Type.BaseType == "System.Nullable`1" &&
            property.Type.TypeArguments != null &&
            property.Type.TypeArguments.Count == 1 &&
            property.Type.TypeArguments[0].BaseType == "System.Int32";
 }
        public void Process(CodeNamespace code, System.Xml.Schema.XmlSchema schema)
        {
            foreach (CodeTypeDeclaration type in code.Types)
            {
                if (type.IsClass || type.IsStruct)
                {
                    // Copy the colletion to an array for safety. We will be
                    // changing this collection.
                    CodeTypeMember[] members = new CodeTypeMember[type.Members.Count];
                    type.Members.CopyTo(members, 0);

                    foreach (CodeTypeMember member in members)
                    {
                        // Process fields only.
                        if (member is CodeMemberField)
                        {
                            CodeMemberProperty prop = new CodeMemberProperty();
                            prop.Name = member.Name;

                            prop.Attributes = member.Attributes;
                            prop.Type = ((CodeMemberField)member).Type;

                            // Copy attributes from field to the property.
                            prop.CustomAttributes.AddRange(member.CustomAttributes);
                            member.CustomAttributes.Clear();

                            // Copy comments from field to the property.
                            prop.Comments.AddRange(member.Comments);
                            member.Comments.Clear();

                            // Modify the field.
                            member.Attributes = MemberAttributes.Private;
                            Char[] letters = member.Name.ToCharArray();
                            letters[0] = Char.ToLower(letters[0]);
                            member.Name = String.Concat("_", new string(letters));

                            prop.HasGet = true;
                            prop.HasSet = true;

                            // Add get/set statements pointing to field. Generates:
                            // return this._fieldname;
                            prop.GetStatements.Add(
                                new CodeMethodReturnStatement(
                                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                                member.Name)));
                            // Generates:
                            // this._fieldname = value;
                            prop.SetStatements.Add(
                                new CodeAssignStatement(
                                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                                member.Name),
                                new CodeArgumentReferenceExpression("value")));

                            // Finally add the property to the type
                            type.Members.Add(prop);
                        }
                    }
                }
            }
        }
Esempio n. 11
0
		public CodeMemberProperty AddProperty(string name, CodeTypeReference propType)
		{
			var property = new CodeMemberProperty();

			property.Attributes = (MemberAttributes)24578; //Public Final
			property.HasGet = true;
			property.HasSet = true;
			property.Name = name;

			property.Type = propType;

			var memberName = char.ToLower(property.Name[0]) + property.Name.Substring(1);
			memberName = memberName.Insert(0, "_");

			var field = new CodeMemberField() {
				Name = memberName,
				Type = propType,
				Attributes = MemberAttributes.Private
			};

			property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), memberName)));
			property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), memberName), new CodePropertySetValueReferenceExpression()));

			_base.Members.Add(field);
			_base.Members.Add(property);
			return property;
		}
Esempio n. 12
0
        protected internal override object InsideCodeTypeDeclaration(CodeTypeDeclaration decl)
        {
            // if getter is omitted, just output the setter like a method
            if (decl.IsInterface || Getter == null) {
                if (Getter != null)
                    Getter.Visit (decl);
                if (Setter != null)
                    Setter.Visit (decl);
                return null;
            } else if (!decl.IsClass)
                return null;

            var prop = new CodeMemberProperty {
                Name = this.Name,
                // FIXME: For now, no properties will be virtual... change this at some point?
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                Type = Getter.ReturnTypeReference
            };

            Getter.Visit (prop.GetStatements);

            if (Setter != null)
                Setter.Visit (prop.SetStatements);

            decl.Members.Add (prop);
            return prop;
        }
Esempio n. 13
0
        public void Visit(ProxyList statement)
        {
            var property = new CodeMemberProperty();
            property.Attributes = MemberAttributes.Override | MemberAttributes.Family;
            property.Name = "Proxies";
            property.HasSet = false;
            property.Type = new CodeTypeReference(typeof(string[]));

            property.GetStatements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(string[])), "proxies",
                new CodeArrayCreateExpression(new CodeTypeReference(typeof(string[])), new CodePrimitiveExpression(statement.Proxies.Length)))
                );

            for (int x = 0; x < statement.Proxies.Length; x++ )
            {
                if (!Proxy.TryParse(statement.Proxies[x].Value))
                    Errors.Add(new BadProxyFormat(new Semantic.LineInfo(statement.Proxies[x].Line.Line, statement.Proxies[x].Line.CharacterPosition)));

               property.GetStatements.Add(new CodeAssignStatement(new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("proxies"),
                    new CodePrimitiveExpression(x)), new CodePrimitiveExpression(statement.Proxies[x].Value))
                    );
            }

            property.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("proxies")));

            _mainType.Type.Members.Add(property);
        }
        public void DecorateProperty(CodeMemberProperty propertyDefinition, KeyValuePair<string, JsonSchema> propertyPair)
        {
            propertyDefinition.ThrowIfNull("propertyDefinition");
            propertyPair.ThrowIfNull("propertyPair");

            propertyDefinition.Comments.AddRange(CreateComment(propertyPair.Value));
        }
        public override void OnProcessGeneratedCode(ControlBuilder controlBuilder, CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod, System.Collections.IDictionary additionalState)
        {
            // only run this once during page compilation, and only use this one builder (so that we don't get master pages, etc.)
            if (controlBuilder.GetType() == typeof(FileLevelPageControlBuilder))
            {
                // the page will only contain one namespace and one type
                var ns = codeCompileUnit.Namespaces.Cast<CodeNamespace>().FirstOrDefault();
                if (ns != null)
                {
                    var type = ns.Types.Cast<CodeTypeDeclaration>().FirstOrDefault();
                    if (type != null)
                    {
                        /* When this is output, it will inject this into every page:
                         *
                         * protected override PageStatePersister PageStatePersister {
                         *   get { return new CompressedHiddenFieldPageStatePersister(this); }
                         * }
                         *
                         */
                        CodeMemberProperty property = new CodeMemberProperty()
                        {
                            Name = "PageStatePersister",
                            HasGet = true,
                            Attributes = MemberAttributes.Override | MemberAttributes.Family,
                            Type = new CodeTypeReference(typeof(PageStatePersister))
                        };
                        var newObj = new CodeObjectCreateExpression(typeof(CompressedHiddenFieldPageStatePersister), new CodeThisReferenceExpression());
                        property.GetStatements.Add(new CodeMethodReturnStatement(newObj));
                        type.Members.Add(property);
                    }
                }
            }

            base.OnProcessGeneratedCode(controlBuilder, codeCompileUnit, baseType, derivedType, buildMethod, dataBindingMethod, additionalState);
        }
Esempio n. 16
0
        private static void GenerateCSharpCode(Entity entity, string path)
        {
            var targetUnit = new CodeCompileUnit();
            var targetNamespace = new CodeNamespace(entity.FullName.Substring(0, entity.FullName.LastIndexOf('.')));
            targetNamespace.Imports.Add(new CodeNamespaceImport("System"));
            var targetClass = new CodeTypeDeclaration(entity.FullName.Substring(entity.FullName.LastIndexOf('.') + 1))
            {
                IsClass = true,
                IsPartial = true,
                TypeAttributes = TypeAttributes.Public
            };
            targetNamespace.Types.Add(targetClass);
            targetUnit.Namespaces.Add(targetNamespace);

            foreach (var property in entity.Properties)
            {
                CodeTypeReference propertyType;
                if (property.IsNavigable)
                {
                    propertyType = new CodeTypeReference(typeof(List<>));
                    propertyType.TypeArguments.Add((string)RemapTypeForCSharp(property.Type));
                }
                else
                {
                    propertyType = new CodeTypeReference(RemapTypeForCSharp(property.Type));
                }

                var backingField = new CodeMemberField(propertyType, "_" + property.Name) {Attributes = MemberAttributes.Private};

                if (property.IsNavigable)
                    backingField.InitExpression = new CodeObjectCreateExpression(propertyType);

                targetClass.Members.Add(backingField);

                var codeProperty = new CodeMemberProperty
                {
                    Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    Name = property.Name,
                    HasGet = true,
                    HasSet = true,
                    Type = propertyType,
                };
                codeProperty.GetStatements.Add(new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backingField.Name)));
                codeProperty.SetStatements.Add(
                    new CodeAssignStatement(
                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backingField.Name),
                        new CodeVariableReferenceExpression("value")));

                targetClass.Members.Add(codeProperty);
            }

            var provider = CodeDomProvider.CreateProvider("CSharp");
            var options = new CodeGeneratorOptions {BracingStyle = "C"};
            using (var writer = new StreamWriter(Path.Combine(path, entity.FullName + '.' + provider.FileExtension)))
            {
                provider.GenerateCodeFromCompileUnit(targetUnit, writer, options);
            }
        }
 private bool SkipProperty(CodeMemberProperty property, CodeTypeDeclaration type)
 {
     List<string> attributes;
     return property == null ||
            !IsOptionSetProperty(property) ||
            (UnmappedProperties.TryGetValue(type.Name.ToLower(), out attributes) && attributes.Contains(property.Name.ToLower())) ||
            property.CustomAttributes.Cast<CodeAttributeDeclaration>().Any(att => att.Name == "System.ObsoleteAttribute");
 }
Esempio n. 18
0
 public CodeDefaultProperty(CodeMemberProperty property, 
     CodeParameterDeclarationExpressionCollection parameters,
     bool isDefault)
 {
     Parameters = parameters;
     IsDefault = isDefault;
     _property = property;
 }
Esempio n. 19
0
		public override void ModifyImplementation(CodeNamespace cns, CodeTypeDeclaration ctd, Type type)
		{
			CodeMemberProperty prop = new CodeMemberProperty();
			prop.Name = name;
			prop.Type = new CodeTypeReference(typeof(bool));
			prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			prop.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t" + code));
			ctd.Members.Add(prop);
		}
Esempio n. 20
0
        public static CodeTypeDeclaration GetEntityForTableDescription(DbSyncTableDescription tableDesc, bool addKeyAttributes, Dictionary<string, string> colsMapping)
        {
            CodeTypeDeclaration entityDeclaration = new CodeTypeDeclaration(SanitizeName(tableDesc.UnquotedGlobalName));
            entityDeclaration.IsPartial = true;
            entityDeclaration.IsClass = true;

            foreach (DbSyncColumnDescription column in tableDesc.Columns)
            {
                string colName = column.UnquotedName;
                if (colsMapping != null)
                {
                    colsMapping.TryGetValue(column.UnquotedName.ToLowerInvariant(), out colName);
                    colName = colName ?? column.UnquotedName;
                }
                CodeTypeReference fieldTypeReference = GetTypeFromSqlType(tableDesc, column);
                CodeMemberField colField = new CodeMemberField(fieldTypeReference, "_" + SanitizeName(colName));
                colField.Attributes = MemberAttributes.Private;

                CodeMemberProperty propertyField = new CodeMemberProperty();
                propertyField.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                propertyField.Name = SanitizeName(colName);
                propertyField.Type = fieldTypeReference;
                propertyField.GetStatements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression(colField.Name)));
                propertyField.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(colField.Name), new CodeVariableReferenceExpression("value")));

                if (addKeyAttributes)
                {
                    if (column.IsPrimaryKey)
                    {
                        //Add the Key attribute
                        propertyField.CustomAttributes.Add(new CodeAttributeDeclaration(Constants.ClientKeyAtributeType));
                    }
                }
                else
                {
                    // This is service entity. Check to see if column mappings is present i.e colName is not the same as column.UnquotedName.
                    if (!colName.Equals(column.UnquotedName, StringComparison.Ordinal))
                    {
                        propertyField.CustomAttributes.Add(new CodeAttributeDeclaration(Constants.ServiceSyncColumnMappingAttribute,
                                    new CodeAttributeArgument("LocalName", new CodeSnippetExpression("\"" + column.UnquotedName + "\""))));
                    }

                    // For a nullable data type, we add the [SyncEntityPropertyNullable] attribute to the property that is code-generated.
                    // This is required because some data types such as string are nullable by default in .NET and so there is no good way to 
                    // later determine whether the type in the underlying data store is nullable or not.
                    if (column.IsNullable)
                    {
                        propertyField.CustomAttributes.Add(new CodeAttributeDeclaration(Constants.EntityPropertyNullableAttributeType));
                    }
                }

                entityDeclaration.Members.Add(colField);
                entityDeclaration.Members.Add(propertyField);
            }

            return entityDeclaration;
        }
 private void AddMemberOverride(string name, Type type, CodeExpression expr) {
     CodeMemberProperty member = new CodeMemberProperty();
     member.Name = name;
     member.Attributes = MemberAttributes.Override | MemberAttributes.Family;
     member.Type = new CodeTypeReference(type.FullName);
     CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement(expr);
     member.GetStatements.Add(returnStmt);
     _sourceDataClass.Members.Add(member);
 }
Esempio n. 22
0
        public CodeMemberProperty ToProperty()
        {
            CodeMemberProperty prop = new CodeMemberProperty();
            prop.Name = this.Member;

            //var provider = new Microsoft.CSharp.CSharpCodeProvider();

            return null;
        }
 private object GetReturnPrimitiveValue(CodeMemberProperty property)
 {
     Assert.That(property.GetStatements.Count, Is.EqualTo(1));
     Assert.That(property.GetStatements[0], Is.TypeOf(typeof(CodeMethodReturnStatement)));
     var returnStatement = property.GetStatements[0] as CodeMethodReturnStatement;
     Assert.That(returnStatement.Expression, Is.TypeOf(typeof(CodePrimitiveExpression)));
     var primitive = returnStatement.Expression as CodePrimitiveExpression;
     return primitive.Value;
 }
        private CodeCompileUnit GeneraCodigo()
        {
            //Unidad de Compilación (ensamblado)
            var cu = new CodeCompileUnit();
            cu.ReferencedAssemblies.Add("System.dll");//Ensamblados que enlaza (aunque este debería estar por defecto)
            //Espacio de nombres
            var n = new CodeNamespace("EjemploGeneracionCodigo1");
            cu.Namespaces.Add(n);
            n.Imports.Add(new CodeNamespaceImport("System"));//Espacios de nombres que utiliza este namespace para compilar
            //Clase
            var c = new CodeTypeDeclaration("ClaseGenerada");
            n.Types.Add(c);
            c.BaseTypes.Add(new CodeTypeReference(typeof(System.Timers.Timer)));//Su clase padre
            c.IsPartial = true;

            //Atributo de la clase
            CodeMemberField mf = new CodeMemberField(typeof(string),"_atributo");
            c.Members.Add(mf);
            //Propiedad de la clase
            CodeMemberProperty cp = new CodeMemberProperty();
            c.Members.Add(cp);
            cp.Attributes = MemberAttributes.Public | MemberAttributes.Final;//lo de Final para que no sea virtual (por defecto si es público es virtual)
            cp.Type = new CodeTypeReference(typeof(string));
            cp.Name = "atributo";
            CodeFieldReferenceExpression cfre = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_atributo");
            CodeMethodReturnStatement mrs = new CodeMethodReturnStatement(cfre);
            cp.GetStatements.Add(mrs);
            //Metodo de la clase
            CodeMemberMethod cmm = new CodeMemberMethod();
            c.Members.Add(cmm);
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            cmm.Name = "Metodo1";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            CodeParameterDeclarationExpression pde = new CodeParameterDeclarationExpression(typeof(int),"enteroDeEntrada");
            cmm.Parameters.Add(pde);
            pde = new CodeParameterDeclarationExpression(typeof(string),"cadenaDeEntrada");
            cmm.Parameters.Add(pde);
            //Declaración de variable
            CodeVariableDeclarationStatement vds = new CodeVariableDeclarationStatement(typeof(string),"aux",new CodePrimitiveExpression("Prueba1") );
            cmm.Statements.Add(vds);
            //Llamar a método arbitrario
            //variable a llamar y método
            CodeMethodReferenceExpression  ctr = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("Console"),"WriteLine");
            //Llamada en sí con sus parámetros
            CodeMethodInvokeExpression invoke1 = new CodeMethodInvokeExpression( ctr, new CodeExpression[] {new CodePrimitiveExpression("Hola mundo")} );
            cmm.Statements.Add(invoke1);

            //Código a pelo. Ojo no se puede generar, por ejemplo, un foreach.
            cmm.Statements.Add(new CodeSnippetStatement("foreach(string s in cadenas){"));
            cmm.Statements.Add(new CodeSnippetStatement("Console.WriteLine(s);"));
            cmm.Statements.Add(new CodeSnippetStatement("}"));
            mrs = new CodeMethodReturnStatement(new CodePrimitiveExpression(42));
            cmm.Statements.Add(mrs);

            return cu;
        }
Esempio n. 25
0
        public override void GenerateCode(AssemblyBuilder myAb)
        {
            XmlDocument carXmlDoc = new XmlDocument();

            using (Stream passedFile = OpenStream())
            {
                carXmlDoc.Load(passedFile);
            }
            XmlNode mainNode = carXmlDoc.SelectSingleNode("/car");
            string selectionMainNode = mainNode.Attributes["name"].Value;

            XmlNode colorNode = carXmlDoc.SelectSingleNode("/car/color");
            string selectionColorNode = colorNode.InnerText;

            XmlNode doorNode = carXmlDoc.SelectSingleNode("/car/door");
            string selectionDoorNode = doorNode.InnerText;

            XmlNode speedNode = carXmlDoc.SelectSingleNode("/car/speed");
            string selectionSpeedNode = speedNode.InnerText;

            CodeCompileUnit ccu = new CodeCompileUnit();
            CodeNamespace cn = new CodeNamespace();
            CodeMemberProperty cmp1 = new CodeMemberProperty();
            CodeMemberProperty cmp2 = new CodeMemberProperty();
            CodeMemberMethod cmm1 = new CodeMemberMethod();

            cn.Imports.Add(new CodeNamespaceImport("System"));

            cmp1.Name = "Color";
            cmp1.Type = new CodeTypeReference(typeof(string));
            cmp1.Attributes = MemberAttributes.Public;
            cmp1.GetStatements.Add(new CodeSnippetExpression("return \"" +
               selectionColorNode + "\""));

            cmp2.Name = "Doors";
            cmp2.Type = new CodeTypeReference(typeof(int));
            cmp2.Attributes = MemberAttributes.Public;
            cmp2.GetStatements.Add(new CodeSnippetExpression("return " +
               selectionDoorNode));

            cmm1.Name = "Go";
            cmm1.ReturnType = new CodeTypeReference(typeof(int));
            cmm1.Attributes = MemberAttributes.Public;
            cmm1.Statements.Add(new CodeSnippetExpression("return " +
               selectionSpeedNode));

            CodeTypeDeclaration ctd = new CodeTypeDeclaration(selectionMainNode);
            ctd.Members.Add(cmp1);
            ctd.Members.Add(cmp2);
            ctd.Members.Add(cmm1);

            cn.Types.Add(ctd);
            ccu.Namespaces.Add(cn);

            myAb.AddCodeCompileUnit(this, ccu);
        }
		protected void SetImplementationTypes(CodeMemberProperty member)
		{			
			if (this.privateImplementationType!=null)
				member.PrivateImplementationType = this.privateImplementationType.TypeReference;

			foreach(ITypeDeclaration td in this.implementationTypes)
			{
				member.ImplementationTypes.Add(td.TypeReference);
			}
		}
Esempio n. 27
0
        /// <summary>
        /// Creates the data member attribute.
        /// </summary>
        /// <param name="prop">Represents a declaration for a property of a type.</param>
        protected override void CreateDataMemberAttribute(CodeMemberProperty prop)
        {
            base.CreateDataMemberAttribute(prop);

            if (GeneratorContext.GeneratorParams.GenerateDataContracts)
            {
                var attrib = new CodeTypeReference("System.Runtime.Serialization.DataMemberAttribute");
                prop.CustomAttributes.Add(new CodeAttributeDeclaration(attrib));
            }
        }
 protected void SetType(CodeMemberProperty propNode, GenericProperty property)
 {
     var hasType = property.Type != null &&
                   Config.TypeMappings.ContainsKey(property.Type.ToLower());
     var typeName = hasType 
         ? Config.TypeMappings[property.Type.ToLower()]
         : Config.TypeMappings.DefaultType;
     if (typeName == null)
         throw new Exception("TypeMappings/Default not set. Cannot guess default property type.");
     propNode.Type = new CodeTypeReference(typeName);
 }
 private void AddMemberOverride(string name, Type type, CodeExpression expr)
 {
     CodeMemberProperty property = new CodeMemberProperty {
         Name = name,
         Attributes = MemberAttributes.Family | MemberAttributes.Override,
         Type = new CodeTypeReference(type.FullName)
     };
     CodeMethodReturnStatement statement = new CodeMethodReturnStatement(expr);
     property.GetStatements.Add(statement);
     base._sourceDataClass.Members.Add(property);
 }
Esempio n. 30
0
        // Generate a codedom property expression and attach it to the codedom type.
        public static void Emit(CodeTypeDeclaration codeTypeDeclaration, Property property)
        {
            // Create the codedom property and attach it to the codedom type.
            var codeProperty = new CodeMemberProperty();
            codeTypeDeclaration.Members.Add(codeProperty);

            // Assign the name.
            codeProperty.Name = property.Name;

            // Assign the return type, making sure to check for null.
            if (property.TypeName == "void")
                codeProperty.Type = null;
            else
                codeProperty.Type = new CodeTypeReference(property.TypeName);

            // Translate the accessibility.
            MemberAttributes memberAttributes = MemberAttributes.Public;
            switch (property.Accessibility)
            {
                case Accessibility.Internal:
                    memberAttributes = MemberAttributes.FamilyAndAssembly;
                    break;
                case Accessibility.Private:
                    memberAttributes = MemberAttributes.Private;
                    break;
                case Accessibility.Protected:
                    memberAttributes = MemberAttributes.Family;
                    break;
                case Accessibility.Public:
                    memberAttributes = MemberAttributes.Public;
                    break;
            }

            // Shared = static
            if (property.IsShared) memberAttributes |= MemberAttributes.Static;
            if (property.IsAbstract) memberAttributes |= MemberAttributes.Abstract;
            if (property.IsOverride) memberAttributes |= MemberAttributes.Override;

            codeProperty.Attributes = memberAttributes;

            // Add the statements for the get block.
            if (property.GetBlock.ChildExpressions.Count > 0)
                foreach (var e in property.GetBlock.ChildExpressions)
                    codeProperty.GetStatements.Add(CodeDomEmitter.EmitCodeStatement(e));
            else
                codeProperty.GetStatements.Add(new CodeCommentStatement("Placeholder statement"));

            // Add the statements for the set block.
            if (property.SetBlock.ChildExpressions.Count > 0)
                foreach (var e in property.SetBlock.ChildExpressions)
                    codeProperty.SetStatements.Add(CodeDomEmitter.EmitCodeStatement(e));
            else
                codeProperty.SetStatements.Add(new CodeCommentStatement("Placeholder statement"));
        }
        /// <summary>
        /// Handles if Ignore keyword is specified in AppInfo tag
        /// </summary>
        /// <param name="memberProperty">Member of particualr class in which AppInfo is available</param>
        /// <param name="appInfoValue">value of AppInfo tag</param>
        public void HandleAppInfo(System.CodeDom.CodeMemberProperty memberProperty, string appInfoValue)
        {
            if (string.Equals(appInfoValue.Trim(), "IGNORE", System.StringComparison.OrdinalIgnoreCase))
            {
                // Add [XmlIgnore] attribute
                memberProperty.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(System.Xml.Serialization.XmlIgnoreAttribute))));

                // Add [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] attribute
                CodeDomHelper.AddEditorBrowsableAttribute(memberProperty);
            }
        }
Esempio n. 32
0
    public static System.CodeDom.CodeCompileUnit BuildGraph(System.Xml.XmlDocument xmlMetaData,
                                                            string tableName)
    {
        System.Xml.XmlNodeList             nodeList;
        System.CodeDom.CodeCompileUnit     compileUnit = new System.CodeDom.CodeCompileUnit();
        System.CodeDom.CodeNamespace       nSpace;
        System.CodeDom.CodeTypeDeclaration clsTable;

        nodeList = xmlMetaData.SelectNodes("/DataSet/Table[@Name='" + tableName + "']/Column");

        nSpace = new System.CodeDom.CodeNamespace("ClassViaCodeDOM");
        compileUnit.Namespaces.Add(nSpace);

        nSpace.Imports.Add(new System.CodeDom.CodeNamespaceImport("System"));

        clsTable = new System.CodeDom.CodeTypeDeclaration(tableName);
        nSpace.Types.Add(clsTable);

        System.CodeDom.CodeMemberField field;
        foreach (System.Xml.XmlNode node in nodeList)
        {
            field            = new System.CodeDom.CodeMemberField();
            field.Name       = "m_" + node.Attributes["Name"].Value;
            field.Attributes = System.CodeDom.MemberAttributes.Private;
            field.Type       = new System.CodeDom.CodeTypeReference(node.Attributes["Type"].Value);
            clsTable.Members.Add(field);
        }

        System.CodeDom.CodeMemberProperty prop;
        string name;

        foreach (System.Xml.XmlNode node in nodeList)
        {
            prop            = new System.CodeDom.CodeMemberProperty();
            name            = node.Attributes["Name"].Value;
            prop.Name       = name;
            prop.Attributes = System.CodeDom.MemberAttributes.Public;
            prop.Type       = new System.CodeDom.CodeTypeReference(node.Attributes["Type"].Value);
            prop.GetStatements.Add(new System.CodeDom.CodeMethodReturnStatement(new System.CodeDom.CodeFieldReferenceExpression(new System.CodeDom.CodeThisReferenceExpression(), "m_" + name)));
            prop.SetStatements.Add(new System.CodeDom.CodeAssignStatement(new System.CodeDom.CodeFieldReferenceExpression(new System.CodeDom.CodeThisReferenceExpression(), "m_" + name), new System.CodeDom.CodePropertySetValueReferenceExpression()));
            clsTable.Members.Add(prop);
        }
        return(compileUnit);
    }
Esempio n. 33
0
 internal DesignTimePropertyInfo(DesignTimeType declaringType, System.CodeDom.CodeMemberProperty property)
 {
     this.property      = property;
     this.declaringType = declaringType;
 }
Esempio n. 34
0
 protected override void GenerateProperty(System.CodeDom.CodeMemberProperty e, System.CodeDom.CodeTypeDeclaration c)
 {
     throw new Exception("The method or operation is not implemented.");
 }