Everything about my daily life as a programmer/Electrical Engineer!

Python Generation using the Code Dom

I was tasked with translating a meta data scripting engine from metadata to ironpython. Luckily, the CodeDom was the solution. I've gotta give those M$ credit here!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.CodeDom;
using IronPython.CodeDom;
using System.CodeDom.Compiler;


namespace TestApp
{
class Program
{
static void Main(string[] args)
{
PythonProvider prov = new PythonProvider();

//Create a test class
StringWriter sw=new StringWriter();
CodeTypeDeclaration targetClass = new CodeTypeDeclaration("testclass");
targetClass.IsClass = true;

System.CodeDom.CodeConstructor cont = new CodeConstructor();
cont.Parameters.Add(new CodeParameterDeclarationExpression("int", "test"));
cont.Name = "testclass";
targetClass.Members.Add(cont);

prov.GenerateCodeFromType(targetClass, sw, new CodeGeneratorOptions());
Console.Write(sw.ToString());

//create an assignment statement
sw = new StringWriter();
CodeAssignStatement as1 = new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodePrimitiveExpression(10));
prov.GenerateCodeFromStatement(as1, sw, new CodeGeneratorOptions());
Console.Write(sw.ToString());
}
}
}


And the output is...

class testclass(object):
__slots__ = []

def __init__(self, test):
pass

i = 10
Press any key to continue . . .