Esempio n. 1
1
        void Compile(string Code, string Path, bool FormProgram, string MainClass)
        {
            Dictionary<string, string> providerOptions = new Dictionary<string, string>();
            providerOptions.Add("CompilerVersion", "v2.0");
            VBCodeProvider CodeProvider = new VBCodeProvider(providerOptions);
            CompilerParameters Parameters = new CompilerParameters();
            Parameters.GenerateExecutable = true;
            Parameters.OutputAssembly = Path;
            if (FormProgram) Parameters.CompilerOptions = "/target:winexe";
            Parameters.MainClass = MainClass;
            Parameters.IncludeDebugInformation = false;
            Parameters.ReferencedAssemblies.Add("System.dll");
            Parameters.ReferencedAssemblies.Add("System.Data.dll");
            Parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            Parameters.ReferencedAssemblies.Add("System.Drawing.dll");
            Parameters.ReferencedAssemblies.Add("System.XML.dll");

            CompilerResults Results = CodeProvider.CompileAssemblyFromSource(Parameters, Code);
            if (Results.Errors.Count > 0)
            {
                foreach (CompilerError E in Results.Errors)
                {
                    MessageBox.Show(E.ErrorText);
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Compiles the source to assembly.
        /// </summary>
        /// <param name="script">The SharpScript.</param>
        /// <returns>Assembly.</returns>
        public static Assembly CompileToAssembly(VBScript script)
        {
            var cdProvider = new VBCodeProvider();
            var param = new CompilerParameters();
            param.ReferencedAssemblies.Add("System.dll");
            param.ReferencedAssemblies.Add("Sharpex2D.dll");
            param.ReferencedAssemblies.Add(Application.ExecutablePath);
            param.GenerateExecutable = false;

            CompilerResults result = cdProvider.CompileAssemblyFromSource(param, script.Content);

            bool flag = false;

            foreach (CompilerError error in result.Errors)
            {
                if (error.IsWarning)
                {
                    Logger.Warn("{0} -> {1} (Line {2})", script.Guid, error.ErrorText, error.Line);
                }
                else
                {
                    Logger.Critical("{0} -> {1} (Line {2})", script.Guid, error.ErrorText, error.Line);
                    flag = true;
                }
            }

            if (flag)
            {
                throw new ScriptException("Critical error while compiling script.");
            }

            return result.CompiledAssembly;
        }
Esempio n. 3
0
        private void CheckAssembly()
        {
            lbErrors.Items.Clear();					// clear out existing items

            // Generate the proxy source code
            List<string> lines = new List<string>();		// hold lines in array in case of error

            VBCodeProvider vbcp =  new VBCodeProvider();
            StringBuilder sb = new StringBuilder();
            //  Generate code with the following general form

            //Imports System
            //Imports Microsoft.VisualBasic
            //Imports System.Convert
            //Imports System.Math
            //Namespace ReportingCloud.vbgen
            //Public Class MyClassn	   // where n is a uniquely generated integer
            //Sub New()
            //End Sub
            //  ' this is the code in the <Code> tag
            //End Class
            //End Namespace
            string unique = Interlocked.Increment(ref CodeCtl.Counter).ToString();
            lines.Add("Imports System");
            lines.Add("Imports Microsoft.VisualBasic");
            lines.Add("Imports System.Convert");
            lines.Add("Imports System.Math");
            lines.Add("Imports ReportingCloud.Engine");
            lines.Add("Namespace ReportingCloud.vbgen");
            string classname = "MyClass" + unique;
            lines.Add("Public Class " + classname);
            lines.Add("Private Shared _report As CodeReport");
            lines.Add("Sub New()");
            lines.Add("End Sub");
            lines.Add("Sub New(byVal def As Report)");
            lines.Add(classname + "._report = New CodeReport(def)");
            lines.Add("End Sub");
            lines.Add("Public Shared ReadOnly Property Report As CodeReport");
            lines.Add("Get");
            lines.Add("Return " + classname + "._report");
            lines.Add("End Get");
            lines.Add("End Property");
            int pre_lines = lines.Count;            // number of lines prior to user VB code

            // Read and write code as lines
            StringReader tr = new StringReader(this.tbCode.Text);
            while (tr.Peek() >= 0)
            {
                string line = tr.ReadLine();
                lines.Add(line);
            }
            tr.Close();
            lines.Add("End Class");
            lines.Add("End Namespace");
            foreach (string l in lines)
            {
                sb.Append(l);
                sb.Append(Environment.NewLine);
            }
            string vbcode = sb.ToString();

            // Create Assembly
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.dll");
            string re = AppDomain.CurrentDomain.BaseDirectory + "ReportingCloud.Engine.dll";
            cp.ReferencedAssemblies.Add(re);

            // also allow access to classes that have been added to report
            XmlNode rNode = _Draw.GetReportNode();
            XmlNode cNode = _Draw.GetNamedChildNode(rNode, "CodeModules");
            if (cNode != null)
            {
                foreach (XmlNode xn in cNode.ChildNodes)
                {
                    if (xn.Name != "CodeModule")
                        continue;
                    cp.ReferencedAssemblies.Add(xn.InnerText);
                }
            }

            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;
            cp.IncludeDebugInformation = false;

            CompilerResults cr = vbcp.CompileAssemblyFromSource(cp, vbcode);
            if(cr.Errors.Count > 0)
            {
                StringBuilder err = new StringBuilder(string.Format("Code has {0} error(s).", cr.Errors.Count));
                foreach (CompilerError ce in cr.Errors)
                {
                    lbErrors.Items.Add(string.Format("Ln {0}- {1}", ce.Line - pre_lines, ce.ErrorText));
                }
            }
            else
                MessageBox.Show("No errors", "Code Verification");

            return ;
        }
Esempio n. 4
0
        // http://stackoverflow.com/questions/2684278/why-does-microsoft-jscript-work-in-the-code-behind-but-not-within-a
        public static object Eval(string vbCode)
        {
            object retValue;

            System.Text.StringBuilder sb = new System.Text.StringBuilder("");

            sb.Append("Imports System" + Constants.vbCrLf);
            // sb.Append("Imports System.Xml" & vbCrLf)
            // sb.Append("Imports System.Data" & vbCrLf)
            // sb.Append("Imports System.Data.SqlClient" & vbCrLf)
            // sb.Append("Imports System.Math" & vbCrLf)
            sb.Append("Imports Microsoft.VisualBasic" + Constants.vbCrLf);

            sb.Append("Namespace MyEvalNamespace_2C04AF0B_8EC8_4D84_AD83_51FFBBBBC8C6BFAC7762_5502_40C9_AE35_A545434012A4528B58FB_641E_4D61_BA15_E64C58CD8CFC  " + Constants.vbCrLf);
            sb.Append("Class MyEvalClass " + Constants.vbCrLf);

            sb.Append("Public Function EvalCode() As Object " + Constants.vbCrLf);
            // sb.Append("YourNamespace.YourBaseClass thisObject = New YourNamespace.YourBaseClass()")
            sb.Append(vbCode + Constants.vbCrLf);
            sb.Append("End Function " + Constants.vbCrLf);
            sb.Append("End Class " + Constants.vbCrLf);
            sb.Append("End Namespace " + Constants.vbCrLf);
            // Debug.WriteLine(sb.ToString()) ' look at this to debug your eval string

            string codeToCompile = sb.ToString();

            sb.Clear();
            sb = null;


            // System.Console.WriteLine(codeToCompile)


            using (Microsoft.VisualBasic.VBCodeProvider codeProvider = new Microsoft.VisualBasic.VBCodeProvider())
            {
                // System.CodeDom.Compiler.ICodeCompiler icc = codeProvider.CreateCompiler();
                System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters();

                cp.ReferencedAssemblies.Add("System.dll");
                // cp.ReferencedAssemblies.Add("System.Xml.dll");
                // cp.ReferencedAssemblies.Add("System.Data.dll");
                // cp.ReferencedAssemblies.Add("Microsoft.JScript.dll");

                // Sample code for adding your own referenced assemblies
                // cp.ReferencedAssemblies.Add(@"C:\YourProjectDir\bin\YourBaseClass.dll");
                // cp.ReferencedAssemblies.Add("YourBaseclass.dll");

                cp.CompilerOptions  = "/t:library";
                cp.GenerateInMemory = true;


                // System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromSource(cp, codeToCompile);
                System.CodeDom.Compiler.CompilerResults cr = codeProvider.CompileAssemblyFromSource(cp, codeToCompile);

                System.Reflection.Assembly a = cr.CompiledAssembly;

                object      o = a.CreateInstance("MyEvalNamespace_2C04AF0B_8EC8_4D84_AD83_51FFBBBBC8C6BFAC7762_5502_40C9_AE35_A545434012A4528B58FB_641E_4D61_BA15_E64C58CD8CFC.MyEvalClass");
                System.Type t = o.GetType();
                System.Reflection.MethodInfo mi = t.GetMethod("EvalCode");

                retValue = mi.Invoke(o, null);
            } // End Using codeProvider


            return(retValue);
        } // End Function Eval
        public object Eval(string vbCode)
        {
            VBCodeProvider oCodeProvider = new VBCodeProvider();
            // Obsolete in 2.0 framework
            // Dim oICCompiler As ICodeCompiler = oCodeProvider.CreateCompiler
            CompilerParameters oCParams = new CompilerParameters();
            CompilerResults oCResults = default(CompilerResults);
            System.Reflection.Assembly oAssy = default(System.Reflection.Assembly);
            object oExecInstance = null;
            object oRetObj = null;
            MethodInfo oMethodInfo = default(MethodInfo);
            Type oType = default(Type);
            List<string> strb = new List<string>();
            string dlls = WebConfigurationManager.AppSettings["dllpath"].ToString();
            try
            {
                // Setup the Compiler Parameters
                // Add any referenced assemblies
                oCParams.ReferencedAssemblies.Add("system.dll");
                oCParams.ReferencedAssemblies.Add("system.xml.dll");
                oCParams.ReferencedAssemblies.Add("system.data.dll");
                oCParams.ReferencedAssemblies.Add("system.io.dll");
                oCParams.ReferencedAssemblies.Add("system.web.dll");
                oCParams.ReferencedAssemblies.Add("system.collections.dll");
                oCParams.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");
                oCParams.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
                oCParams.ReferencedAssemblies.Add("System.Core.dll");
                oCParams.ReferencedAssemblies.Add("System.Data.Linq.dll");
                oCParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                oCParams.ReferencedAssemblies.Add(dlls);
                oCParams.CompilerOptions = "/t:library /optimize";
                oCParams.GenerateInMemory = true;
                oCParams.GenerateExecutable = false;
                oCParams.IncludeDebugInformation = true;
                // Generate the Code Framework
                StringBuilder sb = new StringBuilder("");
                sb.Append("Imports System" + "\r\n");
                sb.Append("Imports Parse" + "\r\n");
                sb.Append("Imports System.Xml" + "\r\n");
                sb.Append("Imports System.Data" + "\r\n");
                sb.Append("Imports System.IO" + "\r\n");
                sb.Append("Imports Microsoft.VisualBasic" + "\r\n");
                sb.Append("Imports Microsoft.VisualBasic.DateAndTime" + "\r\n");
                sb.Append("Imports System.Collections.Generic" + "\r\n");
                sb.Append("Imports System.Data.Linq" + "\r\n");
                sb.Append("Imports System.Windows.Forms" + "\r\n");
                // Build a little wrapper code, with our passed in code in the middle
                sb.Append("Namespace dValuate" + "\r\n");
                sb.Append("Class EvalRunTime " + "\r\n");
                sb.Append("Public Function EvaluateIt() As Object " + "\r\n");
                //sb.Append(GetList());
                sb.Append(vbCode + "\r\n");
                sb.Append("End Function " + "\r\n");
                sb.Append("End Class " + "\r\n");
                sb.Append("End Namespace" + "\r\n");
                //Debug.WriteLine(sb.ToString());
                try
                {
                    // Compile and get results
                    // 2.0 Framework - Method called from Code Provider
                    oCResults = oCodeProvider.CompileAssemblyFromSource(oCParams, sb.ToString());
                    // 1.1 Framework - Method called from CodeCompiler Interface
                    // cr = oICCompiler.CompileAssemblyFromSource (cp, sb.ToString)
                    // Check for compile time errors
                    if (oCResults.Errors.Count > 0)
                    {
                        for (int i = 0; i < oCResults.Errors.Count; i++)
                        {
                            strb.Add(oCResults.Errors[i].ToString().Substring(oCResults.Errors[i].ToString().IndexOf("error ")) + Environment.NewLine);
                        }
                        //return oCResults;
                    }
                    else
                    {
                        // No Errors On Compile, so continue to process...
                        oAssy = oCResults.CompiledAssembly;
                        oExecInstance = oAssy.CreateInstance("dValuate.EvalRunTime");
                        oType = oExecInstance.GetType();
                        oMethodInfo = oType.GetMethod("EvaluateIt");
                        oRetObj = oMethodInfo.Invoke(oExecInstance, null);
                        return oRetObj;
                    }
                }
                catch (Exception ex)
                {
                    // Runtime Errors Are Caught Here
                    strb.Add("Error Runtime: " + ex.InnerException.Message.ToString() + Environment.NewLine);
                }
            }
            catch (Exception ex)
            {
                strb.Add(ex.InnerException.Message.ToString() + Environment.NewLine);
            }

            //return oRetObj;
            StringBuilder result = new StringBuilder();
            var distinct = (
                from item in strb
                orderby item
                select item).Distinct();
            foreach (string value in distinct)
            {
                result.Append(value.ToString());
            }
            return result.ToString();
        }
Esempio n. 6
0
		/// <summary>
		/// Compile source code
		/// </summary>
		/// <param name="code">full source code to compile</param>
		/// <param name="references">assembly references</param>
		/// <param name="language">target language</param>
		/// <param name="profile">compiler profile</param>
		public void Compile(string code, string[] references, SupportedLanguage language, CompilerProfile profile)
		{
			var properties = new Dictionary<string, string> {{CompilerVersion, profile.CompilerVersion}};
			CodeDomProvider provider;

			switch (language)
			{
				case SupportedLanguage.CSharp:
					provider = new CSharpCodeProvider(properties);
					break;
				case SupportedLanguage.VisualBasic:
					provider = new VBCodeProvider(properties);
					break;
				default:
					throw new ArgumentException();
			}

			var parameters = new CompilerParameters
			{
				GenerateExecutable = false,
				GenerateInMemory = false,
				IncludeDebugInformation = false
			};

			parameters.ReferencedAssemblies.AddRange(references);

			var CompilerOptions = new List<string>();
			if (language == SupportedLanguage.CSharp)
				CompilerOptions.Add("/unsafe");

			if (profile.NoStdLib)
				CompilerOptions.Add("/nostdlib");

			if (CompilerOptions.Count > 0)
				parameters.CompilerOptions = string.Join(" ", CompilerOptions.ToArray());

			var results = provider.CompileAssemblyFromSource(parameters, code);
			AssemblyLocation = null;
			Errors = results.Errors;

			if (!results.Errors.HasErrors)
				AssemblyLocation = results.CompiledAssembly.Location;
		}
Esempio n. 7
0
        public CompilerResults Compile()
        {
            CompilerParameters parameters = new CompilerParameters()
            {
                GenerateExecutable = false,
                GenerateInMemory = true,
                IncludeDebugInformation = false,
                CompilerOptions = "/optimize",
                TreatWarningsAsErrors = false
            };
            parameters.ReferencedAssemblies.AddRange(ReferencedAssemblies);

            CodeDomProvider cdp = null;
            switch (Language)
            {
                case Language.CSharp: cdp = new CSharpCodeProvider(); break;
                case Language.VisualBasic: cdp = new VBCodeProvider(); break;
            }
            if (cdp == null)
                throw new Exception("Unsupported script language!");

            compiledAssembly = null;
            
            CompilerResults result = cdp.CompileAssemblyFromSource(parameters, source);
            if (!result.Errors.HasErrors)
                compiledAssembly = result.CompiledAssembly;

            return result;
        }
Esempio n. 8
0
File: CodeCtl.cs Progetto: mnisl/OD
		private void CheckAssembly()
		{
			lbErrors.Items.Clear();					// clear out existing items

			// Generate the proxy source code
			List<string> lines = new List<string>();		// hold lines in array in case of error

			VBCodeProvider vbcp =  new VBCodeProvider();
			StringBuilder sb = new StringBuilder();
			//  Generate code with the following general form

			//Imports System
			//Namespace fyiReportingvbgen
			//Public Class MyClassn	   // where n is a uniquely generated integer
			//Sub New()
			//End Sub
			//  ' this is the code in the <Code> tag
			//End Class
			//End Namespace
			string unique = Interlocked.Increment(ref CodeCtl.Counter).ToString();
			lines.Add("Imports System");
			lines.Add("Namespace fyiReporting.vbgen");
			string className = "MyClass" + unique;
			lines.Add("Public Class " + className);
			lines.Add("Sub New()");
			lines.Add("End Sub");
			// Read and write code as lines
			StringReader tr = new StringReader(this.tbCode.Text);
			while (tr.Peek() >= 0)
			{
				string line = tr.ReadLine();
				lines.Add(line);
			}
			tr.Close();
			lines.Add("End Class");
			lines.Add("End Namespace");
			foreach (string l in lines)
				sb.AppendFormat(l + Environment.NewLine);

			string vbcode = sb.ToString();

			// Create Assembly
			CompilerParameters cp = new CompilerParameters();
			cp.ReferencedAssemblies.Add("System.dll");
			cp.GenerateExecutable = false;
			cp.GenerateInMemory = true;
			cp.IncludeDebugInformation = false; 
			
			CompilerResults cr = vbcp.CompileAssemblyFromSource(cp, vbcode);
			if(cr.Errors.Count > 0)
			{
				StringBuilder err = new StringBuilder(string.Format("Code has {0} error(s).", cr.Errors.Count));
				foreach (CompilerError ce in cr.Errors)
				{
					lbErrors.Items.Add(string.Format("Ln {0}- {1}", ce.Line - 5, ce.ErrorText));
				}
			}
			else
				MessageBox.Show("No errors", "Code Verification");

			return ;
		}
Esempio n. 9
0
        public static CompilerResults CompileFromVBSourceCode(String sourceCode, CompilerParameters cParams)
        {
            using (CodeDomProvider provider = new VBCodeProvider())
            {
                CompilerResults res = provider.CompileAssemblyFromSource(cParams, sourceCode);

                return res;
            }
        }
Esempio n. 10
0
        private void CreateEvaluator()
        {
            // il codice compilato e` in vb.net poiche` semplifica il parsing dell'espressione
            string code = string.Format(
                @"Imports System.Collections.Generic
                 Imports System.Text
                 Imports System
                 Imports Microsoft.VisualBasic
                 Class Evaluator
                     Const e as Double = math.E
                      Public Shared Function Evaluate(x As Single) As Single
                           Return {0}
                      End Function
                 End Class", Expression);

            var parameters = new CompilerParameters();
            var provider = new VBCodeProvider();

            parameters.GenerateExecutable = false;
            parameters.TreatWarningsAsErrors = true;
            parameters.TempFiles.KeepFiles = false;
            parameters.GenerateInMemory = true;

            var results = provider.CompileAssemblyFromSource(parameters, code);

            if (results.Errors.Count > 0)
                throw new Exception("Espressione non valida!");

            var asm = results.CompiledAssembly;
            _evaluateFunction = asm.GetType("Evaluator").GetMethod("Evaluate");
        }
Esempio n. 11
0
        private Assembly GetAssembly()
        {
            // Generate the proxy source code
            List<string> lines = new List<string>();		// hold lines in array in case of error

            VBCodeProvider vbcp =  new VBCodeProvider();
            StringBuilder sb = new StringBuilder();
            //  Generate code with the following general form

            //Imports System
            //Imports Microsoft.VisualBasic
            //Imports System.Convert
            //Imports System.Math
            //Namespace fyiReporting.vbgen
            //Public Class MyClassn	   // where n is a uniquely generated integer
            //Sub New()
            //End Sub
            //  ' this is the code in the <Code> tag
            //End Class
            //End Namespace
            string unique = Interlocked.Increment(ref Parser.Counter).ToString();
            lines.Add("Imports System");
            lines.Add("Imports Microsoft.VisualBasic");
            lines.Add("Imports System.Convert");
            lines.Add("Imports System.Math");
            lines.Add("Imports fyiReporting.RDL");
            lines.Add("Namespace fyiReporting.vbgen");
            _Classname = "MyClass" + unique;
            lines.Add("Public Class " + _Classname);
            lines.Add("Private Shared _report As CodeReport");
            lines.Add("Sub New()");
            lines.Add("End Sub");
            lines.Add("Sub New(byVal def As Report)");
            lines.Add(_Classname + "._report = New CodeReport(def)");
            lines.Add("End Sub");
            lines.Add("Public Shared ReadOnly Property Report As CodeReport");
            lines.Add("Get");
            lines.Add("Return " + _Classname + "._report");
            lines.Add("End Get");
            lines.Add("End Property");
            // Read and write code as lines
            StringReader tr = new StringReader(_Source);
            while (tr.Peek() >= 0)
            {
                string line = tr.ReadLine();
                lines.Add(line);
            }
            tr.Close();
            lines.Add("End Class");
            lines.Add("End Namespace");
            foreach (string l in lines)
            {
                sb.Append(l);
                sb.Append("\r\n");
            }

            string vbcode = sb.ToString();

            // debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //						StreamWriter tsw = File.CreateText(@"c:\temp\vbcode.txt");
            //						tsw.Write(vbcode);
            //						tsw.Close();
            // debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            // Create Assembly
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.dll");
            string re;
            //AJM GJL 250608 - Try the Bin Directory too, for websites
            if (RdlEngineConfig.DirectoryLoadedFrom == null) {
                if (System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "RdlEngine.dll")) {
                    re = AppDomain.CurrentDomain.BaseDirectory + "RdlEngine.dll";   // this can fail especially in web scenarios
                }
                else
                {
                    re = AppDomain.CurrentDomain.BaseDirectory + "Bin\\RdlEngine.dll";   // this can work especially in web scenarios
                }
            }
            else
                re = RdlEngineConfig.DirectoryLoadedFrom + "RdlEngine.dll";     // use RdlEngineConfig.xml directory when available

            cp.ReferencedAssemblies.Add(re);
            // also allow access to classes that have been added to report
            if (this.OwnerReport.CodeModules != null)
            {
                foreach(CodeModule cm in this.OwnerReport.CodeModules.Items)
                {
                    //Changed from Forum, User: solidstate http://www.fyireporting.com/forum/viewtopic.php?t=905
                    string modulePath = Path.Combine(Path.GetDirectoryName(re), cm.CdModule);
                    cp.ReferencedAssemblies.Add(modulePath);
                }
            }
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = false;			// just loading into memory causes problems when instantiating
            cp.IncludeDebugInformation = false;
            CompilerResults cr = vbcp.CompileAssemblyFromSource(cp, vbcode);
            if(cr.Errors.Count > 0)
            {
                StringBuilder err = new StringBuilder(string.Format("Code element has {0} error(s).  Line numbers are relative to Code element.", cr.Errors.Count));
                foreach (CompilerError ce in cr.Errors)
                {
                    string l;
                    if (ce.Line >= 1 && ce.Line <= lines.Count)
                        l = lines[ce.Line - 1] as string;
                    else
                        l = "Unknown";
                    err.AppendFormat("\r\nLine {0} '{1}' : {2} {3}", ce.Line - 5, l, ce.ErrorNumber, ce.ErrorText);
                }
                this.OwnerReport.rl.LogError(4, err.ToString());
                return null;
            }

            return Assembly.LoadFrom(cr.PathToAssembly);	// We need an assembly loaded from the file system
            //   or instantiation of object complains
        }
Esempio n. 12
0
		private Assembly GetAssembly()
		{
			// Generate the proxy source code
            List<string> lines = new List<string>();		// hold lines in array in case of error

			VBCodeProvider vbcp =  new VBCodeProvider();
			StringBuilder sb = new StringBuilder();
			//  Generate code with the following general form

			//Imports System
			//Namespace fyiReportingvbgen
			//Public Class MyClassn	   // where n is a uniquely generated integer
			//Sub New()
			//End Sub
			//  ' this is the code in the <Code> tag
			//End Class
			//End Namespace
			string unique = Interlocked.Increment(ref Parser.Counter).ToString();
			lines.Add("Imports System");
			lines.Add("Namespace fyiReporting.vbgen");
			_Classname = "MyClass" + unique;
			lines.Add("Public Class " + _Classname);
			lines.Add("Sub New()");
			lines.Add("End Sub");
			// Read and write code as lines
			StringReader tr = new StringReader(_Source);
			while (tr.Peek() >= 0)
			{
				string line = tr.ReadLine();
				lines.Add(line);
			}
			tr.Close();
			lines.Add("End Class");
			lines.Add("End Namespace");
			foreach (string l in lines)
				sb.AppendFormat(l + "\r\n");

			string vbcode = sb.ToString();

			// debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//						StreamWriter tsw = File.CreateText(@"c:\temp\vbcode.txt");
//						tsw.Write(vbcode);
//						tsw.Close();
			// debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!   

			// Create Assembly
			CompilerParameters cp = new CompilerParameters();
			cp.ReferencedAssemblies.Add("System.dll");
			cp.GenerateExecutable = false;
			cp.GenerateInMemory = false;			// just loading into memory causes problems when instantiating
			cp.IncludeDebugInformation = false; 
			CompilerResults cr = vbcp.CompileAssemblyFromSource(cp, vbcode);
			if(cr.Errors.Count > 0)
			{
				StringBuilder err = new StringBuilder(string.Format("Code element has {0} error(s).  Line numbers are relative to Code element.", cr.Errors.Count));
				foreach (CompilerError ce in cr.Errors)
				{
					string l;
					if (ce.Line >= 1 && ce.Line <= lines.Count)
						l = lines[ce.Line - 1] as string;
					else
						l = "Unknown";
					err.AppendFormat("\r\nLine {0} '{1}' : {2} {3}", ce.Line - 5, l, ce.ErrorNumber, ce.ErrorText);
				}
				this.OwnerReport.rl.LogError(4, err.ToString());
				return null;
			}

			return Assembly.LoadFrom(cr.PathToAssembly);	// We need an assembly loaded from the file system
			//   or instantiation of object complains
		}
Esempio n. 13
0
        /// <summary>
        /// Compiles a given string script
        /// </summary>
        /// <returns>True if compilation ok</returns>
        public bool Compile()
        {
            // Already compiled ?
            if (IsCompiled)
            {
                return(true);
            }

            IsCompiled       = false;
            IsModified       = false;
            HasErrors        = false;
            Errors           = null;
            CompiledAssembly = null;

            // Generate the compiler provider
            switch (Language)
            {
            case ScriptLanguage.CSharp:
            {
                ScriptProvider = new Microsoft.CSharp.CSharpCodeProvider();
                if (ScriptProvider == null)
                {
                    Trace.WriteLine("Failed to initialize a new instance of the CSharpCodeProvider class");

                    return(false);
                }
            }
            break;

            case ScriptLanguage.VBNet:
            {
                ScriptProvider = new Microsoft.VisualBasic.VBCodeProvider();
                if (ScriptProvider == null)
                {
                    Trace.WriteLine("Failed to initialize a new instance of the VBCodeProvider class");
                    return(false);
                }
            }
            break;

            default:
            {
                Trace.WriteLine("Unknown scripting language !!!");
                return(false);
            }
            }



            // Compile
            CompilerResults results = ScriptProvider.CompileAssemblyFromSource(Params, sourceCode);

            if (results.Errors.Count == 0)
            {
                CompiledAssembly = results.CompiledAssembly;
                IsCompiled       = true;
                return(true);
            }



            Errors    = results.Errors;
            HasErrors = true;

            Trace.WriteLine("Compile complete -- " + Errors.Count + " error(s).");

            foreach (CompilerError error in Errors)
            {
                Trace.WriteLine("line " + error.Line + " : " + error.ErrorText);
            }



            return(IsCompiled);
        }
Esempio n. 14
0
        /// <summary>
        /// Compile source code
        /// </summary>
        /// <param name="code">full source code to compile</param>
        /// <param name="references">assembly references</param>
        /// <param name="language">target language</param>
        /// <param name="compilerVersion">compiler version</param>
        public void Compile(string code, string[] references, ESupportedLanguage language, String compilerVersion)
        {
            var properties = new Dictionary<string, string> {{CompilerVersion, compilerVersion}};
            CodeDomProvider provider;

            switch (language)
            {
                case ESupportedLanguage.CSharp:
                    provider = new CSharpCodeProvider(properties);
                    break;
                case ESupportedLanguage.VisualBasic:
                    provider = new VBCodeProvider(properties);
                    break;
                default:
                    throw new ArgumentException();
            }

            var parameters = new CompilerParameters
                                 {
                                     GenerateExecutable = false,
                                     GenerateInMemory = false,
                                     IncludeDebugInformation = false
                                 };

            parameters.ReferencedAssemblies.AddRange(references);

            if (language == ESupportedLanguage.CSharp)
            {
                parameters.CompilerOptions = "/unsafe";
            }

            CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
            _assemblyLocation = null;
            _errors = results.Errors;

            if (!results.Errors.HasErrors)
            {
                _assemblyLocation = results.CompiledAssembly.Location;
            }
        }
Esempio n. 15
0
        public void gen(string output, string source)
        {
            ICodeCompiler Compiler = new VBCodeProvider().CreateCompiler();
            var Parameters = new CompilerParameters();
            CompilerResults cResults;
            Parameters.GenerateExecutable = true;
            Parameters.OutputAssembly = output;
            Parameters.ReferencedAssemblies.Add("System.dll");
            Parameters.ReferencedAssemblies.Add("System.Data.dll");
            Parameters.ReferencedAssemblies.Add("System.Drawing.dll");
            Parameters.ReferencedAssemblies.Add("System.Design.dll");
            Parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            Parameters.ReferencedAssemblies.Add("System.XML.dll");
            Parameters.ReferencedAssemblies.Add("System.Management.dll");
            Parameters.ReferencedAssemblies.Add("System.Management.dll");
            if (CheckBox26.Checked & (source == this._source))
                Parameters.EmbeddedResources.Add(Application.StartupPath + "\\Process.resources");

            var Version = new Dictionary<string, string>();
            Version.Add("Windows", "v1.0");
            Parameters.CompilerOptions = "/target:winexe";
            cResults = Compiler.CompileAssemblyFromSource(Parameters, source);
            if (cResults.Errors.Count > 0)
            {
                foreach (CompilerError error in cResults.Errors)
                    MessageBox.Show("Error: " + error.ErrorText, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 16
0
        private void Compile(string code, string path, bool formProgram, string mainClass)
        {
            var providerOptions = new Dictionary<string, string> {{"CompilerVersion", "v2.0"}};
            var codeProvider = new VBCodeProvider(providerOptions);
            var parameters = new CompilerParameters {GenerateExecutable = true, OutputAssembly = path};
            if (formProgram) parameters.CompilerOptions = "/target:winexe";
            parameters.MainClass = mainClass;
            parameters.IncludeDebugInformation = false;
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Data.dll");
            parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parameters.ReferencedAssemblies.Add("System.Drawing.dll");
            parameters.ReferencedAssemblies.Add("System.XML.dll");
            if (CheckBox26.Checked && (code == _source))
            {
                parameters.EmbeddedResources.Add(Application.StartupPath + "\\Process.resources");
            }

            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, code);
            if (results.Errors.Count <= 0) return;
            foreach (CompilerError e in results.Errors)
            {
                MessageBox.Show(e.ToString());
            }
        }