Programmatically Format Generated CodeDom Code
Asked Answered
D

2

6

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("};"));
Dekko answered 28/8, 2009 at 16:30 Comment(0)
A
2

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

Appoggiatura answered 28/8, 2009 at 16:36 Comment(1)
ah ok, that's interesting. We are (maybe were!) using codeGenerator.GenerateCodeFromNamespace(cnsCodeDom, sw, cgo); to write out to the file.Dekko
F
0

In Visual Studio, go to

Tool -> Opetions-Text Editor->C#-> Formatting

Ctrl-K-D will use the settings there to format the code.

Fernald answered 28/8, 2009 at 16:33 Comment(1)
Thanks for your reply, I have updated the question to reflect that I want to achieve this programmatically, Ideally at the same time we are writing the CodeDom code. I.e is there something like CodeDom.FormatNicelyDekko

© 2022 - 2024 — McMap. All rights reserved.