System.CodeCom namespace can help you to avoid a lot of waste of time typing property declarations in classes when you did the work in a database or excel or xml file. And when you need to edit the class (to add a new property or field), you must edit the definition template (database, excel, xml) and go to source code to edit class file too. Microsoft give us tools to automate this class generation, lets see this tools.
Fists we see how to create a class on runtime. We use System.CodeCom namespace to create a CodeCompileUnit object. With this CodeCompileUnit you can write it to a text file to use.
Let's see a bit of code
CodeCompileUnit code = new CodeCompileUnit();
//Create a namespace
CodeNamespace unitNamespace = new CodeNamespace("MyNameSpace");
code.Namespaces.Add(unitNamespace);
//Create a class
CodeTypeDeclaration unitClass = new CodeTypeDeclaration("ClassName");
unitClass.IsPartial = true; // You can define a partial class, very useful to avoid write code in the automated file.
CodeCommentStatement coment = new CodeCommentStatement("This class 'ClassName' do nothing");
unitClass.Comments.Add(coment);
unitNamespace.Types.Add(unitClass);
//Create a field and a property related
string fieldName = "myField";
string propertyName = "MyProperty";
CodeMemberField codeField = new CodeMemberField("System.String", fieldName);
unitClass.Members.Add( codeField );
CodeMemberProperty unitProperty = new CodeMemberProperty();
unitProperty.Name = propertyName;
unitProperty.Type = new CodeTypeReference("System.String");
unitProperty.Attributes = MemberAttributes.Public;
unitProperty.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName) ) );
unitProperty.SetStatements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodePropertySetValueReferenceExpression() ) );
unitClass.Members.Add(unitProperty);
This simple code creates a CodeCompileUnit object.
Now you can traslate this object to a file.
CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); //Of course, you can select a Microsoft.VisualBasic.VBCodeProvider
// Create an IndentedTextWriter, constructed with a StreamWriter to the source file.
IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(filename, false), " ");
// Generate source code using the code generator.
provider.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions());
// Close the output file.
tw.Close();
To compile this code you need using that namespaces:
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using Microsoft.CSharp;
Of course a more complete reference is in MSDN pages (http://msdn2.microsoft.com/es-es/library/system.codedom.codecompileunit(VS.80).aspx)
2007-09-04
Let the computer works instead you (I)
Labels: c#, source code
Subscribe to:
Posts (Atom)