Wednesday 10 August 2016

C# compiler


Hello there!

This article will help us to develop code which could basically compile our code. This could help us in creating web/ windows based  C# compiler even TTD as well. Enjoy the code.


using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;


namespace WebSharpCompilerBusiness
{
    public class WebSharpCompiler
    {
        public List<string> Compile(string programText)
        {
            List<string> messages = new List<string>();
            if (String.IsNullOrEmpty(programText))
            {
                messages.Add("program text cannot be null or empty");
            }
            CompilerResults compilerResults = ProcessCompilation(programText);
            foreach (CompilerError error in compilerResults.Errors)
            {
                messages.Add(String.Format("Line {0} Error No:{1} - {2}", error.Line, error.ErrorNumber, error.ErrorText));
            }

            return messages;
        }

        public CompilerResults ProcessCompilation(string programText)
        {
            CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp");
            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            return codeDomProvider.CompileAssemblyFromSource(parameters, programText);
        }
    }
}

Now, for demo purpose I am simply demonstrating an UnitTest over here.

        [TestMethod]
        public void TestCompilerSingleError()
        {
            WebSharpCompiler compiler = new WebSharpCompiler();
            string programText = @"
          using System;
          namespace HelloWorld
          {
              class HelloWorldClass
              {
                  static void Main(string[] args)
                  {
                   
                      //  byte c = 1/0;
                      Console.ReadLine();
                  }
              }
          }";
            List<string> compilerErrors = compiler.Compile(programText);
            Assert.AreEqual(compilerErrors.Count, 0);
        }


That's all!

Cheers!

No comments:

Post a Comment