Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Format Generated CodeDom Code

How can I make sure the CS generated from code like the following is formatted nicely, i.e as if we pressed CTRL+K+D? It is C#

We are doing something along the lines of:

CodeMemberMethod membMethod = new CodeMemberMethod();
membMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public;
membMethod.ReturnType = new CodeTypeReference("IEnumerable<" + TableNameAsSinglular + ">");
membMethod.Name = "Get" + TableName;
membMethod.Statements.Add(new CodeSnippetStatement(DataBaseContext + " dcontext = new " + DataBaseContext + "(ConnectionString);"));
membMethod.Statements.Add(new CodeSnippetStatement("var records = from record in dcontext." + TableName + " select new " + TableNameAsSinglular + "{"));
    int iCount = 0;

    //Add columns fields
    foreach (DataRow dr in sqlTable.Rows)
    {
        if (iCount == 4)
        break;
        string strColName = dr["ColumnName"].ToString().Replace(" ", "");
        membMethod.Statements.Add(new CodeSnippetStatement(strColName + "=" + "record." + strColName + ","));
        iCount++;
    }

membMethod.Statements.Add(new CodeSnippetStatement("};"));
like image 866
Phill Duffy Avatar asked Aug 28 '09 16:08

Phill Duffy


1 Answers

CodeDom is really for runtime code generation. If you are looking to generate code at design time or compile time, you should use T4 templates.

T4 lets you format the code output exactly how you want it to appear:

http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx

like image 57
apiguy Avatar answered Oct 21 '22 00:10

apiguy