protected void AddSpecFlowHeader(CodeDomProvider codeProvider, TextWriter outputWriter) { const string specFlowHeaderTemplate = @"------------------------------------------------------------------------------ <auto-generated> This code was generated by SpecFlow (http://www.specflow.org/). SpecFlow Version:{0} SpecFlow Generator Version:{1} Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. </auto-generated> ------------------------------------------------------------------------------"; var headerReader = new StringReader(string.Format(specFlowHeaderTemplate, GetCurrentSpecFlowVersion(), TestGeneratorFactory.GeneratorVersion )); string line; while ((line = headerReader.ReadLine()) != null) { codeProvider.GenerateCodeFromStatement(new CodeCommentStatement(line), outputWriter, null); } codeProvider.GenerateCodeFromStatement(codeDomHelper.GetStartRegionStatement("Designer generated code"), outputWriter, null); codeProvider.GenerateCodeFromStatement(codeDomHelper.GetDisableWarningsPragma(), outputWriter, null); }
private static void GenerateNUPlixLoaderExceptionLine(TextWriter writer, CodeDomProvider provider) { // This is only valid syntax for C# right now, but if another language does not // recognize this syntax then it will also throw a compile error, which is the intent, // so there is not much to lose here. provider.GenerateCodeFromStatement(new CodeSnippetStatement("#error NUPlixLoader Exception"), writer, null); }
/// <summary> /// Create the code for the Initialize method after its call to base.Initialize /// </summary> private void GeneratePostInitCode(string nameValue, string typeValue, CodeMemberField field) { CodeStatementCollection codeStatementCollection = new CodeStatementCollection(); CodeVariableDeclarationStatement codeVariableDeclarationStatement = new CodeVariableDeclarationStatement(typeof(bool).Ref(), nameValue + "ValueAcquired", false.Prim()); CodeVariableReferenceExpression codeVariableReferenceExpression = codeVariableDeclarationStatement.Ref(); CodeTypeReference typeReference = new CodeTypeReference(typeValue, CodeTypeReferenceOptions.GlobalReference); CodeStatement setValueAcquired = codeVariableReferenceExpression.Assign(true.Prim()); codeStatementCollection.Add(codeVariableDeclarationStatement); GenerateSessionLookup(nameValue, field, codeStatementCollection, setValueAcquired, typeReference); if (hostSpecific) { GenerateHostResolveParameterValueLookup(nameValue, field, codeStatementCollection, codeVariableReferenceExpression, typeReference, setValueAcquired, typeValue); } GenerateCallContextLookup(nameValue, field, codeStatementCollection, codeVariableReferenceExpression, typeReference, typeValue); CodeGeneratorOptions standardOptions = StandardOptions; using (StringWriter writer = new StringWriter(postInitializationBuffer, CultureInfo.InvariantCulture)) { foreach (CodeStatement item in codeStatementCollection) { languageCodeDomProvider.GenerateCodeFromStatement(item, writer, standardOptions); } } }
/// <summary> /// Contribute additively to initialization code for the TextTransformation generated class. /// </summary> /// <remarks> /// This code will be added before the call to the base class. /// </remarks> /// <param name="codeBuffer"></param> /// <param name="languageProvider"></param> /// <param name="requiresArguments"></param> /// <param name="providesArguments"></param> protected override void GeneratePreInitializationCode(string directiveName, StringBuilder codeBuffer, CodeDomProvider languageProvider, IDictionary <string, string> requiresArguments, IDictionary <string, string> providesArguments) { if ((StringComparer.InvariantCultureIgnoreCase.Compare(directiveName, "schemamodel") == 0)) { if (languageProvider != null) { string[] domainModels = { "Microsoft.VisualStudio.Modeling.Diagrams.CoreDesignSurface", "Microsoft.VisualStudio.Modeling.Utilities.UtilitiesModel", "ISpySoft.SFSchemaLanguage.Designer.SFSchemaLanguageDesigner", "ISpySoft.SFSchemaLanguage.DomainModel.SFSchemaLanguage", }; CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = true; options.IndentString = " "; options.VerbatimOrder = true; options.BracingStyle = "C"; using (StringWriter writer = new StringWriter(codeBuffer, CultureInfo.InvariantCulture)) { foreach (string domainModel in domainModels) { CodeExpressionStatement addModel = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "AddDomainModel"), new CodeTypeOfExpression(domainModel))); languageProvider.GenerateCodeFromStatement(addModel, writer, options); } } } } }
public void GenerateStatemets(TextWriter tw, CodeDomProvider provider, CodeGeneratorOptions opts, CodeStatement[] statements) { foreach (var statement in statements) { provider.GenerateCodeFromStatement(statement, tw, opts); } }
private void WriteFile(string file, CodeTypeDeclaration resources, string language, bool isCSharp, IEnumerable <string> aliases) { CodeDomProvider provider = CodeDomProvider.CreateProvider(language); string code = null; using (var o = new StringWriter()) { var options = new CodeGeneratorOptions() { BracingStyle = "C", IndentString = "\t", }; var ns = string.IsNullOrEmpty(Namespace) ? new CodeNamespace() : new CodeNamespace(Namespace); if (resources != null) { ns.Types.Add(resources); } var unit = new CodeCompileUnit(); unit.Namespaces.Add(ns); var resgenatt = new CodeAttributeDeclaration(new CodeTypeReference("Android.Runtime.ResourceDesignerAttribute", CodeTypeReferenceOptions.GlobalReference)); resgenatt.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(Namespace.Length > 0 ? Namespace + ".Resource" : "Resource"))); resgenatt.Arguments.Add(new CodeAttributeArgument("IsApplication", new CodePrimitiveExpression(IsApplication))); unit.AssemblyCustomAttributes.Add(resgenatt); // Add Pragma to disable warnings about no Xml documentation if (isCSharp) { foreach (var alias in aliases) { provider.GenerateCodeFromStatement(new CodeSnippetStatement($"extern alias {alias};"), o, options); } provider.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("#pragma warning disable 1591"), o, options); } provider.CreateGenerator(o).GenerateCodeFromCompileUnit(unit, o, options); // Add Pragma to re-enable warnings about no Xml documentation if (isCSharp) { provider.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("#pragma warning restore 1591"), o, options); } code = o.ToString(); } if (MonoAndroidHelper.CopyIfStringChanged(code, file)) { Log.LogDebugMessage($"Writing to: {file}"); } }
private static string GenerateExceptionInformation(Exception ex, CodeDomProvider provider) { StringWriter writer = new StringWriter(); Exception currentException = ex; provider.GenerateCodeFromStatement(new CodeCommentStatement("Generate threw an exception"), writer, null); while (currentException != null) { provider.GenerateCodeFromStatement(new CodeCommentStatement(ex.Message), writer, null); provider.GenerateCodeFromStatement(new CodeCommentStatement(ex.StackTrace), writer, null); currentException = currentException.InnerException; if (currentException != null) { provider.GenerateCodeFromStatement(new CodeCommentStatement("Info from InnerException"), writer, null); } } GenerateNUPlixLoaderExceptionLine(writer, provider); return(writer.ToString()); }
private void AssignMemberFromCallContext(string name, string type, TextWriter sw) { var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), name); var assign = new CodeAssignStatement(fieldRef, new CodeCastExpression(new CodeTypeReference(type), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(CallContext)) , "LogicalGetData" , new CodeExpression[] { new CodePrimitiveExpression(name) } ))); ; languageProvider.GenerateCodeFromStatement(assign, sw, new CodeGeneratorOptions()); }
string StatementsToCode(List <CodeStatement> statements) { var options = new CodeGeneratorOptions(); using (var sw = new StringWriter()) { foreach (var statement in statements) { provider.GenerateCodeFromStatement(statement, sw, options); } return(sw.ToString()); } }
public virtual void ConvertContentDefinition(CodeMemberMethod method, TextWriter writer) { LoggingService.Info("Generate code for: " + method.Name); CodeGeneratorOptions options = codeDOMGeneratorUtility.CreateCodeGeneratorOptions; options.IndentString = indentation; foreach (CodeStatement statement in method.Statements) { // indentation isn't generated when calling GenerateCodeFromStatement writer.Write(options.IndentString); try { // outputGenerator.PublicGenerateCodeFromStatement(statement, Console.Out, options); codeProvider.GenerateCodeFromStatement(statement, writer, options); } catch (Exception e) { codeProvider.GenerateCodeFromStatement(new CodeCommentStatement("TODO: Error while generating statement : " + e.Message), writer, options); LoggingService.Error(e); } } }
private static void GenrateMeth(CodeGeneratorOptions opts, CodeDomProvider provider, IndentedTextWriter tw, CodeStatementCollection statements, string methName) { tw.WriteLine(methName); tw.WriteLine("{"); tw.Indent++; foreach (CodeStatement statement in statements) { provider.GenerateCodeFromStatement(statement, tw, opts); } tw.Indent--; tw.WriteLine("}"); }
public static string GetActualName(this Type obj) { CodeDomProvider csharpProvider = CodeDomProvider.CreateProvider("C#"); CodeTypeReference typeReference = new CodeTypeReference(obj); CodeVariableDeclarationStatement variableDeclaration = new CodeVariableDeclarationStatement(typeReference, "dummy"); StringBuilder sb = new StringBuilder(); using (StringWriter writer = new StringWriter(sb)) { csharpProvider.GenerateCodeFromStatement(variableDeclaration, writer, new CodeGeneratorOptions()); } sb.Replace(" dummy;", null); sb.Replace("&", null); return(sb.ToString()); }
public string ConcatStatement(CodePrimitiveExpression left, CodeVariableReferenceExpression middle, CodePrimitiveExpression right, CodeTypeReferenceExpression targetObject, string methodName) { CodeExpression evalMessage = new CodeExpression(); evalMessage = ConcatString(left, middle, right); CodeMethodInvokeExpression eval = new CodeMethodInvokeExpression(targetObject, methodName, evalMessage); CodeExpressionStatement evalStatement = new CodeExpressionStatement(eval); using (TextWriter tx = new StringWriter()) { provider.GenerateCodeFromStatement(evalStatement, tx, new CodeGeneratorOptions()); return(tx.ToString()); } }
/// <summary>Called when extension shall process generated code</summary> /// <param name="code">The code</param> /// <param name="provider">CodeDOM provider (the language)</param> /// <version version="1.5.3">Parameter <c>Provider</c> renamed to <c>provider</c></version> public void PostProcess(ref string code, CodeDomProvider provider) { System.IO.StringWriter tw = new System.IO.StringWriter(); provider.GenerateCodeFromStatement(new CodeCommentStatement(FirtsLineOfAccessor), tw, new System.CodeDom.Compiler.CodeGeneratorOptions()); string srch = tw.GetStringBuilder().ToString(); if (srch.EndsWith("\r\n")) { srch = srch.Substring(0, srch.Length - 2); } else if (srch.EndsWith("\r") || srch.EndsWith("\n")) { srch = srch.Substring(0, srch.Length - 1); } tw = new System.IO.StringWriter(); CodeTypeDeclaration foo = new CodeTypeDeclaration("foo"); foo.CustomAttributes.Add(NewAttribute); provider.GenerateCodeFromType(foo, tw, new System.CodeDom.Compiler.CodeGeneratorOptions()); string attr = new System.IO.StringReader(tw.GetStringBuilder().ToString()).ReadLine(); System.IO.StringReader sr = new System.IO.StringReader(code); List <String> Lines = new List <string>(); do { string line = sr.ReadLine(); if (line == null) { break; } if (line.EndsWith(srch)) { Lines[Lines.Count - 1] = attr + "\r\n" + Lines[Lines.Count - 1]; } else { Lines.Add(line); } } while (true); System.Text.StringBuilder b = new System.Text.StringBuilder(); foreach (string line in Lines) { b.AppendLine(line); } code = b.ToString(); }
public static string ToCSharp(this Type type, bool nullable = false) { CodeDomProvider csharpProvider = CodeDomProvider.CreateProvider("C#"); CodeTypeReference typeReference = new CodeTypeReference(type); CodeVariableDeclarationStatement variableDeclaration = new CodeVariableDeclarationStatement(typeReference, "dummy"); StringBuilder sb = new StringBuilder(); using (StringWriter writer = new StringWriter(sb)) { csharpProvider.GenerateCodeFromStatement(variableDeclaration, writer, new CodeGeneratorOptions()); } sb.Replace(" dummy;\r\n", null); if (nullable && type.IsValueType) { return(sb.ToString() + "?"); } return(sb.ToString()); }
public void Generate(TextWriter w, Database database, CodeDomProvider provider, String ns) { CodeCommentStatement c = new CodeCommentStatement( String.Format("Enum for {0}", database.DisplayName.Replace("DataSet", ""))); provider.GenerateCodeFromStatement(c, w, null); //Gen: namespace <NAMESPACE> { // using System; CodeNamespace cnamespace = new CodeNamespace(ns); cnamespace.Imports.Add(new CodeNamespaceImport("System")); string databaseName = database.DisplayName.Replace("DataSet", "").Replace(' ', '_'); //Gen: public enum <typeName> CodeTypeDeclaration enumViewsType = new CodeTypeDeclaration(databaseName + "Views"); enumViewsType.IsEnum = true; //Add this so that VB does not Inherit either interface enumViewsType.TypeAttributes = TypeAttributes.Public; cnamespace.Types.Add(enumViewsType); foreach (View view in database.Views.Values) { enumViewsType.Members.Add(new CodeMemberField(typeof(int), view.Name)); //Gen: public enum <typeName> CodeTypeDeclaration enumViewType = new CodeTypeDeclaration(view.Name); enumViewType.IsEnum = true; //Add this so that VB does not Inherit either interface enumViewType.TypeAttributes = TypeAttributes.Public; cnamespace.Types.Add(enumViewType); foreach (Field field in view.Fields.Values) { enumViewType.Members.Add(new CodeMemberField(typeof(int), field.Name)); } } provider.GenerateCodeFromNamespace(cnamespace, w, null); }
/// <summary> /// Generates source code from given CodeStatement. /// </summary> public static string GenerateFromStatement(CodeDomProvider codeProvider, CodeStatement statement) { StringBuilder result = new StringBuilder(); StringWriter writer = new StringWriter(result); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = false; options.BracingStyle = "C"; // generate the code: codeProvider.GenerateCodeFromStatement(statement, writer, options); // send it to the StringBuilder object: writer.Flush(); return(result.ToString()); }
public static string GenerateErrorString(Exception ex, CodeDomProvider codeProvider) { CodeGeneratorOptions gen = new CodeGeneratorOptions(); gen.BracingStyle = "C"; gen.IndentString = "\t"; gen.VerbatimOrder = true; gen.BlankLinesBetweenMembers = false; CodeCommentStatement[] comments = new CodeCommentStatement[1]; if (ex is CompileException) { CompileException cx = (CompileException)ex; comments[0] = new CodeCommentStatement(string.Format("Error generating shader:{0}{1} (line: {2} col: {3})", Environment.NewLine, cx.Text, cx.Line, cx.Coloumn)); } else if (ex is CompileExceptionCollection) { CompileExceptionCollection cxc = (CompileExceptionCollection)ex; comments = new CodeCommentStatement[cxc.Count]; for (int i = 0; i < cxc.Count; i++) { CompileException cx = cxc.GetException(i); comments[i] = new CodeCommentStatement(string.Format("Error generating shader:{0}{1} (line: {2} col: {3})", Environment.NewLine, cx.Text, cx.Line, cx.Coloumn)); } } else { comments[0] = new CodeCommentStatement(string.Format("Unhandled exception in XenFX:{0}{1}", Environment.NewLine, ex.ToString())); } StringBuilder sb = new StringBuilder(); using (TextWriter writer = new StringWriter(sb)) { foreach (CodeCommentStatement comment in comments) { codeProvider.GenerateCodeFromStatement(comment, writer, gen); } } return(sb.ToString()); }
public override void ProcessDirective(string directiveName, IDictionary <string, string> arguments) { string name = arguments["name"]; string fieldName = string.Format("_{0}", arguments["name"]); string type = arguments["type"]; var field = new CodeMemberField(type, fieldName) { Attributes = MemberAttributes.Private }; _provider.GenerateCodeFromMember(field, _classCodeWriter, _options); var property = new CodeMemberProperty { Name = name, Type = new CodeTypeReference(type), Attributes = MemberAttributes.Public, HasGet = true, HasSet = false }; property.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), fieldName))); _provider.GenerateCodeFromMember(property, _classCodeWriter, _options); CodeAssignStatement assignment = new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodeCastExpression( new CodeTypeReference(type), new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(CallContext)), "LogicalGetData", new CodePrimitiveExpression(name)))); _provider.GenerateCodeFromStatement(assignment, _initializationCodeWriter, _options); }
/// <summary> /// Contribute additively to initialization code for the TextTransformation generated class. /// </summary> /// <remarks> /// This code will be added after the call to the base class. /// </remarks> /// <param name="codeBuffer"></param> /// <param name="languageProvider"></param> /// <param name="requiresArguments"></param> /// <param name="providesArguments"></param> protected override void GeneratePostInitializationCode(string directiveName, StringBuilder codeBuffer, CodeDomProvider languageProvider, IDictionary <string, string> requiresArguments, IDictionary <string, string> providesArguments) { if ((StringComparer.InvariantCultureIgnoreCase.Compare(directiveName, "schemamodel") == 0)) { if (languageProvider != null) { CodeMethodInvokeExpression invokeExpression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(ISpySoft.SFSchemaLanguage.Designer.SFSchemaLanguageFileLoader)), "Load"), new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Errors"), new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Store"), new CodePrimitiveExpression(requiresArguments["fileName"])); CodeAssignStatement assign = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), providesArguments["SchemaModel"].ToLower(CultureInfo.InvariantCulture) + "Value"), invokeExpression); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = true; options.IndentString = " "; options.VerbatimOrder = true; options.BracingStyle = "C"; using (StringWriter writer = new StringWriter(codeBuffer, CultureInfo.InvariantCulture)) { languageProvider.GenerateCodeFromStatement(assign, writer, options); } } } }
/// <summary> /// Gets the post initialization code for processing run. This will /// generate a call to the GetArgument method of the host for each /// private field generated. /// </summary> /// <returns></returns> public override string GetPostInitializationCodeForProcessingRun() { using (var writer = new StringWriter(CultureInfo.InvariantCulture)) { foreach (ArgumentInfo argument in _argumentInfos.Values) { //Generate initialization code for each argument //_FieldName = (FieldType) this.GetHostOption("_FieldName"); var assignment = new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), argument.FieldName), new CodeCastExpression( new CodeTypeReference(argument.Type), new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(CallContext)), MethodGetArgument, new CodePrimitiveExpression(argument.Name)))); _provider.GenerateCodeFromStatement(assignment, writer, _options); } return(writer.ToString()); } }
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()); }
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()); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { if (!(provider is JScriptCodeProvider)) { // GENERATES (C#): // namespace Foo { // public class Foo { // // public int _verifyGlobalGeneration1 = 2147483647; // // public int System { // get { return 42; } // } // // public int Property { // get { return 2147483647; } // } // // public int GlobalTestProperty1 { // get { // return _verifyGlobalGeneration1; // } // set { // _verifyGlobalGeneration1 = value; // } // } // // public global::System.Nullable<int> GlobalTestProperty2 { // get { // return _verifyGlobalGeneration2; // } // set { // _verifyGlobalGeneration2 = value; // } // } // // // public int TestMethod02() { // int iReturn; // iReturn = global::Foo.Foo.Property; // return iReturn; // } // // public int TestMethod03() { // int iReturn; // iReturn = global::System.Math.Abs(-1); // return iReturn; // } // // public int TestMethod04() { // int iReturn; // iReturn = System; // return iReturn; // } // } CodeNamespace ns = new CodeNamespace ("Foo"); ns.Comments.Add (new CodeCommentStatement ("Foo namespace")); cu.Namespaces.Add (ns); CodeTypeDeclaration cd = new CodeTypeDeclaration ("Foo"); ns.Types.Add (cd); CodeMemberProperty property = new CodeMemberProperty (); property.Name = "System"; property.Attributes = MemberAttributes.Public; property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private | MemberAttributes.Static; property.Type = new CodeTypeReference (typeof (int)); property.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (42))); cd.Members.Add (property); property = new CodeMemberProperty (); property.Name = "Property"; property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private | MemberAttributes.Static; property.Type = new CodeTypeReference (typeof (int)); property.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (Int32.MaxValue))); cd.Members.Add (property); AddScenario ("CallTestMethod02", "Call Foo.Foo.TestMethod02."); CodeMemberMethod method2 = new CodeMemberMethod (); method2.Name = "TestMethod02"; method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method2.ReturnType = new CodeTypeReference (typeof (int)); method2.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "iReturn")); CodePropertyReferenceExpression cpr = new CodePropertyReferenceExpression ( new CodeTypeReferenceExpression (new CodeTypeReference ("Foo.Foo", CodeTypeReferenceOptions.GlobalReference)), "Property"); CodeAssignStatement cas = new CodeAssignStatement (new CodeVariableReferenceExpression ("iReturn"), cpr); method2.Statements.Add (cas); method2.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("iReturn"))); cd.Members.Add (method2); AddScenario ("CallTestMethod03", "Call Foo.Foo.TestMethod02."); CodeMemberMethod method3 = new CodeMemberMethod (); method3.Name = "TestMethod03"; method3.Attributes = (method3.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method3.ReturnType = new CodeTypeReference (typeof (int)); method3.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "iReturn")); CodeTypeReferenceOptions ctro = CodeTypeReferenceOptions.GlobalReference; CodeTypeReference ctr = new CodeTypeReference (typeof (Math), ctro); CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression ( new CodeMethodReferenceExpression ( new CodeTypeReferenceExpression (ctr), "Abs"), new CodeExpression[] { new CodePrimitiveExpression (-1) }); cas = new CodeAssignStatement (new CodeVariableReferenceExpression ("iReturn"), cmie); method3.Statements.Add (cas); method3.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("iReturn"))); cd.Members.Add (method3); AddScenario ("CallTestMethod04", "Call Foo.Foo.TestMethod04."); CodeMemberMethod method4 = new CodeMemberMethod (); method4.Name = "TestMethod04"; method4.Attributes = (method4.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method4.ReturnType = new CodeTypeReference (typeof (int)); method4.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "iReturn")); cpr = new CodePropertyReferenceExpression (null, "System"); cas = new CodeAssignStatement (new CodeVariableReferenceExpression ("iReturn"), cpr); method4.Statements.Add (cas); method4.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("iReturn"))); cd.Members.Add (method4); // Verify that what CodeTypeReferenceOptions are correctly set. // Basically this check gives the code coverage for the get property AddScenario ("CTR_GetGlobalRefCheck", "Check that CodeTypeReference.Options gives the proper value."); if (ctr.Options == CodeTypeReferenceOptions.GlobalReference) VerifyScenario ("CTR_GetGlobalRefCheck"); // one-off generate statements StringWriter sw = new StringWriter (); // global shouldn't be generated in this instance CodeTypeReference variableType = new CodeTypeReference (typeof (System.String), CodeTypeReferenceOptions.GlobalReference); CodeVariableDeclarationStatement variable = new CodeVariableDeclarationStatement (variableType, "myVariable"); provider.GenerateCodeFromStatement (variable, sw, null); // global should be generated in this instance CodeTypeReference variableType2 = new CodeTypeReference (typeof (System.Array), CodeTypeReferenceOptions.GlobalReference); CodeVariableDeclarationStatement variable2 = new CodeVariableDeclarationStatement (variableType2, "myVariable2"); provider.GenerateCodeFromStatement (variable2, sw, null); AddScenario ("GlobalKeywordShouldExist", "When an array is referred to, a global qualifier should be generated on it."); if (sw.ToString ().IndexOf ("global") != -1 && sw.ToString ().IndexOf ("Global") != -1) { LogMessage ("Global keyword does not exist in statement: " + sw.ToString ()); } else VerifyScenario ("GlobalKeywordShouldExist"); } }
/// <summary> /// Compile the assembly in memory and get a reference to the assembly itself. /// If compilation fails, returns null. /// </summary> private Assembly CompileInMemoryAssembly() { // Combine our default assembly references with those specified List <string> finalReferencedAssemblies = new List <string>(); CombineReferencedAssemblies(finalReferencedAssemblies); // Combine our default using's with those specified string[] finalUsingNamespaces = CombineUsingNamespaces(); // Language can be anything that has a codedom provider, in the standard naming method // "c#;cs;csharp", "vb;vbs;visualbasic;vbscript", "js;jscript;javascript", "vj#;vjs;vjsharp", "c++;mc;cpp" using (CodeDomProvider provider = CodeDomProvider.CreateProvider(_language)) { if (provider is Microsoft.CSharp.CSharpCodeProvider) { AddReferenceAssemblyToReferenceList(finalReferencedAssemblies, "System"); } CompilerParameters compilerParameters = new CompilerParameters(finalReferencedAssemblies.ToArray()); // We don't need debug information compilerParameters.IncludeDebugInformation = true; // Not a file based assembly compilerParameters.GenerateInMemory = true; // Indicates that a .dll should be generated. compilerParameters.GenerateExecutable = false; // Horrible code dom / compilation declarations CodeTypeDeclaration codeTypeDeclaration; StringBuilder codeBuilder = new StringBuilder(); StringWriter writer = new StringWriter(codeBuilder, CultureInfo.CurrentCulture); CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions(); codeGeneratorOptions.BlankLinesBetweenMembers = true; codeGeneratorOptions.VerbatimOrder = true; CodeCompileUnit compilationUnit = new CodeCompileUnit(); // If our code is in a separate file, then read it in here if (_sourcePath != null) { _sourceCode = File.ReadAllText(_sourcePath); } string fullCode = _sourceCode; // A fragment is essentially the contents of the execute method (except the final return true/false) // A method is the whole execute method specified // Anything else assumes that the whole class is being supplied if (_typeIsFragment || _typeIsMethod) { codeTypeDeclaration = CreateTaskClass(); CreateTaskProperties(codeTypeDeclaration); if (_typeIsFragment) { CreateExecuteMethodFromFragment(codeTypeDeclaration, _sourceCode); } else { CreateTaskBody(codeTypeDeclaration, _sourceCode); } CodeNamespace codeNamespace = new CodeNamespace("InlineCode"); foreach (string importname in finalUsingNamespaces) { codeNamespace.Imports.Add(new CodeNamespaceImport(importname)); } codeNamespace.Types.Add(codeTypeDeclaration); compilationUnit.Namespaces.Add(codeNamespace); // Create the source for the CodeDom provider.GenerateCodeFromCompileUnit(compilationUnit, writer, codeGeneratorOptions); } else { // We are a full class, so just create the CodeDom from the source provider.GenerateCodeFromStatement(new CodeSnippetStatement(_sourceCode), writer, codeGeneratorOptions); } // Our code generation is complete, grab the source from the builder ready for compilation fullCode = codeBuilder.ToString(); FullTaskSpecification fullSpec = new FullTaskSpecification(finalReferencedAssemblies, fullCode); Assembly existingAssembly; if (!s_compiledTaskCache.TryGetValue(fullSpec, out existingAssembly)) { // Invokes compilation. // Note: CompileAssemblyFromSource uses Path.GetTempPath() directory, but will not create it. In some cases // this will throw inside CompileAssemblyFromSource. To work around this, ensure the temp directory exists. // See: https://github.com/Microsoft/msbuild/issues/328 Directory.CreateDirectory(Path.GetTempPath()); CompilerResults compilerResults = provider.CompileAssemblyFromSource(compilerParameters, fullCode); string outputPath = null; if (compilerResults.Errors.Count > 0 || Environment.GetEnvironmentVariable("MSBUILDLOGCODETASKFACTORYOUTPUT") != null) { string tempDirectory = Path.GetTempPath(); string fileName = Guid.NewGuid().ToString() + ".txt"; outputPath = Path.Combine(tempDirectory, fileName); File.WriteAllText(outputPath, fullCode); } if (compilerResults.NativeCompilerReturnValue != 0 && compilerResults.Errors.Count > 0) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.FindSourceFileAt", outputPath); foreach (CompilerError e in compilerResults.Errors) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.CompilerError", e.ToString()); } return(null); } // Add to the cache. Failing to add is not a fatal error. s_compiledTaskCache.TryAdd(fullSpec, compilerResults.CompiledAssembly); return(compilerResults.CompiledAssembly); } else { return(existingAssembly); } } }
/// <summary>生成成员代码块</summary> /// <param name="block"></param> /// <param name="generatorType"></param> /// <param name="lineNumbers"></param> /// <param name="provider"></param> /// <param name="options"></param> /// <param name="firstMemberFound"></param> /// <returns></returns> private static Boolean GenerateMemberForBlock(Block block, CodeTypeDeclaration generatorType, Boolean lineNumbers, CodeDomProvider provider, CodeGeneratorOptions options, Boolean firstMemberFound) { CodeSnippetTypeMember member = null; if (!firstMemberFound) { // 发现第一个<#!后,认为是类成员代码的开始,直到下一个<#!作为结束 if (block.Type == BlockType.Member) { firstMemberFound = true; if (!String.IsNullOrEmpty(block.Text)) { member = new CodeSnippetTypeMember(block.Text); } } } else { // 再次遇到<#!,此时,成员代码准备结束 if (block.Type == BlockType.Member) { firstMemberFound = false; if (!String.IsNullOrEmpty(block.Text)) { member = new CodeSnippetTypeMember(block.Text); } } else if (block.Type == BlockType.Text) { CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodePrimitiveExpression(block.Text) }); CodeExpressionStatement statement = new CodeExpressionStatement(expression); using (StringWriter writer = new StringWriter()) { provider.GenerateCodeFromStatement(statement, writer, options); member = new CodeSnippetTypeMember(writer.ToString()); } } else if (block.Type == BlockType.Expression) { CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodeArgumentReferenceExpression(block.Text.Trim()) }); CodeExpressionStatement statement = new CodeExpressionStatement(expression); using (StringWriter writer = new StringWriter()) { provider.GenerateCodeFromStatement(statement, writer, options); member = new CodeSnippetTypeMember(writer.ToString()); } } else if (block.Type == BlockType.Statement) { member = new CodeSnippetTypeMember(block.Text); } } if (member != null) { if (lineNumbers) { Boolean flag = String.IsNullOrEmpty(block.Name); Int32 lineNumber = (block.StartLine > 0) ? block.StartLine : 1; if (flag) { generatorType.Members.Add(new CodeSnippetTypeMember("#line " + lineNumber)); } else { member.LinePragma = new CodeLinePragma(block.Name, lineNumber); } generatorType.Members.Add(member); if (flag) { generatorType.Members.Add(new CodeSnippetTypeMember("#line default")); } } else { generatorType.Members.Add(member); } } return(firstMemberFound); }
/// <summary> /// Generate a code file for the current xml file contents. Loads /// settings for the file off the Plix.xml settings file in the project to /// get the generation transform and other settings to apply to the specific file. /// </summary> /// <param name="fileContents">Contents of an xml file to transform</param> /// <param name="defaultNamespace">The namespace provided in the property grid</param> /// <returns>Contents of the corresponding code file</returns> private string GenerateCode(string fileContents, string defaultNamespace) { #if VerifyUIThread Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); #endif // Make sure we have a CodeDomProvider CodeDomProvider provider = CodeDomProvider; if (provider == null) { return(string.Empty); } // Get the current project item and project information EnvDTE.ProjectItem projectItem = CurrentProjectItem; string sourceFile = (string)projectItem.Properties.Item("LocalPath").Value; EnvDTE.Project project = projectItem.ContainingProject; string projectFile = (string)project.Properties.Item("LocalPath").Value; string projectLocation = projectFile.Substring(0, projectFile.LastIndexOf('\\') + 1); // If this is the Plix.xml settings file, then regenerate all other mentioned NUPlixLoader files if (0 == string.Compare(projectItem.Name, PlixProjectSettingsFile, true, CultureInfo.InvariantCulture)) { RunCustomTool( project.ProjectItems, projectItem, delegate(EnvDTE.ProjectItem matchItem) { #if VerifyUIThread Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); #endif VSProjectItem vsProjItem = matchItem.Object as VSProjectItem; if (vsProjItem != null) { vsProjItem.RunCustomTool(); } }); StringWriter writer = new StringWriter(); provider.GenerateCodeFromStatement(new CodeCommentStatement( @"Empty file generated by NUPlixLoader for Plix.xml. Setting NUPlixLoader as the custom tool on the Plix.xml settings file enables automatic regeneration of other NUPlixLoader files in the project when the settings file is changed. There is no way to both successfully trigger regeneration and avoid writing this file."), writer, null); return(writer.ToString()); } // Load a language formatter for this file extension string fileExtension = CodeDomProvider.FileExtension; if (fileExtension.StartsWith(".")) { fileExtension = fileExtension.Substring(1); } XslCompiledTransform formatter = FormatterManager.GetFormatterTransform(fileExtension); if (formatter == null) { StringWriter writer = new StringWriter(); provider.GenerateCodeFromStatement(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "A PLiX formatter transform for the '{0}' language was not found.", fileExtension)), writer, null); return(writer.ToString()); } // Get options for this xml file XsltArgumentList arguments = new XsltArgumentList(); string automationObjectName; string transformFile = LoadProjectSettings(sourceFile, projectLocation, arguments, project, out automationObjectName); // MSBUG: Beta2 There's a nasty bug with single-file generators right now where // the text for an open file that is not in a text document is // passed through as encoded bytes in the string. EnvDTE.Document itemDocument = projectItem.Document; if (itemDocument != null && "XML" != itemDocument.Language) { if (fileContents.Length > 1) { char[] leadChars = fileContents.ToCharArray(0, 2); byte[] leadBytes = new byte[2 * sizeof(char)]; GCHandle handle = GCHandle.Alloc(leadBytes, GCHandleType.Pinned); Marshal.Copy(leadChars, 0, Marshal.UnsafeAddrOfPinnedArrayElement(leadBytes, 0), 2); handle.Free(); EncodingInfo[] encodingInfos = Encoding.GetEncodings(); int encodingsCount = encodingInfos.Length; for (int i = 0; i < encodingsCount; ++i) { EncodingInfo encodingInfo = encodingInfos[i]; Encoding encoding = encodingInfo.GetEncoding(); byte[] preamble = encoding.GetPreamble(); int preambleByteCount = preamble.Length; if (preambleByteCount != 0) { Debug.Assert(preambleByteCount <= 4); int j; for (j = 0; j < preambleByteCount; ++j) { if (preamble[j] != leadBytes[j]) { break; } } if (j == preambleByteCount) { Decoder decoder = encoding.GetDecoder(); leadChars = fileContents.ToCharArray(); int startCharCount = leadChars.Length; leadBytes = new byte[startCharCount * sizeof(char)]; int byteCount = leadBytes.Length - preambleByteCount; GCHandle handle2 = GCHandle.Alloc(leadBytes, GCHandleType.Pinned); Marshal.Copy(leadChars, 0, Marshal.UnsafeAddrOfPinnedArrayElement(leadBytes, 0), startCharCount); handle2.Free(); int finalCharCount = decoder.GetCharCount(leadBytes, preambleByteCount, byteCount, true); char[] finalChars = new char[finalCharCount + 1]; decoder.GetChars(leadBytes, preambleByteCount, byteCount, finalChars, 0, true); // Hack within a hack to make sure that the Xml element has a trailing >, // byte data in a string has a tendency to lose the last byte char testChar = finalChars[finalCharCount - 1];; if (testChar != '>' && !char.IsWhiteSpace(testChar)) { finalChars[finalCharCount] = '>'; ++finalCharCount; } fileContents = new string(finalChars, 0, finalCharCount); } } } } } // Resolve any file redirections here. File redirection allows the same source file // to generate multiple outputs via multiple transforms. string alternateSourceFile = null; using (StringReader stringReader = new StringReader(fileContents)) { try { using (XmlTextReader reader = new XmlTextReader(stringReader)) { if (XmlNodeType.Element == reader.MoveToContent()) { if (reader.NamespaceURI == RedirectNamespace && reader.LocalName == RedirectElementName) { string relativeTargetSourceFile = reader.GetAttribute(RedirectTargetAttribute); FileInfo targetSourceFileInfo = new FileInfo(sourceFile.Substring(0, sourceFile.LastIndexOf('\\') + 1) + relativeTargetSourceFile); if (targetSourceFileInfo.Exists) { alternateSourceFile = targetSourceFileInfo.FullName; sourceFile = alternateSourceFile; try { itemDocument = null; itemDocument = project.DTE.Documents.Item(alternateSourceFile); } catch (ArgumentException) { // Swallow if the document is not open } } else { StringWriter writer = new StringWriter(); provider.GenerateCodeFromStatement(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "Redirection target file '{0}' not found", relativeTargetSourceFile)), writer, null); return(writer.ToString()); } } } } } catch (XmlException ex) { return(GenerateExceptionInformation(ex, provider)); } } // Add standard defined attributes to the argument list string projectNamespace = (string)project.Properties.Item("DefaultNamespace").Value; if (null == arguments.GetParam("ProjectPath", "")) { arguments.AddParam("ProjectPath", "", projectLocation); } if (null == arguments.GetParam("SourceFile", "")) { arguments.AddParam("SourceFile", "", sourceFile.Substring(projectLocation.Length)); } if (null == arguments.GetParam("CustomToolNamespace", "")) { if (defaultNamespace == null || defaultNamespace.Length == 0) { defaultNamespace = projectNamespace; } arguments.AddParam("CustomToolNamespace", "", defaultNamespace); } if (null == arguments.GetParam("ProjectNamespace", "")) { arguments.AddParam("ProjectNamespace", "", projectNamespace); } try { XslCompiledTransform transform = null; if (transformFile != null) { transform = new XslCompiledTransform(); using (FileStream transformStream = new FileStream(transformFile, FileMode.Open, FileAccess.Read)) { using (StreamReader reader = new StreamReader(transformStream)) { transform.Load(new XmlTextReader(reader), XsltSettings.TrustedXslt, XmlUtility.CreateFileResolver(transformFile)); } } } MemoryStream plixStream = (transform != null) ? new MemoryStream() : null; using (XmlWriter xmlTextWriter = (transform != null) ? XmlWriter.Create(plixStream, transform.OutputSettings) : null) { // Variables that need to be disposed TextReader reader = null; Stream docStream = null; try { // First try to get data from the live object string docText = null; if (itemDocument != null) { if (automationObjectName != null) { docStream = itemDocument.Object(automationObjectName) as Stream; if (docStream != null) { reader = new StreamReader(docStream); } } // Fall back on getting the contents of the text buffer from the live document if (reader == null) { EnvDTE.TextDocument textDoc = itemDocument.Object("TextDocument") as EnvDTE.TextDocument; if (textDoc != null) { docText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint); reader = new StringReader(docText); } } } // If this is a redirection, then pull direction from the file if (reader == null && alternateSourceFile != null) { reader = new StreamReader(alternateSourceFile); } // Fallback on the default reading mechanism if (reader == null) { docText = fileContents; reader = new StringReader(fileContents); } if (transform == null) { XmlReaderSettings testPlixDocumentReaderSettings = new XmlReaderSettings(); testPlixDocumentReaderSettings.CloseInput = false; bool plixDocument = false; try { using (XmlReader testPlixDocumentReader = XmlReader.Create(reader, testPlixDocumentReaderSettings)) { testPlixDocumentReader.MoveToContent(); if (testPlixDocumentReader.NodeType == XmlNodeType.Element && testPlixDocumentReader.NamespaceURI == PlixSchemaNamespace) { plixDocument = true; } } } catch (XmlException ex) { return(GenerateExceptionInformation(ex, provider)); } if (!plixDocument) { StringWriter writer = new StringWriter(); provider.GenerateCodeFromStatement(new CodeCommentStatement("Transform file not found"), writer, null); GenerateNUPlixLoaderExceptionLine(writer, provider); return(writer.ToString()); } if (docText != null) { reader.Dispose(); reader = new StringReader(docText); } else { StreamReader streamReader = (StreamReader)reader; streamReader.BaseStream.Position = 0; } } else { // Use an XmlTextReader here instead of an XPathDocument // so that our transforms support the xsl:preserve-space element transform.Transform(new XmlTextReader(reader), arguments, xmlTextWriter, XmlUtility.CreateFileResolver(sourceFile)); plixStream.Position = 0; } // From the plix stream, generate the code using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { using (XmlReader plixReader = (plixStream != null) ? XmlReader.Create(plixStream, PlixReaderSettings) : XmlReader.Create(reader, PlixReaderSettings)) { formatter.Transform(plixReader, new XsltArgumentList(), writer); } return(writer.ToString()); } } finally { if (reader != null) { (reader as IDisposable).Dispose(); } if (docStream != null) { (docStream as IDisposable).Dispose(); } } } } catch (Exception ex) { return(GenerateExceptionInformation(ex, provider)); } finally { // Regardless of how we finish process this file, we need to find files redirected to this // one and regenerate them. if (alternateSourceFile == null) // We only redirect one level { FileInfo sourceFileInfo = new FileInfo(sourceFile); RunCustomTool( project.ProjectItems, projectItem, delegate(EnvDTE.ProjectItem matchItem) { #if VerifyUIThread Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); #endif VSProjectItem vsProjItem = matchItem.Object as VSProjectItem; if (vsProjItem != null) { string itemFile = (string)matchItem.Properties.Item("LocalPath").Value; EnvDTE.Document liveDoc; EnvDTE.TextDocument textDoc; string liveText = null; if (null != (liveDoc = matchItem.Document) && null != (textDoc = liveDoc.Object("TextDocument") as EnvDTE.TextDocument)) { liveText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint); } try { using (FileStream fileStream = (liveText == null) ? new FileStream(itemFile, FileMode.Open, FileAccess.Read) : null) { using (XmlTextReader reader = new XmlTextReader((liveText == null) ? new StreamReader(fileStream) as TextReader : new StringReader(liveText))) { if (XmlNodeType.Element == reader.MoveToContent()) { if (reader.NamespaceURI == RedirectNamespace && reader.LocalName == RedirectElementName) { FileInfo targetSourceFileInfo = new FileInfo(itemFile.Substring(0, itemFile.LastIndexOf('\\') + 1) + reader.GetAttribute(RedirectTargetAttribute)); if (0 == string.Compare(sourceFileInfo.FullName, targetSourceFileInfo.FullName, true, CultureInfo.CurrentCulture)) { vsProjItem.RunCustomTool(); } } } } } } catch (XmlException) { // Swallow anything that Xml gripes about } } }); } } }
private void AddSpecFlowFooter(CodeDomProvider codeProvider, TextWriter outputWriter, CodeDomHelper codeDomHelper) { codeProvider.GenerateCodeFromStatement(codeDomHelper.GetEndRegionStatement(), outputWriter, null); }
public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu) { if (!(provider is JScriptCodeProvider)) { // GENERATES (C#): // namespace Foo { // public class Foo { // // public int _verifyGlobalGeneration1 = 2147483647; // // public int System { // get { return 42; } // } // // public int Property { // get { return 2147483647; } // } // // public int GlobalTestProperty1 { // get { // return _verifyGlobalGeneration1; // } // set { // _verifyGlobalGeneration1 = value; // } // } // // public global::System.Nullable<int> GlobalTestProperty2 { // get { // return _verifyGlobalGeneration2; // } // set { // _verifyGlobalGeneration2 = value; // } // } // // // public int TestMethod02() { // int iReturn; // iReturn = global::Foo.Foo.Property; // return iReturn; // } // // public int TestMethod03() { // int iReturn; // iReturn = global::System.Math.Abs(-1); // return iReturn; // } // // public int TestMethod04() { // int iReturn; // iReturn = System; // return iReturn; // } // } CodeNamespace ns = new CodeNamespace("Foo"); ns.Comments.Add(new CodeCommentStatement("Foo namespace")); cu.Namespaces.Add(ns); CodeTypeDeclaration cd = new CodeTypeDeclaration("Foo"); ns.Types.Add(cd); CodeMemberProperty property = new CodeMemberProperty(); property.Name = "System"; property.Attributes = MemberAttributes.Public; property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private | MemberAttributes.Static; property.Type = new CodeTypeReference(typeof(int)); property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(42))); cd.Members.Add(property); property = new CodeMemberProperty(); property.Name = "Property"; property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private | MemberAttributes.Static; property.Type = new CodeTypeReference(typeof(int)); property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(Int32.MaxValue))); cd.Members.Add(property); AddScenario("CallTestMethod02", "Call Foo.Foo.TestMethod02."); CodeMemberMethod method2 = new CodeMemberMethod(); method2.Name = "TestMethod02"; method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method2.ReturnType = new CodeTypeReference(typeof(int)); method2.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "iReturn")); CodePropertyReferenceExpression cpr = new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(new CodeTypeReference("Foo.Foo", CodeTypeReferenceOptions.GlobalReference)), "Property"); CodeAssignStatement cas = new CodeAssignStatement(new CodeVariableReferenceExpression("iReturn"), cpr); method2.Statements.Add(cas); method2.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("iReturn"))); cd.Members.Add(method2); AddScenario("CallTestMethod03", "Call Foo.Foo.TestMethod02."); CodeMemberMethod method3 = new CodeMemberMethod(); method3.Name = "TestMethod03"; method3.Attributes = (method3.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method3.ReturnType = new CodeTypeReference(typeof(int)); method3.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "iReturn")); CodeTypeReferenceOptions ctro = CodeTypeReferenceOptions.GlobalReference; CodeTypeReference ctr = new CodeTypeReference(typeof(Math), ctro); CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeTypeReferenceExpression(ctr), "Abs"), new CodeExpression[] { new CodePrimitiveExpression(-1) }); cas = new CodeAssignStatement(new CodeVariableReferenceExpression("iReturn"), cmie); method3.Statements.Add(cas); method3.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("iReturn"))); cd.Members.Add(method3); AddScenario("CallTestMethod04", "Call Foo.Foo.TestMethod04."); CodeMemberMethod method4 = new CodeMemberMethod(); method4.Name = "TestMethod04"; method4.Attributes = (method4.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method4.ReturnType = new CodeTypeReference(typeof(int)); method4.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "iReturn")); cpr = new CodePropertyReferenceExpression(null, "System"); cas = new CodeAssignStatement(new CodeVariableReferenceExpression("iReturn"), cpr); method4.Statements.Add(cas); method4.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("iReturn"))); cd.Members.Add(method4); // Verify that what CodeTypeReferenceOptions are correctly set. // Basically this check gives the code coverage for the get property AddScenario("CTR_GetGlobalRefCheck", "Check that CodeTypeReference.Options gives the proper value."); if (ctr.Options == CodeTypeReferenceOptions.GlobalReference) { VerifyScenario("CTR_GetGlobalRefCheck"); } // one-off generate statements StringWriter sw = new StringWriter(); // global shouldn't be generated in this instance CodeTypeReference variableType = new CodeTypeReference(typeof(System.String), CodeTypeReferenceOptions.GlobalReference); CodeVariableDeclarationStatement variable = new CodeVariableDeclarationStatement(variableType, "myVariable"); provider.GenerateCodeFromStatement(variable, sw, null); // global should be generated in this instance CodeTypeReference variableType2 = new CodeTypeReference(typeof(System.Array), CodeTypeReferenceOptions.GlobalReference); CodeVariableDeclarationStatement variable2 = new CodeVariableDeclarationStatement(variableType2, "myVariable2"); provider.GenerateCodeFromStatement(variable2, sw, null); AddScenario("GlobalKeywordShouldExist", "When an array is referred to, a global qualifier should be generated on it."); if (sw.ToString().IndexOf("global") != -1 && sw.ToString().IndexOf("Global") != -1) { LogMessage("Global keyword does not exist in statement: " + sw.ToString()); } else { VerifyScenario("GlobalKeywordShouldExist"); } } }
protected void AddSpecFlowFooter(CodeDomProvider codeProvider, TextWriter outputWriter) { codeProvider.GenerateCodeFromStatement(codeDomHelper.GetEnableWarningsPragma(), outputWriter, null); codeProvider.GenerateCodeFromStatement(codeDomHelper.GetEndRegionStatement(), outputWriter, null); }
private Assembly CompileInMemoryAssembly() { List <string> finalReferenceList = new List <string>(); this.CombineReferencedAssemblies(finalReferenceList); string[] strArray = this.CombineUsingNamespaces(); using (CodeDomProvider provider = CodeDomProvider.CreateProvider(this.language)) { if (provider is CSharpCodeProvider) { this.AddReferenceAssemblyToReferenceList(finalReferenceList, "System"); } CompilerParameters parameters = new CompilerParameters(finalReferenceList.ToArray()) { IncludeDebugInformation = true, GenerateInMemory = true, GenerateExecutable = false }; StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb, CultureInfo.CurrentCulture); CodeGeneratorOptions options = new CodeGeneratorOptions { BlankLinesBetweenMembers = true, VerbatimOrder = true }; CodeCompileUnit compileUnit = new CodeCompileUnit(); if (this.sourcePath != null) { this.sourceCode = File.ReadAllText(this.sourcePath); } string sourceCode = this.sourceCode; if (this.typeIsFragment || this.typeIsMethod) { CodeTypeDeclaration codeTypeDeclaration = this.CreateTaskClass(); this.CreateTaskProperties(codeTypeDeclaration); if (this.typeIsFragment) { CreateExecuteMethodFromFragment(codeTypeDeclaration, this.sourceCode); } else { CreateTaskBody(codeTypeDeclaration, this.sourceCode); } CodeNamespace namespace2 = new CodeNamespace("InlineCode"); foreach (string str2 in strArray) { namespace2.Imports.Add(new CodeNamespaceImport(str2)); } namespace2.Types.Add(codeTypeDeclaration); compileUnit.Namespaces.Add(namespace2); provider.GenerateCodeFromCompileUnit(compileUnit, writer, options); } else { provider.GenerateCodeFromStatement(new CodeSnippetStatement(this.sourceCode), writer, options); } sourceCode = sb.ToString(); CompilerResults results = provider.CompileAssemblyFromSource(parameters, new string[] { sourceCode }); string path = null; if ((results.Errors.Count > 0) || (Environment.GetEnvironmentVariable("MSBUILDLOGCODETASKFACTORYOUTPUT") != null)) { string tempPath = Path.GetTempPath(); string str5 = "MSBUILDCodeTaskFactoryGeneratedFile" + Guid.NewGuid().ToString() + ".txt"; path = Path.Combine(tempPath, str5); File.WriteAllText(path, sourceCode); } if ((results.NativeCompilerReturnValue != 0) && (results.Errors.Count > 0)) { this.log.LogErrorWithCodeFromResources("CodeTaskFactory.FindSourceFileAt", new object[] { path }); foreach (CompilerError error in results.Errors) { this.log.LogErrorWithCodeFromResources("CodeTaskFactory.CompilerError", new object[] { error.ToString() }); } return(null); } return(results.CompiledAssembly); } }