How do I access the CodeDomProvider from a class inheriting from Microsoft.VisualStudio.TextTemplating.VSHost.BaseCodeGeneratorWithSite?

Posted by Charlie on Stack Overflow See other posts from Stack Overflow or by Charlie
Published on 2010-07-23T18:38:46Z Indexed on 2011/01/16 9:53 UTC
Read the original article Hit count: 312

Does anyone know how to get a CodeDomProvider in the new Microsoft.VisualStudio.TextTemplating.VSHost.BaseCodeGeneratorWithSite from the Visual Studio 2010 SDK? I used to get access to it just by in mere inheritance of the class Microsoft.CustomTool.BaseCodeGeneratorWithSite, but now with this new class it is not there. I see a GlobalServiceProvider and a SiteServiceProvider but I can't find any example on how to use them.

Microsoft.VisualStudio.TextTemplating.VSHost.BaseCodeGeneratorWithSite: http://msdn.microsoft.com/en-us/library/bb932625.aspx

I was to do this:

public class Generator : Microsoft.VisualStudio.TextTemplating.VSHost.BaseCodeGeneratorWithSite {

    public override string GetDefaultExtension() {
        // GetDefaultExtension IS ALSO NOT ACCESSIBLE...
        return this.InputFilePath.Substring(this.InputFilePath.LastIndexOf(".")) + ".designer" + base.GetDefaultExtension();
    }

    // This method is being called every time the attached xml is saved.
    protected override byte[] GenerateCode(string inputFileName, string inputFileContent) {
        try {
            // Try to generate the wrapper file.
            return GenerateSourceCode(inputFileName);
        } catch (Exception ex) {
            // In case of a faliure - print the exception 
            // as a comment in the source code.
            return GenerateExceptionCode(ex);
        }
    }

    public byte[] GenerateSourceCode(string inputFileName) {
        Dictionary<string, CodeCompileUnit> oCodeUnits;

        // THIS IS WHERE CodeProvider IS NOT ACCESSIBLE
        CodeDomProvider oCodeDomProvider = this.CodeProvider;

        string[] aCode = new MyCustomAPI.GenerateCode(inputFileName, ref oCodeDomProvider);
        return Encoding.ASCII.GetBytes(String.Join(@"
", aCode));
    }

    private byte[] GenerateExceptionCode(Exception ex) {
        CodeCompileUnit oCode = new CodeCompileUnit();

        CodeNamespace oNamespace = new CodeNamespace("System");
        oNamespace.Comments.Add(new CodeCommentStatement(MyCustomAPI.Print(ex)));
        oCode.Namespaces.Add(oNamespace);
        string sCode = null;
        using (StringWriter oSW = new StringWriter()) {
            using (IndentedTextWriter oITW = new IndentedTextWriter(oSW)) {
                this.CodeProvider.GenerateCodeFromCompileUnit(oCode, oITW, null);
                sCode = oSW.ToString();
            }
        }
        return Encoding.ASCII.GetBytes(sCode );
    }
}

Thanks for your help!

© Stack Overflow or respective owner

Related posts about c#

Related posts about visual-studio-2010