This sample demonstrates how to use the code document object model (DOM) to generate a strongly typed collection.
The CodeDOM is an API that gives you the ability to create a programming structure of namespaces, objects, and programming constructs by adding items to different collections. All CodeDOM programs start out with the creation of an ICodeGenerator for the target language. The following code shows the creation of the ICodeGenerator for C#.
ICodeGenerator cg =new CSharpCodeProvider().CreateGenerator(); ... CSharpCodeProvider cdp = new CSharpCodeProvider(); cg = cdp.CreateGenerator();
The ICodeGenerator is used to generate the actual code after a CodeDOM tree is built. To begin building your tree, you need to start with a CodeNamespace object. This object will contain any types and import directives. In the sample, several CodeNamespaceImport objects are used to generate import directives for commonly used namespaces. The sample also needs to generate a class construct by using a CodeTypeDeclaration and setting the IsClass property to true. The following code demonstrates these concepts.
CodeNamespace cnamespace = new CodeNamespace("Microsoft.Samples");
cnamespace.Imports.Add (new CodeNamespaceImport ("System") );
...
CodeTypeDeclaration co = new CodeTypeDeclaration (typeName +"List");
co.IsClass = true;
cnamespace.Types.Add (co);
At the end of the previous example, the class type definition is added to the Types collection of the CodeNamespace object. This is how a CodeDOM tree is built. Starting with a CodeNamespace object and working down through classes to class members. Class members in turn contain different types of code statements and expressions. Once the entire tree is built, the entire source tree can be written with a call to GenerateCodeFromNamespace, a method on ICodeGenerator. The method is being passed the CodeNamespace object and a TextWriter.
baseCompiler.GenerateCodeFromNamespace (cnamespace, w, null);
The ListBuilder sample demonstrates the techniques described above by generating the code for a strongly typed List. It also contains additional information and code for generating code statements and expressions that were left out of the documentation above for brevity.
The sample source is found in sscli\samples\howto\codedom.
The source file is:
The build output location is %TARGETCOMPLUS%\samples\howto\codedom. The output file is an executable assembly named listbuilder.exe.
All samples are built from the buildall script.
You can also build all the
samples by switching to the root of the sample directory, sscli\samples, and typing
build -c.
You can run this specific sample by switching to the sample directory and typing
build -c.
These steps require that the Shared Source CLI (SSCLI) be already built and functional.
clix listbuilder.exe
Copyright (c) 2002 Microsoft Corporation. All rights reserved.