1

I have a C# Visual Studio 2010 console application that reads lines from an Excel spreadsheet and then generates C# classes accordingly using a StreamWriter.

The generated lines of code in the classes are unformatted - as in they are not indented.

I know I could open those files manually and format them by typing ctrl E + D.

But I need to know how to format them programmatically in the generator application please.

I have tried the following code:

Type typeDTE = typeDTE = Type.GetTypeFromProgID("VisualStudio.DTE.10.0");
DTE dte = (DTE)Activator.CreateInstance(typeDTE, true);
dte.ExecuteCommand("Edit.FormatDocument", @"D:\Dev\ClinicalAuditGenerator\src\ClinicalAuditGenerator\Files\Entity\Patient.cs");

but there are 2 problems

1) the CreateInstance takes nearly 30 seconds

2) the ExecuteCommand throws the following exception:

Command Edit.FormatDocument is not available.

Thanks

Stu Harper
  • 721
  • 2
  • 9
  • 22
  • "The generated lines of code in the classes are unformatted." - it sounds to me like this is the thing you need to fix... – Marc Gravell Nov 28 '13 at 09:48
  • Fair comment. But I didn't want to add a load of indents to the generator and then when making changes have to keep up with which sections are indented by how much etc. – Stu Harper Nov 28 '13 at 09:55
  • Just wrap the writer in a subclass and provide indentation levels to that when you write - the write can decide what character to use for indents. – Charleh Nov 28 '13 at 09:58
  • Thanks for the comments, but I have written most of the code already and don't particularly want to go through providing indentation levels. That's why I wanted to have something else do it for me... – Stu Harper Nov 29 '13 at 12:26

1 Answers1

2

It's because Visual Studio didn't opened the file, when Edit.FormatFile is being executed. I'm also looking for a clean solution... Temporary a Quick n' Dirty one for small files only (Sorry):

private void FormatFiles(Project project, List<ProjectItem> ProjectItems)
{
    for (int i = 0; i < ProjectItems.Count- 1; i++)
    {
        ProjectItems[i].Open();
        FromatFileIsOpened(ProjectItems[i]);
        ProjectItems[i].Document.Close();
    }
}


private void FromatFileIsOpened(ProjectItem formatFile)
{
    try
    {
        formatFile.Document.Activate();
        formatFile.DTE.ExecuteCommand("Edit.FormatDocument");
    }
    catch
    {
       FromatFileIsOpened(formatFile);
    }
}