當前位置: 首頁>>代碼示例>>C#>>正文


C# CSharp.CSharpCodeProvider類代碼示例

本文整理匯總了C#中Microsoft.CSharp.CSharpCodeProvider的典型用法代碼示例。如果您正苦於以下問題:C# CSharpCodeProvider類的具體用法?C# CSharpCodeProvider怎麽用?C# CSharpCodeProvider使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


CSharpCodeProvider類屬於Microsoft.CSharp命名空間,在下文中一共展示了CSharpCodeProvider類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: init

 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;
 }
開發者ID:Tony-Liang,項目名稱:Common,代碼行數:27,代碼來源:CSharpBuilder.cs

示例2: Compile

        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);
        }
開發者ID:contactsamie,項目名稱:FunUnit,代碼行數:26,代碼來源:DynaInvoke.cs

示例3: CompileFile

        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;
            }
        }
開發者ID:eslahi,項目名稱:prism,代碼行數:28,代碼來源:CompilerHelper.Desktop.cs

示例4: CompileSiteModels

        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);
            }
        }
開發者ID:dancecoder,項目名稱:NStag-Web-Framework,代碼行數:25,代碼來源:NHibernateModelCompiller.cs

示例5: InvokeWebService

        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));
            }
        }
開發者ID:SLSoft,項目名稱:GGZBTQPT,代碼行數:60,代碼來源:WebServiceProxy.cs

示例6: Compile

        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;
        }
開發者ID:hal1932,項目名稱:cstest,代碼行數:34,代碼來源:Compiler.cs

示例7: ExecuteScript

        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;
        }
開發者ID:chrishensel,項目名稱:ezNReporting,代碼行數:27,代碼來源:CSharpScriptingProvider.cs

示例8: OutputAssembly

        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);
            }
        }
開發者ID:modulexcite,項目名稱:Tx,代碼行數:31,代碼來源:AssemblyBuilder.cs

示例9: UpdateSource

        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();
        }
開發者ID:dermeister0,項目名稱:helix-toolkit,代碼行數:32,代碼來源:DynamicSurface3D.cs

示例10: PrimitiveLiteral

 /// <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();
 }
開發者ID:ChrisFulstow,項目名稱:CSharpCodeGen,代碼行數:11,代碼來源:CodeGenerator.cs

示例11: CompileLegacy

		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();
			}
		}
開發者ID:arkanoid1,項目名稱:dnSpy,代碼行數:27,代碼來源:DecompilerTestBase.cs

示例12: Compile

        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());
        }
開發者ID:BryanApellanes,項目名稱:Naizari,代碼行數:26,代碼來源:CompileHelper.cs

示例13: GenerateHelper

		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);
						}
				}
			}
		}
開發者ID:rsdn,項目名稱:janus,代碼行數:26,代碼來源:MainForm.cs

示例14: ParseAndCompileTemplate

        /// <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;
        }
開發者ID:jhosm,項目名稱:BlissInSoftware.Sandcastle,代碼行數:42,代碼來源:RazorEngineHostWrapper.cs

示例15: Expression

 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");
 }
開發者ID:rivernli,項目名稱:SGP,代碼行數:30,代碼來源:Expression.cs


注:本文中的Microsoft.CSharp.CSharpCodeProvider類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。