views:

132

answers:

1

Hi,

Is there a possibility that I can put some of my code in non-compiled form with my application and then make changes to it on the fly and the application can then just use the new version onwards?

If it is possible (which i secretly know it is using CodeDOM), are there any issue to watch out for using this approach for pluggability (aside from the code protection issue)?

Is there a example available which i can re-use?

+5  A: 

You've already said you know how to do with with CodeDOM - why not just use that?

If you're happy with it being C# code, then CSharpCodeProvider does an admirable job. If you're feeling more adventurous, you might want to consider Boo - read Ayende Rahien's book on building DSLs in Boo for more information and advice.

For an example of using CSharpCodeProvider, you could download Snippy from my C# in Depth web site. Basically Snippy lets you type in a code snippet and run it, without bothering to declare a class etc. It doesn't do much more than build and run code, so it's a fairly handy example :)

For plenty more examples, search for CSharpCodeProvider on Stack Overflow. Here's a short but complete one - code for "hello world" is compiled and then executed.

using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

class Test
{
    public static void Main(string[] args)
    {
        string code = @"
using System;

class CodeToBeCompiled
{
    static void Main()
    {
        Console.WriteLine(""Hello world"");
    }
}";

        var codeProvider = new CSharpCodeProvider();
        var parameters = new CompilerParameters
        {
            GenerateExecutable = true,
            OutputAssembly = "Generated.exe"
        };
        var results = codeProvider.CompileAssemblyFromSource
            (parameters, new[] { code });
        results.CompiledAssembly.EntryPoint.Invoke(null, null);
    }
}
Jon Skeet
Cause its too hard. Is there an example?
Ali Kazmi
It's really not that hard. If you've tried it and got stuck, I suggest you ask a specific question. If you haven't tried it yet, I suggest you find some tutorials - there are *loads* out there.
Jon Skeet
Thanks a ton for the edit :)
Ali Kazmi