GenerateCodeFromNamespace() public method

public GenerateCodeFromNamespace ( CodeNamespace codeNamespace, TextWriter writer, CodeGeneratorOptions options ) : void
codeNamespace CodeNamespace
writer System.IO.TextWriter
options CodeGeneratorOptions
return void
コード例 #1
0
ファイル: SpecFlowGenerator.cs プロジェクト: x97mdr/SpecFlow
        public void GenerateTestFile(SpecFlowFeatureFile featureFile, CodeDomProvider codeProvider, TextReader inputReader, TextWriter outputWriter)
        {
            outputWriter = new HackedWriter(outputWriter);

            var codeNamespace = GenerateTestFileCode(featureFile, inputReader);
            var options = new CodeGeneratorOptions
                {
                    BracingStyle = "C"
                };

            AddSpecFlowHeader(codeProvider, outputWriter);
            codeProvider.GenerateCodeFromNamespace(codeNamespace, outputWriter, options);
            outputWriter.Flush();
        }
コード例 #2
0
        public void GenerateTestFile(FeatureFileInput featureFile, CodeDomProvider codeProvider, TextReader inputReader, TextWriter outputWriter)
        {
            outputWriter = new IndentProcessingWriter(outputWriter);

            CodeDomHelper codeDomHelper = new CodeDomHelper(codeProvider);

            var codeNamespace = GenerateTestFileCode(featureFile, inputReader, codeProvider, codeDomHelper);
            var options = new CodeGeneratorOptions
                {
                    BracingStyle = "C"
                };

            AddSpecFlowHeader(codeProvider, outputWriter, codeDomHelper);
            codeProvider.GenerateCodeFromNamespace(codeNamespace, outputWriter, options);
            AddSpecFlowFooter(codeProvider, outputWriter, codeDomHelper);
            outputWriter.Flush();
        }
コード例 #3
0
		private void GenerateTestCase(CodeDomProvider provider, string extension, string ns, string name, string area, 
			string[] actions, TextWriter output)
		{
			CodeNamespace nsunit = GenerateControllerTestCode(ns, name, area, actions);

			FileInfo controllerFile = new FileInfo( 
				Path.Combine(testsDir.FullName, name + "Tests" + extension) );

			if (!controllerFile.Exists)
			{
				using (StreamWriter sw = new StreamWriter(controllerFile.FullName, false, Encoding.Default))
				{
					CodeGeneratorOptions opts = new CodeGeneratorOptions();
					opts.BracingStyle = "C";
#if DOTNET2
					provider.GenerateCodeFromNamespace(nsunit, sw, opts);
#else
					provider.CreateGenerator().GenerateCodeFromNamespace(nsunit, sw, opts);
#endif
				}
			}
			else
			{
				output.WriteLine("Skipping {0} as the files exists", controllerFile.FullName);
			}
		}
コード例 #4
0
ファイル: Template.cs プロジェクト: g992com/esb
        private static String ConstructGeneratorCode(TemplateItem item, Boolean lineNumbers, String namespaceName, CodeDomProvider provider)
        {
            // 准备类名和命名空间
            CodeNamespace codeNamespace = new CodeNamespace(namespaceName);

            // 加入引用的命名空间
            foreach (String str in item.Imports)
            {
                if (!String.IsNullOrEmpty(str)) codeNamespace.Imports.Add(new CodeNamespaceImport(str));
            }
            CodeTypeDeclaration typeDec = new CodeTypeDeclaration(item.ClassName);
            typeDec.IsClass = true;
            codeNamespace.Types.Add(typeDec);

            // 基类
            if (!String.IsNullOrEmpty(item.BaseClassName))
                typeDec.BaseTypes.Add(new CodeTypeReference(item.BaseClassName));
            else if (!String.IsNullOrEmpty(BaseClassName))
                typeDec.BaseTypes.Add(new CodeTypeReference(BaseClassName));
            else
                typeDec.BaseTypes.Add(new CodeTypeReference(typeof(TemplateBase)));

            if (!String.IsNullOrEmpty(item.Name)) typeDec.LinePragma = new CodeLinePragma(item.Name, 1);

            // Render方法
            CreateRenderMethod(item.Blocks, lineNumbers, typeDec);

            // 代码生成选项
            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.VerbatimOrder = true;
            options.BlankLinesBetweenMembers = false;
            options.BracingStyle = "C";

            // 其它类成员代码块
            Boolean firstMemberFound = false;
            foreach (Block block in item.Blocks)
            {
                firstMemberFound = GenerateMemberForBlock(block, typeDec, lineNumbers, provider, options, firstMemberFound);
            }

            // 模版变量
            if (item.Vars != null && item.Vars.Count > 0)
            {
                // 构建静态构造函数,初始化静态属性Vars
                CreateCctorMethod(typeDec, item.Vars);

                //public Int32 VarName
                //{
                //    get { return (Int32)GetData("VarName"); }
                //    set { Data["VarName"] = value; }
                //}
                foreach (String v in item.Vars.Keys)
                {
                    TypeX vtype = TypeX.Create(item.Vars[v]);
                    String codeName = vtype.FullName;

                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.AppendFormat("public {0} {1}", codeName, v);
                    sb.AppendLine("{");
                    sb.AppendFormat("    get {{ return GetData<{0}>(\"{1}\"); }}", codeName, v);
                    sb.AppendLine();
                    sb.AppendFormat("    set {{ Data[\"{0}\"] = value; }}", v);
                    sb.AppendLine();
                    sb.AppendLine("}");

                    CodeSnippetTypeMember member = new CodeSnippetTypeMember(sb.ToString());
                    typeDec.Members.Add(member);
                }
            }

            // 输出
            using (StringWriter writer = new StringWriter())
            {
                provider.GenerateCodeFromNamespace(codeNamespace, new IndentedTextWriter(writer), options);
                return writer.ToString();
            }
        }
コード例 #5
0
        /// <summary>
        /// Generates source code from given namespace.
        /// </summary>
        private static string GenerateFromNamespace(CodeDomProvider codeProvider, System.CodeDom.CodeNamespace codeNamespace, bool blankLinesBetweenMembers)
        {
            var result = new StringBuilder();
            var writer = new StringWriter(result);

            var options = new CodeGeneratorOptions();
            options.BlankLinesBetweenMembers = blankLinesBetweenMembers;
            options.ElseOnClosing = true;
            options.VerbatimOrder = true;
            options.BracingStyle = "C";

            // generate the code:
            codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, options);

            // send it to the StringBuilder object:
            writer.Flush();

            return result.ToString();
        }
コード例 #6
0
        /// <summary>
        /// Build the assembly using CodeDom.
        /// </summary>
        /// <param name="compiler">instance of compiler</param>
        /// <param name="localVars">string with local variable declarations, generated from expression</param> 
        /// <param name="expression">expression to be compiled</param>
        /// <param name="variables">types of values in this dictionary determine local variable types</param>
        /// <param name="returnsBool">should be true if the expression must return a boolean</param>
        /// <returns>C# source</returns>
        private static string BuildSource(CodeDomProvider compiler, string localVars, string expression, Dictionary<string, object> variables, bool returnsBool)
        {
            var sw = new StringWriter();

            var ns = new CodeNamespace("ExpressionEvaluator");
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            ns.Imports.Add(new CodeNamespaceImport("Imarda.Lib"));
            ns.Imports.Add(new CodeNamespaceImport("IXLCompiler"));

            var decl = new CodeTypeDeclaration("Calculator") { IsClass = true, Attributes = MemberAttributes.Public };

            var method = new CodeMemberMethod { Name = "Evaluate" };
            method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(Dictionary<string, object>)), "args"));
            method.ReturnType = new CodeTypeReference(returnsBool ? typeof(bool) : typeof(object));
            method.Comments.Add(new CodeCommentStatement("Calculate an expression", true));
            method.Attributes = MemberAttributes.Public;

            var stmt = method.Statements;
            foreach (var key in variables.Keys)
            {
                // only generate local variable decl/assignment if the variable occurs on the expression
                if (Regex.IsMatch(expression, @"\b" + Regex.Escape(key) + @"\b"))
                {
                    object obj = variables[key];
                    Type type = obj == null ? typeof(string) : obj.GetType();
                    var vardecl = string.Format("{0} {1} = args.ContainsKey(\"{1}\") ? ({0})(args[\"{1}\"]) : default({0})", type, key);
                    stmt.Add(new CodeSnippetExpression(vardecl));

                }
            }
            if (!string.IsNullOrEmpty(localVars)) stmt.Add(new CodeSnippetStatement(localVars));
            stmt.Add(new CodeSnippetStatement("#line 1"));
            stmt.Add(new CodeAssignStatement(new CodeSnippetExpression(returnsBool ? "bool result" : "object result"), new CodeSnippetExpression(expression)));
            stmt.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("result")));
            decl.Members.Add(method);
            ns.Types.Add(decl);
            compiler.GenerateCodeFromNamespace(ns, sw, new CodeGeneratorOptions
            {
                IndentString = "\t",
                BlankLinesBetweenMembers = false
            });
            sw.Close();
            return sw.ToString();
        }
コード例 #7
0
ファイル: CodeGenerationTests.cs プロジェクト: dotnet/corefx
        private static string GenerateCode(CodeObject c, CodeDomProvider provider)
        {
            var sb = new StringBuilder();
            var writer = new StringWriter(sb);
            var options = new CodeGeneratorOptions();

            if (c is CodeStatement)
            {
                provider.GenerateCodeFromStatement((CodeStatement)c, writer, options);
            }
            else if (c is CodeCompileUnit)
            {
                provider.GenerateCodeFromCompileUnit((CodeCompileUnit)c, writer, options);
            }
            else if (c is CodeExpression)
            {
                provider.GenerateCodeFromExpression((CodeExpression)c, writer, options);
            }
            else if (c is CodeTypeMember)
            {
                provider.GenerateCodeFromMember((CodeTypeMember)c, writer, options);
            }
            else if (c is CodeTypeDeclaration)
            {
                provider.GenerateCodeFromType((CodeTypeDeclaration)c, writer, options);
            }
            else if (c is CodeNamespace)
            {
                provider.GenerateCodeFromNamespace((CodeNamespace)c, writer, options);
            }
            else
            {
                throw new ArgumentException($"Tests not set up for unexpected type: {c.GetType()}");
            }

            return sb.ToString();
        }
コード例 #8
0
        private static string GenerateCode(CodeObject c, CodeDomProvider provider)
        {
            var sb = new StringBuilder();
            var writer = new StringWriter(sb);
            var options = new CodeGeneratorOptions();

            if (c is CodeStatement)
            {
                provider.GenerateCodeFromStatement((CodeStatement)c, writer, options);
            }
            else if (c is CodeCompileUnit)
            {
                provider.GenerateCodeFromCompileUnit((CodeCompileUnit)c, writer, options);
            }
            else if (c is CodeExpression)
            {
                provider.GenerateCodeFromExpression((CodeExpression)c, writer, options);
            }
            else if (c is CodeTypeMember)
            {
                provider.GenerateCodeFromMember((CodeTypeMember)c, writer, options);
            }
            else if (c is CodeTypeDeclaration)
            {
                provider.GenerateCodeFromType((CodeTypeDeclaration)c, writer, options);
            }
            else if (c is CodeNamespace)
            {
                provider.GenerateCodeFromNamespace((CodeNamespace)c, writer, options);
            }
            else
            {
                Assert.False(true, $"Unknown type: {c.GetType()}");
            }

            return sb.ToString();
        }