public void CreateGenerator_ReturnsSame() { CSharpCodeProvider provider = new CSharpCodeProvider(); #pragma warning disable 0618 Assert.Same(provider.CreateGenerator(), provider.CreateGenerator()); #pragma warning restore 0618 }
public void Ctor_IDictionaryStringString(IDictionary<string, string> providerOptions) { CSharpCodeProvider provider = new CSharpCodeProvider(); #pragma warning disable 0618 Assert.NotNull(provider.CreateGenerator()); Assert.Same(provider.CreateGenerator(), provider.CreateCompiler()); #pragma warning restore 0618 }
public void Ctor_Default() { CSharpCodeProvider provider = new CSharpCodeProvider(); #pragma warning disable 0618 Assert.NotNull(provider.CreateGenerator()); Assert.Same(provider.CreateGenerator(), provider.CreateCompiler()); #pragma warning restore 0618 }
public override void SetUp () { base.SetUp (); _typeDeclaration = new CodeTypeDeclaration (); CodeDomProvider provider = new CSharpCodeProvider (); _codeGenerator = provider.CreateGenerator (); }
public virtual string Generate(Window window) { window.ReInitialize(InitializeOption.WithCache); var stringBuilder = new StringBuilder(); var stringWriter = new StringWriter(stringBuilder); var cscProvider = new CSharpCodeProvider(); ICodeGenerator codeGenerator = cscProvider.CreateGenerator(stringWriter); var codeGeneratorOptions = new CodeGeneratorOptions {BlankLinesBetweenMembers = false, VerbatimOrder = false}; codeGenerator.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit(string.Format("using {0};", typeof(UIItem).Namespace)), stringWriter, codeGeneratorOptions); codeGenerator.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit(string.Format("using {0};", typeof(Window).Namespace)), stringWriter, codeGeneratorOptions); codeGenerator.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit(string.Format("using {0};", typeof(AppScreen).Namespace)), stringWriter, codeGeneratorOptions); CodeNamespace codeNamespace = null; if (S.IsNotEmpty(options.Namespace)) { codeNamespace = new CodeNamespace(options.Namespace); } var classDefinition = new CodeTypeDeclaration { IsClass = true, IsPartial = true, Name = window.Title.Trim().Replace(" ", string.Empty), TypeAttributes = TypeAttributes.Public }; classDefinition.BaseTypes.Add(typeof (AppScreen)); var constructor = new CodeConstructor {Attributes = MemberAttributes.Family}; classDefinition.Members.Add(constructor); constructor = new CodeConstructor {Attributes = MemberAttributes.Public}; constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Window), "window")); constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof (ScreenRepository), "screenRepository")); constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("window")); constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("screenRepository")); classDefinition.Members.Add(constructor); var visitor = new CodeGenerationVisitor(new WindowCodeGenerationStrategy(options)); window.Visit(visitor); visitor.Generate(classDefinition); if (codeNamespace != null) { codeNamespace.Types.Add(classDefinition); codeGenerator.GenerateCodeFromNamespace(codeNamespace, stringWriter, codeGeneratorOptions); } else { codeGenerator.GenerateCodeFromType(classDefinition, stringWriter, codeGeneratorOptions); } stringWriter.Close(); return stringBuilder.ToString(); }
/// <summary> /// Main driving routine for building a class /// </summary> void BuildClass(string expression) { // need a string to put the code into _source = new StringBuilder(); StringWriter sw = new StringWriter(_source); //Declare your provider and generator CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeGenerator generator = codeProvider.CreateGenerator(sw); CodeGeneratorOptions codeOpts = new CodeGeneratorOptions(); CodeNamespace myNamespace = new CodeNamespace("ExpressionEvaluator"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); myNamespace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); //Build the class declaration and member variables CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration(); classDeclaration.IsClass = true; classDeclaration.Name = "Calculator"; classDeclaration.Attributes = MemberAttributes.Public; classDeclaration.Members.Add(FieldVariable("answer", typeof(string), MemberAttributes.Private)); //default constructor CodeConstructor defaultConstructor = new CodeConstructor(); defaultConstructor.Attributes = MemberAttributes.Public; defaultConstructor.Comments.Add(new CodeCommentStatement("Default Constructor for class", true)); defaultConstructor.Statements.Add(new CodeSnippetStatement("//TODO: implement default constructor")); classDeclaration.Members.Add(defaultConstructor); //property classDeclaration.Members.Add(this.MakeProperty("Answer", "answer", typeof(string))); //Our Calculate Method CodeMemberMethod myMethod = new CodeMemberMethod(); myMethod.Name = "Calculate"; myMethod.ReturnType = new CodeTypeReference(typeof(string)); myMethod.Comments.Add(new CodeCommentStatement("Calculate an expression", true)); myMethod.Attributes = MemberAttributes.Public; myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Object obj"), new CodeSnippetExpression(expression))); myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Answer"), new CodeSnippetExpression("obj.ToString()"))); myMethod.Statements.Add( new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Answer"))); classDeclaration.Members.Add(myMethod); //write code myNamespace.Types.Add(classDeclaration); generator.GenerateCodeFromNamespace(myNamespace, sw, codeOpts); sw.Flush(); sw.Close(); }
public static System.Reflection.Assembly CreateAssemblyFromDataTable(DataTable DataValues) { System.Random rnd = new Random(); if(DataValues.TableName == null || DataValues.TableName == "") DataValues.TableName = rnd.Next().ToString(); object result = null; CodeTypeDeclaration classDec = new CodeTypeDeclaration(DataValues.TableName); classDec.IsClass = true; CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; classDec.Members.Add(classDec); foreach(System.Data.DataColumn col in DataValues.Columns) { AddPropertyAndField(classDec, col.DataType, "", col.ColumnName); } AddPropertyAndField(classDec, null, "System.Collections.Generic.List<" + DataValues.TableName + ">", "ListOf" + DataValues.TableName); using(CSharpCodeProvider provider = new CSharpCodeProvider()) { ICodeGenerator generator = provider.CreateGenerator(); CodeNamespace ns = new CodeNamespace("Terminals.Generated"); ns.Types.Add((CodeTypeDeclaration)classDec); CodeGeneratorOptions options = new CodeGeneratorOptions(); //options.BlankLinesBetweenMembers = true; string filename = System.IO.Path.GetTempFileName(); using(System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, false)) { generator.GenerateCodeFromNamespace(ns, sw, options); ICodeCompiler icc = provider.CreateCompiler(); CompilerParameters compileParams = new CompilerParameters(); compileParams.GenerateExecutable = false; compileParams.GenerateInMemory = true; return icc.CompileAssemblyFromSource(compileParams, System.IO.File.ReadAllText(filename)).CompiledAssembly; } } return null; }
/// <summary> /// Constructor for the XsdGen class. /// </summary> /// <param name="args">Command-line arguments passed to the program.</param> private XsdGen(string[] args) { this.ParseCommandlineArgs(args); // show usage information if (this.showHelp) { Console.WriteLine("usage: XsdGen.exe <schema>.xsd <outputFile> <namespace>"); return; } // ensure that the schema file exists if (!File.Exists(this.xsdFile)) { throw new ApplicationException(String.Format("Schema file does not exist: '{0}'.", this.xsdFile)); } XmlSchema document = null; using (StreamReader xsdFileReader = new StreamReader(this.xsdFile)) { document = XmlSchema.Read(xsdFileReader, new ValidationEventHandler(this.ValidationHandler)); } CodeCompileUnit codeCompileUnit = StronglyTypedClasses.Generate(document, this.outputNamespace); using (CSharpCodeProvider codeProvider = new CSharpCodeProvider()) { ICodeGenerator generator = codeProvider.CreateGenerator(); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = true; options.BracingStyle = "C"; options.IndentString = " "; using (StreamWriter csFileWriter = new StreamWriter(this.outFile)) { generator.GenerateCodeFromCompileUnit(codeCompileUnit, csFileWriter, options); } } }
public void Deny_Unrestricted () { CSharpCodeProvider csprov = new CSharpCodeProvider (); Assert.AreEqual ("cs", csprov.FileExtension, "FileExtension"); Assert.IsNotNull (csprov.CreateCompiler (), "CreateCompiler"); Assert.IsNotNull (csprov.CreateGenerator (), "CreateGenerator"); try { Assert.IsNotNull (csprov.GetConverter (typeof (string)), "GetConverter"); } catch (NotImplementedException) { // mono } CodeTypeMember ctm = new CodeTypeMember (); StringWriter sw = new StringWriter (); CodeGeneratorOptions cgo = new CodeGeneratorOptions (); try { csprov.GenerateCodeFromMember (ctm, sw, cgo); } catch (NotImplementedException) { // mono } }
[Category ("NotWorking")] // TODO: order of DefaultValueAttribute, ... public void ExportTypeMapping_Field () { CodeNamespace codeNamespace = ExportCode (typeof (Field)); Assert.IsNotNull (codeNamespace, "#1"); StringWriter sw = new StringWriter (); CodeDomProvider provider = new CSharpCodeProvider (); ICodeGenerator generator = provider.CreateGenerator (); generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ()); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}{0}" + "/// <remarks/>{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Diagnostics.DebuggerStepThroughAttribute()]{0}" + "[System.ComponentModel.DesignerCategoryAttribute(\"code\")]{0}" + "[System.Xml.Serialization.XmlRootAttribute(\"field\", Namespace=\"\", IsNullable=true)]{0}" + "public partial class Field {{{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.FlagEnum flags1Field;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.FlagEnum flags2Field;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.FlagEnum flags3Field;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.FlagEnum flags4Field;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.MapModifiers modifiersField;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.MapModifiers modifiers2Field;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.MapModifiers modifiers3Field;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.MapModifiers modifiers4Field;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.MapModifiers modifiers5Field;{0}" + " {0}" + " private string[] namesField;{0}" + " {0}" + " private string streetField;{0}" + " {0}" + " public Field() {{{0}" + " this.flags1Field = MonoTests.System.Xml.TestClasses.FlagEnum.e1;{0}" + " this.flags2Field = MonoTests.System.Xml.TestClasses.FlagEnum.e1;{0}" + " this.flags3Field = (MonoTests.System.Xml.TestClasses.FlagEnum.e1 | MonoTests.System.Xml.TestClasses.FlagEnum.e2);{0}" + " this.modifiers3Field = MonoTests.System.Xml.TestClasses.MapModifiers.Public;{0}" + " this.modifiers4Field = MonoTests.System.Xml.TestClasses.MapModifiers.Protected;{0}" + " this.modifiers5Field = MonoTests.System.Xml.TestClasses.MapModifiers.Public;{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlAttributeAttribute(\"flag1\")]{0}" + " public MonoTests.System.Xml.TestClasses.FlagEnum Flags1 {{{0}" + " get {{{0}" + " return this.flags1Field;{0}" + " }}{0}" + " set {{{0}" + " this.flags1Field = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlAttributeAttribute(\"flag2\")]{0}" + " public MonoTests.System.Xml.TestClasses.FlagEnum Flags2 {{{0}" + " get {{{0}" + " return this.flags2Field;{0}" + " }}{0}" + " set {{{0}" + " this.flags2Field = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlAttributeAttribute(\"flag3\", Form=System.Xml.Schema.XmlSchemaForm.Qualified)]{0}" + " public MonoTests.System.Xml.TestClasses.FlagEnum Flags3 {{{0}" + " get {{{0}" + " return this.flags3Field;{0}" + " }}{0}" + " set {{{0}" + " this.flags3Field = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlAttributeAttribute(\"flag4\")]{0}" + " public MonoTests.System.Xml.TestClasses.FlagEnum Flags4 {{{0}" + " get {{{0}" + " return this.flags4Field;{0}" + " }}{0}" + " set {{{0}" + " this.flags4Field = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlAttributeAttribute(\"modifiers\")]{0}" + " public MonoTests.System.Xml.TestClasses.MapModifiers Modifiers {{{0}" + " get {{{0}" + " return this.modifiersField;{0}" + " }}{0}" + " set {{{0}" + " this.modifiersField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlAttributeAttribute(\"modifiers2\")]{0}" + " public MonoTests.System.Xml.TestClasses.MapModifiers Modifiers2 {{{0}" + " get {{{0}" + " return this.modifiers2Field;{0}" + " }}{0}" + " set {{{0}" + " this.modifiers2Field = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlAttributeAttribute(\"modifiers3\")]{0}" + " public MonoTests.System.Xml.TestClasses.MapModifiers Modifiers3 {{{0}" + " get {{{0}" + " return this.modifiers3Field;{0}" + " }}{0}" + " set {{{0}" + " this.modifiers3Field = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlAttributeAttribute(\"modifiers4\")]{0}" + " public MonoTests.System.Xml.TestClasses.MapModifiers Modifiers4 {{{0}" + " get {{{0}" + " return this.modifiers4Field;{0}" + " }}{0}" + " set {{{0}" + " this.modifiers4Field = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlAttributeAttribute(\"modifiers5\", Form=System.Xml.Schema.XmlSchemaForm.Qualified)]{0}" + " public MonoTests.System.Xml.TestClasses.MapModifiers Modifiers5 {{{0}" + " get {{{0}" + " return this.modifiers5Field;{0}" + " }}{0}" + " set {{{0}" + " this.modifiers5Field = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlAttributeAttribute(\"names\")]{0}" + " public string[] Names {{{0}" + " get {{{0}" + " return this.namesField;{0}" + " }}{0}" + " set {{{0}" + " this.namesField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlAttributeAttribute(\"street\")]{0}" + " public string Street {{{0}" + " get {{{0}" + " return this.streetField;{0}" + " }}{0}" + " set {{{0}" + " this.streetField = value;{0}" + " }}{0}" + " }}{0}" + "}}{0}" + "{0}" + "/// <remarks/>{0}" + "[System.FlagsAttribute()]{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Xml\", \"{1}\")]{0}" + "[System.SerializableAttribute()]{0}" + "public enum FlagEnum {{{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"one\")]{0}" + " e1 = 1,{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"two\")]{0}" + " e2 = 2,{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"four\")]{0}" + " e4 = 4,{0}" + "}}{0}" + "{0}" + "/// <remarks/>{0}" + "[System.FlagsAttribute()]{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" + "[System.SerializableAttribute()]{0}" + "public enum MapModifiers {{{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"public\")]{0}" + " Public = 1,{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"protected\")]{0}" + " Protected = 2,{0}" + "}}{0}", Environment.NewLine), sw.ToString (), "#2"); }
public void ExportTypeMapping_ItemChoiceType () { CodeNamespace codeNamespace = ExportCode (typeof (ItemChoiceType)); Assert.IsNotNull (codeNamespace, "#1"); StringWriter sw = new StringWriter (); CodeDomProvider provider = new CSharpCodeProvider (); ICodeGenerator generator = provider.CreateGenerator (); generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ()); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}{0}" + "/// <remarks/>{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Xml.Serialization.XmlTypeAttribute(IncludeInSchema=false)]{0}" + "[System.Xml.Serialization.XmlRootAttribute(Namespace=\"\", IsNullable=false)]{0}" + "public enum ItemChoiceType {{{0}" + " {0}" + " /// <remarks/>{0}" + " ChoiceZero,{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"ChoiceOne\")]{0}" + " StrangeOne,{0}" + " {0}" + " /// <remarks/>{0}" + " ChoiceTwo,{0}" + "}}{0}", Environment.NewLine), sw.ToString (), "#2"); codeNamespace = ExportCode (typeof (ItemChoiceType[])); Assert.IsNotNull (codeNamespace, "#3"); sw.GetStringBuilder ().Length = 0; generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ()); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}{0}" + "/// <remarks/>{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Xml.Serialization.XmlTypeAttribute(IncludeInSchema=false)]{0}" + "public enum ItemChoiceType {{{0}" + " {0}" + " /// <remarks/>{0}" + " ChoiceZero,{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"ChoiceOne\")]{0}" + " StrangeOne,{0}" + " {0}" + " /// <remarks/>{0}" + " ChoiceTwo,{0}" + "}}{0}", Environment.NewLine), sw.ToString (), "#4"); }
public void SetUp () { provider = new CSharpCodeProvider (); generator = provider.CreateGenerator (); options = new CodeGeneratorOptions (); }
static void Main(string[] args) { // Prompt for target language. Console.Write("Do you want to generate C# or VB .NET code? "); syntaxTarget = Console.ReadLine(); // Get ICodeGenerator interface. switch(syntaxTarget.ToUpper()) { case "C#": case "CSharp": case "CS": syntaxTarget = "cs"; CSharpCodeProvider cdp = new CSharpCodeProvider(); itfCG = cdp.CreateGenerator(); itfCC = cdp.CreateCompiler(); break; case "VB .NET": case "VB.NET": case "VB": syntaxTarget = "vb"; VBCodeProvider vbdp = new VBCodeProvider(); itfCG = vbdp.CreateGenerator(); itfCC = vbdp.CreateCompiler(); break; default: Console.WriteLine("Sorry...can't do it..."); syntaxTarget = null; break; } // Only proceed if they picked a valid language // supported by System.CodeDOM. if(syntaxTarget != null) { // Now create the file and generate the code! TextWriter txtWriter = CreateFile(syntaxTarget); PopulateNamespace(itfCG, txtWriter); txtWriter.Close(); Console.WriteLine("Done!"); // Now compile the code into a .NET DLL. Console.WriteLine("Compiling code..."); CompileCode(itfCC, syntaxTarget); // Now launch the application! Console.Write("Enter your message: "); string msg = Console.ReadLine(); LoadAndRunAsm(msg); Console.WriteLine("Thanks for playing..."); } }
/// <summary> /// Generate the actual C# code. /// </summary> /// <param name="codeCompileUnit">The code DOM.</param> /// <param name="destClassFile">Destination C# source file.</param> public static void GenerateCSharpCode(CodeCompileUnit codeCompileUnit, string destClassFile) { // generate the code with the C# code provider CSharpCodeProvider provider = new CSharpCodeProvider(); // obtain an ICodeGenerator from the CodeDomProvider class ICodeGenerator gen = provider.CreateGenerator(); // create a TextWriter to a StreamWriter to the output file using (StreamWriter sw = new StreamWriter(destClassFile)) { using (IndentedTextWriter tw = new IndentedTextWriter(sw, " ")) { CodeGeneratorOptions options = new CodeGeneratorOptions(); // code generation options options.BlankLinesBetweenMembers = true; options.BracingStyle = "C"; // generate source code using the code generator gen.GenerateCodeFromCompileUnit(codeCompileUnit, tw, options); } } }
public static String GenerateFullClass(ICollection<String> references, ICollection<String> imports, String CodeNamespace, String className, string methodBody, String method = "Method") { CodeCompileUnit unit = new CodeCompileUnit(); if (references != null) { foreach (var item in references) { unit.ReferencedAssemblies.Add(item); } } CodeNamespace customEntityRoot = new CodeNamespace(CodeNamespace);//Create a namespace unit.Namespaces.Add(customEntityRoot); if (imports != null) { foreach (var item in imports) { customEntityRoot.Imports.Add(new CodeNamespaceImport(item)); } } CodeTypeDeclaration derived = new CodeTypeDeclaration(className); customEntityRoot.Types.Add(derived); CodeConstructor derivedClassConstructor = new CodeConstructor(); derivedClassConstructor.Attributes = MemberAttributes.Public; derived.Members.Add(derivedClassConstructor); CodeMemberMethod derivedMethod = new CodeMemberMethod(); derivedMethod.Attributes = MemberAttributes.Public ; derivedMethod.Name = method; derivedMethod.ReturnType = new CodeTypeReference(typeof(void)); CodeSnippetStatement code = new CodeSnippetStatement(methodBody); derivedMethod.Statements.Add(code); derived.Members.Add(derivedMethod); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeGenerator codeGenerator = codeProvider.CreateGenerator(); StringBuilder generatedCode = new StringBuilder(); StringWriter codeWriter = new StringWriter(generatedCode); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BracingStyle = "C"; codeGenerator.GenerateCodeFromCompileUnit(unit, codeWriter, options); return generatedCode.ToString(); }
public void ExportTypeMapping_ClassArrayContainer () { CodeNamespace codeNamespace = ExportCode (typeof (ClassArrayContainer)); Assert.IsNotNull (codeNamespace, "#1"); StringWriter sw = new StringWriter (); CodeDomProvider provider = new CSharpCodeProvider (); ICodeGenerator generator = provider.CreateGenerator (); generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ()); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}{0}" + "/// <remarks/>{0}" + #if NET_2_0 "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Xml\", \"{1}\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Diagnostics.DebuggerStepThroughAttribute()]{0}" + "[System.ComponentModel.DesignerCategoryAttribute(\"code\")]{0}" + "[System.Xml.Serialization.XmlRootAttribute(Namespace=\"\", IsNullable=true)]{0}" + "public partial class ClassArrayContainer {{{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.SimpleClass[] itemsField;{0}" + " {0}" + " /// <remarks/>{0}" + " public MonoTests.System.Xml.TestClasses.SimpleClass[] items {{{0}" + " get {{{0}" + " return this.itemsField;{0}" + " }}{0}" + " set {{{0}" + " this.itemsField = value;{0}" + " }}{0}" + " }}{0}" + "}}{0}" + "{0}" + "/// <remarks/>{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Xml\", \"{1}\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Diagnostics.DebuggerStepThroughAttribute()]{0}" + "[System.ComponentModel.DesignerCategoryAttribute(\"code\")]{0}" + "public partial class SimpleClass {{{0}" + " {0}" + " private string somethingField;{0}" + " {0}" + " /// <remarks/>{0}" + " public string something {{{0}" + " get {{{0}" + " return this.somethingField;{0}" + " }}{0}" + " set {{{0}" + " this.somethingField = value;{0}" + " }}{0}" + " }}{0}" + "}}{0}", Environment.NewLine, XmlFileVersion), sw.ToString (), "#2"); #else "[System.Xml.Serialization.XmlRootAttribute(Namespace=\"\", IsNullable=true)]{0}" + "public class ClassArrayContainer {{{0}" + " {0}" + " /// <remarks/>{0}" + " public MonoTests.System.Xml.TestClasses.SimpleClass[] items;{0}" + "}}{0}" + "{0}" + "/// <remarks/>{0}" + "public class SimpleClass {{{0}" + " {0}" + " /// <remarks/>{0}" + " public string something;{0}" + "}}{0}", Environment.NewLine), sw.ToString (), "#2"); #endif }
/// <summary> /// Main driving routine for building a class /// </summary> void BuildClass(string expression, Dictionary<string, double> vars, bool bSimpleAssign, bool bRetArray, int arrayLen) { // need a string to put the code into _source = new StringBuilder(); StringWriter sw = new StringWriter(_source); //Declare provider and generator CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeGenerator generator = codeProvider.CreateGenerator(sw); CodeGeneratorOptions codeOpts = new CodeGeneratorOptions(); CodeNamespace myNamespace = new CodeNamespace("ExpressionEvaluator"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); //myNamespace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); //Build the class declaration and member variables CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration(); classDeclaration.IsClass = true; classDeclaration.Name = "Calculator"; classDeclaration.Attributes = MemberAttributes.Public; classDeclaration.Members.Add(FieldVariable("ans", typeof(double), MemberAttributes.Private)); classDeclaration.Members.Add(FieldVariable("arrAns", typeof(double[]), MemberAttributes.Private)); foreach (KeyValuePair<string, double> k in vars) classDeclaration.Members.Add(FieldVariable(k.Key, typeof(double), MemberAttributes.Private)); //default constructor CodeConstructor defaultConstructor = new CodeConstructor(); defaultConstructor.Attributes = MemberAttributes.Public; defaultConstructor.Comments.Add(new CodeCommentStatement("Default Constructor for class", true)); classDeclaration.Members.Add(defaultConstructor); CodeTypeDelegate dg = new CodeTypeDelegate("FN1"); dg.ReturnType = new CodeTypeReference(typeof(double)); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p0")); classDeclaration.Members.Add(dg); dg = new CodeTypeDelegate("FN2"); dg.ReturnType = new CodeTypeReference(typeof(double)); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p0")); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p1")); classDeclaration.Members.Add(dg); dg = new CodeTypeDelegate("FN3"); dg.ReturnType = new CodeTypeReference(typeof(double)); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p0")); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p1")); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p2")); classDeclaration.Members.Add(dg); //property classDeclaration.Members.Add(this.MakeProperty("Ans", "ans", typeof(double))); classDeclaration.Members.Add(this.MakeProperty("ArrAns", "arrAns", typeof(double[]))); //Our Calculate Method CodeMemberMethod myMethod = new CodeMemberMethod(); myMethod.Name = "Calculate"; myMethod.Attributes = MemberAttributes.Public; if (bRetArray) { myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("arrAns"), new CodeSnippetExpression("new double["+arrayLen.ToString(CultureInfo.InvariantCulture)+"]"))); myMethod.ReturnType = new CodeTypeReference(typeof(double[])); } else { myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("ans"), new CodeSnippetExpression("0.0"))); myMethod.ReturnType = new CodeTypeReference(typeof(double)); } foreach (KeyValuePair<string, double> k in vars) myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression(k.Key), new CodeSnippetExpression(k.Value.ToString(CultureInfo.InvariantCulture)))); if (bSimpleAssign) //require a full statement? myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression(bRetArray?"arrAns":"ans"), new CodeSnippetExpression(expression))); else myMethod.Statements.Add(new CodeSnippetExpression(expression)); if (bRetArray) myMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "arrAns"))); else myMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Ans"))); classDeclaration.Members.Add(myMethod); //write code myNamespace.Types.Add(classDeclaration); generator.GenerateCodeFromNamespace(myNamespace, sw, codeOpts); sw.Flush(); sw.Close(); }
public Interpreter() { this.varTable = new HashtableWithItemGetterHook(this); AddNamespace("System"); AddNamespace("System.Collections"); AddReference("System.dll"); // Also works on Mono SetValue("interpreter", this); SetValue("_", this); Utils.interpreter = this; string fullExecutablePath = FullExecutablePath(); if (File.Exists(fullExecutablePath)) { AddReference(fullExecutablePath); } string localNamespace = typeof(Interpreter).Namespace; if (!string.IsNullOrEmpty(localNamespace)) { AddNamespace(localNamespace); } prov = new CSharpCodeProvider(); using (StringWriter stringWriter = new StringWriter()) { gen = prov.CreateGenerator(stringWriter); } }
void Run (string[] args) { if (args.Length < 1) Usage ("Invalid number of parameters"); Stack context = new Stack (); GroupDefinition groupZero = new GroupDefinition (); GroupDefinition group, current; XmlReader reader = null; string outfile = null, infile = null; string a; for (int i = 0; i < args.Length; i++) { a = args [i]; if (a [0] == '-' && a.Length > 1) { a = a.Substring (1).Trim (); switch (a.ToLower ()) { case "o": case "output": case "-output": i++; if (i > args.Length) Usage ("Missing output file name"); outfile = args [i]; break; case "h": case "help": case "-help": Usage (null); break; default: Usage ("Unknown command line option: '{0}'", a); break; } } else if (infile == null) infile = args [i]; } if (infile == null) Usage ("Missing input file on the command line."); try { XmlNodeType nodeType; int level = 1; bool ingroup = false; reader = new XmlTextReader (infile); while (reader.Read ()) { nodeType = reader.NodeType; if (nodeType != XmlNodeType.Element && nodeType != XmlNodeType.EndElement) continue; current = context.Count > 0 ? context.Peek () as GroupDefinition : null; if (ingroup && reader.LocalName == "except") { if (current == null) throw new ApplicationException ("Inside a group but there is no group on the stack"); current.AddExcept (reader); continue; } if (reader.LocalName != "group") continue; if (reader.NodeType == XmlNodeType.EndElement) { if (current == null) throw new ApplicationException ("Found group end, but no current group on stack"); context.Pop (); if (context.Count == 0) { groupZero.ChildGroups.Add (current); current.GroupId = groupZero.ChildGroups.Count; } level--; ingroup = false; continue; } group = new GroupDefinition (reader); group.Level = level++; if (current != null) { current.ChildGroups.Add (group); group.GroupId = current.ChildGroups.Count; } context.Push (group); ingroup = true; } } catch (Exception) { throw; } finally { if (reader != null) reader.Close(); } CodeCompileUnit unit = groupZero.GenerateCode (); if (unit == null) Environment.Exit (1); CodeDomProvider provider = new CSharpCodeProvider (); ICodeGenerator gen = provider.CreateGenerator (); TextWriter tw; if (outfile == null) tw = Console.Out; else tw = new IndentedTextWriter (new StreamWriter (outfile, false), "\t"); gen.GenerateCodeFromCompileUnit (unit, tw, new CodeGeneratorOptions ()); if (outfile != null) tw.Close (); }
public void ExportTypeMapping_ZeroFlagEnum () { CodeNamespace codeNamespace = ExportCode (typeof (ZeroFlagEnum)); Assert.IsNotNull (codeNamespace, "#1"); StringWriter sw = new StringWriter (); CodeDomProvider provider = new CSharpCodeProvider (); ICodeGenerator generator = provider.CreateGenerator (); generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ()); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}{0}" + "/// <remarks/>{0}" + "[System.FlagsAttribute()]{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Xml.Serialization.XmlRootAttribute(Namespace=\"\", IsNullable=false)]{0}" + "public enum ZeroFlagEnum {{{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"zero\")]{0}" + " e0 = 1,{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"o<n>e\")]{0}" + " e1 = 2,{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"tns:t<w>o\")]{0}" + " e2 = 4,{0}" + "}}{0}", Environment.NewLine), sw.ToString (), "#2"); }
[Category ("NotWorking")] // bug #78214 public void ExportTypeMapping_Root () { CodeNamespace codeNamespace = ExportCode (typeof (Root)); Assert.IsNotNull (codeNamespace, "#1"); StringWriter sw = new StringWriter (); CodeDomProvider provider = new CSharpCodeProvider (); ICodeGenerator generator = provider.CreateGenerator (); generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ()); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}{0}" + "/// <remarks/>{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Diagnostics.DebuggerStepThroughAttribute()]{0}" + "[System.ComponentModel.DesignerCategoryAttribute(\"code\")]{0}" + "[System.Xml.Serialization.XmlTypeAttribute(Namespace=\"urn:aNS\")]{0}" + "[System.Xml.Serialization.XmlRootAttribute(\"root\", Namespace=\"urn:aNS\", IsNullable=false)]{0}" + "public partial class Root {{{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.OptionalValueTypeContainer optionalValueField;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.TestDefault defaultField;{0}" + " {0}" + " /// <remarks/>{0}" + " public MonoTests.System.Xml.TestClasses.OptionalValueTypeContainer OptionalValue {{{0}" + " get {{{0}" + " return this.optionalValueField;{0}" + " }}{0}" + " set {{{0}" + " this.optionalValueField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public MonoTests.System.Xml.TestClasses.TestDefault Default {{{0}" + " get {{{0}" + " return this.defaultField;{0}" + " }}{0}" + " set {{{0}" + " this.defaultField = value;{0}" + " }}{0}" + " }}{0}" + "}}{0}" + "{0}" + "/// <remarks/>{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Diagnostics.DebuggerStepThroughAttribute()]{0}" + "[System.ComponentModel.DesignerCategoryAttribute(\"code\")]{0}" + "[System.Xml.Serialization.XmlTypeAttribute(TypeName=\"optionalValueType\", Namespace=\"some:urn\")]{0}" + "public partial class OptionalValueTypeContainer {{{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.FlagEnum attributesField;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.FlagEnum flagsField;{0}" + " {0}" + " private bool flagsFieldSpecified;{0}" + " {0}" + " private bool isEmptyField;{0}" + " {0}" + " private bool isEmptyFieldSpecified;{0}" + " {0}" + " private bool isNullField;{0}" + " {0}" + " public OptionalValueTypeContainer() {{{0}" + " this.attributesField = (MonoTests.System.Xml.TestClasses.FlagEnum.e1 | MonoTests.System.Xml.TestClasses.FlagEnum.e4);{0}" + " this.flagsField = MonoTests.System.Xml.TestClasses.FlagEnum.e1;{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public MonoTests.System.Xml.TestClasses.FlagEnum Attributes {{{0}" + " get {{{0}" + " return this.attributesField;{0}" + " }}{0}" + " set {{{0}" + " this.attributesField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public MonoTests.System.Xml.TestClasses.FlagEnum Flags {{{0}" + " get {{{0}" + " return this.flagsField;{0}" + " }}{0}" + " set {{{0}" + " this.flagsField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlIgnoreAttribute()]{0}" + " public bool FlagsSpecified {{{0}" + " get {{{0}" + " return this.flagsFieldSpecified;{0}" + " }}{0}" + " set {{{0}" + " this.flagsFieldSpecified = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public bool IsEmpty {{{0}" + " get {{{0}" + " return this.isEmptyField;{0}" + " }}{0}" + " set {{{0}" + " this.isEmptyField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlIgnoreAttribute()]{0}" + " public bool IsEmptySpecified {{{0}" + " get {{{0}" + " return this.isEmptyFieldSpecified;{0}" + " }}{0}" + " set {{{0}" + " this.isEmptyFieldSpecified = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public bool IsNull {{{0}" + " get {{{0}" + " return this.isNullField;{0}" + " }}{0}" + " set {{{0}" + " this.isNullField = value;{0}" + " }}{0}" + " }}{0}" + "}}{0}" + "{0}" + "/// <remarks/>{0}" + "[System.FlagsAttribute()]{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Xml.Serialization.XmlTypeAttribute(Namespace=\"some:urn\")]{0}" + "public enum FlagEnum {{{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"one\")]{0}" + " e1 = 1,{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"two\")]{0}" + " e2 = 2,{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"four\")]{0}" + " e4 = 4,{0}" + "}}{0}" + "{0}" + "/// <remarks/>{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Xml\", \"{1}\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Diagnostics.DebuggerStepThroughAttribute()]{0}" + "[System.ComponentModel.DesignerCategoryAttribute(\"code\")]{0}" + "[System.Xml.Serialization.XmlTypeAttribute(Namespace=\"urn:myNS\")]{0}" + "public partial class TestDefault {{{0}" + " {0}" + " private string strField;{0}" + " {0}" + " private string strDefaultField;{0}" + " {0}" + " private bool boolTField;{0}" + " {0}" + " private bool boolFField;{0}" + " {0}" + " private decimal decimalvalField;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.FlagEnum flagField;{0}" + " {0}" + " private MonoTests.System.Xml.TestClasses.FlagEnum_Encoded flagencodedField;{0}" + " {0}" + " public TestDefault() {{{0}" + " this.strDefaultField = \"Default Value\";{0}" + " this.flagField = (MonoTests.System.Xml.TestClasses.FlagEnum.e1 | MonoTests.System.Xml.TestClasses.FlagEnum.e4);{0}" + " this.flagencodedField = (MonoTests.System.Xml.TestClasses.FlagEnum_Encoded.e1 | MonoTests.System.Xml.TestClasses.FlagEnum_Encoded.e4);{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public string str {{{0}" + " get {{{0}" + " return this.strField;{0}" + " }}{0}" + " set {{{0}" + " this.strField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public string strDefault {{{0}" + " get {{{0}" + " return this.strDefaultField;{0}" + " }}{0}" + " set {{{0}" + " this.strDefaultField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public bool boolT {{{0}" + " get {{{0}" + " return this.boolTField;{0}" + " }}{0}" + " set {{{0}" + " this.boolTField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public bool boolF {{{0}" + " get {{{0}" + " return this.boolFField;{0}" + " }}{0}" + " set {{{0}" + " this.boolFField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public decimal decimalval {{{0}" + " get {{{0}" + " return this.decimalvalField;{0}" + " }}{0}" + " set {{{0}" + " this.decimalvalField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public MonoTests.System.Xml.TestClasses.FlagEnum flag {{{0}" + " get {{{0}" + " return this.flagField;{0}" + " }}{0}" + " set {{{0}" + " this.flagField = value;{0}" + " }}{0}" + " }}{0}" + " {0}" + " /// <remarks/>{0}" + " public MonoTests.System.Xml.TestClasses.FlagEnum_Encoded flagencoded {{{0}" + " get {{{0}" + " return this.flagencodedField;{0}" + " }}{0}" + " set {{{0}" + " this.flagencodedField = value;{0}" + " }}{0}" + " }}{0}" + "}}{0}" + "{0}" + "/// <remarks/>{0}" + "[System.FlagsAttribute()]{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Xml.Serialization.XmlTypeAttribute(Namespace=\"urn:myNS\")]{0}" + "public enum FlagEnum {{{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"one\")]{0}" + " e1 = 1,{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"two\")]{0}" + " e2 = 2,{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlEnumAttribute(\"four\")]{0}" + " e4 = 4,{0}" + "}}{0}" + "{0}" + "/// <remarks/>{0}" + "[System.FlagsAttribute()]{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Xml.Serialization.XmlTypeAttribute(Namespace=\"urn:myNS\")]{0}" + "public enum FlagEnum_Encoded {{{0}" + " {0}" + " /// <remarks/>{0}" + " e1 = 1,{0}" + " {0}" + " /// <remarks/>{0}" + " e2 = 2,{0}" + " {0}" + " /// <remarks/>{0}" + " e4 = 4,{0}" + "}}{0}", Environment.NewLine), sw.ToString (), "#2"); }
private static Assembly GenerateAssembly(string asmxFile) { string strWsdl = WsdlFromUrl(GetApplicationPath() + "/" + asmxFile + "?wsdl"); // Xml text reader StringReader wsdlStringReader = new StringReader(strWsdl); XmlTextReader tr = new XmlTextReader(wsdlStringReader); ServiceDescription sd = ServiceDescription.Read(tr); tr.Close(); // WSDL service description importer CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace codeNamespaceFluorine = new CodeNamespace("FluorineFx"); codeCompileUnit.Namespaces.Add(codeNamespaceFluorine); CodeNamespace codeNamespace = new CodeNamespace(FluorineConfiguration.Instance.WsdlProxyNamespace); codeCompileUnit.Namespaces.Add(codeNamespace); #if (NET_1_1) ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, null, null); sdi.ProtocolName = "Soap"; sdi.Import(codeNamespace, codeCompileUnit); CSharpCodeProvider provider = new CSharpCodeProvider(); #else // Create a WSDL collection. DiscoveryClientDocumentCollection wsdlCollection = new DiscoveryClientDocumentCollection(); wsdlCollection.Add(asmxFile, sd); // Create a web refererence using the WSDL collection. WebReference reference = new WebReference(wsdlCollection, codeNamespace); reference.ProtocolName = "Soap12"; // Create a web reference collection. WebReferenceCollection references = new WebReferenceCollection(); references.Add(reference); WebReferenceOptions options = new WebReferenceOptions(); options.Style = ServiceDescriptionImportStyle.Client; options.CodeGenerationOptions = CodeGenerationOptions.None; options.SchemaImporterExtensions.Add(typeof(DataTableSchemaImporterExtension).AssemblyQualifiedName); CSharpCodeProvider provider = new CSharpCodeProvider(); ServiceDescriptionImporter.GenerateWebReferences(references, provider, codeCompileUnit, options); // Compile a proxy client //provider.GenerateCodeFromCompileUnit(codeCompileUnit, Console.Out, new CodeGeneratorOptions()); #endif //http://support.microsoft.com/default.aspx?scid=kb;en-us;326790 //http://pluralsight.com/wiki/default.aspx/Craig.RebuildingWsdlExe if (!FluorineConfiguration.Instance.WsdlGenerateProxyClasses) { //Strip any code that isn't the proxy class itself. foreach (CodeNamespace cns in codeCompileUnit.Namespaces) { // Remove anything that isn't the proxy itself ArrayList typesToRemove = new ArrayList(); foreach (CodeTypeDeclaration codeType in cns.Types) { bool webDerived = false; foreach (CodeTypeReference baseType in codeType.BaseTypes) { if (baseType.BaseType == "System.Web.Services.Protocols.SoapHttpClientProtocol") { webDerived = true; break; } } if (!webDerived) typesToRemove.Add(codeType); else { CodeAttributeDeclaration codeAttributeDeclaration = new CodeAttributeDeclaration(typeof(FluorineFx.RemotingServiceAttribute).FullName); codeType.CustomAttributes.Add(codeAttributeDeclaration); foreach (CodeTypeMember member in codeType.Members) { CodeConstructor ctor = member as CodeConstructor; if (ctor != null) { // We got a constructor // Add CookieContainer code // this.CookieContainer = new System.Net.CookieContainer(); //Session Cookie CodeSnippetStatement statement = new CodeSnippetStatement("this.CookieContainer = new System.Net.CookieContainer(); //Session Cookie"); ctor.Statements.Add(statement); } } } } foreach (CodeTypeDeclaration codeType in typesToRemove) { codeNamespace.Types.Remove(codeType); } } } else { foreach (CodeNamespace cns in codeCompileUnit.Namespaces) { foreach (CodeTypeDeclaration codeType in cns.Types) { bool webDerived = false; foreach (CodeTypeReference baseType in codeType.BaseTypes) { if (baseType.BaseType == "System.Web.Services.Protocols.SoapHttpClientProtocol") { webDerived = true; break; } } if (webDerived) { CodeAttributeDeclaration codeAttributeDeclaration = new CodeAttributeDeclaration(typeof(FluorineFx.RemotingServiceAttribute).FullName); codeType.CustomAttributes.Add(codeAttributeDeclaration); foreach (CodeTypeMember member in codeType.Members) { CodeConstructor ctor = member as CodeConstructor; if (ctor != null) { // We got a constructor // Add CookieContainer code // this.CookieContainer = new System.Net.CookieContainer(); //Session Cookie CodeSnippetStatement statement = new CodeSnippetStatement("this.CookieContainer = new System.Net.CookieContainer(); //Session Cookie"); ctor.Statements.Add(statement); } } } } } } if (FluorineConfiguration.Instance.ImportNamespaces != null) { for (int i = 0; i < FluorineConfiguration.Instance.ImportNamespaces.Count; i++) { ImportNamespace importNamespace = FluorineConfiguration.Instance.ImportNamespaces[i]; codeNamespace.Imports.Add(new CodeNamespaceImport(importNamespace.Namespace)); } } // source code generation StringBuilder srcStringBuilder = new StringBuilder(); StringWriter sw = new StringWriter(srcStringBuilder); #if (NET_1_1) ICodeGenerator icg = provider.CreateGenerator(); icg.GenerateCodeFromCompileUnit(codeCompileUnit, sw, null); #else provider.GenerateCodeFromCompileUnit(codeCompileUnit, sw, null); #endif string srcWSProxy = srcStringBuilder.ToString(); sw.Close(); // assembly compilation. CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Data.dll"); cp.ReferencedAssemblies.Add("System.Xml.dll"); cp.ReferencedAssemblies.Add("System.Web.Services.dll"); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.GlobalAssemblyCache) { //Only System namespace if (assembly.GetName().Name.StartsWith("System")) { if (!cp.ReferencedAssemblies.Contains(assembly.GetName().Name + ".dll")) cp.ReferencedAssemblies.Add(assembly.Location); } } else { if (assembly.GetName().Name.StartsWith("mscorlib")) continue; //if( assembly.Location.ToLower().StartsWith(System.Web.HttpRuntime.CodegenDir.ToLower()) ) // continue; try { if (assembly.Location != null && assembly.Location != string.Empty) cp.ReferencedAssemblies.Add(assembly.Location); } catch (NotSupportedException) { //NET2 } } } cp.GenerateExecutable = false; //http://support.microsoft.com/kb/815251 //http://support.microsoft.com/kb/872800 cp.GenerateInMemory = false;//true; cp.IncludeDebugInformation = false; #if (NET_1_1) ICodeCompiler icc = provider.CreateCompiler(); CompilerResults cr = icc.CompileAssemblyFromSource(cp, srcWSProxy); #else CompilerResults cr = provider.CompileAssemblyFromSource(cp, srcWSProxy); #endif if (cr.Errors.Count > 0) { StringBuilder sbMessage = new StringBuilder(); sbMessage.Append(string.Format("Build failed: {0} errors", cr.Errors.Count)); if (log.IsErrorEnabled) log.Error(__Res.GetString(__Res.Wsdl_ProxyGenFail)); foreach (CompilerError e in cr.Errors) { log.Error(__Res.GetString(__Res.Compiler_Error, e.Line, e.Column, e.ErrorText)); sbMessage.Append("\n"); sbMessage.Append(e.ErrorText); } StringBuilder sbSourceTrace = new StringBuilder(); sbSourceTrace.Append("Attempt to compile the generated source code:"); sbSourceTrace.Append(Environment.NewLine); StringWriter swSourceTrace = new StringWriter(sbSourceTrace); IndentedTextWriter itw = new IndentedTextWriter(swSourceTrace, " "); provider.GenerateCodeFromCompileUnit(codeCompileUnit, itw, new CodeGeneratorOptions()); itw.Close(); log.Error(sbSourceTrace.ToString()); throw new FluorineException(sbMessage.ToString()); } return cr.CompiledAssembly; }
private void GetGeneralCode(string selectName,string name) { CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeGenerator generator = provider.CreateGenerator(); StreamWriter writer = new StreamWriter(@"c:\" + txtClassName.Text + ".cs",false); CodeCompileUnit unit = new CodeCompileUnit(); CodeNamespace nspace = new CodeNamespace("SQLNetPlus"); //������ƿռ� nspace.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration info = new CodeTypeDeclaration(txtClassName.Text); CodeConstructor ct = new CodeConstructor(); DataAccess da = getDataAccess(); DataSet ds = da.GetDataSet(selectName,false); if(name != "proc") { ct.Attributes=MemberAttributes.Public; ct.Statements.Add(new CodeSnippetStatement("this.conStr=System.Configuration.ConfigurationSettings.AppSettings[\"DBConnStr\"];")); //���� ct.Statements.Add(new CodeSnippetStatement("if( this.conStr==null || this.conStr.Length==0)")); //���� ct.Statements.Add(new CodeSnippetStatement("throw new Exception();")); info.Members.Add(ct); for(int i=0;i<ds.Tables[0].Rows.Count;i++) { //˽�г�Ա������ֱ�����ֶ���(����s_)�������� CodeMemberField f = new CodeMemberField(); f.Name="s_" + ds.Tables[0].Rows[i]["Name"]; f.Type = new CodeTypeReference((da.getTypeString(ds.Tables[0].Rows[i]["datatype"].ToString()))); info.Members.Add(f); //�������ԣ����ֶ����������� CodeMemberProperty p = new CodeMemberProperty(); p.Name=ds.Tables[0].Rows[i]["Name"].ToString(); p.Type=f.Type; p.Attributes = MemberAttributes.Public|MemberAttributes.Final; p.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),f.Name))); p.SetStatements.Add(new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),f.Name), new CodePropertySetValueReferenceExpression())); info.Members.Add(p); } } else { ct.Attributes=MemberAttributes.Public; info.Members.Add(ct); //��ӷ��� CodeMemberMethod m = new CodeMemberMethod(); m.ReturnType = new CodeTypeReference("System.Data.DataSet"); m.Name = "ExecProc_" + selectName; m.Attributes = MemberAttributes.Public|MemberAttributes.Final; int rows = ds.Tables[0].Rows.Count; CodeSnippetStatement codebody = null; codebody = new CodeSnippetStatement("SqlParameter[] parms =new SqlParameter[" + (rows+1).ToString() + "];"); m.Statements.Add(codebody); for(int i=0;i<rows;i++) { string paramName = ds.Tables[0].Rows[i]["name"].ToString(); string paramName1 = "p_" + paramName.Substring(1,paramName.Length-1); CodeTypeReference paramType = new CodeTypeReference((da.getTypeString(ds.Tables[0].Rows[i]["datatype"].ToString()))); CodeParameterDeclarationExpression parameters = null; parameters = new CodeParameterDeclarationExpression(paramType, paramName1); m.Parameters.Add(parameters); string paramOutput = ds.Tables[0].Rows[i]["isoutparam"].ToString(); codebody = new CodeSnippetStatement("parms[" + i.ToString() + "]=new SqlParameter(\"" + paramName + "\", " + paramName1 + ");"); m.Statements.Add(codebody); if(paramOutput == "1") { codebody = new CodeSnippetStatement("parms[" + i.ToString() + "].Direction=ParameterDirection.Output;"); m.Statements.Add(codebody); } } codebody = new CodeSnippetStatement("parms[" + rows.ToString() + "]=new SqlParameter(\"RETURN_VALUE\", SqlDbType.Int);"); m.Statements.Add(codebody); codebody = new CodeSnippetStatement("parms[" + rows.ToString() + "].Direction=ParameterDirection.ReturnValue;"); m.Statements.Add(codebody); codebody = new CodeSnippetStatement("return ExecuteDataset(\"" + selectName + "\",parms);"); m.Statements.Add(codebody); info.Members.Add(m); } nspace.Types.Add(info); unit.Namespaces.Add(nspace); generator.GenerateCodeFromCompileUnit(unit,writer,new CodeGeneratorOptions()); writer.Close(); StreamReader sr = new StreamReader(@"c:\" + txtClassName.Text + ".cs",System.Text.Encoding.GetEncoding("GB2312")); txtCode.Text = sr.ReadToEnd(); sr.Close(); }
private void GenerateAssemblerSource() { CSharpCodeProvider csp = new CSharpCodeProvider(); CodeGeneratorOptions cop = new CodeGeneratorOptions(); cop.BracingStyle = "C"; StreamWriter sw = File.CreateText(m_context.AssemblerGenerationOptions.OutputFile); ICodeGenerator gen = csp.CreateGenerator(sw); gen.GenerateCodeFromNamespace(m_namespace, sw, cop); sw.Close(); }
public void ExportTypeMapping_XsdPrimitive_Arrays () { ArrayList types = new ArrayList (); types.Add (typeof (sbyte[])); types.Add (typeof (bool[])); types.Add (typeof (short[])); types.Add (typeof (int[])); types.Add (typeof (long[])); types.Add (typeof (float[])); types.Add (typeof (double[])); types.Add (typeof (decimal[])); types.Add (typeof (ushort[])); types.Add (typeof (uint[])); types.Add (typeof (ulong[])); types.Add (typeof (DateTime[])); types.Add (typeof (XmlQualifiedName[])); types.Add (typeof (string[])); StringWriter sw = new StringWriter (); CodeDomProvider provider = new CSharpCodeProvider (); ICodeGenerator generator = provider.CreateGenerator (); foreach (Type type in types) { CodeNamespace codeNamespace = ExportCode (type); Assert.IsNotNull (codeNamespace, type.FullName + "#1"); generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ()); Assert.AreEqual (Environment.NewLine, sw.ToString (), type.FullName + "#2"); sw.GetStringBuilder ().Length = 0; } }
public TypedDataSetGeneratorTest () { CodeDomProvider p = new CSharpCodeProvider (); gen = p.CreateGenerator (); compiler = p.CreateCompiler (); }
public void ExportTypeMapping_ArrayContainer () { CodeNamespace codeNamespace = ExportCode (typeof (ArrayContainer)); Assert.IsNotNull (codeNamespace, "#1"); StringWriter sw = new StringWriter (); CodeDomProvider provider = new CSharpCodeProvider (); ICodeGenerator generator = provider.CreateGenerator (); generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ()); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}{0}" + "/// <remarks/>{0}" + "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Diagnostics.DebuggerStepThroughAttribute()]{0}" + "[System.ComponentModel.DesignerCategoryAttribute(\"code\")]{0}" + "[System.Xml.Serialization.XmlRootAttribute(Namespace=\"\", IsNullable=true)]{0}" + "public partial class ArrayContainer {{{0}" + " {0}" + " private object[] itemsField;{0}" + " {0}" + " /// <remarks/>{0}" + " public object[] items {{{0}" + " get {{{0}" + " return this.itemsField;{0}" + " }}{0}" + " set {{{0}" + " this.itemsField = value;{0}" + " }}{0}" + " }}{0}" + "}}{0}", Environment.NewLine), sw.ToString (), "#2"); }
/// <summary> /// CreateSourceFiles - Parse Wsdl Schema and generate DataContract, DataContractSerializer types, /// HostedServices and Client Proxies. /// </summary> /// <remarks>Currently only generates C# source files.</remarks> /// <param name="contractFilename">The name of a contract source code (.cs) file.</param> /// <param name="hostedServiceFilename">The name of a hosted service source code (.cs) file.</param> /// <param name="clientProxyFilename">The name of a client proxy source code (.cs) file.</param> /// <param name="targetPlatform">Specifies the target runtime platform.</param> public void CreateSourceFiles(string contractFilename, string hostedServiceFilename, string clientProxyFilename, TargetPlatform targetPlatform) { m_platform = targetPlatform; Logger.WriteLine("", LogLevel.Normal); Logger.WriteLine("Generating contract source: " + contractFilename + "...", LogLevel.Normal); if (contractFilename == null) throw new ArgumentNullException("codeFilename", "You must pass a valid code filename."); if (m_svcDesc.Types == null) { throw new Exception("No wsdl types found."); } string path = Path.GetDirectoryName(contractFilename).Trim(); if(!string.IsNullOrEmpty(path) && !Directory.Exists(path)) { Directory.CreateDirectory(path); } // Create code file stream FileStream dcStream = new FileStream(contractFilename, FileMode.Create, FileAccess.Write, FileShare.None); StreamWriter dcStreamWriter = new StreamWriter(dcStream); // Write the auto generated header dcStreamWriter.Write(AutoGenTextHeader.Message); try { // Set up data contract code generator CSharpCodeProvider cSharpCP = new CSharpCodeProvider(); ICodeGenerator codeGen = cSharpCP.CreateGenerator(dcStreamWriter); CodeGeneratorOptions codeGenOptions = new CodeGeneratorOptions(); codeGenOptions.BracingStyle = "C"; // Cobble up a valid .net namespace. Turn any progression that's not a-z or A-Z to a single '.' string targetNamespaceName = CodeGenUtils.GenerateDotNetNamespace(m_svcDesc.TargetNamespace); // For some reason we have to force schemas to compile. Though it was suppose to automatically. Huh! foreach (XmlSchema schema in m_svcDesc.Types.Schemas) { XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(schema); schemaSet.Compile(); } // Create new code namespace CodeNamespace targetNamespace = new CodeNamespace(targetNamespaceName); // Add data contract using directives CodeSnippetCompileUnit compileUnit = new CodeSnippetCompileUnit("using System;"); codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using System.Xml;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); if (m_platform == TargetPlatform.MicroFramework) { compileUnit.Value = "using System.Ext;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using System.Ext.Xml;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); } compileUnit.Value = "using Ws.ServiceModel;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using Ws.Services.Mtom;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using Ws.Services.Serialization;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using XmlElement = Ws.Services.Xml.WsXmlNode;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using XmlAttribute = Ws.Services.Xml.WsXmlAttribute;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using XmlConvert = Ws.Services.Serialization.WsXmlConvert;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = ""; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Namespaces.Add(targetNamespace); m_dcCodeGen.CodeNamespaces = compileUnit.Namespaces; Logger.WriteLine("", LogLevel.Normal); // Create HostedServices and ClientProxies collections HostedServices hostedServices = new HostedServices(targetNamespaceName); ClientProxies clientProxies = new ClientProxies(targetNamespaceName); // For each PortType process foreach (PortType portType in m_svcDesc.PortTypes) { // For each operation in the port type: // Get input and output message parts. // If the message part is a simple type: // Build HostedService operation. // Else if the message part is an element: // Find elements in Schema // If element type is native xml type: // Build HostedService operation. // Else if element references a simple or complex type: // If simpleType is base xml type with restrictions: // Build HostedService operation. // Else // Build DataContract and DataContractSerializer. // Build HostedService Operation. // if (!CodeGenUtils.IsSoapBinding(portType, m_svcDesc)) { continue; } // Create instance of a HostedService to hold the port type details HostedService hostedService = new HostedService(portType.Name, m_svcDesc.TargetNamespace, m_platform); // Create instance of ClientProxyGenerator ClientProxy clientProxy = new ClientProxy(portType.Name, m_platform); // Create service contract interface CodeTypeDeclaration serviceCodeType = new CodeTypeDeclaration("I" + portType.Name); CodeAttributeArgument codeAttr = new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(m_svcDesc.TargetNamespace)); CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration("ServiceContract", codeAttr); serviceCodeType.CustomAttributes.Add(codeAttrDecl); // Check for Policy assertions. If found add policy assertion attributes. Policy assertion attributes // are required to regenerate policy assertions when converting a service to Wsdl. List<PolicyAssertion> policyAssertions = GetPolicyAssertions(); bool OptimizedMimeEncoded = false; foreach (PolicyAssertion assert in policyAssertions) { serviceCodeType.CustomAttributes.Add(CreatePolicyAssertions(assert.Name, assert.Namespace.ToString(), assert.PolicyID)); // if Optimized Mime assertion id found set a processing flag if (assert.Name == "OptimizedMimeSerialization") { OptimizedMimeEncoded = true; } } // Add type declaration serviceCodeType.TypeAttributes = TypeAttributes.Public; serviceCodeType.IsInterface = true; // Create service contract callback client interface CodeTypeDeclaration serviceCallbackCodeType = new CodeTypeDeclaration("I" + portType.Name + "Callback"); // Add type declaration serviceCallbackCodeType.TypeAttributes = TypeAttributes.Public; serviceCallbackCodeType.IsInterface = true; // If the binding contains a ref to Mtom encoding type set the Mtom flag if (OptimizedMimeEncoded) { m_dcCodeGen.EncodingType = MessageEncodingType.Mtom; hostedService.EncodingType = MessageEncodingType.Mtom; clientProxy.EncodingType = MessageEncodingType.Mtom; } // Step through port operations, get method names and parse elements. for (int pt_index = 0; pt_index < portType.Operations.Count; ++pt_index) { Operation operation = portType.Operations[pt_index]; string operationName = operation.Name; string inputMessageName = null; string outputMessageName = null; MessagePartCollection inputMessageParts = null; MessagePartCollection outputMessageParts = null; string inAction = null; string outAction = null; GetAction(portType, operation, m_svcDesc.TargetNamespace, ref inAction, ref outAction); // Oneway request port type if (operation.Messages.Flow == OperationFlow.OneWay) { OperationInput input = operation.Messages.Input; inputMessageName = input.Message.Name; // Add operation for HostedService code generation hostedService.AddOperation(operation, inAction, outAction); // Add method for ClientProxy code generation clientProxy.AddOperation(operation, inAction, outAction); } // Twoway request/response pattern else if (operation.Messages.Flow == OperationFlow.RequestResponse) { OperationInput input = operation.Messages.Input; inputMessageName = input.Message.Name; OperationOutput output = operation.Messages.Output; outputMessageName = output.Message.Name; // Add operation for HostedService code generation hostedService.AddOperation(operation, inAction, outAction); // Add method for ClientProxy code generation clientProxy.AddOperation(operation, inAction, outAction); } // Event pattern else if (operation.Messages.Flow == OperationFlow.Notification) { OperationOutput output = operation.Messages.Output; outputMessageName = output.Message.Name; // Add operation for HostedService code generation hostedService.AddOperation(operation, inAction, outAction); // Add method for ClientProxy code generation clientProxy.AddOperation(operation, inAction, outAction); } // Find input and output message parts collection in messages collection // and store for later. foreach (Message message in m_svcDesc.Messages) { if (inputMessageName != null) if (message.Name == inputMessageName) { inputMessageParts = message.Parts; // Add operation for HostedService code generation hostedService.Messages.Add(message); // Add Message to ClientProxy generator for later clientProxy.Messages.Add(message); } if (outputMessageName != null) if (message.Name == outputMessageName) { outputMessageParts = message.Parts; // Add operation for HostedService code generation hostedService.Messages.Add(message); // Add Message to ClientProxy generator for later clientProxy.Messages.Add(message); } } try { // Try to generate Data Contracts and DataContractSerializers GenerateTypeContracts(operation, inputMessageParts, outputMessageParts); // If operation flow is notification (event) add OperationContract to ServiceContractCallback // else add OperationContract to ServiceContract if (operation.Messages.Flow == OperationFlow.Notification) { AddServiceOperationToInterface(operation, outAction, serviceCallbackCodeType); } else AddServiceOperationToInterface(operation, inAction, serviceCodeType); } catch (Exception e) { dcStreamWriter.Close(); File.Delete(contractFilename); Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal); return; } } // Add serviceCodeType Service Contract interface to namespace // A serviceCodeType is added even if the wsdl only contains notifications. In that case // the contract will be empty but the ServiceContract attribute and CallbackContract argument // will be used to point to the notification or callback contract interace targetNamespace.Types.Add(serviceCodeType); // If service contract callback type contains members add callback contract to namespace // and add CallbackContract reference attribute to serviceCodeType contract. if (serviceCallbackCodeType.Members.Count > 0) { // Add the callback argument to the service description attribute CodeAttributeArgument callbackArg = new CodeAttributeArgument("CallbackContract", new CodeTypeOfExpression(serviceCallbackCodeType.Name) ); serviceCodeType.CustomAttributes[0].Arguments.Add(callbackArg); // Add the callback interface to namespace targetNamespace.Types.Add(serviceCallbackCodeType); } // If the hosted service has opeations add to Hosted Services collection for Code Gen if (hostedService.ServiceOperations.Count > 0) hostedServices.Add(hostedService); // If the client Proxy service has opeations add to client proxy collection for Code Gen if (clientProxy.ServiceOperations.Count > 0) clientProxies.Add(clientProxy); } // MOD: 12-02-08 Added code to handle multiple type namespaces // Generate contract source file foreach (CodeNamespace codeNamespace in compileUnit.Namespaces) { codeGen.GenerateCodeFromNamespace(codeNamespace, dcStreamWriter, codeGenOptions); } dcStreamWriter.Flush(); dcStreamWriter.Close(); // Generate Hosted Service code Logger.WriteLine("Generating Hosted Service source: " + hostedServiceFilename + "...", LogLevel.Normal); HostedServiceGenerator hsGen = new HostedServiceGenerator(); hsGen.GenerateCode(hostedServiceFilename, hostedServices); // Generate Client proxy code Logger.WriteLine("Generating Client Proxy source: " + clientProxyFilename + "...", LogLevel.Normal); ClientProxyGenerator cpGen = new ClientProxyGenerator(); cpGen.GenerateCode(clientProxyFilename, clientProxies); } catch (Exception e) { dcStreamWriter.Close(); File.Delete(contractFilename); Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal); throw new Exception("Failed to generate service code. ", e); } }
private void UpdateCodeWindows() { TabControl tc = this.host.GetService(typeof(TabControl)) as TabControl; CodeGeneratorOptions o = new CodeGeneratorOptions(); o.BlankLinesBetweenMembers = true; o.BracingStyle = "C"; o.ElseOnClosing = false; o.IndentString = " "; StringWriter sw = new StringWriter(); CSharpCodeProvider cs = new CSharpCodeProvider(); cs.CreateGenerator().GenerateCodeFromCompileUnit(this.codeCompileUnit, sw, o); sw.Close(); sw = new StringWriter(); VBCodeProvider vb = new VBCodeProvider(); vb.CreateGenerator().GenerateCodeFromCompileUnit(this.codeCompileUnit, sw, o); sw.Close(); sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); xtw.Formatting = Formatting.Indented; this.xmlDocument.WriteTo(xtw); string cleanup = sw.ToString().Replace("<DOCUMENT_ELEMENT>", "").Replace("</DOCUMENT_ELEMENT>", ""); sw.Close(); }
[Category ("NotDotNet")] // Mono bug ##77117 and MS.NET randomly modifies the order of the elements! public void ExportTypeMapping_Choices () { CodeNamespace codeNamespace = ExportCode (typeof (Choices)); Assert.IsNotNull (codeNamespace, "#1"); StringWriter sw = new StringWriter (); CodeDomProvider provider = new CSharpCodeProvider (); ICodeGenerator generator = provider.CreateGenerator (); generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ()); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}{0}" + "/// <remarks/>{0}" + #if NET_2_0 "[System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Xml\", \"{1}\")]{0}" + "[System.SerializableAttribute()]{0}" + "[System.Diagnostics.DebuggerStepThroughAttribute()]{0}" + "[System.ComponentModel.DesignerCategoryAttribute(\"code\")]{0}" + "[System.Xml.Serialization.XmlRootAttribute(Namespace=\"\", IsNullable=true)]{0}" + "public partial class Choices {{{0}" + " {0}" + " private string myChoiceField;{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlElementAttribute(\"ChoiceZero\", typeof(string))]{0}" + " [System.Xml.Serialization.XmlElementAttribute(\"ChoiceOne\", typeof(string))]{0}" + " [System.Xml.Serialization.XmlElementAttribute(\"ChoiceTwo\", typeof(string))]{0}" + " [System.Xml.Serialization.XmlChoiceIdentifierAttribute(\"ItemType\")]{0}" + " public string MyChoice {{{0}" + " get {{{0}" + " return this.myChoiceField;{0}" + " }}{0}" + " set {{{0}" + " this.myChoiceField = value;{0}" + " }}{0}" + " }}{0}" + "}}{0}", Environment.NewLine, XmlFileVersion), sw.ToString (), "#2"); #else "[System.Xml.Serialization.XmlRootAttribute(Namespace=\"\", IsNullable=true)]{0}" + "public class Choices {{{0}" + " {0}" + " /// <remarks/>{0}" + " [System.Xml.Serialization.XmlElementAttribute(\"ChoiceZero\", typeof(string))]{0}" + " [System.Xml.Serialization.XmlElementAttribute(\"ChoiceTwo\", typeof(string))]{0}" + " [System.Xml.Serialization.XmlElementAttribute(\"ChoiceOne\", typeof(string))]{0}" + " [System.Xml.Serialization.XmlChoiceIdentifierAttribute(\"ItemType\")]{0}" + " public string MyChoice;{0}" + "}}{0}", Environment.NewLine), sw.ToString (), "#2"); #endif }