Monday, January 5, 2009

CodeDom and Picture to exe converter


If you have ever though of creating an exe or assembly from .net program, CodeDom is your answer.In simple words CodeDom is the memory representation of .Net code which can be saved or compiled afterwards.

CodeDom contains classes which represent each and every element of .Net code.for example CodeNamespace class represents a namespace declaration and CodeConstructor represents a constructor.More details here.

We can build the code model using these classes.Once we complete building the CodeDom model we can either get the source code or compile that code to get executable.

The CodeDom can be compiled or generated using any .net compiler which implements CLR specifications.For that we have to create a code provider first which can be of C Sharp or will give a generator object for code generation and compiler object to compile the CodeDom.

Code to create CodeDom

CodeNamespace myNamespace = new CodeNamespace();
CodeTypeDeclaration myclass = new CodeTypeDeclaration();

//Add more classes here

Code to Generate Source Code in C#

CSharpCodeProvider provider = new CSharpCodeProvider();
ICodeGenerator codeGen=provider.CreateGenerator("mypgm.cs");
codeGen.GenerateCodeFromNamespace(myNamespace, textWriter, options);

Code to compile CodeDom using C# compiler

CSharpCodeProvider provider = new CSharpCodeProvider();
ICodeCompiler compiler = provider.CreateCompiler();
CodeCompileUnit myCodeunit = new CodeCompileUnit();
CompilerParameters parameters = new CompilerParameters();

compiler.CompileAssemblyFromDom(parameters, myCodeunit);

Picture to exe converter

Now the things are clear.We can create an exe using code dom which have the given picture embedded in it and a windows form in that application can display the same from resource.Its simple and standalone.The flow is as follows

  1. Code a 'Form' derived class named 'Pic2Exe' which shows have a piturebox and gets picture from resource stream.This should also contain Main method to start execution.

  2. Get the path to the picture which need to be converted as exe

  3. Create object of class Compilerparameters and set appropriate paramaeters.(For details see sample)

  4. Embedd the input picture through the CompilerParameters object.

  5. Create object of CSharpCodeProvider class and get the compiler object.

  6. Compile the Pic2Exe class using the compiler object.

If you are confused about the settings and flow please see the sample here.

Future enhancements

  • Modify the Pic2Exe (Which is responsible for showing the image from resource) to have Zooming and Panning.

  • It can be modified as a slide show application.

  • Can be used to protect your video files if your target audience don't know about reflector.

No comments: