Inheritance: CodeDomProvider
Esempio n. 1
2
 private bool init(string generateCode, params string[] referenceAssemblies)
 {
     bool flag = false;
     result = null;
     using (CSharpCodeProvider provider = new CSharpCodeProvider())
     {
         ICodeCompiler objICodeCompiler = provider.CreateCompiler();
         CompilerParameters objCompilerParameters = new CompilerParameters();
         if (referenceAssemblies != null)
             objCompilerParameters.ReferencedAssemblies.AddRange(referenceAssemblies);
         objCompilerParameters.GenerateExecutable = false;
         objCompilerParameters.GenerateInMemory = true;
         result = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, generateCode);
     }
     if (result != null)
     {
         if (result.Errors.Count > 0 && ErrorHandler != null)
         {
             ErrorHandler(result.Errors);
         }
         else
         {
             flag = true;
         }
     }
     return flag;
 }
        public void CompileSiteModels()
        {
            DirectoryInfo di = new DirectoryInfo(SysPath.SiteModelsDirectory);
            FileInfo[] fiar = di.GetFiles("*.cs");
            String[] fisar = new String[fiar.Length];

            for (int i = 0; i < fiar.Length; i++)
            {
                fisar[i] = fiar[i].FullName;
            }

            CompilerParameters parameters = new CompilerParameters(new String[] { "System.dll", "NStag.dll", "nhibernate.dll" });
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = true;
            parameters.OutputAssembly = this.DomainName;
            parameters.CompilerOptions = String.Concat("/lib:", SysPath.GetLibDirectory());

            CSharpCodeProvider cprovider = new CSharpCodeProvider();
            CompilerResults results = cprovider.CompileAssemblyFromFile(parameters, cspath);

            if (results.Errors.HasErrors)
            {
                throw new Exception(results.Errors[0].ErrorText);
            }
        }
Esempio n. 3
1
        public Tuple<StringCollection, Assembly> Compile(string[] dllFiles, string[] sourceFiles, string outputAssemblyPath)
        {
            var providerOptions = new Dictionary<string,
            string> { {
                    "CompilerVersion",
                    "v4.0"
                }
            };
            CodeDomProvider codeProvider = new CSharpCodeProvider(providerOptions);
            var compilerParameters = new CompilerParameters
            {
                GenerateExecutable = false,
                GenerateInMemory = true,
                IncludeDebugInformation = true
            };

            compilerParameters.ReferencedAssemblies.AddRange(dllFiles);
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
            compilerParameters.ReferencedAssemblies.Add("System.ComponentModel.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Xml.Serialization.dll");
            var result = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFiles);
            return new Tuple<StringCollection,
            Assembly>(result.Output, result.Errors.Count > 0 ? null : result.CompiledAssembly);
        }
Esempio n. 4
1
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
            if ((classname == null) || (classname == ""))
            {
                classname = WebServiceProxy.GetWsClassName(url);
            }

            try
            {
                //获取WSDL
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription sd = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();
                ICodeCompiler icc = csc.CreateCompiler();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type t = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
Esempio n. 5
1
        public static void OutputAssembly(Dictionary<string, string> generated, IEnumerable<string> assemblies, string assemblyPath)
        {
            var providerOptions = new Dictionary<string, string> {{"CompilerVersion", "v4.0"}};

            using (var codeProvider = new CSharpCodeProvider(providerOptions))
            {
                string[] sources = (from p in generated.Keys select generated[p]).ToArray();

                List<string> assemblyPaths = new List<string>(assemblies);
                assemblyPaths.Add(typeof (ManifestEventAttribute).Assembly.Location);

                var compilerParameters = new CompilerParameters(
                    assemblyPaths.ToArray(),
                    assemblyPath, 
                    false);

                CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParameters, sources);

                if (results.Errors.Count == 0)
                    return;

                var sb = new StringBuilder();
                foreach (object o in results.Errors)
                {
                    sb.AppendLine(o.ToString());
                }

                string errors = sb.ToString();
                throw new Exception(errors);
            }
        }
        private static object ExecuteScript(string script, ScriptExecutionOptions options)
        {
            object result = null;

            CompilerParameters cpar = new CompilerParameters();
            cpar.GenerateInMemory = true;
            cpar.ReferencedAssemblies.Add("mscorlib.dll");
            cpar.ReferencedAssemblies.Add("System.dll");
            cpar.ReferencedAssemblies.Add("System.Core.dll");
            cpar.ReferencedAssemblies.Add("System.Data.dll");
            cpar.ReferencedAssemblies.Add("System.Xml.dll");
            cpar.ReferencedAssemblies.Add(typeof(CSharpScriptingProvider).Assembly.Location);

            string code = Properties.Resources.ScriptProviderCSharpTemplate;
            code = code.Replace("{Source}", script);

            CSharpCodeProvider csp = new CSharpCodeProvider();
            CompilerResults res = csp.CompileAssemblyFromSource(cpar, code);

            if (!res.Errors.HasErrors)
            {
                MethodInfo func = res.CompiledAssembly.ExportedTypes.First().GetMethods().First();
                result = func.Invoke(null, new object[] { options });
            }

            return result;
        }
Esempio n. 7
1
        public bool Compile(string src)
        {
            var param = new CompilerParameters(new string[]
            {
                "System.dll",
                "mscorlib.dll",
                "System.Data.dll",
                "System.Xml.dll",
                "System.Xml.Linq.dll",
                "lib.dll",
                "compiler.dll",
            });
            param.GenerateInMemory = true;
            param.GenerateExecutable = false;
            param.IncludeDebugInformation = false;

            _provider = new CSharpCodeProvider(
                new Dictionary<string, string>()
                {
                    { "CompilerVersion", "v4.0" },
                });
            _results = _provider.CompileAssemblyFromSource(param, src);
            if (_results.Errors.Count > 0)
            {
                foreach (CompilerError err in _results.Errors)
                {
                    if (err.IsWarning) Console.WriteLine("[Warning] {0}: [{1}] {2}", err.Line, err.ErrorNumber, err.ErrorText);
                    else Console.WriteLine("[Error] {0}: [{1}] {2}", err.Line, err.ErrorNumber, err.ErrorText);
                }
                return false;
            }

            return true;
        }
        public void UpdateSource()
        {
            _codeType = null;
            _codeInstance = null;
            if (Source == null)
                return;

            var provider = new CSharpCodeProvider();
            var options = new CompilerParameters { GenerateInMemory = true };
            string qn = typeof(Point3D).Assembly.Location;
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add(qn);
            string src = template.Replace("#code#", Source);
            CompilerResults compilerResults = provider.CompileAssemblyFromSource(options, src);
            if (!compilerResults.Errors.HasErrors)
            {
                Errors = null;
                var assembly = compilerResults.CompiledAssembly;
                _codeInstance = assembly.CreateInstance("MyNamespace.MyEvaluator");
                _codeType = _codeInstance.GetType();
            }
            else
            {
                // correct line numbers
                Errors = compilerResults.Errors;
                for (int i = 0; i < Errors.Count; i++)
                    Errors[i].Line -= 17;
            }

            _w = ParameterW;
            UpdateModel();
        }
 /// <summary>
 /// Returns the C# literal representation of a given primitive expression.
 /// (Useful for escaping strings)
 /// </summary>
 private static string PrimitiveLiteral(this string input)
 {
     var writer = new StringWriter();
     var provider = new CSharpCodeProvider();
     provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
     return writer.ToString();
 }
Esempio n. 10
1
        public static CompilerResults CompileFile(string input, string output, params string[] references)
        {
            CreateOutput(output);

            List<string> referencedAssemblies = new List<string>(references.Length + 3);

            referencedAssemblies.AddRange(references);
            referencedAssemblies.Add("System.dll");
            referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", ""));
            referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", ""));

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters(referencedAssemblies.ToArray(), output);

            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(input))
            {
                if (stream == null)
                {
                    throw new ArgumentException("input");
                }

                StreamReader reader = new StreamReader(stream);
                string source = reader.ReadToEnd();
                CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, source);
                ThrowIfCompilerError(results);
                return results;
            }
        }
Esempio n. 11
0
 public void Execute(string scriptCode)
 {
     string[] source = new string[1];
     source[0] = scriptCode;
     CSharp.CSharpCodeProvider cscp = new CSharp.CSharpCodeProvider();
     this.Compile(cscp, source[0]);
 }
        /// <summary>
        /// get an Assembly according to wsdl path.
        /// </summary>
        /// <param name="wsdl">wsdl path</param>
        /// <param name="nameSpace">namespace</param>
        /// <returns>return Assembly</returns>
        public static Assembly GetWebServiceAssembly(string wsdl, string nameSpace)
        {
            try
            {
                System.Net.WebClient webClient = new System.Net.WebClient();
                System.IO.Stream     webStream = webClient.OpenRead(wsdl);

                ServiceDescription         serviceDescription      = ServiceDescription.Read(webStream);
                ServiceDescriptionImporter serviceDescroptImporter = new ServiceDescriptionImporter();

                serviceDescroptImporter.AddServiceDescription(serviceDescription, "", "");
                System.CodeDom.CodeNamespace   codeNameSpace   = new System.CodeDom.CodeNamespace(nameSpace);
                System.CodeDom.CodeCompileUnit codeCompileUnit = new System.CodeDom.CodeCompileUnit();
                codeCompileUnit.Namespaces.Add(codeNameSpace);
                serviceDescroptImporter.Import(codeNameSpace, codeCompileUnit);

                System.CodeDom.Compiler.CodeDomProvider    codeDom        = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters codeParameters = new System.CodeDom.Compiler.CompilerParameters();
                codeParameters.GenerateExecutable = false;
                codeParameters.GenerateInMemory   = true;

                codeParameters.ReferencedAssemblies.Add("System.dll");
                codeParameters.ReferencedAssemblies.Add("System.XML.dll");
                codeParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
                codeParameters.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults compilerResults = codeDom.CompileAssemblyFromDom(codeParameters, codeCompileUnit);

                return(compilerResults.CompiledAssembly);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        public SIC_WebServiceAgent(string url)
        {
            XmlTextReader reader = new XmlTextReader(url + "?wsdl");

            //创建和格式化 WSDL 文档
            ServiceDescription sd = ServiceDescription.Read(reader);

            //创建客户端代理代理类
            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();

            sdi.AddServiceDescription(sd, null, null);

            //使用 CodeDom 编译客户端代理类
            CodeNamespace   cn  = new CodeNamespace(CODE_NAMESPACE);
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            CompilerResults    cr = icc.CompileAssemblyFromDom(cp, ccu);

            agentType = cr.CompiledAssembly.GetTypes()[0];
            Agent     = Activator.CreateInstance(agentType);
        }
        /// <summary>
        /// This method Parses and compiles the source code into an Assembly and returns it
        /// </summary>
        /// <param name="baseClassType">The Type of the Base class the generated class descends from</param>
        /// <param name="namespaceOfGeneratedClass">The Namespace of the generated class</param>
        /// <param name="generatedClassName">The Class Name of the generated class</param>
        /// <param name="sourceCodeReader">A Text reader that is a warpper around the "Template" that is to be parsed and compiled</param>
        /// <returns>An instance of a generated assembly that contains the generated class</returns>
        public Assembly ParseAndCompileTemplate(Type baseClassType, string namespaceOfGeneratedClass, string generatedClassName, TextReader sourceCodeReader)
        {
            RazorTemplateEngine engine = InitializeRazorEngine(baseClassType, namespaceOfGeneratedClass, generatedClassName);
            GeneratorResults razorResults = engine.GenerateCode(sourceCodeReader);

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CodeGeneratorOptions options = new CodeGeneratorOptions();

            string generatedCode = null;
            using (StringWriter writer = new StringWriter())
            {
                codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options);
                generatedCode = writer.GetStringBuilder().ToString();
            }

            var outputAssemblyName = Path.GetTempPath() + Guid.NewGuid().ToString("N") + ".dll";
            CompilerParameters compilerParameters = new CompilerParameters(new string[]{}, outputAssemblyName);
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8));
            compilerParameters.GenerateInMemory = false;

            CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode);
            if (compilerResults.Errors.Count > 0)
            {
                var compileErrors = new StringBuilder();
                foreach (System.CodeDom.Compiler.CompilerError compileError in compilerResults.Errors)
                    compileErrors.Append(String.Format("Line: {0}\t Col: {1}\t Error: {2}\r\n", compileError.Line, compileError.Column, compileError.ErrorText));

                throw new Exception(compileErrors.ToString() + generatedCode);
            }

            return compilerResults.CompiledAssembly;
        }
Esempio n. 15
0
 public Expression(string expression)
 {
     CompilerParameters p = new CompilerParameters();
     p.GenerateInMemory = true;
     System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(expression, @"\{([^\}]*)\}");
     string paramsStr = "";
     for (int i = 0; i < mc.Count; i++)
     {
         string mcValue = mc[i].Value;
         string mcGroupValue = mc[i].Groups[1].Value;
         if (!ExpressionKey.Contains(mcGroupValue))
         {
             ExpressionKey.Add(mcGroupValue);
             paramsStr += "double d" + i + ",";
             expression = expression.Replace(mcValue, "d" + i);
         }
     }
     this.ExpressionBody = expression;
     paramsStr = paramsStr.TrimEnd(',');
     string clsStr = String.Format("using System;sealed class Expression{{public double Compute({0}){{return {1};}}}}", paramsStr, expression);
     CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, clsStr);
     if (cr.Errors.Count > 0)
     {
         string msg = "Expression(\"" + expression + "\"): \n";
         foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
         throw new Exception(msg);
     }
     instance = cr.CompiledAssembly.CreateInstance("Expression");
     method = instance.GetType().GetMethod("Compute");
 }
Esempio n. 16
0
        static void CompileAndRun(string code)
        {
            var csc = new CSharpCodeProvider();
            var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "teste.exe", true)
            {
                GenerateExecutable = true
            };
            CompilerResults compiledAssembly = csc.CompileAssemblyFromSource(parameters,
            code);

            var errors = compiledAssembly.Errors
                                         .Cast<CompilerError>()
                                         .ToList();

            if (errors.Any())
            {
                errors.ForEach(Console.WriteLine);
                return;
            }

            Module module = compiledAssembly.CompiledAssembly.GetModules()[0];

            Type mt = null;
            if (module != null)
                mt = module.GetType("Program");

            MethodInfo methInfo = null;
            if (mt != null)
                methInfo = mt.GetMethod("Main");

            if (methInfo != null)
                Console.WriteLine(methInfo.Invoke(null, null));
        }
Esempio n. 17
0
        public static void RunTransformations(string userCode)
        {
            using (var codeProvider = new CSharpCodeProvider())
            {
                string code =
                    @"using Aitako.DSL;using System; using Aitako.DSL.Components;using System.Collections.Generic;  public class Runner { public void Execute() { " +
                    userCode + " Service.Execute();}}";

                CompilerResults compilerResult =
                    codeProvider.CompileAssemblyFromSource(
                        new CompilerParameters(new[] {"Aitako.DSL.dll"}) {GenerateInMemory = true}, code);

                if (compilerResult.Errors.Count > 0)
                {
                    foreach (object error in compilerResult.Errors)
                    {
                        Console.WriteLine(error.ToString());
                    }
                    return;
                }

                Type compiledType = compilerResult.CompiledAssembly.GetType("Runner");
                object instance = Activator.CreateInstance(compiledType);
                object output = compiledType.GetMethod("Execute").Invoke(instance, new object[] {});

                Console.WriteLine(output);
            }
        }
Esempio n. 18
0
        public static void CompileIntoAssembly(string outputPath, IEnumerable<string> references, List<string> files)
        {
            CodeDomProvider provider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters()
            {
                GenerateExecutable = false,
                OutputAssembly = outputPath,
                IncludeDebugInformation = true,
                CompilerOptions = "/unsafe"
            };

            foreach (var @ref in references)
                cp.ReferencedAssemblies.Add(@ref);

            CompilerResults cr = provider.CompileAssemblyFromFile(cp, files.ToArray());

            if (cr.Errors.HasErrors)
            {
                var message = new StringBuilder();
                message.Append("Error compiling generated files.\n");
                foreach(var error in cr.Errors)
                    message.AppendFormat("  {0}\n",error.ToString());
                throw new Exception(message.ToString());
            }
        }
Esempio n. 19
0
        public static ICalc GetCalc(string csCode)
        {
            ICalc obj = null;

#if !NETCOREAPP3_0 && !NETSTANDARD2_0 && !NETSTANDARD2_1
            using (Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider())
            {
                var prm = new System.CodeDom.Compiler.CompilerParameters();
                prm.GenerateInMemory   = true;
                prm.GenerateExecutable = false;
#if NET451 || NET471
                prm.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
#endif

                counter++;
                // Implement the interface in the dynamic code
                var res = csProvider.CompileAssemblyFromSource(prm,
                                                               String.Format(@"public class CompiledCalc{0} : ICalc { public Exception LastError { get; set; }
                            public object Calc() { {1} }}", counter, csCode));
                var type = res.CompiledAssembly.GetType(string.Format("CompiledCalc{0}", counter));

                try
                {
                    obj = Activator.CreateInstance(type) as ICalc;
                }
                catch (Exception ex)
                {
                    obj           = obj ?? new CalcEmpty();
                    obj.LastError = ex;
                }
            }
#endif
            return(obj);
        }
Esempio n. 20
0
        public static string compilerte(string outputname, string sourcecode)
        {
            var codeProvider = new CSharpCodeProvider();
            var provider = CodeDomProvider.CreateProvider("CSharp");

            var exeName = outputname;

            var cp = new CompilerParameters
            {
                GenerateExecutable = true,
                OutputAssembly = exeName,
                GenerateInMemory = false,
                TreatWarningsAsErrors = false
            };

            var cr = provider.CompileAssemblyFromSource(cp, translatetocsharp(sourcecode));

            if (cr.Errors.Count > 0)
            {
                var builder = new StringBuilder();
                builder.Append("Cehape broke our codes that were supposed to be compiled here: " + cr.PathToAssembly);
                foreach (CompilerError ce in cr.Errors)
                {
                    builder.Append(Environment.NewLine + ce.ToString());
                }
                codeProvider.Dispose();
                return builder.ToString();
            }
            else
            {
                codeProvider.Dispose();
                return ("We were able to compile {0} successfully without cehape messing with it.".Replace("{0}", cr.PathToAssembly));
            }
        }
Esempio n. 21
0
        static Assembly CompileSettings(string inputFilePath)
        {
            string fileName = Path.GetFileNameWithoutExtension(inputFilePath);

            string code = File.ReadAllText(inputFilePath);
            code = "using SettingsCompiler;\r\n\r\n" + "namespace " + fileName + "\r\n{\r\n" + code;
            code += "\r\n}";

            Dictionary<string, string> compilerOpts = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
            CSharpCodeProvider compiler = new CSharpCodeProvider(compilerOpts);

            string[] sources = { code };
            CompilerParameters compilerParams = new CompilerParameters();
            compilerParams.GenerateInMemory = true;
            compilerParams.ReferencedAssemblies.Add("System.dll");
            compilerParams.ReferencedAssemblies.Add("SettingsCompilerAttributes.dll");
            CompilerResults results = compiler.CompileAssemblyFromSource(compilerParams, sources);
            if(results.Errors.HasErrors)
            {
                string errMsg = "Errors were returned from the C# compiler:\r\n\r\n";
                foreach(CompilerError compilerError in results.Errors)
                {
                    int lineNum = compilerError.Line - 4;
                    errMsg += inputFilePath + "(" + lineNum + "): " + compilerError.ErrorText + "\r\n";
                }
                throw new Exception(errMsg);
            }

            return results.CompiledAssembly;
        }
Esempio n. 22
0
		private void GenerateHelper()
		{
			using (GenParamsForm gpf = new GenParamsForm())
			{
				gpf.Namespace = _rootCategory.Name;
				if (gpf.ShowDialog(this) == DialogResult.OK)
				{
					CodeCompileUnit ccu = HelperGenerator.Generate(_rootCategory,
						gpf.Namespace, gpf.IsInternal);
					CSharpCodeProvider cscp = new CSharpCodeProvider();
					CodeGeneratorOptions cgo = new CodeGeneratorOptions();
					cgo.BracingStyle = "C";
					using (StreamWriter sw = new StreamWriter(
							Path.Combine(_directory, _rootCategory.TreeName + ".cs")))
						cscp.GenerateCodeFromCompileUnit(ccu, sw, cgo);
					if (gpf.ShowResult)
						using (ShowResultForm srf = new ShowResultForm())
						using (StringWriter strW = new StringWriter())
						{
							cscp.GenerateCodeFromCompileUnit(ccu, strW, cgo);
							srf.Result = strW.ToString();
							srf.ShowDialog(this);
						}
				}
			}
		}
Esempio n. 23
0
        /// <summary>
        /// Compiles the srcipt and returns an evaluator (a delegate) 
        /// which takes in time and returns audioFrame values
        /// </summary>
        /// <returns>A delegate of type Func&lt;double,double&gt;</returns>
        public Func<double, double> Compile()
        {
            var codeProvider = new CSharpCodeProvider();
            var compilerResults =
                codeProvider.CompileAssemblyFromSource(
                    new CompilerParameters(new[] {"TuneItDynamicBase.dll"}) {GenerateInMemory = true},
                    @"
            using System;
            using TuneItDynamicBase;

            public class DynamicCompiledScript : DynamicCompiledScriptBase
            {
            public override Func<double, double> Evaluator
            {
            get
            {
            return delegate(double time)
                   {"
                        + script + @"
                   };
            }
            }
            }
            ");
            if (compilerResults.Errors.HasErrors)
            {
                return null;
            }
            var dynamicScriptInstance = (IDynamicScript) compilerResults.CompiledAssembly.CreateInstance("DynamicCompiledScript");
            if (dynamicScriptInstance == null)
            {
                return null;
            }
            return dynamicScriptInstance.Evaluator;
        }
Esempio n. 24
0
		protected static AssemblyDef CompileLegacy(string code, bool optimize, bool useDebug, int compilerVersion)
		{
			CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v" + new Version(compilerVersion, 0) } });
			CompilerParameters options = new CompilerParameters();
			options.CompilerOptions = "/unsafe /o" + (optimize ? "+" : "-") + (useDebug ? " /debug" : "");
			if (compilerVersion >= 4)
				options.ReferencedAssemblies.Add("System.Core.dll");
			CompilerResults results = provider.CompileAssemblyFromSource(options, code);
			try
			{
				if (results.Errors.Count > 0)
				{
					StringBuilder b = new StringBuilder("Compiler error:");
					foreach (var error in results.Errors)
					{
						b.AppendLine(error.ToString());
					}
					throw new Exception(b.ToString());
				}
				return Utils.OpenAssembly(results.PathToAssembly);
			}
			finally
			{
				File.Delete(results.PathToAssembly);
				results.TempFiles.Delete();
			}
		}
Esempio n. 25
0
        internal static void MainThreadEntry(object state)
        {
            var args = (string[])state;

            if (args.Length < 2)
                throw new Exception("Dunno what to run.");

            var appDirectory = Path.GetFullPath(args[1]);
            var appFile = Path.Combine(appDirectory, "App.cs");
            var appConfigFile = Path.Combine(appDirectory, "BlazeApp.json.config");

            if (!File.Exists(appConfigFile))
                throw new Exception("App configuration file was not found.");
            if (!File.Exists(appFile))
                throw new Exception("No app entry found.");

            var appConfigFileContent = File.ReadAllText(appConfigFile);
            var appConfig = JsonConvert.DeserializeObject<AppConfiguration>(appConfigFileContent);

            var tempAssemblyPath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
            var codeProvider = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", appConfig.CompilerVersion } });
            var compilerParameters = new CompilerParameters(appConfig.References, tempAssemblyPath, false)
            {
                GenerateInMemory = true
            };
            var compilerResult = codeProvider.CompileAssemblyFromFile(compilerParameters, new[] { appFile });

            if (compilerResult.Errors.Count > 0)
                throw new Exception("There were errors during compilation.");

            // TODO: Invoke compiled entry method -- http://stackoverflow.com/questions/14479074/c-sharp-reflection-load-assembly-and-invoke-a-method-if-it-exists
        }
Esempio n. 26
0
        public static CompilerResults Compile(this DirectoryInfo[] compileTargets, string fileName, string[] referenceAssemblies, bool executable)
        {
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();

            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = executable;
            parameters.OutputAssembly = fileName;
            List<string> compilerOptions = new List<string>();

            foreach (string referenceAssembly in referenceAssemblies)
            {
                compilerOptions.Add("/reference:" + referenceAssembly);
            }
            parameters.CompilerOptions = compilerOptions.ToArray().ToDelimited(" ");

            List<string> fileNames = new List<string>();
            foreach (DirectoryInfo targetDirectory in compileTargets)
            {
                foreach (FileInfo fileInfo in FsUtil.GetFilesWithExtension(targetDirectory.FullName, ".cs"))
                {
                    fileNames.Add(fileInfo.FullName);
                }
            }

            return codeProvider.CompileAssemblyFromFile(parameters, fileNames.ToArray());//.CompileAssemblyFromFileBatch(parameters, fileNames.ToArray());
        }
        static void Main(string[] args)
        {
            // Output some program information using Console.WriteLine.
            Console.WriteLine("This program compiles a CodeDOM program that incorrectly declares multiple data");
            Console.WriteLine("types to demonstrate handling compiler errors programmatically.");
            Console.WriteLine("");

            // Compile the CodeCompileUnit retrieved from the GetCompileUnit() method.
            CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

            // Initialize a CompilerParameters with the options for compilation.
            string[]           assemblies = new String[] { "System.dll" };
            CompilerParameters options    = new CompilerParameters(assemblies, "output.exe");

            // Compile the CodeDOM graph and store the results in a CompilerResults.
            CompilerResults results = provider.CompileAssemblyFromDom(options, GetCompileUnit());

            // Compilation produces errors. Print out each error.
            Console.WriteLine("Listing errors from compilation: ");
            Console.WriteLine("");
            for (int i = 0; i < results.Errors.Count; i++)
            {
                Console.WriteLine(results.Errors[i].ToString());
            }
        }
        public void PostProcessGeneratedCodeAddsApplicationInstanceProperty() {
            const string expectedPropertyCode = @"
protected Foo.Bar ApplicationInstance {
    get {
        return ((Foo.Bar)(Context.ApplicationInstance));
    }
}
";

            // Arrange
            CodeCompileUnit generatedCode = new CodeCompileUnit();
            CodeNamespace generatedNamespace = new CodeNamespace();
            CodeTypeDeclaration generatedClass = new CodeTypeDeclaration();
            CodeMemberMethod executeMethod = new CodeMemberMethod();
            WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml") {
                GlobalAsaxTypeName = "Foo.Bar"
            };

            // Act
            host.PostProcessGeneratedCode(generatedCode, generatedNamespace, generatedClass, executeMethod);

            // Assert
            CodeMemberProperty property = generatedClass.Members[0] as CodeMemberProperty;
            Assert.IsNotNull(property);

            CSharpCodeProvider provider = new CSharpCodeProvider();
            StringBuilder builder = new StringBuilder();
            using(StringWriter writer = new StringWriter(builder)) {
                provider.GenerateCodeFromMember(property, writer, new CodeDom.Compiler.CodeGeneratorOptions());
            }

            Assert.AreEqual(expectedPropertyCode, builder.ToString());
        }
Esempio n. 29
0
File: Program.cs Progetto: nyet/nyet
        public static String GenerateCSharpCode(CodeCompileUnit compileunit)
        {
            // Generate the code with the C# code provider.
            CSharpCodeProvider provider = new CSharpCodeProvider();

            // Build the output file name.
            String sourceFile;
            if (provider.FileExtension[0] == '.')
            {
                sourceFile = "HelloWorld" + provider.FileExtension;
            }
            else
            {
                sourceFile = "HelloWorld." + provider.FileExtension;
            }

            // Create a TextWriter to a StreamWriter to the output file.
            IndentedTextWriter tw = new IndentedTextWriter(
                    new StreamWriter(sourceFile, false), "    ");

            // Generate source code using the code provider.
            provider.GenerateCodeFromCompileUnit(compileunit, tw,
                    new CodeGeneratorOptions());

            // Close the output file.
            tw.Close();

            return sourceFile;
        }
        private static Assembly Compile(CodeCompileUnit codeCompileUnit)
        {   
            var compilerParameters = new CompilerParameters();

            compilerParameters.GenerateInMemory = true; 
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8));

            var codeProvider = new CSharpCodeProvider();

            var result = codeProvider.CompileAssemblyFromDom(compilerParameters, codeCompileUnit);

            if (result.Errors.HasErrors)
            {
                foreach (var error in result.Errors)
                {
                    Console.WriteLine(error);
                }

                return null;
            }

            return result.CompiledAssembly;
        }
Esempio n. 31
0
        public void CanCreateDataTableAssignment()
        {
            CodeNamespace nsdecl = new CodeNamespace("My.Data");
            CodeTypeDeclaration cdecl = new CodeTypeDeclaration("ResultSet");
            CodeMemberMethod method = new CodeMemberMethod();
            method.Name = "GetData";
            method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            method.ReturnType = new CodeTypeReference("System.Data.DataTable");
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "name"));
            method.Statements.Add(new CodeVariableDeclarationStatement(
                typeof(DataTable),
                "result",
                new CodeObjectCreateExpression(typeof(DataTable))));
            cdecl.Members.Add(method);
            method.Statements.Add(
                new CodeVariableDeclarationStatement(
                    typeof(DataColumnCollection),
                    "columns",
                    new CodePropertyReferenceExpression(
                        new CodeVariableReferenceExpression("result"),
                        "Columns")));
            method.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("columns"), "Add", new CodeTypeOfExpression(typeof(string)), new CodeSnippetExpression("name")));

            nsdecl.Types.Add(cdecl);
            CSharpCodeProvider provider = new CSharpCodeProvider();
            provider.GenerateCodeFromNamespace(nsdecl, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions());
        }
        public string CreateExe(string exeName, string sourceString)
        {
            Directory.CreateDirectory(this.ExeDirectory);
            var outputExePath = this.ExeDirectory + exeName;
            if (File.Exists(outputExePath))
            {
                File.Delete(outputExePath);
            }

            var codeProvider = new CSharpCodeProvider();
            var parameters = new CompilerParameters
                                 {
                                     GenerateExecutable = true,
                                     OutputAssembly = outputExePath,
                                 };
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, sourceString);
            foreach (var error in results.Errors)
            {
                Console.WriteLine(error.ToString());
            }

            Assert.IsFalse(results.Errors.HasErrors, "Code compilation contains errors!");
            return outputExePath;
        }
Esempio n. 33
0
 public IRazorHost CreateHost(string fullPath, string projectRelativePath)
 {
     using (var codeDomProvider = new CSharpCodeProvider())
     {
         return CreateHost(fullPath, projectRelativePath, codeDomProvider);
     }
 }
 private static Assembly BuildAssembly(string code)
 {
     CSharpCodeProvider provider =
        new CSharpCodeProvider();
     ICodeCompiler compiler = provider.CreateCompiler();
     CompilerParameters compilerparams = new CompilerParameters();
     compilerparams.GenerateExecutable = false;
     compilerparams.GenerateInMemory = true;
     compilerparams.ReferencedAssemblies.Add("PageTypeBuilder.dll");
     compilerparams.ReferencedAssemblies.Add("PageTypeBuilder.Migrations.dll");
     CompilerResults results =
        compiler.CompileAssemblyFromSource(compilerparams, code);
     if (results.Errors.HasErrors)
     {
         StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
         foreach (CompilerError error in results.Errors)
         {
             errors.AppendFormat("Line {0},{1}\t: {2}\n",
                    error.Line, error.Column, error.ErrorText);
         }
         throw new Exception(errors.ToString());
     }
     else
     {
         return results.CompiledAssembly;
     }
 }
Esempio n. 35
0
 public static void compileSource()
 {
     //UNDER CONSTRUCTION
     string source = @"
     namespace Foo
     {
     public class Bar
     {
     public void SayHello()
     {
     System.Console.WriteLine(""Hello World"");
     }
     }
     }
     ";
     Dictionary<string, string> providerOptions = new Dictionary<string, string>
     {
         {"CompilerVersion", "v4" }
     };
     CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
     CompilerParameters compilerParams = new CompilerParameters
         {GenerateInMemory = true,
         GenerateExecutable = false};
     CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
     if (results.Errors.Count != 0)
         throw new Exception("Mission Failed");
     object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
     MethodInfo mi = o.GetType().GetMethod("SayHello");
     mi.Invoke(o, null);
 }
Esempio n. 36
0
        static void Main(string[] args)
        {
            Uri wsdlLocation = new Uri(Directory.GetCurrentDirectory() + "\\..\\..\\..\\OrderService.wsdl");

            Console.WriteLine("Beginning schema import.");
            Console.WriteLine();

            DiscoveryClientProtocol client = new DiscoveryClientProtocol();

            client.AllowAutoRedirect = true;
            DiscoveryDocument doc = client.DiscoverAny(wsdlLocation.ToString());

            client.ResolveAll();

            WebReferenceCollection references = new WebReferenceCollection();

            //add 1st web reference document
            WebReference wr = new WebReference(client.Documents, new CodeNamespace("Microsoft.Samples"));

            references.Add(wr);

            //add other web reference documents if needed

            CodeDomProvider codeProvider = new
                                           Microsoft.CSharp.CSharpCodeProvider();
            CodeCompileUnit Ccu = new CodeCompileUnit();

            Ccu.Namespaces.Add(wr.ProxyCode);
            try
            {
                //This is the new API call
                ServiceDescriptionImporter.GenerateWebReferences(
                    references,
                    codeProvider, Ccu, new WebReferenceOptions());
            }
            catch (Exception ex)
            {
                //do exception handling
                Console.WriteLine("An exception occured during importation:\n {0}", ex.ToString());
            }

            StreamWriter writer = new StreamWriter("OrderProxy.cs", false,
                                                   new System.Text.UTF8Encoding(true));

            codeProvider.GenerateCodeFromCompileUnit(Ccu, writer, new CodeGeneratorOptions());
            writer.Close();


//			importer.Import(new CodeNamespace("Microsoft.Samples"), compileUnit);
            Console.WriteLine();
            Console.WriteLine("Schema import completed.");

            //reader.Close();

            Console.WriteLine("Finished. Press any key to continue...");
            Console.ReadLine();

            System.Diagnostics.Process.Start("notepad", "OrderProxy.cs");
        }
Esempio n. 37
0
        public static object WebserviceInvoke(string p_strUrl, string p_strNameSpace, string p_strClassName, string p_strMethodName, object[] p_objArgs)
        {
            object oReturnValue = null;

            try
            {
                if (p_strNameSpace == "")
                {
                    p_strNameSpace = "EnterpriseServerBase.WebService.DynamicWebCalling";
                }
                if (p_strClassName == "")
                {
                    p_strClassName = WebServiceHelper.GetWsClassName(p_strUrl);
                }
                System.Net.WebClient wc     = new System.Net.WebClient();
                System.IO.Stream     stream = wc.OpenRead(p_strUrl + "?wsdl");
                System.Web.Services.Description.ServiceDescription         sd  = System.Web.Services.Description.ServiceDescription.Read(stream);
                System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                System.CodeDom.CodeNamespace   cn  = new System.CodeDom.CodeNamespace(p_strNameSpace);
                System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);

                Microsoft.CSharp.CSharpCodeProvider        csc    = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(p_strNameSpace + "." + p_strClassName, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(p_strMethodName);
                oReturnValue = mi.Invoke(obj, p_objArgs);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
            return(oReturnValue);
        }
Esempio n. 38
0
        /// <summary>
        /// Executes the processed code from Process() function.
        /// </summary>
        /// <param name="errors">If execution was not successful, returns CompilerErrorCollection or Exception</param>
        /// <returns>Values to put in each code segment (output) or null if there were errors</returns>
        public string[] Execute(out object errors)
        {
            errors         = null;
            segmentsOutput = new string[segmentNum];
            for (int i = 0; i < segmentNum; i++)
            {
                segmentsOutput[i] = "";
            }
            segmentNum = -1;
            CSHARP.CSharpCodeProvider provider = new CSHARP.CSharpCodeProvider();


            CompilerParameters parms = new CompilerParameters();

            parms.GenerateInMemory        = true;
            parms.TreatWarningsAsErrors   = false;
            parms.TempFiles               = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
            parms.IncludeDebugInformation = true;
            parms.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location);
            try
            {
                string[] assms = File.ReadAllText(ConfigurationManager.SETTINGS["ASSEMBLIES"]).Split(new char[] { '\n' });
                for (int i = 0; i < assms.Length; i++)
                {
                    parms.ReferencedAssemblies.Add(assms[i].Trim());
                }
            }
            catch { }

            CompilerResults res = provider.CompileAssemblyFromSource(parms, FinalCode);

            if (res.Errors.HasErrors) // Handling compiler errors
            {
                errors = res.Errors;
                return(null);
            }

            Assembly   ass  = res.CompiledAssembly;
            Type       prog = ass.GetType("LWASP_Console.WebApp");
            MethodInfo main = prog.GetMethod("Rain");

            try
            {
                main.Invoke(null, new object[] { connection, connection.queryString, connection.formData, connection.PostData() });
            }
            catch (Exception exx)
            {
                errors = exx != null ? exx.InnerException ?? exx : new Exception("LWASP Error");
                return(null);
            }

            return(segmentsOutput);
        }
Esempio n. 39
0
        private String GenerateDll()
        {
            String csName = "ConfigCommon.cs";

            if (!File.Exists(csName))
            {
                return(String.Empty);
            }

            String dllName = csName.Substring(0, csName.LastIndexOf(".")) + ".dll";

            CodeDomProvider codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider();

            CompilerParameters parameters = new CompilerParameters();

            parameters.GenerateExecutable = false;
            parameters.OutputAssembly     = dllName;

            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory   = true;

            parameters.ReferencedAssemblies.Add("mscorlib.dll");
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("protobuf-net.dll");

            try
            {
                CompilerResults results = codeDomProvider.CompileAssemblyFromFile(parameters, csName);

                if (results.Errors.HasErrors)
                {
                    StringBuilder sb = new StringBuilder();

                    foreach (CompilerError error in results.Errors)
                    {
                        sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                    }

                    return(String.Empty);
                }
            }
            catch (System.Exception)
            {
                return(String.Empty);
            }

            return(dllName);
        }
Esempio n. 40
0
        void downloadJob_OnJobTransferredEvent(object sender, JobNotificationEventArgs e)
        {
            try {
                // complete the job
                _downloadJob.Complete();
                CodeDomProvider    provider = new Microsoft.CSharp.CSharpCodeProvider();
                ICodeCompiler      compiler = provider.CreateCompiler();
                CompilerParameters cpar     = new CompilerParameters();
                cpar.GenerateInMemory   = true;
                cpar.GenerateExecutable = false;
                cpar.ReferencedAssemblies.Add(
                    Process.GetCurrentProcess().MainModule.FileName
                    );
                cpar.ReferencedAssemblies.Add("System.dll");
                cpar.ReferencedAssemblies.Add("System.Drawing.dll");
                cpar.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                cpar.ReferencedAssemblies.Add("RSIWarrior.Common.dll");
                cpar.ReferencedAssemblies.Add("RSIWarrior.AutoUpdate.dll");
                CompilerResults cres = compiler.CompileAssemblyFromFile(
                    cpar,
                    LocalPatchFile
                    );

                foreach (CompilerError ce in cres.Errors)
                {
                    throw new Exception(ce.ErrorText);
                }
                if (cres.Errors.Count == 0 && cres.CompiledAssembly != null)
                {
                    Type[] exportedTypes = cres.CompiledAssembly.GetExportedTypes();
                    foreach (Type type in exportedTypes)
                    {
                        if (type.GetInterface("RSIWarrior.AutoUpdate.IPatch") != null &&
                            !type.IsAbstract)
                        {
                            IPatch patch = (IPatch)Activator.CreateInstance(type);
                            patch.Execute();
                        }
                    }
                }
            } catch (Exception ex) {
            } finally {
                try {
                    File.Delete(LocalPatchFile);
                } catch {
                }
            }
        }
Esempio n. 41
0
    public static object InvokeWebService(string url, string @namespace, string classname, string methodname, object[] args)
    {
        try
        {
            System.Net.WebClient wc     = new System.Net.WebClient();
            System.IO.Stream     stream = wc.OpenRead(url + "?WSDL");
            System.Web.Services.Description.ServiceDescription         sd  = System.Web.Services.Description.ServiceDescription.Read(stream);
            System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
            sdi.AddServiceDescription(sd, "", "");
            System.CodeDom.CodeNamespace   cn  = new System.CodeDom.CodeNamespace(@namespace);
            System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);

            Microsoft.CSharp.CSharpCodeProvider   csc = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler();

            System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters();
            cplist.GenerateExecutable = false;
            cplist.GenerateInMemory   = true;
            cplist.ReferencedAssemblies.Add("System.dll");
            cplist.ReferencedAssemblies.Add("System.XML.dll");
            cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
            cplist.ReferencedAssemblies.Add("System.Data.dll");

            System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
            if (true == cr.Errors.HasErrors)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                {
                    sb.Append(ce.ToString());
                    sb.Append(System.Environment.NewLine);
                }
                throw new Exception(sb.ToString());
            }
            System.Reflection.Assembly assembly = cr.CompiledAssembly;
            Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
            object obj = Activator.CreateInstance(t);
            System.Reflection.MethodInfo mi = t.GetMethod(methodname);
            return(mi.Invoke(obj, args));
        }
        catch (Exception ex)
        {
            throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
        }
    }
        /// <summary>
        /// Compile the sharp code in SourceString and link it with the assemblies
        /// provided in the parameter LinkedAssemblies
        /// </summary>
        /// <param name="SourceString">the code to compile as string</param>
        /// <param name="LinkedAssemblies">assemblies to link with separated by semi-column ';'</param>
        /// <returns>true if success, else false and you can call GetLastError</returns>
        public bool Compile(string SourceString, string LinkedAssemblies)
        {
            CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();

            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateInMemory   = true;
            parameters.GenerateExecutable = false;

            // add the linked assemblies
            foreach (string assembly in LinkedAssemblies.Split(';'))
            {
                parameters.ReferencedAssemblies.Add(assembly);
            }

            // compile
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, SourceString);

            //if errors
            if (results.Errors.Count > 0)
            {
                _ErrorMsg = new StringBuilder();

                // append all errors
                foreach (CompilerError CompErr in results.Errors)
                {
                    _ErrorMsg.AppendFormat("Line: {0} , Code: {1}, Msg: {2}",
                                           CompErr.Line, CompErr.ErrorNumber, CompErr.ErrorText);

                    Tracer.Error("CSharpCodeCompiler", "Line: {0} , Code: {1}, Msg {2}", CompErr.Line, CompErr.ErrorNumber, CompErr.ErrorText);
                    //EventManager.Instance.SendMessage(SourceString);
                }
            }

            if (results.Errors.Count == 0 && results.CompiledAssembly != null)
            {
                _assembly = results.CompiledAssembly;
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 43
0
        protected virtual CodeDomProvider GetCodeProvider(string fileName)
        {
            CodeDomProvider provider  = null;
            string          extension = Path.GetExtension(fileName);

            if (String.Compare(extension, ".cs", true) == 0)
            {
                provider = new Microsoft.CSharp.CSharpCodeProvider();
            }
            else if (String.Compare(extension, ".vb", true) == 0)
            {
                provider = new Microsoft.VisualBasic.VBCodeProvider();
            }
            else
            {
                throw new InvalidOperationException("Programming language not supported for:" + fileName);
            }
            return(provider);
        }
Esempio n. 44
0
        public void SaveDesignerClass(string outdir, string className, string ns)
        {
            var designerCsPath = Path.Combine(outdir, $"{className}.Designer.cs");

            string[] errors;
            var      codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            var      data         = _data.ToDictionary(d => d.Key, d => d.Value.Value);
            var      code         = StronglyTypedResourceBuilder.Create(data, className, ns, codeProvider, false, out errors);

            if (errors.Length > 0)
            {
                foreach (var error in errors)
                {
                    Console.WriteLine(error);
                }
            }
            using (StreamWriter writer = new StreamWriter(designerCsPath, false, System.Text.Encoding.UTF8))
            {
                codeProvider.GenerateCodeFromCompileUnit(code, writer, new CodeGeneratorOptions());
            }
        }
Esempio n. 45
0
        private Type CreateType(string className, string codeFragment, string statement)
        {
            CompilerParameters compilerParameters = CreateCompilerParameters();

            statement = String.Format("{0}{2}{1}", BuildNameSpaces(), statement, Environment.NewLine);

            CodeDomProvider codeDomProvider = null;

            switch (_language)
            {
            case ChoCodeProviderLanguage.VB:
                codeDomProvider = new Microsoft.VisualBasic.VBCodeProvider();
                break;

            default:
                codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider();
                break;
            }

            using (codeDomProvider)
            {
                var res = codeDomProvider.CompileAssemblyFromSource(compilerParameters, statement);

                if (res.Errors.Count > 0)
                {
                    StringBuilder errors = new StringBuilder();
                    foreach (CompilerError CompErr in res.Errors)
                    {
                        errors.AppendFormat("Line number {0}, Error Number: {1}, {2}{3}", CompErr.Line, CompErr.ErrorNumber, CompErr.ErrorText, Environment.NewLine);
                    }

                    throw new ApplicationException("Exception compiling code fragment: {1}{1}{0}{1}{1}Exceptions:{1}{2}".FormatString(
                                                       codeFragment.Indent(1), Environment.NewLine, errors.ToString().Indent(1)));
                }

                return(res.CompiledAssembly.GetType(className));
            }
        }
Esempio n. 46
0
        public CodeCompileUnit ConvertToCodeComlieUnit(String strText)
        {
            TextReader inputstream = new StringReader(strText);

            #region New
            //CSharpParser parser=new CSharpParser();
            //CompilationUnit compilationUnit=parser.Parse( inputstream , @"D:\bbb.cs" );

            //IProjectContent project=new CSharpProjectContent();
            //var parsedFile=compilationUnit.ToTypeSystem();

            //project=project.UpdateProjectContent( null , parsedFile );
            //project=project.AddAssemblyReferences( builtInLibs.Value );

            //ICompilation compilation=project.CreateCompilation();

            //CodeCompileUnit cUnit=new CodeDomConvertVisitor().Convert( compilation , compilationUnit , parsedFile );

            ////// Remove Unsed Namespaces
            //for ( int i=cUnit.Namespaces.Count-1; i>=0; i-- )
            //{
            //    if ( cUnit.Namespaces[i].Types.Count==0 )
            //        cUnit.Namespaces.RemoveAt( i );
            //}
            //return cUnit;
            #endregion

            #region Old
            ICSharpCode.NRefactory.IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, inputstream);
            parser.ParseMethodBodies     = true;
            parser.Lexer.SkipAllComments = false;
            parser.Parse();
            if (parser.Errors.Count > 0)
            {
                return(null);
            }

            //foreach ( var node in parser.CompilationUnit.Children )
            //{
            //    // fix StartLocation / EndLocation
            //    node.AcceptVisitor( new ICSharpCode.NRefactory.Visitors.SetRegionInclusionVisitor() , null );
            //}

            CodeDomProvider codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider();
            CodeDomVisitor  visit           = new CodeDomVisitor();

            visit.VisitCompilationUnit(parser.CompilationUnit, null);

            // Remove Unsed Namespaces
            for (int i = visit.codeCompileUnit.Namespaces.Count - 1; i >= 0; i--)
            {
                if (visit.codeCompileUnit.Namespaces[i].Types.Count == 0)
                {
                    visit.codeCompileUnit.Namespaces.RemoveAt(i);
                }
            }

            return(visit.codeCompileUnit);

            #endregion
        }
Esempio n. 47
0
        /// <summary>
        /// Loads all content from a folder hierarchy (overlaying anything already existing)
        /// </summary>
        /// <param name="project"></param>
        /// <param name="path"></param>
        public static void LoadFolder(DocProject project, string path)
        {
            // get all files within folder hierarchy
            string pathSchema         = path + @"\schemas";
            IEnumerable <string> en   = System.IO.Directory.EnumerateFiles(pathSchema, "*.cs", System.IO.SearchOption.AllDirectories);
            List <string>        list = new List <string>();

            foreach (string s in en)
            {
                list.Add(s);
            }
            string[] files = list.ToArray();

            Dictionary <string, string> options = new Dictionary <string, string> {
                { "CompilerVersion", "v4.0" }
            };

            Microsoft.CSharp.CSharpCodeProvider        prov  = new Microsoft.CSharp.CSharpCodeProvider(options);
            System.CodeDom.Compiler.CompilerParameters parms = new System.CodeDom.Compiler.CompilerParameters();
            parms.GenerateInMemory   = true;
            parms.GenerateExecutable = false;
            parms.ReferencedAssemblies.Add("System.dll");
            parms.ReferencedAssemblies.Add("System.Core.dll");
            parms.ReferencedAssemblies.Add("System.ComponentModel.dll");
            parms.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll");
            parms.ReferencedAssemblies.Add("System.Data.dll");
            parms.ReferencedAssemblies.Add("System.Runtime.Serialization.dll");
            parms.ReferencedAssemblies.Add("System.Xml.dll");

            System.CodeDom.Compiler.CompilerResults results = prov.CompileAssemblyFromFile(parms, files);
            System.Reflection.Assembly assem = results.CompiledAssembly;

            LoadAssembly(project, assem);

            // EXPRESS rules (eventually in C#, though .exp file snippets for now)
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.exp", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string name = Path.GetFileNameWithoutExtension(file);
                string expr = null;
                using (StreamReader readExpr = new StreamReader(file, Encoding.UTF8))
                {
                    if (name.Contains('-'))
                    {
                        // where rule
                        expr = readExpr.ReadToEnd();
                    }
                    else
                    {
                        // function: skip first and last lines
                        readExpr.ReadLine();

                        StringBuilder sbExpr = new StringBuilder();
                        while (!readExpr.EndOfStream)
                        {
                            string line = readExpr.ReadLine();
                            if (!readExpr.EndOfStream)
                            {
                                sbExpr.AppendLine(line);
                            }
                        }

                        expr = sbExpr.ToString();
                    }
                }

                if (name.Contains('-'))
                {
                    // where rule
                    string[] parts = name.Split('-');
                    if (parts.Length == 2)
                    {
                        DocWhereRule docWhere = new DocWhereRule();
                        docWhere.Name       = parts[1];
                        docWhere.Expression = expr;

                        DocDefinition docDef = project.GetDefinition(parts[0]);
                        if (docDef is DocEntity)
                        {
                            DocEntity docEnt = (DocEntity)docDef;
                            docEnt.WhereRules.Add(docWhere);
                        }
                        else if (docDef is DocDefined)
                        {
                            DocDefined docEnt = (DocDefined)docDef;
                            docEnt.WhereRules.Add(docWhere);
                        }
                        else if (docDef == null)
                        {
                            //... global rule...
                        }
                    }
                }
                else
                {
                    // function
                    string schema = Path.GetDirectoryName(file);
                    schema = Path.GetDirectoryName(schema);
                    schema = Path.GetFileName(schema);
                    DocSchema docSchema = project.GetSchema(schema);
                    if (docSchema != null)
                    {
                        DocFunction docFunction = new DocFunction();
                        docSchema.Functions.Add(docFunction);
                        docFunction.Name       = name;
                        docFunction.Expression = expr;
                    }
                }
            }

            // now, hook up html documentation
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.htm", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string    name   = Path.GetFileNameWithoutExtension(file);
                DocObject docObj = null;
                if (name == "schema")
                {
                    string schema = Path.GetDirectoryName(file);
                    schema = Path.GetFileName(schema);
                    docObj = project.GetSchema(schema);
                }
                else if (name.Contains('-'))
                {
                    // where rule
                    string[] parts = name.Split('-');
                    if (parts.Length == 2)
                    {
                        DocDefinition docDef = project.GetDefinition(parts[0]);
                        if (docDef is DocEntity)
                        {
                            DocEntity docEnt = (DocEntity)docDef;
                            foreach (DocWhereRule docWhereRule in docEnt.WhereRules)
                            {
                                if (docWhereRule.Name.Equals(parts[1]))
                                {
                                    docObj = docWhereRule;
                                    break;
                                }
                            }
                        }
                        else if (docDef is DocDefined)
                        {
                            DocDefined docEnt = (DocDefined)docDef;
                            foreach (DocWhereRule docWhereRule in docEnt.WhereRules)
                            {
                                if (docWhereRule.Name.Equals(parts[1]))
                                {
                                    docObj = docWhereRule;
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    docObj = project.GetDefinition(name);

                    if (docObj == null)
                    {
                        docObj = project.GetFunction(name);
                    }
                }

                if (docObj != null)
                {
                    using (StreamReader readHtml = new StreamReader(file, Encoding.UTF8))
                    {
                        docObj.Documentation = readHtml.ReadToEnd();
                    }
                }
            }

            // load schema diagrams
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.svg", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string schema = Path.GetDirectoryName(file);
                schema = Path.GetFileName(schema);

                DocSchema docSchema = project.GetSchema(schema);
                if (docSchema != null)
                {
                    using (IfcDoc.Schema.SVG.SchemaSVG schemaSVG = new IfcDoc.Schema.SVG.SchemaSVG(file, docSchema, project, DiagramFormat.UML))
                    {
                        schemaSVG.Load();
                    }
                }
            }

            // psets, qsets
            //...

            // exchanges
            en = System.IO.Directory.EnumerateFiles(path, "*.mvdxml", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                IfcDoc.Schema.MVD.SchemaMVD.Load(project, file);
            }

            // examples
            string pathExamples = path + @"\examples";

            if (Directory.Exists(pathExamples))
            {
                en = System.IO.Directory.EnumerateFiles(pathExamples, "*.htm", SearchOption.TopDirectoryOnly);
                foreach (string file in en)
                {
                    DocExample docExample = new DocExample();
                    docExample.Name = Path.GetFileNameWithoutExtension(file);
                    project.Examples.Add(docExample);

                    using (StreamReader reader = new StreamReader(file))
                    {
                        docExample.Documentation = reader.ReadToEnd();
                    }

                    string dirpath = file.Substring(0, file.Length - 4);
                    if (Directory.Exists(dirpath))
                    {
                        IEnumerable <string> suben = System.IO.Directory.EnumerateFiles(dirpath, "*.ifc", SearchOption.TopDirectoryOnly);
                        foreach (string ex in suben)
                        {
                            DocExample docEx = new DocExample();
                            docEx.Name = Path.GetFileNameWithoutExtension(ex);
                            docExample.Examples.Add(docEx);

                            // read the content of the file
                            using (FileStream fs = new FileStream(ex, FileMode.Open, FileAccess.Read))
                            {
                                docEx.File = new byte[fs.Length];
                                fs.Read(docEx.File, 0, docEx.File.Length);
                            }

                            // read documentation
                            string exdoc = ex.Substring(0, ex.Length - 4) + ".htm";
                            if (File.Exists(exdoc))
                            {
                                using (StreamReader reader = new StreamReader(exdoc))
                                {
                                    docEx.Documentation = reader.ReadToEnd();
                                }
                            }
                        }
                    }
                }
            }

            // localization
            en = System.IO.Directory.EnumerateFiles(path, "*.txt", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                using (FormatCSV format = new FormatCSV(file))
                {
                    try
                    {
                        format.Instance = project;
                        format.Load();
                    }
                    catch
                    {
                    }
                }
            }
        }
Esempio n. 48
0
        private void btnCompileRun_Click(object sender, EventArgs e)
        {
            string code = null;

            code += "using System;\r\n";
            code += "using TextIndex;\r\n";
            code += "using System.Collections;\r\n";

            code += "using System.Data;\r\n";
            code += "public class TestParser : SiteParser{ ";
            code += "    public override string Parse(HtmlDocument document) { ";
            code += "       " + textCode.Text;
            code += "    } ";
            code += "}";

            // CodeDOM'dan C# compiler'ı elde edelim
            Microsoft.CSharp.CSharpCodeProvider   cp = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.ICodeCompiler ic = cp.CreateCompiler();

            // compiler parametrelerini ayarlayalım
            System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();
            cpar.GenerateInMemory   = true;
            cpar.GenerateExecutable = false;
            cpar.ReferencedAssemblies.Add("system.dll");
            cpar.ReferencedAssemblies.Add("System.Drawing.dll");
            cpar.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cpar.ReferencedAssemblies.Add("System.Data.dll");
            cpar.ReferencedAssemblies.Add(Application.ExecutablePath);

            // kodu derletim ve sonuçları alalım
            System.CodeDom.Compiler.CompilerResults cr = ic.CompileAssemblyFromSource(cpar, code);

            // eğer derleme hatası varsa bu hataları bir bir gösterelim.
            foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
            {
                // hata mesajı, hatanın oluştuğu satır, önceki üç satır ve sonraki üç satırı içeren
                // bir hata mesajı hazırlayalım.
                string[] srcArr     = code.Split('\n');
                string   errMessage = ce.ErrorText + " at line " + (ce.Line - 1) + "\n\n";
                for (int i = ce.Line - 3; i < ce.Line + 3; i++)
                {
                    if (i < 0 || i >= srcArr.Length)
                    {
                        continue;
                    }
                    errMessage += i + " " + srcArr[i] + "\n";
                }
                // hatayı gösterelim
                MessageBox.Show(errMessage);

                return;
            }

            // kod hatasız derlendiyse test işlemlerine başlayalım.
            if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)
            {
                // test edilecek iki koda (sınıfa) ait tipleri elde edelim.
                Type type = cr.CompiledAssembly.GetType("TestParser");
                try
                {
                    SiteParser parser = (SiteParser)Activator.CreateInstance(type);
                    string     result = parser.Parse(document);
                    textBox2.Text = result;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Esempio n. 49
0
        public static void TestSpecific(string str, object[] result)
        {
            Protocol protocol = Protocol.Parse(str);
            var      codegen  = new CodeGen();

            codegen.AddProtocol(protocol);
            var compileUnit = codegen.GenerateCode();

            // add a constructor to the main class using the passed assignment statements
            CodeTypeDeclaration ctd         = compileUnit.Namespaces[0].Types[(int)result[0]];
            CodeConstructor     constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;
            CodeSnippetExpression snippet = new CodeSnippetExpression((string)result[2]);

            constructor.Statements.Add(snippet);
            ctd.Members.Add(constructor);

            // compile
            var comparam = new CompilerParameters(new string[] { "mscorlib.dll" });

            comparam.ReferencedAssemblies.Add("System.dll");
            comparam.ReferencedAssemblies.Add("System.Core.dll");
            comparam.ReferencedAssemblies.Add(Type.GetType("Mono.Runtime") != null ? "Mono.CSharp.dll" : "Microsoft.CSharp.dll");
            comparam.ReferencedAssemblies.Add("Avro.dll");
            comparam.GenerateInMemory = true;
            var ccp     = new Microsoft.CSharp.CSharpCodeProvider();
            var units   = new CodeCompileUnit[] { compileUnit };
            var compres = ccp.CompileAssemblyFromDom(comparam, units);

            if (compres == null || compres.Errors.Count > 0)
            {
                for (int i = 0; i < compres.Errors.Count; i++)
                {
                    Console.WriteLine(compres.Errors[i]);
                }
            }
            if (null != compres)
            {
                Assert.IsTrue(compres.Errors.Count == 0);
            }

            // create record
            ISpecificRecord rec = compres.CompiledAssembly.CreateInstance((string)result[1]) as ISpecificRecord;

            Assert.IsFalse(rec == null);

            // serialize
            var stream     = new MemoryStream();
            var binEncoder = new BinaryEncoder(stream);
            var writer     = new SpecificDefaultWriter(rec.Schema);

            writer.Write(rec.Schema, rec, binEncoder);

            // deserialize
            stream.Position = 0;
            var decoder = new BinaryDecoder(stream);
            var reader  = new SpecificDefaultReader(rec.Schema, rec.Schema);
            var rec2    = (ISpecificRecord)reader.Read(null, rec.Schema, rec.Schema, decoder);

            Assert.IsFalse(rec2 == null);
        }
Esempio n. 50
0
        public static object GetDbInfo(System.Data.DataSet ds)
        {
            // Get a code provider object.
            System.CodeDom.Compiler.CodeDomProvider cdp = new Microsoft.CSharp.CSharpCodeProvider();

            // Create the namespace and import the default "System" namespace.
            System.CodeDom.CodeNamespace nmspc = new System.CodeDom.CodeNamespace("DataExplorer");
            nmspc.Imports.Add(new System.CodeDom.CodeNamespaceImport("System"));
            nmspc.Imports.Add(new System.CodeDom.CodeNamespaceImport("System.ComponentModel"));

            // Create a class object.
            System.CodeDom.CodeTypeDeclaration clsDbInfo = new System.CodeDom.CodeTypeDeclaration("DbInfo");
            clsDbInfo.IsClass = true;
            nmspc.Types.Add(clsDbInfo);

            // Add fields to the class for each value returned.
            List <string> fldNms = new List <string>();

            for (int i = 0; i < ds.Tables.Count; i++)
            {
                for (int j = 0; j < ds.Tables[i].Columns.Count; j++)
                {
                    string fldNm = "_" + ds.Tables[i].Columns[j].ColumnName.ToLower();
                    if (!fldNms.Contains(fldNm))
                    {
                        System.CodeDom.CodeMemberField fld = new System.CodeDom.CodeMemberField(typeof(System.String), fldNm);
                        fld.Attributes = System.CodeDom.MemberAttributes.Public;
                        clsDbInfo.Members.Add(fld);
                        fldNms.Add(fldNm);
                    }
                }
            }

            // Add properties for the class to access each field.
            List <string> propNms = new List <string>();

            for (int i = 0; i < ds.Tables.Count; i++)
            {
                for (int j = 0; j < ds.Tables[i].Columns.Count; j++)
                {
                    string
                        fldNm  = "_" + ds.Tables[i].Columns[j].ColumnName.ToLower(),
                        propNm = ds.Tables[i].Columns[j].ColumnName;

                    if (!propNms.Contains(propNm))
                    {
                        System.CodeDom.CodeMemberProperty prop = new System.CodeDom.CodeMemberProperty();
                        prop.Attributes = System.CodeDom.MemberAttributes.Public;
                        prop.Name       = propNm;
                        prop.Type       = new System.CodeDom.CodeTypeReference(typeof(System.String));
                        System.CodeDom.CodeVariableReferenceExpression retExp    = new System.CodeDom.CodeVariableReferenceExpression(fldNm);
                        System.CodeDom.CodeMethodReturnStatement       getReturn = new System.CodeDom.CodeMethodReturnStatement(retExp);
                        prop.GetStatements.Add(getReturn);
                        prop.HasGet = true;
                        prop.HasSet = false;
                        string catName = (ds.Tables[i].TableName.EndsWith("1")) ? "File Group" : "Database";
                        System.CodeDom.CodeAttributeDeclaration attrCat = new System.CodeDom.CodeAttributeDeclaration("Category", new System.CodeDom.CodeAttributeArgument(new System.CodeDom.CodePrimitiveExpression(catName)));
                        prop.CustomAttributes.Add(attrCat);
                        // Add the property to our class.
                        clsDbInfo.Members.Add(prop);
                        propNms.Add(propNm);
                    }
                }
            }

            // Add a constructor to the class
            System.CodeDom.CodeConstructor clsDbInfoConstr = new System.CodeDom.CodeConstructor();
            clsDbInfoConstr.Attributes = System.CodeDom.MemberAttributes.Public;
            clsDbInfo.Members.Add(clsDbInfoConstr);

            // Create a CompileUnit for this new type.
            System.CodeDom.CodeCompileUnit cu = new System.CodeDom.CodeCompileUnit();
            cu.ReferencedAssemblies.Add("system.dll");
            cu.Namespaces.Add(nmspc);

            // Now, we're ready to generate some code!
#if DEBUG
            // If we're running in DEBUG mode, I want to see the generated code.
            using (System.IO.FileStream fs = new System.IO.FileStream("dbinfo.cs", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                using (System.IO.StreamWriter sr = new System.IO.StreamWriter(fs))
                    cdp.GenerateCodeFromCompileUnit(cu, sr, null);
#endif
            System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters();
            cp.ReferencedAssemblies.Add("system.dll");
            cp.GenerateExecutable      = false;
            cp.IncludeDebugInformation = false;
            cp.GenerateInMemory        = false;
            //cp.OutputAssembly = _outputName;
            System.CodeDom.Compiler.CompilerResults cr = cdp.CompileAssemblyFromDom(cp, cu);

            if (!cr.Errors.HasErrors)
            {
                System.Reflection.Assembly asm = cr.CompiledAssembly;
                object dbInfo = asm.CreateInstance("DataExplorer.DbInfo");
                return(dbInfo);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 51
0
        public static void TestSpecific(string str, object[] result)
        {
            Protocol protocol = Protocol.Parse(str);
            var      codegen  = new CodeGen();

            codegen.AddProtocol(protocol);
            var compileUnit = codegen.GenerateCode();

            // add a constructor to the main class using the passed assignment statements
            CodeTypeDeclaration ctd         = compileUnit.Namespaces[0].Types[(int)result[0]];
            CodeConstructor     constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;
            CodeSnippetExpression snippet = new CodeSnippetExpression((string)result[2]);

            constructor.Statements.Add(snippet);
            ctd.Members.Add(constructor);

            // add a function to the main class to populate the data
            // This has been moved from constructor, as it was causing some tests to pass that shouldn't when referencing a blank object on READ.

            CodeMemberMethod method = new CodeMemberMethod();

            method.Attributes = MemberAttributes.Public;
            method.Name       = "Populate";
            CodeSnippetExpression snippet2 = new CodeSnippetExpression((string)result[3]);

            method.Statements.Add(snippet2);
            ctd.Members.Add(method);



            // compile
            var comparam = new CompilerParameters(new string[] { "mscorlib.dll" });

            comparam.ReferencedAssemblies.Add("System.dll");
            comparam.ReferencedAssemblies.Add("Avro.dll");
            comparam.GenerateInMemory = true;
            var ccp     = new Microsoft.CSharp.CSharpCodeProvider();
            var units   = new CodeCompileUnit[] { compileUnit };
            var compres = ccp.CompileAssemblyFromDom(comparam, units);

            if (compres == null || compres.Errors.Count > 0)
            {
                for (int i = 0; i < compres.Errors.Count; i++)
                {
                    Console.WriteLine(compres.Errors[i]);
                }
            }
            if (null != compres)
            {
                Assert.IsTrue(compres.Errors.Count == 0);
            }

            // create record
            ISpecificRecord rec = compres.CompiledAssembly.CreateInstance((string)result[1]) as ISpecificRecord;

            // Call populate to put some data in it.
            Type       recType    = rec.GetType();;
            MethodInfo methodInfo = recType.GetMethod("Populate");

            methodInfo.Invoke(rec, null);

            var x1 = compres.CompiledAssembly.FullName;

            Assert.IsFalse(rec == null);

            // serialize
            var stream     = new MemoryStream();
            var binEncoder = new BinaryEncoder(stream);
            var writer     = new SpecificDefaultWriter(rec.Schema);

            writer.Write(rec.Schema, rec, binEncoder);

            // deserialize
            stream.Position = 0;
            var decoder = new BinaryDecoder(stream);
            var reader  = new SpecificDefaultReader(rec.Schema, rec.Schema);
            var rec2    = (ISpecificRecord)reader.Read(null, rec.Schema, rec.Schema, decoder);

            Assert.IsFalse(rec2 == null);
        }
Esempio n. 52
0
        /// <summary>
        /// Loads all content from a folder hierarchy (overlaying anything already existing)
        /// </summary>
        /// <param name="project"></param>
        /// <param name="path"></param>
        public static void Load(DocProject project, string path)
        {
            // get all files within folder hierarchy
            string pathSchema         = path + @"\schemas";
            IEnumerable <string> en   = System.IO.Directory.EnumerateFiles(pathSchema, "*.cs", System.IO.SearchOption.AllDirectories);
            List <string>        list = new List <string>();

            foreach (string s in en)
            {
                list.Add(s);
            }
            string[] files = list.ToArray();

            Dictionary <string, string> options = new Dictionary <string, string> {
                { "CompilerVersion", "v4.0" }
            };

            Microsoft.CSharp.CSharpCodeProvider        prov  = new Microsoft.CSharp.CSharpCodeProvider(options);
            System.CodeDom.Compiler.CompilerParameters parms = new System.CodeDom.Compiler.CompilerParameters();
            parms.GenerateInMemory   = true;
            parms.GenerateExecutable = false;
            parms.ReferencedAssemblies.Add("System.dll");
            parms.ReferencedAssemblies.Add("System.Core.dll");
            parms.ReferencedAssemblies.Add("System.ComponentModel.dll");
            parms.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll");
            parms.ReferencedAssemblies.Add("System.Data.dll");
            parms.ReferencedAssemblies.Add("System.Runtime.Serialization.dll");
            parms.ReferencedAssemblies.Add("System.Xml.dll");

            System.CodeDom.Compiler.CompilerResults results = prov.CompileAssemblyFromFile(parms, files);
            System.Reflection.Assembly assem = results.CompiledAssembly;

            // look through classes of assembly
            foreach (Type t in assem.GetTypes())
            {
                string[]   namespaceparts = t.Namespace.Split('.');
                string     schema         = namespaceparts[namespaceparts.Length - 1];
                DocSection docSection     = null;
                if (t.Namespace.EndsWith("Resource"))
                {
                    docSection = project.Sections[7];
                }
                else if (t.Namespace.EndsWith("Domain"))
                {
                    docSection = project.Sections[6];
                }
                else if (t.Namespace.Contains("Shared"))
                {
                    docSection = project.Sections[5];
                }
                else
                {
                    docSection = project.Sections[4]; // kernel, extensions
                }

                // find schema
                DocSchema docSchema = null;
                foreach (DocSchema docEachSchema in docSection.Schemas)
                {
                    if (docEachSchema.Name.Equals(schema))
                    {
                        docSchema = docEachSchema;
                        break;
                    }
                }

                if (docSchema == null)
                {
                    docSchema      = new DocSchema();
                    docSchema.Name = schema;
                    docSection.Schemas.Add(docSchema);
                    docSection.SortSchemas();
                }

                DocDefinition docDef = null;
                if (t.IsEnum)
                {
                    DocEnumeration docEnum = new DocEnumeration();
                    docSchema.Types.Add(docEnum);
                    docDef = docEnum;

                    System.Reflection.FieldInfo[] fields = t.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                    foreach (System.Reflection.FieldInfo field in fields)
                    {
                        DocConstant docConst = new DocConstant();
                        docEnum.Constants.Add(docConst);
                        docConst.Name = field.Name;

                        DescriptionAttribute[] attrs = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                        if (attrs.Length == 1)
                        {
                            docConst.Documentation = attrs[0].Description;
                        }
                    }
                }
                else if (t.IsValueType)
                {
                    DocDefined docDefined = new DocDefined();
                    docSchema.Types.Add(docDefined);
                    docDef = docDefined;

                    PropertyInfo[] fields = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                    docDefined.DefinedType = fields[0].PropertyType.Name;
                }
                else if (t.IsInterface)
                {
                    DocSelect docSelect = new DocSelect();
                    docSchema.Types.Add(docSelect);
                    docDef = docSelect;
                }
                else if (t.IsClass)
                {
                    DocEntity docEntity = new DocEntity();
                    docSchema.Entities.Add(docEntity);
                    docDef = docEntity;

                    if (t.BaseType != typeof(object))
                    {
                        docEntity.BaseDefinition = t.BaseType.Name;
                    }

                    if (!t.IsAbstract)
                    {
                        docEntity.EntityFlags = 0x20;
                    }

                    Dictionary <int, DocAttribute> attrsDirect  = new Dictionary <int, DocAttribute>();
                    List <DocAttribute>            attrsInverse = new List <DocAttribute>();
                    PropertyInfo[] fields = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
                    foreach (PropertyInfo field in fields)
                    {
                        DocAttribute docAttr = new DocAttribute();
                        docAttr.Name = field.Name.Substring(1);

                        Type typeField = field.PropertyType;
                        if (typeField.IsGenericType)
                        {
                            Type typeGeneric = typeField.GetGenericTypeDefinition();
                            typeField = typeField.GetGenericArguments()[0];
                            if (typeGeneric == typeof(Nullable <>))
                            {
                                docAttr.IsOptional = true;
                            }
                            else if (typeGeneric == typeof(ISet <>))
                            {
                                docAttr.AggregationType = (int)DocAggregationEnum.SET;
                            }
                            else if (typeGeneric == typeof(IList <>))
                            {
                                docAttr.AggregationType = (int)DocAggregationEnum.LIST;
                            }
                        }

                        docAttr.DefinedType = typeField.Name;


                        MinLengthAttribute mla = (MinLengthAttribute)field.GetCustomAttribute(typeof(MinLengthAttribute));
                        if (mla != null)
                        {
                            docAttr.AggregationLower = mla.Length.ToString();
                        }

                        MaxLengthAttribute mxa = (MaxLengthAttribute)field.GetCustomAttribute(typeof(MaxLengthAttribute));
                        if (mxa != null)
                        {
                            docAttr.AggregationUpper = mxa.Length.ToString();
                        }

                        PropertyInfo propinfo = t.GetProperty(docAttr.Name);
                        if (propinfo != null)
                        {
                            DescriptionAttribute da = (DescriptionAttribute)propinfo.GetCustomAttribute(typeof(DescriptionAttribute));
                            if (da != null)
                            {
                                docAttr.Documentation = da.Description;
                            }
                        }

                        DataMemberAttribute dma = (DataMemberAttribute)field.GetCustomAttribute(typeof(DataMemberAttribute));
                        if (dma != null)
                        {
                            attrsDirect.Add(dma.Order, docAttr);

                            RequiredAttribute rqa = (RequiredAttribute)field.GetCustomAttribute(typeof(RequiredAttribute));
                            if (rqa == null)
                            {
                                docAttr.IsOptional = true;
                            }

                            CustomValidationAttribute cva = (CustomValidationAttribute)field.GetCustomAttribute(typeof(CustomValidationAttribute));
                            if (cva != null)
                            {
                                docAttr.IsUnique = true;
                            }
                        }
                        else
                        {
                            InversePropertyAttribute ipa = (InversePropertyAttribute)field.GetCustomAttribute(typeof(InversePropertyAttribute));
                            if (ipa != null)
                            {
                                docAttr.Inverse = ipa.Property;
                                attrsInverse.Add(docAttr);
                            }
                        }

                        // xml
                        XmlIgnoreAttribute xia = (XmlIgnoreAttribute)field.GetCustomAttribute(typeof(XmlIgnoreAttribute));
                        if (xia != null)
                        {
                            docAttr.XsdFormat = DocXsdFormatEnum.Hidden;
                        }
                        else
                        {
                            XmlElementAttribute xea = (XmlElementAttribute)field.GetCustomAttribute(typeof(XmlElementAttribute));
                            if (xea != null)
                            {
                                if (!String.IsNullOrEmpty(xea.ElementName))
                                {
                                    docAttr.XsdFormat = DocXsdFormatEnum.Element;
                                }
                                else
                                {
                                    docAttr.XsdFormat = DocXsdFormatEnum.Attribute;
                                }
                            }
                        }
                    }

                    foreach (DocAttribute docAttr in attrsDirect.Values)
                    {
                        docEntity.Attributes.Add(docAttr);
                    }

                    foreach (DocAttribute docAttr in attrsInverse)
                    {
                        docEntity.Attributes.Add(docAttr);
                    }

                    // get derived attributes based on properties
                    PropertyInfo[] props = t.GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
                    foreach (PropertyInfo prop in props)
                    {
                        // if no backing field, then derived
                        FieldInfo field = t.GetField("_" + prop.Name, BindingFlags.NonPublic | BindingFlags.Instance);
                        if (field == null)
                        {
                            DocAttribute docDerived = new DocAttribute();
                            docDerived.Name = prop.Name;
                            docEntity.Attributes.Add(docDerived);
                        }
                    }
                }

                if (docDef != null)
                {
                    docDef.Name = t.Name;
                    docDef.Uuid = t.GUID;
                }

                docSchema.SortTypes();
                docSchema.SortEntities();
            }

            // pass 2: hook up selects
            foreach (Type t in assem.GetTypes())
            {
                Type[] typeInterfaces = t.GetInterfaces();
                if (typeInterfaces.Length > 0)
                {
                    foreach (Type typeI in typeInterfaces)
                    {
                        DocSelect docSelect = project.GetDefinition(typeI.Name) as DocSelect;
                        if (docSelect != null)
                        {
                            DocSelectItem docItem = new DocSelectItem();
                            docItem.Name = t.Name;
                            docSelect.Selects.Add(docItem);
                        }
                    }
                }
            }

            // EXPRESS rules (eventually in C#, though .exp file snippets for now)
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.exp", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string name = Path.GetFileNameWithoutExtension(file);
                string expr = null;
                using (StreamReader readExpr = new StreamReader(file, Encoding.UTF8))
                {
                    expr = readExpr.ReadToEnd();
                }

                if (name.Contains('-'))
                {
                    // where rule
                    string[] parts = name.Split('-');
                    if (parts.Length == 2)
                    {
                        DocWhereRule docWhere = new DocWhereRule();
                        docWhere.Name       = parts[1];
                        docWhere.Expression = expr;

                        DocDefinition docDef = project.GetDefinition(parts[0]);
                        if (docDef is DocEntity)
                        {
                            DocEntity docEnt = (DocEntity)docDef;
                            docEnt.WhereRules.Add(docWhere);
                        }
                        else if (docDef is DocDefined)
                        {
                            DocDefined docEnt = (DocDefined)docDef;
                            docEnt.WhereRules.Add(docWhere);
                        }
                        else if (docDef == null)
                        {
                            //... global rule...
                        }
                    }
                }
                else
                {
                    // function
                    string schema = Path.GetDirectoryName(file);
                    schema = Path.GetDirectoryName(schema);
                    schema = Path.GetFileName(schema);
                    DocSchema docSchema = project.GetSchema(schema);
                    if (docSchema != null)
                    {
                        DocFunction docFunction = new DocFunction();
                        docSchema.Functions.Add(docFunction);
                        docFunction.Name       = name;
                        docFunction.Expression = expr;
                    }
                }
            }

            // now, hook up html documentation
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.htm", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string    name   = Path.GetFileNameWithoutExtension(file);
                DocObject docObj = null;
                if (name == "schema")
                {
                    string schema = Path.GetDirectoryName(file);
                    schema = Path.GetFileName(schema);
                    docObj = project.GetSchema(schema);
                }
                else if (name.Contains('-'))
                {
                    // where rule
                    string[] parts = name.Split('-');
                    if (parts.Length == 2)
                    {
                        DocDefinition docDef = project.GetDefinition(parts[0]);
                        if (docDef is DocEntity)
                        {
                            DocEntity docEnt = (DocEntity)docDef;
                            foreach (DocWhereRule docWhereRule in docEnt.WhereRules)
                            {
                                if (docWhereRule.Name.Equals(parts[1]))
                                {
                                    docObj = docWhereRule;
                                    break;
                                }
                            }
                        }
                        else if (docDef is DocDefined)
                        {
                            DocDefined docEnt = (DocDefined)docDef;
                            foreach (DocWhereRule docWhereRule in docEnt.WhereRules)
                            {
                                if (docWhereRule.Name.Equals(parts[1]))
                                {
                                    docObj = docWhereRule;
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    docObj = project.GetDefinition(name);

                    if (docObj == null)
                    {
                        docObj = project.GetFunction(name);
                    }
                }

                if (docObj != null)
                {
                    using (StreamReader readHtml = new StreamReader(file, Encoding.UTF8))
                    {
                        docObj.Documentation = readHtml.ReadToEnd();
                    }
                }
            }

            // load schema diagrams
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.svg", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string schema = Path.GetDirectoryName(file);
                schema = Path.GetFileName(schema);

                DocSchema docSchema = project.GetSchema(schema);
                if (docSchema != null)
                {
                    using (IfcDoc.Schema.SVG.SchemaSVG schemaSVG = new IfcDoc.Schema.SVG.SchemaSVG(file, docSchema, project))
                    {
                        schemaSVG.Load();
                    }
                }
            }

            // psets, qsets
            //...

            // exchanges
            en = System.IO.Directory.EnumerateFiles(path, "*.mvdxml", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                IfcDoc.Schema.MVD.SchemaMVD.Load(project, file);
            }

            // examples
            string pathExamples = path + @"\examples";

            if (Directory.Exists(pathExamples))
            {
                en = System.IO.Directory.EnumerateFiles(pathExamples, "*.htm", SearchOption.TopDirectoryOnly);
                foreach (string file in en)
                {
                    DocExample docExample = new DocExample();
                    docExample.Name = Path.GetFileNameWithoutExtension(file);
                    project.Examples.Add(docExample);

                    using (StreamReader reader = new StreamReader(file))
                    {
                        docExample.Documentation = reader.ReadToEnd();
                    }

                    string dirpath = file.Substring(0, file.Length - 4);
                    if (Directory.Exists(dirpath))
                    {
                        IEnumerable <string> suben = System.IO.Directory.EnumerateFiles(dirpath, "*.ifc", SearchOption.TopDirectoryOnly);
                        foreach (string ex in suben)
                        {
                            DocExample docEx = new DocExample();
                            docEx.Name = Path.GetFileNameWithoutExtension(ex);
                            docExample.Examples.Add(docEx);

                            // read the content of the file
                            using (FileStream fs = new FileStream(ex, FileMode.Open, FileAccess.Read))
                            {
                                docEx.File = new byte[fs.Length];
                                fs.Read(docEx.File, 0, docEx.File.Length);
                            }

                            // read documentation
                            string exdoc = ex.Substring(0, ex.Length - 4) + ".htm";
                            if (File.Exists(exdoc))
                            {
                                using (StreamReader reader = new StreamReader(exdoc))
                                {
                                    docEx.Documentation = reader.ReadToEnd();
                                }
                            }
                        }
                    }
                }
            }

            // localization
            en = System.IO.Directory.EnumerateFiles(path, "*.txt", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                using (FormatCSV format = new FormatCSV(file))
                {
                    try
                    {
                        format.Instance = project;
                        format.Load();
                    }
                    catch
                    {
                    }
                }
            }
        }
Esempio n. 53
0
        private static Assembly CompileStrings(
            string[] src,
            string[] referenceAssemblies,
            bool toAssembly,
            string outputAssemblyPath,
            out string errors
            )
        {
            var cpar = new System.CodeDom.Compiler.CompilerParameters()
            {
                GenerateInMemory = !toAssembly,
                OutputAssembly   = outputAssemblyPath,
            };

            // Add default references...
            cpar.ReferencedAssemblies.Add(typeof(System.Activities.Activity).Assembly.Location);
            cpar.ReferencedAssemblies.Add(typeof(System.CodeDom.Compiler.CodeCompiler).Assembly.Location);
            cpar.ReferencedAssemblies.Add(typeof(PSObject).Assembly.Location);
            cpar.ReferencedAssemblies.Add(typeof(Microsoft.PowerShell.Activities.PSActivity).Assembly.Location);
            cpar.ReferencedAssemblies.Add(ResolveReferencedAssembly("Microsoft.Management.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
            cpar.ReferencedAssemblies.Add(ResolveReferencedAssembly("Microsoft.PowerShell.Commands.Management, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));

            // Add user supplied references...
            if (referenceAssemblies != null)
            {
                foreach (string asm in referenceAssemblies)
                {
                    cpar.ReferencedAssemblies.Add(ResolveReferencedAssembly(asm));
                }
            }

            var compiler = new Microsoft.CSharp.CSharpCodeProvider();
            var cr       = compiler.CompileAssemblyFromSource(cpar, src);

            if (cr.Errors == null || cr.Errors.Count == 0)
            {
                errors = string.Empty;
            }
            else
            {
                StringBuilder errorBuilder = new StringBuilder();
                foreach (var err in cr.Errors)
                {
                    errorBuilder.Append(err.ToString());
                    errorBuilder.Append('\n');
                }

                errors = errorBuilder.ToString();
            }

            if (errors.Length > 0)
            {
                return(null);
            }

            // If the assembly was written to disk, return null
            // since we don't want to load the assembly we've just created.
            if (toAssembly)
            {
                return(null);
            }
            else
            {
                return(cr.CompiledAssembly);
            }
        }