Introduction

I find writing CodeDom code kind of like writing assembly. It's like cutting the grass with a pair of scissors or unloading a truck load of sand with a spoon. Its long winded, it can be done, but it is tedious. However, there are advantages in using CodeDom.

Now, it would be nice if you could whip up a class in VB or C# and generate the CodeDom code. CodeDom Assistant does this with the help of SharpDevelop's NRefactory Library in conjunction with writing our own CodeDomProvider to generate C# CodeDom code. The code you get will construct a CodeDom compileunit, and it will definitely be ugly. But what can you expect from a machine?

Background

Code Generation can be done using various techniques. In essence, code generation saves time, and enables you to create code using established patterns.

In the world of .NET, one technique is to use CodeDom. It allows you create a document object model of the code. This can by either compiled into an assembly or used to generate code. Every .NET language should have an implementation of a CodeDomProvider to generate code. The problem is that CodeDom does not implement every syntax construct of every language. In essence, it is a subset, but there are enough operations to emulate most language constructs.

Parsing C# or VB is going to be the toughest part, but luckily one of SharpDevelop's little libraries is NRefactory. This has the machinerary required to parse C# or VB code. The key component for us is the CodeDomVisitor class. Sadly, it is only a partial implementation. They implement enough to run SharpDevelop's form generation. I am not saying I have completed the implementation, rather, I have filled most of the holes in the CodeDomVisitor.

The second part is implementing a CodeDomCodeProvider. This will take a CodeDom compile unit and generate C# code that will create a CodeDom compile unit.

Alternatives To Unsupported CodeDom Constructs

When converting C# to CodeDom, certain constructs will not be able to be mapped directly into a CodeDom element. Rather we have to emulate the intent of the code. I am sure better transformations can be made, but these are sufficient for my needs. For example: int a = b++; is definitely not the same as the transformed CodeDom int a = (b = (b + 1));.

Not all constructs are going to be able to be transformed perfectly into CodeDom; they are merely sufficient for my needs. When I originally wrote the code in C# I did so with these limitations in mind. For example:

The foreach statement is handled using the for iterator and GetEnumerator(). Behold:

Constructing CodeDom Using NRefactory

The generate function uses NRefactory parser. NRefactory supports C# and VB. I tend to use C#, and have not tested the VB. The OutputClass is essentially the output combobox selection. There are native C# and VB NRefactory output transformations, which are much more complete than CodeDom. For other languages we use the CodeDomVisitor which maps the NRefactory parser output to CodeDom. The CodeDom CodeCompileUnit is then passed to a CodeDomProvider which generates output.

The NRefactory CodeDomVisitor class needed to be updated to implement more C# constructs. I am sure I have have missed a few.

Generating C# Code CodeDom

All CodeDom compile units can be passed to any CodeDomProvider to generate code. So, we write a new CodeDom provider that will generate CodeDom code for us. The implementation is quite simple. The main job of the CodeDomCodeProvider is to create an ICodeGenerator.

The CodeGenerator then traverses the CodeDom elements and outputs code that will reconstruct the tree when compiled.

Using Other CodeDomProviders

On initialisation CodeDom Assistant scans the GAC to find assemblies that have an implementation of CodeDomProvider. Since the output of the parsed C#/VB is CodeDom the output can be generated by any CodeDomProvider. So it could act as an effective language Convertor.

Points of Interest

You can only convert code that compiles. It is not very good at telling why it did not compile. The other issue I have found is that it may parse the file, but the CodeDom it produces is incomplete. This may cause the CodeDomProvider CodeGenerator to barf. Usually with some obscure error, like e value is null.

The output of CodeDomCodeProvider is ugly, but assists you in the construction of creating code generators with CodeDom. A lot of our code generation is done through the meta-data of a database. So this code would only be a starting point.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

Great tool, I haven't seen anything else like it. It seems to have bugs here and there and isn't updated for later versions of .NET and doesn't do well with conversion to VB CodeDom. But all of that said, it's still an amazing piece of work. Would love to see it updated.

I only have two suggestion for the next version:
1) Provide some comments in the generated CodeDomCodeProvider output. The orgin code would be usefull to find snippets in the output
2) Make the variables in the CodeDomCodeProvider output more unique. Like _method1_arg1 instead of _arg1. Addons to the orgin code can easier been made.

Does anyone have any ideas on how to get the output code to include the events? This might be something to do with the fact that C# wires up the events in the Designer.cs file instead of in the form file like vb does.

Could not load file or assembly 'file:///C:\CodeDom Assistant\CodeDomAssistant_Demo\script_44d3a227-aaf1-431b-a788-c14c939c8037.dll' or one of its dependencies. The system cannot find the file specified.

Personally, under Win7-64 bits and VS 2010 C# express, I had to:
1. Change the target from AnyCPU to x86 (if not, I have an error 193 '%1 is not a valid win32 DLL').
2. Update the sources of ScintillaNET.
Now it works fine.

i need coding for language translator english to arabic in C# .Net if any body knows the coding for desired software please send me at my ID m.s.kworld81@gotmail.com , msardar999@yahoo.com. i will be vey thankful to you people helping me in my project

However, the insentive for generating CodeDom code is not clear to me.

If I understand correctly, your motivation was to have (dynamic) code that will
generate the desired CodeCompileUnit at runtime. I see two easy solutions to this.
1. Your code that parses the C# already does exactly this. All you have to do is
save the original C# as data and run the same parsing code at runtime. The C#
code functions as a Template which is parsed at runtime and your code creates
CodeCompileUnit from it.

2. The other option I see is to use the fact that CodeCompileUnit is marked as
Serializable and just serialize it after the first parsing. At runtime you
can load the serialized data and Deserialize to create the CodeCompileUnit runtime
instance. (I have not tried it, but it should work.)

To test the script I compile a temporary assembly on the fly. So error usually occurs when the C# has an incomplete conversion to CodeDom. I would then track down the conversion error and implement it the CodeDomOutputVisitor class.

I've been working on a code generator myself lately, an open source scripting language, and I wish I would've seen this a little sooner -- would've saved me a bit of hassle with some of the generation stuff. And you're completely right -- CodeDom is really nice, but extremely tedious.

One thing about the using(blah) {} "translation" -- why are you creating a plain object and then checking if it implements IDisposable, instead of an instance of a specific class? I'm sure if you're writing a system that's capable of parsing, it can most certainly determine if the class being used implements IDisposable and then just call Dispose(). And, if it's a pre-determined class, you'd already know ahead of time that you could (or could not) call Dispose().

And you should use parser.Errors.ErrorOutput to get more information about parser errors.
The NRefactory error messages are not as nice as the C# compiler messages, but at least you get line/column numbers where the syntax error is.