public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu) { //cu.UserData["AllowLateBound"] = true; // GENERATES (C#): // namespace Namespace1 { // using System; // // // public class Class1 { // // public virtual string Foo1(string format, [System.Runtime.InteropServices.OptionalAttribute()] params object[] array) { // string str; // str = format.Replace("{0}", array[0].ToString()); // str = str.Replace("{1}", array[1].ToString()); // str = str.Replace("{2}", array[2].ToString()); // return str; // } // } // } CodeNamespace ns = new CodeNamespace("Namespace1"); ns.Imports.Add(new CodeNamespaceImport("System")); cu.Namespaces.Add(ns); // Full Verification Objects CodeTypeDeclaration class1 = new CodeTypeDeclaration(); class1.Name = "Class1"; ns.Types.Add(class1); AddScenario ("CheckFoo1"); CodeMemberMethod fooMethod1 = new CodeMemberMethod(); fooMethod1.Name = "Foo1"; fooMethod1.Attributes = MemberAttributes.Public ; fooMethod1.ReturnType = new CodeTypeReference(typeof(string)); CodeParameterDeclarationExpression parameter1 = new CodeParameterDeclarationExpression(); parameter1.Name = "format"; parameter1.Type = new CodeTypeReference(typeof(string)); fooMethod1.Parameters.Add(parameter1); CodeParameterDeclarationExpression parameter2 = new CodeParameterDeclarationExpression(); parameter2.Name = "array"; parameter2.Type = new CodeTypeReference(typeof(object[])); if (Supports (provider, GeneratorSupport.ParameterAttributes)) { parameter2.CustomAttributes.Add( new CodeAttributeDeclaration("System.ParamArrayAttribute")); parameter2.CustomAttributes.Add( new CodeAttributeDeclaration("System.Runtime.InteropServices.OptionalAttribute")); } fooMethod1.Parameters.Add(parameter2); class1.Members.Add(fooMethod1); fooMethod1.Statements.Add( new CodeVariableDeclarationStatement(typeof(string), "str")); fooMethod1.Statements.Add(CreateStatement(new CodeArgumentReferenceExpression ("format"), 0)); fooMethod1.Statements.Add(CreateStatement(new CodeVariableReferenceExpression ("str"), 1)); fooMethod1.Statements.Add(CreateStatement(new CodeVariableReferenceExpression ("str"), 2)); fooMethod1.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("str"))); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace ns = new CodeNamespace ("Namespace1"); cu.Namespaces.Add (ns); // GENERATES (C#): // // namespace Namespace1 { // public class Class1 { // public int Method1 { // #line 300 "LinedStatement" // return 0; // // #line default // #line hidden // } // } // } CodeTypeDeclaration class1 = new CodeTypeDeclaration ("Class1"); class1.IsClass = true; class1.Attributes = MemberAttributes.Public; ns.Types.Add (class1); CodeMemberMethod method1 = new CodeMemberMethod (); method1.ReturnType = new CodeTypeReference (typeof (int)); method1.Name = "Method1"; class1.Members.Add (method1); AddScenario ("FindLinedStatement"); CodeMethodReturnStatement ret = new CodeMethodReturnStatement (new CodePrimitiveExpression (0)); ret.LinePragma = new CodeLinePragma ("LinedStatement", 300); method1.Statements.Add (ret); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { if (!(provider is JScriptCodeProvider)) { // GENERATES (C#): // // namespace Namespace1 { // // public class TEST { // // public static void Main() { // // the following is repeated Char.MaxValue times // System.Console.WriteLine(/* character value goes here */); // } // } // } CodeNamespace ns = new CodeNamespace ("Namespace1"); ns.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (ns); CodeTypeDeclaration cd = new CodeTypeDeclaration ("TEST"); cd.IsClass = true; ns.Types.Add (cd); CodeEntryPointMethod methodMain = new CodeEntryPointMethod (); for (int i = 0; i < Char.MaxValue; i+=50) methodMain.Statements.Add (CDHelper.ConsoleWriteLineStatement (new CodePrimitiveExpression (System.Convert.ToChar (i)))); cd.Members.Add (methodMain); } }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { // GENERATES (C#): // // namespace NSPC { // // public class ClassWithMethod { // // public int MethodName() { // This is a CODE SNIPPET #*$*@; // return 3; // } // } // } AddScenario ("FindSnippet", "Find code snippet in the code."); CodeNamespace nspace = new CodeNamespace ("NSPC"); cu.Namespaces.Add (nspace); CodeTypeDeclaration class1 = new CodeTypeDeclaration ("ClassWithMethod"); class1.IsClass = true; nspace.Types.Add (class1); CodeMemberMethod cmm = new CodeMemberMethod (); cmm.Name = "MethodName"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Statements.Add (new CodeExpressionStatement (new CodeSnippetExpression ("This is a CODE SNIPPET #*$*@"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (3))); class1.Members.Add (cmm); }
public ToCSharpBase(string inSpace, string inClassName, string inFolderName) { spaceName = inSpace.Trim(); className = Stringer.FirstLetterUp(inClassName); folderName = inFolderName; classer = new CodeTypeDeclaration(className); classer.IsClass = true; }
private static CodeMemberField CreateBeginOperationDelegate(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName) { CodeMemberField field = new CodeMemberField(); field.Attributes = MemberAttributes.Private; field.Type = new CodeTypeReference(beginOperationDelegateTypeName); field.Name = NamingHelper.GetUniqueName(GetBeginOperationDelegateName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations); clientType.Members.Add(field); return field; }
public void CodeMemberField_OpenGenericType_Works() { var cd = new CodeTypeDeclaration("SomeClass") { IsClass = true }; cd.Members.Add(new CodeMemberField(typeof(List<>), "_field")); AssertEqual(cd, @"public class SomeClass { private System.Collections.Generic.List<> _field; }"); }
public void CodeMemberField_ByRefType_Works() { var cd = new CodeTypeDeclaration("SomeClass") { IsClass = true }; cd.Members.Add(new CodeMemberField(typeof(int).MakeByRefType(), "_field")); AssertEqual(cd, @"public class SomeClass { private System.Int32& _field; }"); }
public OperationContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ServiceContractGenerationContext contract, OperationDescription operation, CodeTypeDeclaration declaringType, CodeMemberMethod method) : this(serviceContractGenerator, contract, operation, declaringType) { if (method == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("method")); } this.syncMethod = method; this.beginMethod = null; this.endMethod = null; }
public void AccessingFields() { var cd = new CodeTypeDeclaration("ClassWithFields") { IsClass = true }; var field = new CodeMemberField("System.String", "Microsoft"); field.Attributes = MemberAttributes.Public | MemberAttributes.Static; field.InitExpression = new CodePrimitiveExpression("hi"); cd.Members.Add(field); field = new CodeMemberField(); field.Name = "StaticPublicField"; field.Attributes = MemberAttributes.Public | MemberAttributes.Static; field.Type = new CodeTypeReference(typeof(int)); field.InitExpression = new CodePrimitiveExpression(5); cd.Members.Add(field); field = new CodeMemberField(); field.Name = "NonStaticPublicField"; field.Attributes = MemberAttributes.Public | MemberAttributes.Final; field.Type = new CodeTypeReference(typeof(int)); field.InitExpression = new CodePrimitiveExpression(6); cd.Members.Add(field); field = new CodeMemberField(); field.Name = "PrivateField"; field.Attributes = MemberAttributes.Private | MemberAttributes.Final; field.Type = new CodeTypeReference(typeof(int)); field.InitExpression = new CodePrimitiveExpression(7); cd.Members.Add(field); var cmm = new CodeMemberMethod(); cmm.Name = "UsePrivateField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PrivateField"), new CodeVariableReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PrivateField"))); cd.Members.Add(cmm); AssertEqual(cd, @"public class ClassWithFields { public static string Microsoft = ""hi""; public static int StaticPublicField = 5; public int NonStaticPublicField = 6; private int PrivateField = 7; public int UsePrivateField(int i) { this.PrivateField = i; return this.PrivateField; } }"); }
private void GenerateType(CodeTypeDeclaration e) { _currentClass = e; if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); } GenerateCommentStatements(e.Comments); if (e.LinePragma != null) { GenerateLinePragmaStart(e.LinePragma); } GenerateTypeStart(e); if (Options.VerbatimOrder) { foreach (CodeTypeMember member in e.Members) { GenerateTypeMember(member, e); } } else { GenerateFields(e); GenerateSnippetMembers(e); GenerateTypeConstructors(e); GenerateConstructors(e); GenerateProperties(e); GenerateEvents(e); GenerateMethods(e); GenerateNestedTypes(e); } // Nested types clobber the current class, so reset it. _currentClass = e; GenerateTypeEnd(e); if (e.LinePragma != null) { GenerateLinePragmaEnd(e.LinePragma); } if (e.EndDirectives.Count > 0) { GenerateDirectives(e.EndDirectives); } }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { // GENERATES (C#): // // public class MyConverter : System.ComponentModel.TypeConverter { // // private void Foo() { // this.Foo(null); // } // // private void Foo(string s) { // } // // public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { // return base.CanConvertFrom(context, sourceType); // } // } CodeNamespace ns = new CodeNamespace (); cu.Namespaces.Add (ns); CodeTypeDeclaration class1 = new CodeTypeDeclaration (); class1.Name = "MyConverter"; class1.BaseTypes.Add (new CodeTypeReference (typeof (System.ComponentModel.TypeConverter))); ns.Types.Add (class1); CodeMemberMethod foo1 = new CodeMemberMethod (); foo1.Name = "Foo"; foo1.Statements.Add (new CodeMethodInvokeExpression (new CodeThisReferenceExpression (), "Foo", new CodePrimitiveExpression (null))); class1.Members.Add (foo1); CodeMemberMethod foo2 = new CodeMemberMethod (); foo2.Name = "Foo"; foo2.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "s")); class1.Members.Add (foo2); CodeMemberMethod convert = new CodeMemberMethod (); convert.Name = "CanConvertFrom"; convert.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded; convert.ReturnType = new CodeTypeReference (typeof (bool)); convert.Parameters.Add (new CodeParameterDeclarationExpression (typeof (System.ComponentModel.ITypeDescriptorContext), "context")); convert.Parameters.Add (new CodeParameterDeclarationExpression (typeof (System.Type), "sourceType")); convert.Statements.Add ( new CodeMethodReturnStatement ( new CodeMethodInvokeExpression ( new CodeBaseReferenceExpression (), "CanConvertFrom", new CodeArgumentReferenceExpression ("context"), new CodeArgumentReferenceExpression ("sourceType")))); class1.Members.Add (convert); }
public void AccessingFields() { var cd = new CodeTypeDeclaration("ClassWithFields") { IsClass = true }; var field = new CodeMemberField("System.String", "Microsoft"); field.Attributes = MemberAttributes.Public | MemberAttributes.Static; field.InitExpression = new CodePrimitiveExpression("hi"); cd.Members.Add(field); field = new CodeMemberField(); field.Name = "StaticPublicField"; field.Attributes = MemberAttributes.Public | MemberAttributes.Static; field.Type = new CodeTypeReference(typeof(int)); field.InitExpression = new CodePrimitiveExpression(5); cd.Members.Add(field); field = new CodeMemberField(); field.Name = "NonStaticPublicField"; field.Attributes = MemberAttributes.Public | MemberAttributes.Final; field.Type = new CodeTypeReference(typeof(int)); field.InitExpression = new CodePrimitiveExpression(6); cd.Members.Add(field); field = new CodeMemberField(); field.Name = "PrivateField"; field.Attributes = MemberAttributes.Private | MemberAttributes.Final; field.Type = new CodeTypeReference(typeof(int)); field.InitExpression = new CodePrimitiveExpression(7); cd.Members.Add(field); var cmm = new CodeMemberMethod(); cmm.Name = "UsePrivateField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PrivateField"), new CodeVariableReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PrivateField"))); cd.Members.Add(cmm); AssertEqual(cd, @"Public Class ClassWithFields Public Shared Microsoft As String = ""hi"" Public Shared StaticPublicField As Integer = 5 Public NonStaticPublicField As Integer = 6 Private PrivateField As Integer = 7 Public Function UsePrivateField(ByVal i As Integer) As Integer Me.PrivateField = i Return Me.PrivateField End Function End Class"); }
static void Main(string[] args) { int namespaces = 10; int classesPerNamespace = 10; int methodsPerClass = 10; CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); for (int i = 0; i < namespaces; ++i) { CodeNamespace codeNamespace = new CodeNamespace(); codeCompileUnit.Namespaces.Add(codeNamespace); codeNamespace.Name = "Namespace" + i; for (int j = 0; j < classesPerNamespace; ++j) { CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration(); codeNamespace.Types.Add(codeTypeDeclaration); codeTypeDeclaration.Name = "Class" + j; codeTypeDeclaration.TypeAttributes = TypeAttributes.Public; codeTypeDeclaration.Comments.Add( new CodeCommentStatement( "<summary>This is a summary.</summary>", true ) ); for (int k = 0; k < methodsPerClass; ++k) { CodeMemberMethod codeMemberMethod = new CodeMemberMethod(); codeTypeDeclaration.Members.Add(codeMemberMethod); codeMemberMethod.Name = "Method" + k; codeMemberMethod.Attributes = MemberAttributes.Public; codeMemberMethod.Comments.Add( new CodeCommentStatement( "<summary>This is a summary.</summary>", true ) ); } } } CodeDomProvider codeDomProvider = new CSharpCodeProvider(); ICodeGenerator codeGenerator = codeDomProvider.CreateGenerator(); CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions(); codeGenerator.GenerateCodeFromCompileUnit(codeCompileUnit, Console.Out, codeGeneratorOptions); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace ns = new CodeNamespace (); ns.Name = "MyNamespace"; cu.Namespaces.Add (ns); // GENERATES (C#): // // namespace MyNamespace { // public class MyClass { // private void PrimitiveTest() { // char var1 = 'a'; // char var2 = '\0'; // string var3 = "foo\0bar\0baz\0"; // object var4 = null; // int var5 = 42; // double var6 = 3.14; // System.Console.Write(var1); // System.Console.Write(var2); // System.Console.Write(var3); // System.Console.Write(var4); // System.Console.Write(var5); // System.Console.Write(var6); // } // } // } CodeTypeDeclaration class1 = new CodeTypeDeclaration (); class1.Name = "MyClass"; class1.IsClass = true; class1.Attributes = MemberAttributes.Public; ns.Types.Add (class1); CodeMemberMethod method = new CodeMemberMethod (); method.Name = "PrimitiveTest"; method.Statements.Add (new CodeVariableDeclarationStatement (typeof (char), "var1", new CodePrimitiveExpression ('a'))); method.Statements.Add (new CodeVariableDeclarationStatement (typeof (char), "var2", new CodePrimitiveExpression ('\0'))); method.Statements.Add (new CodeVariableDeclarationStatement (typeof (string), "var3", new CodePrimitiveExpression ("foo\0bar\0baz\0"))); method.Statements.Add (new CodeVariableDeclarationStatement (typeof (Object), "var4", new CodePrimitiveExpression (null))); method.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "var5", new CodePrimitiveExpression (42))); method.Statements.Add (new CodeVariableDeclarationStatement (typeof (double), "var6", new CodePrimitiveExpression (3.14))); method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var1"))); method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var2"))); method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var3"))); method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var4"))); method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var5"))); method.Statements.Add (new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof (Console)), "Write", new CodeVariableReferenceExpression ("var6"))); class1.Members.Add (method); }
private static string GenerateCode(string expression) { var source = new StringBuilder(); var sw = new StringWriter(source); var options = new CodeGeneratorOptions(); var myNamespace = new CodeNamespace("ExpressionEvaluator"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); var classDeclaration = new CodeTypeDeclaration { IsClass = true, Name = "Calculator", Attributes = MemberAttributes.Public }; var myMethod = new CodeMemberMethod { Name = "Calculate", ReturnType = new CodeTypeReference(typeof(double)), Attributes = MemberAttributes.Public }; myMethod.Statements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression(expression))); classDeclaration.Members.Add(myMethod); myNamespace.Types.Add(classDeclaration); provider.GenerateCodeFromNamespace(myNamespace, sw, options); sw.Flush(); sw.Close(); return source.ToString(); }
public void ClassWithStaticFields() { var cd = new CodeTypeDeclaration("SomeClass") { IsClass = true }; cd.Members.Add(new CodeMemberField(typeof(int), "s_privateNumber") { Attributes = MemberAttributes.Private | MemberAttributes.Static }); cd.Members.Add(new CodeMemberField(typeof(string), "s_internalString") { Attributes = MemberAttributes.Assembly | MemberAttributes.Static }); cd.Members.Add(new CodeMemberField(typeof(DateTime), "s_protectedDateTime") { Attributes = MemberAttributes.Family | MemberAttributes.Static }); cd.Members.Add(new CodeMemberField(typeof(TimeSpan), "PublicTimeSpan") { Attributes = MemberAttributes.Public | MemberAttributes.Static }); cd.Members.Add(new CodeMemberField(typeof(Guid), "s_protectedInternalGuid") { Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Static }); AssertEqual(cd, @"Public Class SomeClass Private Shared s_privateNumber As Integer Friend Shared s_internalString As String Protected Shared s_protectedDateTime As Date Public Shared PublicTimeSpan As System.TimeSpan Protected Friend Shared s_protectedInternalGuid As System.Guid End Class"); }
public void ClassWithStaticFields() { var cd = new CodeTypeDeclaration("SomeClass") { IsClass = true }; cd.Members.Add(new CodeMemberField(typeof(int), "s_privateNumber") { Attributes = MemberAttributes.Private | MemberAttributes.Static }); cd.Members.Add(new CodeMemberField(typeof(string), "s_internalString") { Attributes = MemberAttributes.Assembly | MemberAttributes.Static }); cd.Members.Add(new CodeMemberField(typeof(DateTime), "s_protectedDateTime") { Attributes = MemberAttributes.Family | MemberAttributes.Static }); cd.Members.Add(new CodeMemberField(typeof(TimeSpan), "PublicTimeSpan") { Attributes = MemberAttributes.Public | MemberAttributes.Static }); cd.Members.Add(new CodeMemberField(typeof(Guid), "s_protectedInternalGuid") { Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Static }); AssertEqual(cd, @"public class SomeClass { private static int s_privateNumber; internal static string s_internalString; protected static System.DateTime s_protectedDateTime; public static System.TimeSpan PublicTimeSpan; protected internal static System.Guid s_protectedInternalGuid; }"); }
// Methods public ServiceContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ContractDescription contract, CodeTypeDeclaration contractType) { this.operations = new Collection<OperationContractGenerationContext>(); if (serviceContractGenerator == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serviceContractGenerator")); } if (contract == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("contract")); } if (contractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("contractType")); } this.serviceContractGenerator = serviceContractGenerator; this.contract = contract; this.contractType = contractType; }
public void DocumentAttributeProperty(CodeTypeMember cmm, CodeTypeDeclaration type) { if (this.memberDocumentation.ContainsKey(type)) { IList<string> docs = this.memberDocumentation[type]; string typeName = Regex.Escape(type.Name); string originalName = Char.ToLowerInvariant(cmm.Name[0]) + cmm.Name.Substring(1); const string memberDoc = @"{0}::{1}\n\W*(?<docs>.*?)(\n\s*){{3}}"; for (int i = 0; i < docs.Count; i++) { Match match = Regex.Match(docs[i], string.Format(memberDoc, typeName, originalName), RegexOptions.Singleline | RegexOptions.ExplicitCapture); if (match.Success) { FormatComment(match.Groups["docs"].Value, cmm, i > 0); break; } } } }
// Methods private OperationContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ServiceContractGenerationContext contract, OperationDescription operation, CodeTypeDeclaration declaringType) { if (serviceContractGenerator == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serviceContractGenerator")); } if (contract == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("contract")); } if (declaringType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("declaringType")); } this.serviceContractGenerator = serviceContractGenerator; this.contract = contract; this.operation = operation; this.declaringType = declaringType; }
public void Compilation_NotSupported() { CodeDomProvider provider = GetProvider(); var options = new CompilerParameters(new string[] { }, "test.exe"); var cu = new CodeCompileUnit(); var ns = new CodeNamespace("ns"); var cd = new CodeTypeDeclaration("Program"); var mm = new CodeEntryPointMethod(); cd.Members.Add(mm); ns.Types.Add(cd); cu.Namespaces.Add(ns); string tempPath = Path.GetTempFileName(); try { File.WriteAllText(tempPath, GetEmptyProgramSource()); Assert.Throws<PlatformNotSupportedException>(() => provider.CompileAssemblyFromFile(options, tempPath)); Assert.Throws<PlatformNotSupportedException>(() => provider.CompileAssemblyFromDom(options, cu)); Assert.Throws<PlatformNotSupportedException>(() => provider.CompileAssemblyFromSource(options, GetEmptyProgramSource())); #pragma warning disable 0618 // obsolete ICodeCompiler cc = provider.CreateCompiler(); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromDom(options, cu)); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromDomBatch(options, new[] { cu })); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromFile(options, tempPath)); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromFileBatch(options, new[] { tempPath })); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromSource(options, GetEmptyProgramSource())); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromSourceBatch(options, new[] { GetEmptyProgramSource() })); #pragma warning restore 0618 } finally { File.Delete(tempPath); } }
public void MetadataAttributes() { var cu = new CodeCompileUnit(); var ns = new CodeNamespace(); ns.Name = "MyNamespace"; ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Drawing")); ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); cu.Namespaces.Add(ns); var attrs = cu.AssemblyCustomAttributes; attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly")))); attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2")))); attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false)))); var class1 = new CodeTypeDeclaration() { Name = "MyClass" }; class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable")); class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class")))); ns.Types.Add(class1); var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic }; nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable")); class1.Members.Add(nestedClass); var method1 = new CodeMemberMethod() { Name = "MyMethod" }; method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method")))); method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That")))); var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah"); param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute", new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false)))); method1.Parameters.Add(param1); var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit"); param2.CustomAttributes.Add( new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute", new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false)))); method1.Parameters.Add(param2); class1.Members.Add(method1); var function1 = new CodeMemberMethod(); function1.Name = "MyFunction"; function1.ReturnType = new CodeTypeReference(typeof(string)); function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function")))); function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute")); function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe")))); function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return"))); class1.Members.Add(function1); CodeMemberMethod function2 = new CodeMemberMethod(); function2.Name = "GlobalKeywordFunction"; function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function")))); CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference); CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef); function2.ReturnTypeCustomAttributes.Add(codeAttrib); class1.Members.Add(function2); CodeMemberField field1 = new CodeMemberField(); field1.Name = "myField"; field1.Type = new CodeTypeReference(typeof(string)); field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute")); field1.InitExpression = new CodePrimitiveExpression("hi!"); class1.Members.Add(field1); CodeMemberProperty prop1 = new CodeMemberProperty(); prop1.Name = "MyProperty"; prop1.Type = new CodeTypeReference(typeof(string)); prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property")))); prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField"))); class1.Members.Add(prop1); CodeConstructor const1 = new CodeConstructor(); const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor")))); class1.Members.Add(const1); class1 = new CodeTypeDeclaration("Test"); class1.IsClass = true; class1.BaseTypes.Add(new CodeTypeReference("Form")); ns.Types.Add(class1); CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b"); mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button")); class1.Members.Add(mfield); CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Public; ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"), new CodePrimitiveExpression(600), new CodePrimitiveExpression(600)))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "Text"), new CodePrimitiveExpression("Test"))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "TabIndex"), new CodePrimitiveExpression(0))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"), new CodePrimitiveExpression(400), new CodePrimitiveExpression(525)))); ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler") , new CodeThisReferenceExpression(), "b_Click"))); class1.Members.Add(ctor); CodeMemberEvent evt = new CodeMemberEvent(); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference("System.EventHandler"); evt.Attributes = MemberAttributes.Public; evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false)))); class1.Members.Add(evt); CodeMemberMethod cmm = new CodeMemberMethod(); cmm.Name = "b_Click"; cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender")); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e")); class1.Members.Add(cmm); AssertEqual(cu, @"'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict Off Option Explicit On Imports System Imports System.ComponentModel Imports System.Drawing Imports System.Windows.Forms <Assembly: System.Reflection.AssemblyTitle(""MyAssembly""), _ Assembly: System.Reflection.AssemblyVersion(""1.0.6.2""), _ Assembly: System.CLSCompliantAttribute(false)> Namespace MyNamespace <System.Serializable(), _ System.Obsolete(""Don't use this Class"")> _ Public Class [MyClass] <System.Xml.Serialization.XmlElementAttribute()> _ Private myField As String = ""hi!"" <System.Obsolete(""Don't use this Constructor"")> _ Private Sub New() MyBase.New End Sub <System.Obsolete(""Don't use this Property"")> _ Private ReadOnly Property MyProperty() As String Get Return Me.myField End Get End Property <System.Obsolete(""Don't use this Method""), _ System.ComponentModel.Editor(""This"", ""That"")> _ Private Sub MyMethod(<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal blah As String, <System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal arrayit() As Integer) End Sub <System.Obsolete(""Don't use this Function"")> _ Private Function MyFunction() As <System.Xml.Serialization.XmlIgnoreAttribute(), System.Xml.Serialization.XmlRootAttribute([Namespace]:=""Namespace Value"", ElementName:=""Root, hehehe"")> String Return ""Return"" End Function <Global.System.ObsoleteAttribute(""Don't use this Function"")> _ Private Sub GlobalKeywordFunction() End Sub <System.Serializable()> _ Public Class NestedClass End Class End Class Public Class Test Inherits Form Private b As Button = New Button() Public Sub New() MyBase.New Me.Size = New Size(600, 600) b.Text = ""Test"" b.TabIndex = 0 b.Location = New Point(400, 525) AddHandler MyEvent, AddressOf Me.b_Click End Sub <System.CLSCompliantAttribute(false)> _ Public Event MyEvent As System.EventHandler Private Sub b_Click(ByVal sender As Object, ByVal e As System.EventArgs) End Sub End Class End Namespace"); }
protected override void AddCreateObjectReferenceMethods(GrainInterfaceData grainInterfaceData, CodeTypeDeclaration factoryClass) { throw new NotImplementedException("AddCreateObjectReferenceMethods"); }
public void MethodWithRefParameter() { CodeTypeDeclaration cd = new CodeTypeDeclaration("TEST"); cd.IsClass = true; CodeMemberMethod cmm = new CodeMemberMethod(); cmm.Name = "Work"; cmm.ReturnType = new CodeTypeReference("System.void"); cmm.Attributes = MemberAttributes.Static; // add parameter with ref direction CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i"); param.Direction = FieldDirection.Ref; cmm.Parameters.Add(param); // add parameter with out direction param = new CodeParameterDeclarationExpression(typeof(int), "j"); param.Direction = FieldDirection.Out; cmm.Parameters.Add(param); cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(4)))); cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("j"), new CodePrimitiveExpression(5))); cd.Members.Add(cmm); cmm = new CodeMemberMethod(); cmm.Name = "CallingWork"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression(typeof(int), "a"); cmm.Parameters.Add(parames); cmm.ReturnType = new CodeTypeReference("System.int32"); cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new CodePrimitiveExpression(10))); cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "b")); // invoke the method called "work" CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression (new CodeTypeReferenceExpression("TEST"), "Work")); // add parameter with ref direction CodeDirectionExpression parameter = new CodeDirectionExpression(FieldDirection.Ref, new CodeVariableReferenceExpression("a")); methodinvoked.Parameters.Add(parameter); // add parameter with out direction parameter = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("b")); methodinvoked.Parameters.Add(parameter); cmm.Statements.Add(methodinvoked); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression (new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b")))); cd.Members.Add(cmm); AssertEqual(cd, @"Public Class TEST Shared Sub Work(ByRef i As Integer, ByRef j As Integer) i = (i + 4) j = 5 End Sub Public Shared Function CallingWork(ByVal a As Integer) As Integer a = 10 Dim b As Integer TEST.Work(a, b) Return (a + b) End Function End Class"); }
public override async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(CodeTypeDeclaration codeClass, CodeStatementCollection codeStatementCollection, LinkPinControl element, GenerateCodeContext_Method context) { //if (!mCtrlValueLinkHandle.RecursionReached) //{ // mCtrlValueLinkHandle.RecursionReached = true; // /* // EngineNS.GamePlay.StateMachine.AnimationState State = new EngineNS.GamePlay.StateMachine.AnimationState("State", StateMachine); // State.AnimationPose = StateMachine.AnimationPose; // */ // var stateMachineRef = context.AnimStateMachineReferenceExpression; // var validName = StringRegex.GetValidName(NodeName); // System.CodeDom.CodeVariableDeclarationStatement stateStateMent = new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(EngineNS.Bricks.Animation.AnimStateMachine.LogicAnimationState)), // validName, new CodeObjectCreateExpression(new CodeTypeReference(typeof(EngineNS.Bricks.Animation.AnimStateMachine.LogicAnimationState)), new CodeExpression[] { new CodePrimitiveExpression(validName), stateMachineRef })); // codeStatementCollection.Add(stateStateMent); // stateRef = new CodeVariableReferenceExpression(validName); // CodeFieldReferenceExpression animPoseField = new CodeFieldReferenceExpression(stateRef, "AnimationPoseProxy"); // CodeAssignStatement animPoseAssign = new CodeAssignStatement(); // animPoseAssign.Left = animPoseField; // animPoseAssign.Right = context.StateMachineAnimPoseReferenceExpression; // codeStatementCollection.Add(animPoseAssign); // context.StateAnimPoseReferenceExpression = animPoseField; // //子图 // context.AminStateReferenceExpression = stateRef; // if (mLinkedNodesContainer != null) // { // foreach (var ctrl in mLinkedNodesContainer.CtrlNodeList) // { // if ((ctrl is CodeDomNode.MethodOverride) || // (ctrl is CodeDomNode.MethodCustom) || ctrl is FinalAnimPoseControl || ctrl is CodeDomNode.Animation.StateEntryControl) // { // await ctrl.GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, element, context); // } // } // } // //指向的节点 // for (int i = 0; i < mCtrlValueLinkHandle.GetLinkInfosCount(); ++i) // { // var linkInfo = mCtrlValueLinkHandle.GetLinkInfo(i); // if (linkInfo.m_linkFromObjectInfo == mCtrlValueLinkHandle) // { // //需要返回state,来添加两者之间 的转换关系 // await linkInfo.m_linkToObjectInfo.HostNodeControl.GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, element, context); // if (mCtrlValueLinkHandle.LinkCurveType == enLinkCurveType.Line) // { // var linkCurve = linkInfo.LinkPath as CodeGenerateSystem.Base.AnimStateTransitionCurve; // foreach (var transitionCtrl in linkCurve.TransitionControlList) // { // //构建状态转换宏图 // await transitionCtrl.GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, element, context); // } // var desState = context.ReturnedAminStateReferenceExpression; // var stateTransitionMethod = context.StateTransitionMethodReferenceExpression; // if (stateTransitionMethod != null) // { // //生成转换代码 // CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression(stateRef, "AddStateTransition"); // CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(methodRef, new CodeExpression[] { desState, new CodeMethodReferenceExpression(null, stateTransitionMethod.Name) }); // codeStatementCollection.Add(methodInvoke); // } // } // } // } //} ////将自己的state返回给上层递归 //context.ReturnedAminStateReferenceExpression = stateRef; ////返回currentState //foreach (var node in mCtrlValueLinkHandle.GetLinkedObjects()) //{ // if (node is CodeDomNode.Animation.StateEntryControl) // { // context.FirstStateReferenceExpression = stateRef; // } //} }
protected override void AddGetGrainMethods(GrainInterfaceData iface, CodeTypeDeclaration factoryClass) { throw new NotImplementedException("AddGetGrainMethods"); }
/// <summary> /// hook event to a generic event handler /// </summary> /// <param name="ep">event sender</param> /// <param name="gh">the generic event handler</param> /// <returns></returns> static public CompilerErrorCollection LinkEvent(IEventPointer ep, fnGenericHandler gh) { EventLinkerCollection ec = null; if (eventLinks.ContainsKey(ep.Info.EventHandlerType)) { ec = eventLinks[ep.Info.EventHandlerType]; } else { string nsName = "DynamicEventLinker"; // Create a code compile unit and a namespace CodeCompileUnit ccu = new CodeCompileUnit(); CodeNamespace ns = new CodeNamespace(nsName); // Add some imports statements to the namespace ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("DynamicEventLinker")); //ns.Imports.Add(new CodeNamespaceImport("System.Drawing")); //ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); // Add the namespace to the code compile unit ccu.Namespaces.Add(ns); // //Make class name unique string className = "DLink1"; int n = 1; while (true) { bool bFound = false; foreach (KeyValuePair <Type, EventLinkerCollection> kv in eventLinks) { if (kv.Value.DynamicClassType.Name == className) { bFound = true; n++; className = "DLink" + n.ToString(); } } if (!bFound) { break; } } CodeTypeDeclaration ctd = new CodeTypeDeclaration(className); ctd.BaseTypes.Add(typeof(object)); ns.Types.Add(ctd); // CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; ctd.Members.Add(constructor); constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IEventPointer), "eventId")); constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(fnGenericHandler), "handler")); ctd.Members.Add(new CodeMemberField(typeof(IEventPointer), "_eventId")); ctd.Members.Add(new CodeMemberField(typeof(fnGenericHandler), "_handler")); constructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_eventId"), new CodeVariableReferenceExpression("eventId"))); constructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_handler"), new CodeVariableReferenceExpression("handler"))); // //payload CodeMemberMethod method = new CodeMemberMethod(); MethodInfo mif = ep.Info.EventHandlerType.GetMethod("Invoke"); ParameterInfo[] pifs = mif.GetParameters(); method.Name = "HookEvent"; method.Attributes = MemberAttributes.Public; method.ReturnType = new CodeTypeReference(typeof(void)); for (int i = 0; i < pifs.Length; i++) { method.Parameters.Add(new CodeParameterDeclarationExpression(pifs[i].ParameterType, pifs[i].Name)); } //call _handler passing eventId and parameters to it //create parameter array CodeExpression[] paramArray = new CodeExpression[pifs.Length]; for (int i = 0; i < pifs.Length; i++) { paramArray[i] = new CodeVariableReferenceExpression(pifs[i].Name); } //make the array variable name unique string arrayName = "paramArray"; n = 1; while (true) { bool bFound = false; for (int i = 0; i < pifs.Length; i++) { if (pifs[i].Name == arrayName) { bFound = true; n++; arrayName = "paramArray" + n.ToString(); } } if (!bFound) { break; } } method.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), arrayName, new CodeArrayCreateExpression(typeof(object), paramArray))); //call _handler method.Statements.Add(new CodeDelegateInvokeExpression(new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "_handler"), new CodeExpression[] { new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_eventId"), new CodeVariableReferenceExpression(arrayName) })); // ctd.Members.Add(method); //method returns a delegate for the event-specific handler to be added to the event's handler method = new CodeMemberMethod(); method.Name = "GetHookEvent"; method.Attributes = MemberAttributes.Public; method.ReturnType = new CodeTypeReference(ep.Info.EventHandlerType); method.Statements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression( ep.Info.EventHandlerType, new CodeExpression[] { new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "HookEvent") } ))); ctd.Members.Add(method); //compile it CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); //ICodeCompiler compiler = provider.CreateGenerator() as ICodeCompiler; string linker = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DynamicEventLinker.dll"); if (!System.IO.File.Exists(linker)) { CompilerErrorCollection errs = new CompilerErrorCollection(); errs.Add(new CompilerError("DynamicLinker", 3, 3, "3", "Linker not found:" + linker)); return(errs); } CompilerParameters cp = new CompilerParameters(new string[] { "System.dll", linker /*"System.Windows.Forms.dll", "System.Drawing.dll"*/ }); cp.GenerateInMemory = true; cp.OutputAssembly = "AutoGenerated"; CompilerResults results = provider.CompileAssemblyFromDom(cp, ccu); if (results.Errors == null || results.Errors.Count == 0) { Type[] tps = results.CompiledAssembly.GetExportedTypes(); for (int i = 0; i < tps.Length; i++) { if (tps[i].Name == className) { ec = new EventLinkerCollection(tps[i]); eventLinks.Add(ep.Info.EventHandlerType, ec); break; } } } else { return(results.Errors); } } if (ec != null) { try { object ev = Activator.CreateInstance(ec.DynamicClassType, new object[] { ep, gh }); MethodInfo mi = ec.DynamicClassType.GetMethod("GetHookEvent"); Delegate eh = (Delegate)mi.Invoke(ev, new object[] { }); ep.Info.AddEventHandler(ep.ObjectInstance, eh); if (ec.ContainsKey(ep)) { ec[ep] = ev; } else { ec.Add(ep, ev); } } catch (Exception er) { CompilerErrorCollection errs = new CompilerErrorCollection(); errs.Add(new CompilerError("DynamicLinker", 2, 2, "2", string.Format("{0}. {1}", er.Message, er.StackTrace))); return(errs); } } else { CompilerErrorCollection errs = new CompilerErrorCollection(); errs.Add(new CompilerError("DynamicLinker", 1, 1, "1", "Dynamic type not found")); return(errs); } return(null); }
public override async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(CodeTypeDeclaration codeClass, CodeStatementCollection codeStatementCollection, LinkPinControl element, GenerateCodeContext_Method context) { var valueEvaluateMethod = new CodeMemberMethod(); valueEvaluateMethod.Name = ValidName + "_InputEvaluate"; valueEvaluateMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; valueEvaluateMethod.ReturnType = new CodeTypeReference(typeof(EngineNS.Vector3)); var valueEvaluateMethodContex = new GenerateCodeContext_Method(context.ClassContext, valueEvaluateMethod); var tempInputName = "tempInput"; CodeVariableDeclarationStatement tempInput = new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(EngineNS.Vector3)), tempInputName, new CodeObjectCreateExpression(typeof(EngineNS.Vector3), new CodeExpression[] { new CodePrimitiveExpression(0), new CodePrimitiveExpression(0), new CodePrimitiveExpression(0) })); valueEvaluateMethod.Statements.Add(tempInput); CodeExpression xValue = null; CodeExpression yValue = null; xValue = await Helper.GetEvaluateValueExpression(codeClass, valueEvaluateMethodContex, valueEvaluateMethod, mXLinkHandle, 0); if (!Is1D) { yValue = await Helper.GetEvaluateValueExpression(codeClass, valueEvaluateMethodContex, valueEvaluateMethod, mYLinkHandle, 0); } CodeAssignStatement xValueAssign = new CodeAssignStatement(); xValueAssign.Left = new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tempInputName), "X"); xValueAssign.Right = xValue; valueEvaluateMethod.Statements.Add(xValueAssign); if (!Is1D) { CodeAssignStatement yValueAssign = new CodeAssignStatement(); yValueAssign.Left = new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tempInputName), "Y"); yValueAssign.Right = yValue; valueEvaluateMethod.Statements.Add(yValueAssign); } valueEvaluateMethod.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(tempInputName))); codeClass.Members.Add(valueEvaluateMethod); Type bsType; if (Is1D) { bsType = typeof(EngineNS.Bricks.Animation.BlendTree.Node.BlendTree_AdditiveBlendSpace1D); } else { bsType = typeof(EngineNS.Bricks.Animation.BlendTree.Node.BlendTree_AdditiveBlendSpace2D); } var createLABSMethodInvoke = new CodeGenerateSystem.CodeDom.CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(bsType), "CreateSync"), new CodeExpression[] { new CodeGenerateSystem.CodeDom.CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(EngineNS.RName)), "GetRName", new CodeExpression[] { new CodePrimitiveExpression(FileName.Name) }) }); CodeVariableDeclarationStatement stateVarDeclaration = new CodeVariableDeclarationStatement(bsType, ValidName, createLABSMethodInvoke); codeStatementCollection.Add(stateVarDeclaration); var syncPlayPercentGropAssign = new CodeAssignStatement(); syncPlayPercentGropAssign.Left = new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(ValidName), "SyncPlayPercentGrop"); syncPlayPercentGropAssign.Right = new CodePrimitiveExpression(SyncPlayPercentGrop); codeStatementCollection.Add(syncPlayPercentGropAssign); CodeAssignStatement inputFuncAssign = new CodeAssignStatement(); inputFuncAssign.Left = new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(ValidName), "EvaluateInput"); inputFuncAssign.Right = new CodeVariableReferenceExpression(valueEvaluateMethod.Name); codeStatementCollection.Add(inputFuncAssign); List <string> nofifies = new List <string>(); var info = await EditorCommon.Resources.ResourceInfoManager.Instance.CreateResourceInfoFromFile(FileName.Address + ".rinfo", null); EngineNS.Bricks.Animation.AnimNode.BlendSpace bs = null; if (Is1D) { bs = EngineNS.Bricks.Animation.AnimNode.BlendSpace1D.CreateSync(FileName); } else { bs = EngineNS.Bricks.Animation.AnimNode.BlendSpace2D.CreateSync(FileName); } if (info != null) { for (int j = 0; j < bs.Samples.Count; ++j) { var clip = bs.GetAnimationSample(j); var refInfo = await EditorCommon.Resources.ResourceInfoManager.Instance.CreateResourceInfoFromFile(clip.AnimationName.Address + ".rinfo", null); var animationInfo = refInfo as EditorCommon.ResourceInfos.AnimationClipResourceInfo; nofifies.Clear(); foreach (var pair in animationInfo.NotifyTrackMap) { nofifies.Add(pair.NotifyName); } for (int i = 0; i < nofifies.Count; ++i) { var notify = nofifies[i]; var validNotifyName = StringRegex.GetValidName(notify); validNotifyName = "Anim_Notify_" + validNotifyName; if (hasTheNotifyMethod(codeClass, validNotifyName)) { var attachNotifyEventExp = new CodeGenerateSystem.CodeDom.CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(ValidName), "AdditiveBlendSpace"), "AttachNotifyEvent"), new CodeExpression[] { new CodePrimitiveExpression(j), new CodePrimitiveExpression(i), new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), validNotifyName) }); //CodeArrayIndexerExpression arrayIndex = new CodeArrayIndexerExpression(new CodeFieldReferenceExpression(animRef, "Notifies"), new CodePrimitiveExpression(i)); //CodeAttachEventStatement attachEvent = new CodeAttachEventStatement(arrayIndex, "OnNotify", new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), validNotifyName)); codeStatementCollection.Add(attachNotifyEventExp); } } } } return; }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace nspace = new CodeNamespace ("NSPC"); nspace.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (nspace); CodeTypeDeclaration cd = new CodeTypeDeclaration ("TestingStructs"); cd.IsClass = true; nspace.Types.Add (cd); if (Supports (provider, GeneratorSupport.DeclareValueTypes)) { // GENERATES (C#): // public int CallingStructMethod(int i) { // StructImplementation o = new StructImplementation (); // return o.StructMethod(i); // } AddScenario ("CheckCallingStructMethod"); CodeMemberMethod cmm = new CodeMemberMethod (); cmm.Name = "CallingStructMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("StructImplementation"), "o", new CodeObjectCreateExpression (new CodeTypeReference ("StructImplementation")))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression ( new CodeVariableReferenceExpression ("o"), "StructMethod"), new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); // GENERATES (C#): // public int UsingValueStruct(int i) { // ValueStruct StructObject = new ValueStruct(); // StructObject.x = i; // return StructObject.x; // } AddScenario ("CheckUsingValueStruct"); cmm = new CodeMemberMethod (); cmm.Name = "UsingValueStruct"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement ("ValueStruct", "StructObject", new CodeObjectCreateExpression ("ValueStruct"))); cmm.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("StructObject"), "x"), new CodeArgumentReferenceExpression ("i"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("StructObject"), "x"))); cd.Members.Add (cmm); // GENERATES (C#): // public int UsingStructProperty(int i) { // StructImplementation StructObject = new StructImplementation(); // StructObject.UseIField = i; // return StructObject.UseIField; // } AddScenario ("CheckUsingStructProperty"); cmm = new CodeMemberMethod (); cmm.Name = "UsingStructProperty"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement ("StructImplementation", "StructObject", new CodeObjectCreateExpression ("StructImplementation"))); cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("StructObject"), "UseIField"), new CodeArgumentReferenceExpression ("i"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("StructObject"), "UseIField"))); cd.Members.Add (cmm); // GENERATES (C#): // public int UsingInterfaceStruct(int i) { // ImplementInterfaceStruct IStructObject = new ImplementInterfaceStruct(); // return IStructObject.InterfaceMethod(i); // } if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { AddScenario ("CheckUsingInterfaceStruct"); // method to test struct implementing interfaces cmm = new CodeMemberMethod (); cmm.Name = "UsingInterfaceStruct"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement ("ImplementInterfaceStruct", "IStructObject", new CodeObjectCreateExpression ("ImplementInterfaceStruct"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression ( new CodeVariableReferenceExpression ("IStructObject"), "InterfaceMethod", new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); } // GENERATES (C#): // public struct StructImplementation { // int i; // public int UseIField { // get { // return i; // } // set { // i = value; // } // } // public int StructMethod(int i) { // return (5 + i); // } // } cd = new CodeTypeDeclaration ("StructImplementation"); cd.IsStruct = true; nspace.Types.Add (cd); // declare an integer field CodeMemberField field = new CodeMemberField (new CodeTypeReference (typeof (int)), "i"); field.Attributes = MemberAttributes.Public; cd.Members.Add (field); CodeMemberProperty prop = new CodeMemberProperty (); prop.Name = "UseIField"; prop.Type = new CodeTypeReference (typeof (int)); prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeFieldReferenceExpression fref = new CodeFieldReferenceExpression (); fref.FieldName = "i"; prop.GetStatements.Add (new CodeMethodReturnStatement (fref)); prop.SetStatements.Add (new CodeAssignStatement (fref, new CodePropertySetValueReferenceExpression ())); cd.Members.Add (prop); cmm = new CodeMemberMethod (); cmm.Name = "StructMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodePrimitiveExpression (5), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); // GENERATES (C#): // public struct ValueStruct { // public int x; // } cd = new CodeTypeDeclaration ("ValueStruct"); cd.IsStruct = true; nspace.Types.Add (cd); // declare an integer field field = new CodeMemberField (new CodeTypeReference (typeof (int)), "x"); field.Attributes = MemberAttributes.Public; cd.Members.Add (field); if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { // interface to be implemented // GENERATES (C#): // public interface InterfaceStruct { // int InterfaceMethod(int i); // } cd = new CodeTypeDeclaration ("InterfaceStruct"); cd.IsInterface = true; nspace.Types.Add (cd); // method in the interface cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cd.Members.Add (cmm); // struct to implement an interface // GENERATES (C#): // public struct ImplementInterfaceStruct : InterfaceStruct { // public int InterfaceMethod(int i) { // return (8 + i); // } // } cd = new CodeTypeDeclaration ("ImplementInterfaceStruct"); cd.BaseTypes.Add (new CodeTypeReference ("InterfaceStruct")); cd.IsStruct = true; nspace.Types.Add (cd); field = new CodeMemberField (new CodeTypeReference (typeof (int)), "i"); field.Attributes = MemberAttributes.Public; cd.Members.Add (field); // implement interface method cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceStruct")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodePrimitiveExpression (8), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("i")))); cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cd.Members.Add (cmm); } } }
private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName) { DiscoveryClientProtocol dcp = new DiscoveryClientProtocol(); //if paramset is defaultcredential, set the flag in wcclient if (_usedefaultcredential.IsPresent) { dcp.UseDefaultCredentials = true; } //if paramset is credential, assign the credentials if (ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase)) { dcp.Credentials = _credential.GetNetworkCredential(); } try { dcp.AllowAutoRedirect = true; dcp.DiscoverAny(_uri.ToString()); dcp.ResolveAll(); } catch (WebException ex) { ErrorRecord er = new ErrorRecord(ex, "WebException", ErrorCategory.ObjectNotFound, _uri); if (ex.InnerException != null) { er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); } WriteError(er); return(null); } catch (InvalidOperationException ex) { ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _uri); WriteError(er); return(null); } // create the namespace CodeNamespace codeNS = new CodeNamespace(); if (!string.IsNullOrEmpty(NameSpace)) { codeNS.Name = NameSpace; } //create the class and add it to the namespace if (!string.IsNullOrEmpty(ClassName)) { CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName); codeClass.IsClass = true; codeClass.Attributes = MemberAttributes.Public; codeNS.Types.Add(codeClass); } //create a web reference to the uri docs WebReference wref = new WebReference(dcp.Documents, codeNS); WebReferenceCollection wrefs = new WebReferenceCollection(); wrefs.Add(wref); //create a codecompileunit and add the namespace to it CodeCompileUnit codecompileunit = new CodeCompileUnit(); codecompileunit.Namespaces.Add(codeNS); WebReferenceOptions wrefOptions = new WebReferenceOptions(); wrefOptions.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; wrefOptions.Verbose = true; //create a csharpprovider and compile it CSharpCodeProvider csharpprovider = new CSharpCodeProvider(); StringCollection Warnings = ServiceDescriptionImporter.GenerateWebReferences(wrefs, csharpprovider, codecompileunit, wrefOptions); StringBuilder codegenerator = new StringBuilder(); StringWriter writer = new StringWriter(codegenerator, CultureInfo.InvariantCulture); try { csharpprovider.GenerateCodeFromCompileUnit(codecompileunit, writer, null); } catch (NotImplementedException ex) { ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri); WriteError(er); } //generate the hashcode of the CodeCompileUnit _sourceHash = codegenerator.ToString().GetHashCode(); //if the sourcehash matches the hashcode in the cache,the proxy hasnt changed and so // return the instance of th eproxy in the cache if (s_srccodeCache.ContainsKey(_sourceHash)) { object obj; s_srccodeCache.TryGetValue(_sourceHash, out obj); WriteObject(obj, true); return(null); } CompilerParameters options = new CompilerParameters(); CompilerResults results = null; foreach (string warning in Warnings) { this.WriteWarning(warning); } // add the references to the required assemblies options.ReferencedAssemblies.Add("System.dll"); options.ReferencedAssemblies.Add("System.Data.dll"); options.ReferencedAssemblies.Add("System.Xml.dll"); options.ReferencedAssemblies.Add("System.Web.Services.dll"); options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); GetReferencedAssemblies(typeof(Cmdlet).Assembly, options); options.GenerateInMemory = true; options.TreatWarningsAsErrors = false; options.WarningLevel = 4; options.GenerateExecutable = false; try { results = csharpprovider.CompileAssemblyFromSource(options, codegenerator.ToString()); } catch (NotImplementedException ex) { ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri); WriteError(er); } return(results.CompiledAssembly); }
public void CastingOperations() { var cd = new CodeTypeDeclaration(); cd.Name = "Test"; cd.IsClass = true; // create method to test casting float to int CodeMemberMethod castReturnValue = new CodeMemberMethod(); castReturnValue.Name = "CastReturnValue"; castReturnValue.ReturnType = new CodeTypeReference(typeof(int)); castReturnValue.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression strParam = new CodeParameterDeclarationExpression(typeof(string), "value"); castReturnValue.Parameters.Add(strParam); castReturnValue.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Single"), "Parse", new CodeExpression[] { new CodeVariableReferenceExpression("value"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("System.Globalization.CultureInfo"), "InvariantCulture") })))); cd.Members.Add(castReturnValue); // create method to test casting interface -> class CodeMemberMethod castInterface = new CodeMemberMethod(); castInterface.Name = "CastInterface"; castInterface.ReturnType = new CodeTypeReference(typeof(string)); castInterface.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression interfaceParam = new CodeParameterDeclarationExpression(typeof(System.ICloneable), "value"); castInterface.Parameters.Add(interfaceParam); castInterface.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(typeof(string), new CodeVariableReferenceExpression("value")))); cd.Members.Add(castInterface); // create method to test casting value type -> reference type CodeMemberMethod valueToReference = new CodeMemberMethod(); valueToReference.Name = "ValueToReference"; valueToReference.ReturnType = new CodeTypeReference(typeof(System.Object)); valueToReference.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression valueParam = new CodeParameterDeclarationExpression(typeof(int), "value"); valueToReference.Parameters.Add(valueParam); valueToReference.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(typeof(System.Object), new CodeVariableReferenceExpression("value")))); cd.Members.Add(valueToReference); AssertEqual(cd, @"Public Class Test Public Shared Function CastReturnValue(ByVal value As String) As Integer Return CType(Single.Parse(value, System.Globalization.CultureInfo.InvariantCulture),Integer) End Function Public Shared Function CastInterface(ByVal value As System.ICloneable) As String Return CType(value,String) End Function Public Shared Function ValueToReference(ByVal value As Integer) As Object Return CType(value,Object) End Function End Class"); }
public virtual void GenerateCodeFromType(CodeTypeDeclaration codeType, TextWriter writer, CodeGeneratorOptions options) { ICodeGenerator cg = CreateGenerator(); if (cg == null) throw GetNotImplemented(); cg.GenerateCodeFromType(codeType, writer, options); }
public abstract void AddEnumMembers(CodeTypeDeclaration typeDeclaration, IList <IOpenApiAny> enumTypeList);
private static void GenerateConstructors(IEnumerable <ConstructorInfo> constructors, CodeTypeDeclaration codeType) { if (constructors == null || !constructors.Any()) { return; } var existingConstructors = codeType.Members.OfType <CodeConstructor>().ToArray(); foreach (var existingConstructor in existingConstructors) { codeType.Members.Remove(existingConstructor); } foreach (var constructor in constructors) { var ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Public; foreach (var param in constructor.GetParameters()) { ctor.Parameters.Add(new CodeParameterDeclarationExpression(param.ParameterType, param.Name)); ctor.BaseConstructorArgs.Add(new CodeSnippetExpression(param.Name)); } codeType.Members.Add(ctor); } }
/// <summary> /// Processes the generators. /// </summary> /// <param name="source">source</param> /// <param name="classType">Type of the class.</param> /// <param name="method">The initialize method.</param> /// <param name="generateFields">if set to <c>true</c> [generate fields].</param> /// <returns></returns> public CodeExpression ProcessGenerators(object source, CodeTypeDeclaration classType, CodeMemberMethod method, bool generateFields) { if (source == null) { return(null); } IGeneratorType generator; Type elementType = source.GetType(); bool customUserControl = false; if (elementType.BaseType == typeof(UserControl)) { // we have to retype any custom user control to fake generator so we can generate code for it customUserControl = true; elementType = typeof(CustomUserControlGeneratorType); } if (!Generators.TryGetValue(elementType, out generator)) { //skusim vytvorit generator cez reflexiu IGeneratorType reflectedGenerator = CreateGeneratorFromReflection(elementType); if (reflectedGenerator != null) { Generators.Add(elementType, reflectedGenerator); } } if (Generators.TryGetValue(elementType, out generator)) { DependencyObject xamlSource = source as DependencyObject; if (xamlSource != null) { CodeExpression parent = generator.Generate(xamlSource, classType, method, generateFields); CodeComHelper.GenerateAttachedProperties(method, parent, xamlSource); Type oldDataType = BindingGenerator.Instance.ActiveDataType; Type newType = xamlSource.GetValue(GeneratedBindings.DataTypeProperty) as Type; if (newType != null) { BindingGenerator.Instance.ActiveDataType = newType; } FrameworkElement elem = source as FrameworkElement; if (elem != null) { CodeComHelper.GenerateBindings(method, parent, elem, elem.Name); CodeComHelper.GenerateResourceReferences(method, parent, elem); if (!customUserControl && (elem.Resources.Count != 0 || elem.Resources.MergedDictionaries.Count != 0)) { ResourceDictionaryGenerator resourcesGenerator = new ResourceDictionaryGenerator(); CodeMemberMethod resourcesMethod = new CodeMemberMethod(); resourcesMethod.Attributes = MemberAttributes.Static | MemberAttributes.Private; resourcesMethod.Name = "InitializeElement" + elem.Name + "Resources"; resourcesMethod.Parameters.Add(new CodeParameterDeclarationExpression("UIElement", "elem")); classType.Members.Add(resourcesMethod); resourcesGenerator.Generate(elem.Resources, classType, resourcesMethod, new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("elem"), "Resources")); method.Statements.Add(new CodeMethodInvokeExpression(null, resourcesMethod.Name, parent)); } } IEnumerable children = generator.GetChildren(xamlSource); if (children != null) { foreach (DependencyObject child in children) { if (child == null) { continue; } int index = method.Statements.Count; CodeExpression childRef = ProcessGenerators(child, classType, method, generateFields); if (childRef != null) { generator.AddChild(parent, childRef, method, index + 2); // +1 for creating instance +1 for comment } } } BindingGenerator.Instance.ActiveDataType = oldDataType; return(parent); } } string errorText = "Unknown type : " + source.GetType(); Console.WriteLine(errorText); CodeSnippetStatement error = new CodeSnippetStatement("#error " + errorText); method.Statements.Add(error); return(null); }
private void Generate(CodeTypeDeclaration type) { this.WriteCustomAttributes(type.CustomAttributes); var attributes = type.Attributes; if (type.IsEnum) { attributes |= MemberAttributes.Final; } this.WriteAttributes(attributes); this.WriteIfTrue(type.IsPartial, "partial"); this.WriteIfTrue(type.IsClass, "class"); this.WriteIfTrue(type.IsStruct, "struct"); this.WriteIfTrue(type.IsEnum, "enum"); this.WriteIfTrue(type.IsInterface, "interface"); this.Write(type.Name); if (type.BaseTypes.Count > 0) { this.Write(" : "); bool isFirst = true; foreach (CodeTypeReference baseType in type.BaseTypes) { if (!isFirst) { this.Write(", "); } else { isFirst = false; } this.Generate(baseType); } } // Write the methods this.WriteLine(); this.WriteLine("{"); this.Indent++; foreach (var member in type.Members.OfType <CodeMemberField>()) { this.WriteLine(); this.Generate(member); } foreach (var member in type.Members.OfType <CodeConstructor>()) { this.WriteLine(); this.Generate(type, member); } foreach (var member in type.Members.OfType <CodeMemberProperty>()) { this.WriteLine(); this.Generate(member); } foreach (var member in type.Members.OfType <CodeMemberMethod>()) { if (member is CodeConstructor) { continue; } this.WriteLine(); this.Generate(member, isInterface: type.IsInterface); } this.Indent--; this.WriteLine("}"); }
private void CopyClassProperties(CodeTypeDeclaration source, CodeTypeDeclaration target) { target.Name = source.Name; target.Attributes = source.Attributes; }
private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String nameSpace, String baseName, String resourcesNamespace, bool internalClass, bool useStatic) { const String tmpVarName = "temp"; String resMgrCtorParam; if (resourcesNamespace != null) { if (resourcesNamespace.Length > 0) { resMgrCtorParam = resourcesNamespace + '.' + baseName; } else { resMgrCtorParam = baseName; } } else if (!string.IsNullOrEmpty(nameSpace)) { resMgrCtorParam = nameSpace + '.' + baseName; } else { resMgrCtorParam = baseName; } var suppressMessageAttrib = new CodeAttributeDeclaration(new CodeTypeReference(typeof(SuppressMessageAttribute))); suppressMessageAttrib.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference; suppressMessageAttrib.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("Microsoft.Performance"))); suppressMessageAttrib.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("CA1811:AvoidUncalledPrivateCode"))); // Emit a constructor - make it protected even if it is a "static" class to allow subclassing CodeConstructor ctor = new CodeConstructor(); ctor.CustomAttributes.Add(suppressMessageAttrib); if (useStatic || internalClass) { ctor.Attributes = MemberAttributes.FamilyAndAssembly; } else { ctor.Attributes = MemberAttributes.Public; } srClass.Members.Add(ctor); // Emit _resMgr field. var ResMgrCodeTypeReference = new CodeTypeReference(typeof(ResourceManager), CodeTypeReferenceOptions.GlobalReference); var field = new CodeMemberField(ResMgrCodeTypeReference, ResMgrFieldName) { Attributes = MemberAttributes.Private }; if (useStatic) { field.Attributes |= MemberAttributes.Static; } srClass.Members.Add(field); // Emit _resCulture field, and leave it set to null. var CultureTypeReference = new CodeTypeReference(typeof(CultureInfo), CodeTypeReferenceOptions.GlobalReference); field = new CodeMemberField(CultureTypeReference, CultureInfoFieldName); field.Attributes = MemberAttributes.Private; if (useStatic) { field.Attributes |= MemberAttributes.Static; } srClass.Members.Add(field); // Emit ResMgr property CodeMemberProperty resMgr = new CodeMemberProperty(); srClass.Members.Add(resMgr); resMgr.Name = ResMgrPropertyName; resMgr.HasGet = true; resMgr.HasSet = false; resMgr.Type = ResMgrCodeTypeReference; if (internalClass) { resMgr.Attributes = MemberAttributes.Assembly; } else { resMgr.Attributes = MemberAttributes.Public; } if (useStatic) { resMgr.Attributes |= MemberAttributes.Static; } // Mark the ResMgr property as advanced var editorBrowsableStateTypeRef = new CodeTypeReference(typeof(System.ComponentModel.EditorBrowsableState)) { Options = CodeTypeReferenceOptions.GlobalReference }; var editorBrowsableStateAdvanced = new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(editorBrowsableStateTypeRef), "Advanced")); var editorBrowsableAdvancedAttribute = new CodeAttributeDeclaration("System.ComponentModel.EditorBrowsableAttribute", editorBrowsableStateAdvanced); editorBrowsableAdvancedAttribute.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference; resMgr.CustomAttributes.Add(editorBrowsableAdvancedAttribute); // Emit the Culture property (read/write) var culture = new CodeMemberProperty(); srClass.Members.Add(culture); culture.Name = CultureInfoPropertyName; culture.HasGet = true; culture.HasSet = true; culture.Type = CultureTypeReference; if (internalClass) { culture.Attributes = MemberAttributes.Assembly; } else { culture.Attributes = MemberAttributes.Public; } if (useStatic) { culture.Attributes |= MemberAttributes.Static; } // Mark the Culture property as advanced culture.CustomAttributes.Add(editorBrowsableAdvancedAttribute); /* * // Here's what I'm trying to emit. Since not all languages support * // try/finally, we'll avoid our double lock pattern here. * // This will only hurt perf when we get two threads racing through * // this method the first time. Unfortunate, but not a big deal. * // Also, the .NET Compact Framework doesn't support * // Thread.MemoryBarrier (they only run on processors w/ a strong * // memory model, and who knows about IA64...) * // Once we have Interlocked.CompareExchange<T>, we should use it here. * if (_resMgr == null) { * ResourceManager tmp = new ResourceManager("<resources-name-with-namespace>", typeof("<class-name>").Assembly); * _resMgr = tmp; * } * return _resMgr; */ var field_resMgr = new CodeFieldReferenceExpression(null, ResMgrFieldName); var object_equalsMethod = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Object)), "ReferenceEquals"); var isResMgrNull = new CodeMethodInvokeExpression(object_equalsMethod, field_resMgr, new CodePrimitiveExpression(null)); // typeof(<class-name>).Assembly var getAssembly = new CodePropertyReferenceExpression(new CodeTypeOfExpression(new CodeTypeReference(srClass.Name)), "Assembly"); // new ResourceManager(resMgrCtorParam, typeof(<class-name>).Assembly); var newResMgr = new CodeObjectCreateExpression(ResMgrCodeTypeReference, new CodePrimitiveExpression(resMgrCtorParam), getAssembly); var init = new CodeStatement[2]; init[0] = new CodeVariableDeclarationStatement(ResMgrCodeTypeReference, tmpVarName, newResMgr); init[1] = new CodeAssignStatement(field_resMgr, new CodeVariableReferenceExpression(tmpVarName)); resMgr.GetStatements.Add(new CodeConditionStatement(isResMgrNull, init)); resMgr.GetStatements.Add(new CodeMethodReturnStatement(field_resMgr)); // Add a doc comment to the ResourceManager property resMgr.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true)); resMgr.Comments.Add(new CodeCommentStatement(SR.GetString(SR.ResMgrPropertyComment), true)); resMgr.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true)); // Emit code for Culture property var field_resCulture = new CodeFieldReferenceExpression(null, CultureInfoFieldName); culture.GetStatements.Add(new CodeMethodReturnStatement(field_resCulture)); var newCulture = new CodePropertySetValueReferenceExpression(); culture.SetStatements.Add(new CodeAssignStatement(field_resCulture, newCulture)); // Add a doc comment to Culture property culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true)); culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment1), true)); culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment2), true)); culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true)); }
// Called by the WinForm designer at save time public override void GenerateCodeFromCompileUnit(CodeCompileUnit compileUnit, TextWriter writer, CodeGeneratorOptions options) { // Does that CodeCompileUnit comes from a "Merged" unit ? if (compileUnit is XMergedCodeCompileUnit mergedUnit) { // Retrieve the Form Class CodeTypeDeclaration combinedClass = XSharpCodeDomHelper.FindDesignerClass(compileUnit); // and retrieve the filename of the prg file string prgFileName = mergedUnit.FileName; // Build the Designer FileName // Retrieve Both CodeCompileUnit var formCCU = mergedUnit.FormUnit; var designCCU = mergedUnit.DesignerUnit; string designerPrgFile = designCCU.FileName; var formMembers = new CodeTypeMemberCollection(formCCU.Members); foreach (CodeTypeMember m in formMembers) { m.SetWritten(false); } // suppress generating the "generated code" header in the form.prg formCCU.GenerateHeader = false; CodeTypeDeclaration formClass = formCCU.GetFirstClass(); CodeTypeDeclaration designClass = designCCU.GetFirstClass(); // Now, remove the members CopyClassProperties(combinedClass, formClass); CopyClassProperties(combinedClass, designClass); combinedClass.IsPartial = true; formClass.Members.Clear(); designClass.Members.Clear(); // Now, split the members // And make sure no members are deleted foreach (CodeTypeMember ctm in combinedClass.Members) { // Was it a member that we have found in the original merged CodeCompileUnits ? if (ctm is IXCodeObject xco) { if (ctm.GetFromDesigner()) { // Comes from the Designer.prg file // so go back to Designer.prg designClass.Members.Add(ctm); ctm.SetWritten(true); } else { // Comes from the original Form file formClass.Members.Add(ctm); foreach (CodeTypeMember member in formMembers) { if (member == ctm) { member.SetWritten(true); formMembers.Remove(member); break; } } } } else { // This must be a member generated by the Designer ! // So we will move Methods to the Form and all others to the Designer if (ctm is CodeMemberMethod) { formClass.Members.Add(ctm); ctm.SetWritten(true); } else { designClass.Members.Add(ctm); ctm.SetWritten(true); } } } // Check for members that are not written foreach (CodeTypeMember member in formMembers) { if (!member.WasWritten()) { formClass.Members.Add(member); } } // now, we must save both CodeCompileUnit // The received TextWriter is pointing to the Form // so we must create our own TextWriter for the Designer // First, let's make in Memory String generatedSource; MemoryStream inMemory = new MemoryStream(); StreamWriter designerStream = new StreamWriter(inMemory, Encoding.UTF8); // // Backup original Form file and Form.Designer file // if (XSharpModel.XSettings.FormEditorMakeBackupFiles) { if (File.Exists(prgFileName)) { var bak = Path.ChangeExtension(prgFileName, ".bak"); Utilities.CopyFileSafe(prgFileName, bak); } if (File.Exists(designerPrgFile)) { var bak = Path.ChangeExtension(designerPrgFile, ".bak"); Utilities.CopyFileSafe(designerPrgFile, bak); } } base.GenerateCodeFromCompileUnit(designCCU, designerStream, options); // and force Flush designerStream.Flush(); // Reset and read to String inMemory.Position = 0; StreamReader reader = new StreamReader(inMemory, Encoding.UTF8, true); generatedSource = reader.ReadToEnd(); generatedSource = this._projectNode.SynchronizeKeywordCase(generatedSource, prgFileName); Encoding realencoding = reader.CurrentEncoding; reader.Close(); designerStream.Close(); XSharpFileNode node = _fileNode.FindChild(designerPrgFile) as XSharpFileNode; bool done = false; if (node != null) { // assign the source to the open buffer when possible if (node.DocumentSetText(generatedSource)) { // then use automation to save the file, because that is much easier // since we do not have to worry about the docdata etc. var oaFile = (OAXSharpFileItem)node.GetAutomationObject(); oaFile.Save(designerPrgFile); done = true; } } if (!done) { // File is not open in editor, so write to disk designerStream = new StreamWriter(designerPrgFile, false, realencoding); designerStream.Write(generatedSource); designerStream.Flush(); designerStream.Close(); } // The problem here, is that we "may" have some new members, like EvenHandlers, and we need to update their position (line/col) XSharpCodeParser parser = new XSharpCodeParser(_projectNode, formClass); parser.FileName = designerPrgFile; CodeCompileUnit resultDesigner = parser.Parse(generatedSource); CodeTypeDeclaration resultClass = XSharpCodeDomHelper.FindDesignerClass(resultDesigner); // just to be sure... if (resultClass != null) { // Now push all elements from resultClass to designClass designClass.Members.Clear(); foreach (CodeTypeMember ctm in resultClass.Members) { ctm.SetFromDesigner(true); designClass.Members.Add(ctm); } } // Ok,we MUST do the same thing for the Form file base.GenerateCodeFromCompileUnit(formCCU, writer, options); // BUT, the writer is hold by the Form Designer, don't close it !! writer.Flush(); // Now, we must re-read it and parse again IServiceProvider provider = (DocDataTextWriter)writer; DocData docData = (DocData)provider.GetService(typeof(DocData)); DocDataTextReader ddtr = new DocDataTextReader(docData); // Retrieve generatedSource = ddtr.ReadToEnd(); var newsource = this._projectNode.SynchronizeKeywordCase(generatedSource, prgFileName); if (string.Compare(newsource, generatedSource) != 0) { // get DocDataTextWriter and update the source after the case has been synchronized generatedSource = newsource; DocDataTextWriter dtw = new DocDataTextWriter(docData); dtw.Write(generatedSource); dtw.Flush(); } // Don't forget to set the name of the file where the source is... parser.FileName = prgFileName; resultDesigner = parser.Parse(generatedSource); resultClass = resultDesigner.GetFirstClass(); // just to be sure... if (resultClass != null) { // Now push all elements from resultClass to formClass formClass.Members.Clear(); foreach (CodeTypeMember ctm in resultClass.Members) { ctm.SetFromDesigner(false); formClass.Members.Add(ctm); } } // Ok, it should be ok.... // We have updated the file and the types that are stored inside each CCU that have been merged in compileUnit //XSharpCodeDomHelper.MergeCodeCompileUnit(compileUnit, formCCU, designCCU); // And update... combinedClass.Members.Clear(); combinedClass.Members.AddRange(designClass.Members); combinedClass.Members.AddRange(formClass.Members); } else { var xcompileUnit = ToXCodeCompileUnit(compileUnit); // suppress generating the "generated code" header if (writer is DocDataTextWriter) // Form Editor { compileUnit.SetNoHeader(); } base.GenerateCodeFromCompileUnit(compileUnit, writer, options); writer.Flush(); // Designer gave us these informations // Now, we must re-read it and parse again if (writer is DocDataTextWriter) { CodeTypeDeclaration formClass = compileUnit.GetFirstClass(); IServiceProvider provider = (DocDataTextWriter)writer; DocData docData = (DocData)provider.GetService(typeof(DocData)); DocDataTextReader ddtr = new DocDataTextReader(docData); // Retrieve string generatedSource = ddtr.ReadToEnd(); XSharpCodeParser parser = new XSharpCodeParser(_projectNode); parser.FileName = xcompileUnit.FileName; generatedSource = _projectNode.SynchronizeKeywordCase(generatedSource, parser.FileName); CodeCompileUnit resultCcu = parser.Parse(generatedSource); CodeTypeDeclaration resultClass = resultCcu.GetFirstClass(); // just to be sure... if (resultClass != null) { // Now push all elements from resultClass to formClass formClass.Members.Clear(); foreach (CodeTypeMember ctm in resultClass.Members) { formClass.Members.Add(ctm); } } } } }
/*/// <summary> * /// Compose additional items of the test setup method. * /// </summary> * /// <param name="setUpMethod">The test setup method.</param> * /// <param name="testObjectMemberField">The member field of the object under test.</param> * /// <param name="testObjectName">The name of the object under test.</param> * /// <returns> * /// The initialization expression of the object under test. * /// Is <c>null</c>, when none is created. * /// </returns> * protected override CodeObjectCreateExpression ComposeTestSetupMethod( * CodeMemberMethod setUpMethod, * CodeMemberField testObjectMemberField, * string testObjectName) * { * //var invokeExpression = new CodeMethodInvokeExpression( * // new CodeTypeReferenceExpression("Assert"), * // "AreEqual", * //new CodePrimitiveExpression("expected") * // new CodeFieldReferenceExpression(testObjectMemberField, "bla") * // , new CodeVariableReferenceExpression("actual")); * var fieldRef1 = * new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), testObjectMemberField.Name); * * var testObjectMemberFieldCreate = new CodeObjectCreateExpression(testObjectName, new CodeExpression[] { }); * var as1 = new CodeAssignStatement(fieldRef1, testObjectMemberFieldCreate); * * // Creates a statement using a code expression. * // var expressionStatement = new CodeExpressionStatement(fieldRef1); * setUpMethod.Statements.Add(as1); * return testObjectMemberFieldCreate; * }*/ /// <summary> /// Compose additional items of the test setup method. /// </summary> /// <param name="context">The setup context.</param> /// <param name="testObjectMemberField">The member field of the object under test.</param> /// <param name="testObjectName">The name of the object under test.</param> /// <returns> /// The list of assigned mock objects. /// </returns> protected virtual IEnumerable <CodeAssignStatement> ComposeTestSetupMockery( ISetupAndTearDownCreationContext context, CodeMemberField testObjectMemberField, string testObjectName) { CodeTypeDeclaration testClassDeclaration = context.TestClassDeclaration; CodeMemberMethod setUpMethod = context.SetUpMethod; // Todo: only the Type is necs, the CodeTypeDeclaration is too much knowledge. var testObjectClassType = (Type)testClassDeclaration.UserData[NStubConstants.UserDataClassTypeKey]; Type[] parameters = { /*typeof(int)*/ }; // Get the constructor that takes an integer as a parameter. var flags = BindingFlags.Instance; var noPrivate = true; switch (Configuration.MethodGeneratorLevelOfDetail) { case MemberVisibility.Public: flags |= BindingFlags.Public; break; case MemberVisibility.Internal: flags |= BindingFlags.Public | BindingFlags.NonPublic; break; case MemberVisibility.Private: flags |= BindingFlags.Public | BindingFlags.NonPublic; noPrivate = false; break; default: break; } var ctor = testObjectClassType.GetConstructor(flags, Type.DefaultBinder, parameters, null); if (ctor == null) { // outputBlock.Text += // "There is no public constructor of MyClass that takes an integer as a parameter.\n"; } // else // { // outputBlock.Text += // "The public constructor of MyClass that takes an integer as a parameter is:\n"; // outputBlock.Text += ctor.ToString() + "\n"; // } var testObjectConstructors = testObjectClassType.GetConstructors(flags); bool hasInterfaceInCtorParameters = false; var ctorParameterTypes = new List <ParameterInfo>(); foreach (var constructor in testObjectConstructors) { if (noPrivate && constructor.IsPrivate) { continue; } var ctorParameters = constructor.GetParameters(); foreach (var para in ctorParameters) { if (para.ParameterType.IsInterface /*&& !para.ParameterType.IsGenericType*/) { hasInterfaceInCtorParameters = true; ctorParameterTypes.Add(para); } } } if (!hasInterfaceInCtorParameters) { return(new CodeAssignStatement[0]); } var testObjectInitializerPosition = setUpMethod.Statements.Count - 1; var mockRepositoryMemberField = this.AddMockRepository( testClassDeclaration, setUpMethod, "mocks"); var mockAssignments = new List <CodeAssignStatement>(); foreach (var paraInfo in ctorParameterTypes) { IBuilderData data; ConstructorAssignment ctorassignment = null; if (paraInfo.ParameterType.IsGenericType) { var genericTypeDefinition = paraInfo.ParameterType.GetGenericTypeDefinition(); if (typeof(IEnumerable <>).IsAssignableFrom(genericTypeDefinition)) { // try to find the testobjcomposer assigned sub items for IEnumerable<T>'s. BuildProperties.TryGetValue( "CreateAssignments." + testObjectClassType.FullName + "." + paraInfo.Name, paraInfo.Name + "Item", out data); if (data != null) { ctorassignment = data.GetData() as ConstructorAssignment; } if (testObjectClassType.Name == "DefaultMemberBuilderFactory") { } if (ctorassignment != null) { this.CreateMocker( testClassDeclaration, setUpMethod, mockRepositoryMemberField, mockAssignments, ctorassignment.MemberType, paraInfo.Name, ctorassignment); } continue; } } BuildProperties.TryGetValue( "Assignments." + testObjectClassType.FullName, paraInfo.Name, out data); if (data != null) { ctorassignment = data.GetData() as ConstructorAssignment; } this.CreateMocker( testClassDeclaration, setUpMethod, mockRepositoryMemberField, mockAssignments, paraInfo.ParameterType, paraInfo.Name, ctorassignment); } // reorder the testObject initializer to the bottom of the SetUp method. // var removedTypedec = setUpMethod.Statements[testObjectInitializerPosition]; // setUpMethod.Statements.RemoveAt(testObjectInitializerPosition); // setUpMethod.Statements.Add(removedTypedec); return(mockAssignments); }
public XDocDataTextReader(DocData docData, CodeTypeDeclaration classname) : base(docData) { ClassName = classname; }
/// <summary> /// Creates the CodeDOM for a strongly typed index on a table. /// </summary> /// <param name="schema">The parent schema.</param> /// <param name="keySchema">The key schema.</param> public TypedIndexClass(ConstraintSchema constraintSchema) { // Initialize the object. this.constraintSchema = constraintSchema; // Construct the type names for the table and rows within the table. string indexTypeName = string.Format("{0}Index", constraintSchema.Name); string indexRowName = string.Format("{0}Row", constraintSchema.Selector.Name); // /// <summary> // /// Represents a means of identifying a Department row using a set of columns in which all values must be unique. // /// </summary> // [System.Diagnostics.DebuggerStepThrough()] // public class DepartmentKeyIndex // { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(string.Format("Represents a means of identifying a {0} row using a set of columns in which all values must be unique.", constraintSchema.Selector.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); CodeTypeDeclaration tableClass = new CodeTypeDeclaration(); this.IsClass = true; this.Name = indexTypeName; this.TypeAttributes = TypeAttributes.Public; this.CustomAttributes.Add(new CodeAttributeDeclaration("System.Diagnostics.DebuggerStepThrough")); // // A non-primary index is created using a DataView find rows matching the keys. // private DataView dataView; CodeMemberField dataViewField = new CodeMemberField(); dataViewField.Comments.Add(new CodeCommentStatement("A non-primary index is created using a DataView find rows matching the keys.")); dataViewField.Attributes = MemberAttributes.Private; dataViewField.Type = new CodeTypeReference(typeof(System.Data.DataView)); dataViewField.Name = "dataView"; this.Members.Add(dataViewField); // /// <summary> // /// Create an index on the Object table. // /// </summary> // /// <param name="name">The name of the index.</param> // /// <param name="columns">The columns that describe a unique key.</param> // public ObjectKeyExternalId0Index(Column[] columns) // { CodeConstructor constructor = new CodeConstructor(); constructor.Comments.Add(new CodeCommentStatement("<summary>", true)); constructor.Comments.Add(new CodeCommentStatement(string.Format("Create an index on the {0} table.", constraintSchema.Selector.Name), true)); constructor.Comments.Add(new CodeCommentStatement("</summary>", true)); constructor.Comments.Add(new CodeCommentStatement("<param name=\"name\">The name of the index.</param>", true)); constructor.Comments.Add(new CodeCommentStatement("<param name=\"columns\">The columns that describe a unique key.</param>", true)); constructor.Attributes = MemberAttributes.Public; constructor.Name = indexTypeName; constructor.Parameters.Add(new CodeParameterDeclarationExpression("Column[]", "columns")); // // The DataView is used to implement an index on the table that can be used to find elements. // this.dataView = new System.Data.DataView(); constructor.Statements.Add(new CodeCommentStatement("The DataView is used to implement an index on the table that can be used to find elements.")); constructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), new CodeObjectCreateExpression(typeof(System.Data.DataView)))); // // When a meaningful key is specified, the DataView is used to find current rows containing non-null values in the // // specified columns that match key elements. // if ((columns.Length != 0)) // { constructor.Statements.Add(new CodeCommentStatement("When a meaningful key is specified, the DataView is used to find current rows containing non-null values in the ")); constructor.Statements.Add(new CodeCommentStatement("specified columns that match key elements.")); List <CodeStatement> constructorTrueStatements = new List <CodeStatement>(); // // This will construct the strings that the DataView uses to sort and filter the rows. Note that only non-null // // keys are allowed into the view. // string sort = string.Empty; // string rowFilter = string.Empty; // for (int columnIndex = 0; (columnIndex < columns.Length); columnIndex = (columnIndex + 1)) // { // Column column = columns[columnIndex]; // if ((columnIndex // < (columns.Length - 1))) // { // sort = string.Format("{0}{1},", sort, column.ColumnName); // rowFilter = string.Format("{0}IsNull({1}, \'null\')<>\'null\',", rowFilter, column.ColumnName); // } // else // { // sort = string.Format("{0}{1}", sort, column.ColumnName); // rowFilter = string.Format("{0}IsNull({1}, \'null\')<>\'null\'", rowFilter, column.ColumnName); // } // } constructorTrueStatements.Add(new CodeCommentStatement("This will construct the strings that the DataView uses to sort and filter the rows. Note that only non-null")); constructorTrueStatements.Add(new CodeCommentStatement("keys are allowed into the view.")); constructorTrueStatements.Add(new CodeVariableDeclarationStatement(typeof(System.String), "sort", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.String)), "Empty"))); List <CodeStatement> constructorIterationStatements = new List <CodeStatement>(); constructorIterationStatements.Add(new CodeVariableDeclarationStatement("Column", "column", new CodeIndexerExpression(new CodeVariableReferenceExpression("columns"), new CodeVariableReferenceExpression("columnIndex")))); constructorIterationStatements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("columnIndex"), CodeBinaryOperatorType.LessThan, new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("columns"), "Length"), CodeBinaryOperatorType.Subtract, new CodePrimitiveExpression(1))), new CodeStatement[] { new CodeAssignStatement(new CodeVariableReferenceExpression("sort"), new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(System.String)), "Format"), new CodePrimitiveExpression("{0}{1},"), new CodeVariableReferenceExpression("sort"), new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("column"), "ColumnName"))), }, new CodeStatement[] { new CodeAssignStatement(new CodeVariableReferenceExpression("sort"), new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(System.String)), "Format"), new CodePrimitiveExpression("{0}{1}"), new CodeVariableReferenceExpression("sort"), new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("column"), "ColumnName"))), })); constructorTrueStatements.Add(new CodeIterationStatement(new CodeVariableDeclarationStatement(typeof(System.Int32), "columnIndex", new CodePrimitiveExpression(0)), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("columnIndex"), CodeBinaryOperatorType.LessThan, new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("columns"), "Length")), new CodeAssignStatement(new CodeVariableReferenceExpression("columnIndex"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("columnIndex"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))), constructorIterationStatements.ToArray())); // // This DataView will be used to find the current rows in the Department table that contain the non-null key // // elements. // this.dataView.Table = columns[0].Table; // this.dataView.Sort = sort; // this.dataView.RowStateFilter = System.Data.DataViewRowState.CurrentRows; constructorTrueStatements.Add(new CodeCommentStatement("This DataView will be used to find the current rows in the Department table that contain the non-null key ")); constructorTrueStatements.Add(new CodeCommentStatement("elements.")); constructorTrueStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), "Table"), new CodeFieldReferenceExpression(new CodeIndexerExpression(new CodeArgumentReferenceExpression("columns"), new CodePrimitiveExpression(0)), "Table"))); constructorTrueStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), "Sort"), new CodeVariableReferenceExpression("sort"))); constructorTrueStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), "RowStateFilter"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Data.DataViewRowState)), "CurrentRows"))); // } constructor.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("columns"), "Length"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(0)), constructorTrueStatements.ToArray())); // } this.Members.Add(constructor); // /// <summary> // /// Finds a row in the Department table containing the key elements. // /// </summary> // /// <param name="departmentId">The DepartmentId element of the key.</param> // /// <returns>A DepartmentRow that contains the key elements, or null if there is no match.</returns> // public DepartmentRow Find(int departmentId) // { // // This will find the first row in the DataView that contains the key values. A 'null' indicates that there was no // // matching column. // int index = this.dataView.Find(new object[] { // departmentId}); // if ((index == -1)) // { // return null; // } // else // { // return ((DepartmentRow)(this.dataView[index].Row)); // } // } CodeMemberMethod findMethod = new CodeMemberMethod(); findMethod.Comments.Add(new CodeCommentStatement("<summary>", true)); findMethod.Comments.Add(new CodeCommentStatement(string.Format("Finds a row in the {0} table containing the key elements.", this.constraintSchema.Selector.Name), true)); findMethod.Comments.Add(new CodeCommentStatement("</summary>", true)); foreach (ColumnSchema columnSchema in constraintSchema.Fields) { string camelCaseColumnName = string.Format("{0}", columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1)); findMethod.Comments.Add(new CodeCommentStatement(string.Format("<param name=\"{0}\">The {1} element of the key.</param>", camelCaseColumnName, columnSchema.Name), true)); } findMethod.Comments.Add(new CodeCommentStatement(string.Format("<returns>A {0} that contains the key elements, or null if there is no match.</returns>", indexRowName), true)); findMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; findMethod.ReturnType = new CodeTypeReference(indexRowName); findMethod.Name = "Find"; List <CodeExpression> findByArguments = new List <CodeExpression>(); foreach (ColumnSchema columnSchema in constraintSchema.Fields) { string camelCaseColumnName = string.Format("{0}", columnSchema.Name[0].ToString().ToLower() + columnSchema.Name.Remove(0, 1)); findMethod.Parameters.Add(new CodeParameterDeclarationExpression(columnSchema.DataType, camelCaseColumnName)); findByArguments.Add(new CodeArgumentReferenceExpression(camelCaseColumnName)); } findMethod.Statements.Add(new CodeCommentStatement("This will find the first row in the DataView that contains the key values. A 'null' indicates that there was no")); findMethod.Statements.Add(new CodeCommentStatement("matching column.")); findMethod.Statements.Add(new CodeVariableDeclarationStatement(typeof(System.Int32), "index", new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), "Find", new CodeArrayCreateExpression(typeof(System.Object), findByArguments.ToArray())))); findMethod.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("index"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(-1)), new CodeStatement[] { new CodeMethodReturnStatement(new CodePrimitiveExpression(null)) }, new CodeStatement[] { new CodeMethodReturnStatement(new CodeCastExpression(indexRowName, new CodeFieldReferenceExpression(new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataView"), new CodeVariableReferenceExpression("index")), "Row"))) })); this.Members.Add(findMethod); // } }
static CodeNamespace CreateNamespace() { CodeNamespace mimsyNamespace = new CodeNamespace { Name = "Mimsy", Imports = { new CodeNamespaceImport("System"), new CodeNamespaceImport("System.Text"), new CodeNamespaceImport("System.Collections"), } }; CodeTypeDeclaration jubJubClass = new CodeTypeDeclaration("Jubjub") { TypeAttributes = TypeAttributes.Public, Members = { new CodeMemberField(typeof(int), "_wabeCount") { Attributes = MemberAttributes.Private }, new CodeMemberField(new CodeTypeReference("ArrayList"), "_updates") } }; CodeFieldReferenceExpression this_wabeCount = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_wabeCount"); var suppliedPropertyValue = new CodePropertySetValueReferenceExpression(); var zero = new CodePrimitiveExpression(0); var suppliedPropValIsLessThanZero = new CodeBinaryOperatorExpression(suppliedPropertyValue, CodeBinaryOperatorType.LessThan, zero); var testSuppliedPropValAndAssign = new CodeConditionStatement(suppliedPropValIsLessThanZero, new CodeStatement[] { new CodeAssignStatement(this_wabeCount, zero) }, new CodeStatement[] { new CodeAssignStatement(this_wabeCount, suppliedPropertyValue) } ); CodeFieldReferenceExpression refUpdatesFld = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_updates"); CodeMemberProperty wabeCountProp = new CodeMemberProperty() { Attributes = MemberAttributes.Public | MemberAttributes.Final, Type = new CodeTypeReference(typeof(int)), Name = "WabeCount", GetStatements = { new CodeMethodReturnStatement(this_wabeCount) }, SetStatements = { testSuppliedPropValAndAssign, new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( refUpdatesFld, "Add"), this_wabeCount ) } }; jubJubClass.Members.Add(wabeCountProp); mimsyNamespace.Types.Add(jubJubClass); CodeConstructor jubjubCtor = new CodeConstructor { Attributes = MemberAttributes.Public, Parameters = { new CodeParameterDeclarationExpression(typeof(int), "wabeCount") }, Statements = { new CodeAssignStatement( refUpdatesFld, new CodeObjectCreateExpression(new CodeTypeReference("ArrayList")) ), new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(),"WabeCount"), new CodeArgumentReferenceExpression("wabeCount") ) } }; jubJubClass.Members.Add(jubjubCtor); CodeMemberMethod methGetWabeCountHistory = new CodeMemberMethod { Attributes = MemberAttributes.Public | MemberAttributes.Final, Name = "GetWabeCountHistory", ReturnType = new CodeTypeReference(typeof(String)) }; jubJubClass.Members.Add(methGetWabeCountHistory); methGetWabeCountHistory.Statements.Add(new CodeVariableDeclarationStatement("StringBuilder", "result")); var refResultVar = new CodeVariableReferenceExpression("result"); methGetWabeCountHistory.Statements.Add( new CodeAssignStatement( refResultVar, new CodeObjectCreateExpression("StringBuilder"))); methGetWabeCountHistory.Statements.Add( new CodeVariableDeclarationStatement(typeof(int), "ndx")); var refNdxVar = new CodeVariableReferenceExpression("ndx"); methGetWabeCountHistory.Statements.Add( new CodeIterationStatement( new CodeAssignStatement(refNdxVar, new CodePrimitiveExpression(0)), new CodeBinaryOperatorExpression( refNdxVar, CodeBinaryOperatorType.LessThan, new CodePropertyReferenceExpression( refUpdatesFld, "Count")), new CodeAssignStatement( refNdxVar, new CodeBinaryOperatorExpression( refNdxVar, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))), new CodeConditionStatement( new CodeBinaryOperatorExpression( refNdxVar, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0)), new CodeStatement[] { new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( refResultVar, "AppendFormat"), new CodePrimitiveExpression("{0}"), new CodeArrayIndexerExpression( refUpdatesFld, refNdxVar))) }, new CodeStatement[] { new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( refResultVar, "AppendFormat"), new CodePrimitiveExpression(", {0}"), new CodeArrayIndexerExpression( refUpdatesFld, refNdxVar))) }))); methGetWabeCountHistory.Statements.Add( new CodeMethodReturnStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( refResultVar, "ToString")))); return(mimsyNamespace); }
/// <summary> /// Generate Cast method in CodeDom and add it in reference class /// </summary> /// <param name="si">The service interface this grain reference type is being generated for</param> /// <param name="isFactory">whether the class being generated is a factory class rather than a grainref implementation</param> /// <param name="referenceClass">The class being generated for this grain reference type</param> protected override void AddCastMethods(GrainInterfaceData si, bool isFactory, CodeTypeDeclaration referenceClass) { throw new NotImplementedException("AddCastMethods"); }
public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod) { if (!String.IsNullOrWhiteSpace(Inherits)) { derivedType.BaseTypes[0] = new CodeTypeReference(Inherits); } }
protected override string GetInvokerImpl(GrainInterfaceData si, CodeTypeDeclaration invokerClass, Type grainType, GrainInterfaceInfo grainInterfaceInfo, bool isClient) { throw new NotImplementedException("GetInvokerImpl"); }
private static CodeCompileUnit InternalCreate(Dictionary <String, ResourceData> resourceList, String baseName, String generatedCodeNamespace, String resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out String[] unmatchable) { if (baseName == null) { throw new ArgumentNullException(nameof(baseName)); } if (codeProvider == null) { throw new ArgumentNullException(nameof(codeProvider)); } // Keep a list of errors describing known strings that couldn't be // fixed up (like "4"), as well as listing all duplicate resources that // were fixed up to the same name (like "A B" and "A-B" both going to // "A_B"). var errors = new List <string>(); // Verify the resource names are valid property names, and they don't // conflict. This includes checking for language-specific keywords, // translating spaces to underscores, etc. SortedList <string, ResourceData> cleanedResourceList = VerifyResourceNames(resourceList, codeProvider, errors, out Dictionary <string, string> reverseFixupTable); // Verify the class name is legal. String className = baseName; // Attempt to fix up class name, and throw an exception if it fails. if (!codeProvider.IsValidIdentifier(className)) { String fixedClassName = VerifyResourceName(className, codeProvider); if (fixedClassName != null) { className = fixedClassName; } } if (!codeProvider.IsValidIdentifier(className)) { throw new ArgumentException(SR.GetString(SR.InvalidIdentifier, className)); } // If we have a namespace, verify the namespace is legal, // attempting to fix it up if needed. if (!String.IsNullOrEmpty(generatedCodeNamespace)) { if (!codeProvider.IsValidIdentifier(generatedCodeNamespace)) { String fixedNamespace = VerifyResourceName(generatedCodeNamespace, codeProvider, true); if (fixedNamespace != null) { generatedCodeNamespace = fixedNamespace; } } // Note we cannot really ensure that the generated code namespace // is a valid identifier, as namespaces can have '.' and '::', but // identifiers cannot. } var ccu = new CodeCompileUnit(); ccu.ReferencedAssemblies.Add("System.dll"); ccu.UserData.Add("AllowLateBound", false); ccu.UserData.Add("RequireVariableDeclaration", true); var ns = new CodeNamespace(generatedCodeNamespace); ns.Imports.Add(new CodeNamespaceImport("System")); ccu.Namespaces.Add(ns); // Generate class var srClass = new CodeTypeDeclaration(className); ns.Types.Add(srClass); AddGeneratedCodeAttributeforMember(srClass); TypeAttributes ta = internalClass ? TypeAttributes.NotPublic : TypeAttributes.Public; //ta |= TypeAttributes.Sealed; srClass.TypeAttributes = ta; srClass.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true)); srClass.Comments.Add(new CodeCommentStatement(SR.GetString(SR.ClassDocComment), true)); var comment = new CodeCommentStatement(SR.GetString(SR.ClassComments1), true); srClass.Comments.Add(comment); comment = new CodeCommentStatement(SR.GetString(SR.ClassComments3), true); srClass.Comments.Add(comment); srClass.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true)); var debuggerAttrib = new CodeTypeReference(typeof(System.Diagnostics.DebuggerNonUserCodeAttribute)) { Options = CodeTypeReferenceOptions.GlobalReference }; srClass.CustomAttributes.Add(new CodeAttributeDeclaration(debuggerAttrib)); var compilerGenedAttrib = new CodeTypeReference(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute)) { Options = CodeTypeReferenceOptions.GlobalReference }; srClass.CustomAttributes.Add(new CodeAttributeDeclaration(compilerGenedAttrib)); // Figure out some basic restrictions to the code generation bool useStatic = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers); EmitBasicClassMembers(srClass, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic); // Now for each resource, add a property foreach (KeyValuePair <string, ResourceData> entry in cleanedResourceList) { String propertyName = entry.Key; // The resourceName will be the original value, before fixups, if any. if (!reverseFixupTable.TryGetValue(propertyName, out string resourceName)) { resourceName = propertyName; } bool r = DefineResourceFetchingProperty(propertyName, resourceName, entry.Value, srClass, internalClass, useStatic); if (!r) { errors.Add(propertyName); } } unmatchable = errors.ToArray(); // Validate the generated class now CodeGenerator.ValidateIdentifiers(ccu); return(ccu); }
protected override void GenerateStateClassProperty(CodeTypeDeclaration stateClass, PropertyInfo propInfo, string name, string type) { throw new NotImplementedException("GenerateStateClassProperty"); }
// Emit protected abstract void Emit(CodeTypeDeclaration ctd);
public CXChildVisitResult Visit(CXCursor cursor, CXCursor parent, IntPtr data) { if (clang.Location_isFromMainFile(clang.getCursorLocation(cursor)) == 0) { return(CXChildVisitResult.CXChildVisit_Continue); } CXCursorKind curKind = clang.getCursorKind(cursor); if (curKind == CXCursorKind.CXCursor_StructDecl) { this.fieldPosition = 0; var nativeName = clang.getCursorSpelling(cursor).ToString(); // struct names can be empty, and so we visit its sibling to find the name if (string.IsNullOrEmpty(nativeName)) { var forwardDeclaringVisitor = new ForwardDeclarationVisitor(cursor); clang.visitChildren(clang.getCursorSemanticParent(cursor), forwardDeclaringVisitor.Visit, new CXClientData(IntPtr.Zero)); nativeName = clang.getCursorSpelling(forwardDeclaringVisitor.ForwardDeclarationCursor).ToString(); if (string.IsNullOrEmpty(nativeName)) { nativeName = "_"; } } var clrName = NameConversions.ToClrName(nativeName, NameConversion.Type); if (!this.generator.NameMapping.ContainsKey(nativeName)) { this.current = new CodeTypeDeclaration(clrName); this.current.IsStruct = true; this.current.Attributes = MemberAttributes.Public | MemberAttributes.Final; this.generator.AddType(nativeName, this.current); var layoutAttribute = new CodeAttributeDeclaration( new CodeTypeReference(typeof(StructLayoutAttribute)), new CodeAttributeArgument( new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(typeof(LayoutKind)), nameof(LayoutKind.Sequential)))); this.current.CustomAttributes.Add(layoutAttribute); clang.visitChildren(cursor, this.Visit, new CXClientData(IntPtr.Zero)); } return(CXChildVisitResult.CXChildVisit_Continue); } if (curKind == CXCursorKind.CXCursor_FieldDecl) { var fieldName = clang.getCursorSpelling(cursor).ToString(); if (string.IsNullOrEmpty(fieldName)) { fieldName = "field" + this.fieldPosition; // what if they have fields called field*? :) } this.fieldPosition++; foreach (var member in cursor.ToCodeTypeMember(fieldName, this.generator)) { this.current.Members.Add(member); } return(CXChildVisitResult.CXChildVisit_Continue); } return(CXChildVisitResult.CXChildVisit_Recurse); }
private static bool DefineResourceFetchingProperty(String propertyName, String resourceName, ResourceData data, CodeTypeDeclaration srClass, bool internalClass, bool useStatic) { var prop = new CodeMemberProperty { Name = propertyName, HasGet = true, HasSet = false }; Type type = data.Type; if (type == null) { return(false); } if (type == typeof(MemoryStream)) { type = typeof(UnmanagedMemoryStream); } // Ensure type is internalally visible. This is necessary to ensure // users can access classes via a base type. Imagine a class like // Image or Stream as a internalally available base class, then an // internal type like MyBitmap or __UnmanagedMemoryStream as an // internal implementation for that base class. For internalally // available strongly typed resource classes, we must return the // internal type. For simplicity, we'll do that for internal strongly // typed resource classes as well. Ideally we'd also like to check // for interfaces like IList, but I don't know how to do that without // special casing collection interfaces & ignoring serialization // interfaces or IDisposable. while (!type.IsPublic) { type = type.BaseType; } var valueType = new CodeTypeReference(type); prop.Type = valueType; if (internalClass) { prop.Attributes = MemberAttributes.Assembly; } else { prop.Attributes = MemberAttributes.Public; } if (useStatic) { prop.Attributes |= MemberAttributes.Static; } // For Strings, emit this: // return ResourceManager.GetString("name", _resCulture); // For Streams, emit this: // return ResourceManager.GetStream("name", _resCulture); // For Objects, emit this: // Object obj = ResourceManager.GetObject("name", _resCulture); // return (MyValueType) obj; var resMgr = new CodePropertyReferenceExpression(null, "ResourceManager"); var resCultureField = new CodeFieldReferenceExpression((useStatic) ? null : new CodeThisReferenceExpression(), CultureInfoFieldName); bool isString = type == typeof(String); bool isStream = type == typeof(UnmanagedMemoryStream) || type == typeof(MemoryStream); String getMethodName; String text; String valueAsString = TruncateAndFormatCommentStringForOutput(data.ValueAsString); String typeName = String.Empty; if (!isString) // Stream or Object { typeName = TruncateAndFormatCommentStringForOutput(type.ToString()); } if (isString) { getMethodName = "GetString"; } else if (isStream) { getMethodName = "GetStream"; } else { getMethodName = "GetObject"; } if (isString) { text = SR.GetString(SR.StringPropertyComment, valueAsString); } else { // Stream or Object if (valueAsString == null || String.Equals(typeName, valueAsString)) // If the type did not override ToString, ToString just returns the type name. { text = SR.GetString(SR.NonStringPropertyComment, typeName); } else { text = SR.GetString(SR.NonStringPropertyDetailedComment, typeName, valueAsString); } } prop.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true)); prop.Comments.Add(new CodeCommentStatement(text, true)); prop.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true)); var getValue = new CodeMethodInvokeExpression(resMgr, getMethodName, new CodePrimitiveExpression(resourceName), resCultureField); CodeMethodReturnStatement ret; if (isString || isStream) { ret = new CodeMethodReturnStatement(getValue); } else { var returnObj = new CodeVariableDeclarationStatement(typeof(Object), "obj", getValue); prop.GetStatements.Add(returnObj); ret = new CodeMethodReturnStatement(new CodeCastExpression(valueType, new CodeVariableReferenceExpression("obj"))); } prop.GetStatements.Add(ret); srClass.Members.Add(prop); return(true); }
protected abstract void AddProperty(KeyValuePair <string, OpenApiSchema> p, CodeTypeDeclaration typeDeclaration, OpenApiSchema schema, string currentTypeName, string ns);
public CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod method, bool generateField) { FrameworkElement element = source as FrameworkElement; string typeName = element.GetType().Name; if (string.IsNullOrEmpty(element.Name)) { element.Name = "e_" + nameUniqueId; nameUniqueId++; } if (generateField) { CodeMemberField field = new CodeMemberField(typeName, element.Name); classType.Members.Add(field); } CodeComment comment = new CodeComment(element.Name + " element"); method.Statements.Add(new CodeCommentStatement(comment)); CodeExpression fieldReference = null; if (!generateField) { fieldReference = new CodeVariableReferenceExpression(element.Name); CodeTypeReference variableType = new CodeTypeReference(typeName); CodeVariableDeclarationStatement declaration = new CodeVariableDeclarationStatement(variableType, element.Name); declaration.InitExpression = new CodeObjectCreateExpression(typeName); method.Statements.Add(declaration); } else { fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), element.Name); method.Statements.Add(new CodeAssignStatement(fieldReference, new CodeObjectCreateExpression(typeName))); } //var refExpr2 = new CodeObjectCreateExpression(ValueType, new CodeExpression[] { }); //CodeVariableDeclarationStatement variable = new CodeVariableDeclarationStatement( // ValueType, baseName, refExpr2 // ); //method.Statements.Add(variable); //var refExpr = new CodeVariableReferenceExpression(baseName); throw new NotImplementedException("TODO"); return(null); /*foreach (var pi in ValueType.GetProperties()) * { * var getM = pi.GetGetMethod(); * * if (getM.GetParameters().Length == 0 && pi.GetSetMethod() != null) * { * object o = getM.Invoke(value, new object[] { }); * CodeComHelper.GenerateField(method, fieldReference, pi.Name, o); * } * } * * * * return refExpr;*/ /* * * var properties = XamlType.GetProperties(); * * foreach (var pi in properties) * { * if (pi.PropertyType == typeof(String)) * { * CodeComHelper.GenerateField(method, fieldReference, pi.Name, ""); * } * else if (pi.PropertyType == typeof(decimal)) * { * CodeComHelper.GenerateField(method, fieldReference, pi.Name, (decimal)0); * } * }*/ return(fieldReference); }
public void BinaryOperators() { CodeNamespace ns = new CodeNamespace("Namespace1"); ns.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration class1 = new CodeTypeDeclaration(); class1.Name = "Class1"; class1.BaseTypes.Add(new CodeTypeReference(typeof(object))); ns.Types.Add(class1); CodeMemberMethod retMethod = new CodeMemberMethod(); retMethod.Name = "ReturnMethod"; retMethod.Attributes = (retMethod.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; retMethod.ReturnType = new CodeTypeReference(typeof(int)); retMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "intInput")); CodeBinaryOperatorExpression cboExpression = new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression( new CodePrimitiveExpression(18), CodeBinaryOperatorType.Divide, new CodeBinaryOperatorExpression( new CodePrimitiveExpression(6), CodeBinaryOperatorType.Subtract, new CodePrimitiveExpression(4))), CodeBinaryOperatorType.Multiply, new CodeArgumentReferenceExpression("intInput")); CodeVariableDeclarationStatement variableDeclaration = null; variableDeclaration = new CodeVariableDeclarationStatement(typeof(int), "x1", cboExpression); retMethod.Statements.Add(variableDeclaration); retMethod.Statements.Add( new CodeVariableDeclarationStatement( typeof(int), "x2", new CodeBinaryOperatorExpression( new CodePrimitiveExpression(19), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(8)))); retMethod.Statements.Add( new CodeVariableDeclarationStatement( typeof(int), "x3", new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression( new CodePrimitiveExpression(15), CodeBinaryOperatorType.BitwiseAnd, new CodePrimitiveExpression(35)), CodeBinaryOperatorType.BitwiseOr, new CodePrimitiveExpression(129)))); retMethod.Statements.Add( new CodeVariableDeclarationStatement( typeof(int), "x4", new CodePrimitiveExpression(0))); retMethod.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("x2"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(3)), CodeBinaryOperatorType.BooleanOr, new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("x3"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(129))), new CodeStatement[] { CreateVariableIncrementExpression("x4", 1) }, new CodeStatement[] { CreateVariableIncrementExpression("x4", 2) })); retMethod.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("x2"), CodeBinaryOperatorType.GreaterThan, new CodePrimitiveExpression(-1)), CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("x3"), CodeBinaryOperatorType.GreaterThanOrEqual, new CodePrimitiveExpression(5000))), new CodeStatement[] { CreateVariableIncrementExpression("x4", 4) }, new CodeStatement[] { CreateVariableIncrementExpression("x4", 8) })); retMethod.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("x2"), CodeBinaryOperatorType.LessThanOrEqual, new CodePrimitiveExpression(3)), CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("x3"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(1))), new CodeStatement[] { CreateVariableIncrementExpression("x4", 16) }, new CodeStatement[] { CreateVariableIncrementExpression("x4", 32) })); retMethod.Statements.Add( new CodeMethodReturnStatement( new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("x1"), CodeBinaryOperatorType.Add, new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("x2"), CodeBinaryOperatorType.Add, new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("x3"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("x4")))))); class1.Members.Add(retMethod); retMethod = new CodeMemberMethod(); retMethod.Name = "SecondReturnMethod"; retMethod.Attributes = (retMethod.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; retMethod.ReturnType = new CodeTypeReference(typeof(int)); retMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "intInput")); retMethod.Statements.Add(new CodeCommentStatement("To test CodeBinaryOperatorType.IdentiEquality operator")); retMethod.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression(new CodeCastExpression("Object", new CodeVariableReferenceExpression("intInput")), CodeBinaryOperatorType.IdentityEquality, new CodeCastExpression("Object", new CodePrimitiveExpression(5))), new CodeStatement[] { new CodeMethodReturnStatement(new CodePrimitiveExpression(5)) }, new CodeStatement[] { new CodeMethodReturnStatement(new CodePrimitiveExpression(4))})); class1.Members.Add(retMethod); AssertEqual(ns, @"Imports System Namespace Namespace1 Public Class Class1 Inherits Object Public Function ReturnMethod(ByVal intInput As Integer) As Integer Dim x1 As Integer = ((18 _ / (6 - 4)) _ * intInput) Dim x2 As Integer = (19 Mod 8) Dim x3 As Integer = ((15 And 35) _ Or 129) Dim x4 As Integer = 0 If ((x2 = 3) _ OrElse (x3 < 129)) Then x4 = (x4 + 1) Else x4 = (x4 + 2) End If If ((x2 > -1) _ AndAlso (x3 >= 5000)) Then x4 = (x4 + 4) Else x4 = (x4 + 8) End If If ((x2 <= 3) _ AndAlso (x3 <> 1)) Then x4 = (x4 + 16) Else x4 = (x4 + 32) End If Return (x1 _ + (x2 _ + (x3 + x4))) End Function Public Function SecondReturnMethod(ByVal intInput As Integer) As Integer 'To test CodeBinaryOperatorType.IdentiEquality operator If (CType(intInput,[Object]) Is CType(5,[Object])) Then Return 5 Else Return 4 End If End Function End Class End Namespace"); }
/// <summary> /// /// </summary> /// <param name="propertySchema"></param> /// <param name="typeDeclarationName"></param> /// <param name="propertyName"></param> /// <param name="currentTypeName"></param> /// <param name="ns"></param> /// <returns>CodeTypeReference and CasualTypeName. Empty if no casualTypeName.</returns> public Tuple <CodeTypeReference, string> CreateArrayCodeTypeReference(OpenApiSchema propertySchema, string typeDeclarationName, string propertyName, string currentTypeName, string ns) { OpenApiSchema arrayItemsSchema = propertySchema.Items; if (arrayItemsSchema == null) //ritekit.com has parameter as array but without items type. Presumbly it may be string. { Type clrType = TypeRefHelper.PrimitiveSwaggerTypeToClrType("string", null); CodeTypeReference arrayCodeTypeReference = TypeRefHelper.CreateArrayTypeReference(clrType, 1); return(Tuple.Create(arrayCodeTypeReference, String.Empty)); } else if (arrayItemsSchema.Reference != null) //array of custom type { string arrayTypeSchemaRefId = arrayItemsSchema.Reference.Id; var arrayTypeNs = NameFunc.GetNamespaceOfClassName(arrayTypeSchemaRefId); var arrayTypeName = NameFunc.RefineTypeName(arrayTypeSchemaRefId, arrayTypeNs); var arrayTypeWithNs = NameFunc.CombineNamespaceWithClassName(arrayTypeNs, arrayTypeName); var existingType = FindTypeDeclarationInNamespaces(arrayTypeName, arrayTypeNs); if (existingType == null) // Referencing to a type not yet added to namespace { var existingSchema = FindSchema(arrayTypeSchemaRefId); if (existingSchema != null && !RegisteredSchemaRefIdExists(arrayTypeSchemaRefId)) { AddTypeToCodeDom(new KeyValuePair <string, OpenApiSchema>(arrayTypeSchemaRefId, existingSchema)); } } if (TypeAliasDic.TryGet(arrayTypeSchemaRefId, out string arrayTypeNameAlias)) { if (!TypeRefHelper.IsSwaggerPrimitive(arrayTypeNameAlias)) { return(Tuple.Create(ComponentsHelper.CreateArrayOfCustomTypeReference(arrayTypeNameAlias, 1), String.Empty)); } else { var clrType = TypeRefHelper.PrimitiveSwaggerTypeToClrType(arrayTypeNameAlias, null); return(Tuple.Create(ComponentsHelper.CreateArrayOfCustomTypeReference(clrType.FullName, 1), String.Empty)); } } else { return(Tuple.Create(ComponentsHelper.CreateArrayOfCustomTypeReference(arrayTypeWithNs, 1), String.Empty)); } } else { string arrayType = arrayItemsSchema.Type; if (arrayItemsSchema.Enum != null && arrayItemsSchema.Enum.Count > 0) { string[] enumMemberNames; try { enumMemberNames = (String.IsNullOrEmpty(arrayItemsSchema.Type) || arrayItemsSchema.Type == "string") ? arrayItemsSchema.Enum.Cast <OpenApiString>().Select(m => m.Value).ToArray() : arrayItemsSchema.Enum.Cast <OpenApiInteger>().Select(m => "_" + m.Value.ToString()).ToArray(); } catch (InvalidCastException ex) { throw new CodeGenException($"When dealing with {propertyName} of {arrayType}, error: {ex.Message}"); } CodeTypeDeclaration existingDeclaration = FindEnumDeclaration(enumMemberNames); if (existingDeclaration != null) { string existingTypeName = existingDeclaration.Name; CodeTypeReference enumArrayReference = TypeRefHelper.CreateArrayOfCustomTypeReference(existingTypeName, 1); return(Tuple.Create(enumArrayReference, String.Empty)); } //warning about bad yaml design. Trace.TraceWarning($"Property {NameFunc.RefineParameterName(propertyName)} has referenced some enum members {String.Join(", ", enumMemberNames)} which are not of any declared components."); } else if (arrayItemsSchema.Properties != null && arrayItemsSchema.Properties.Count > 0) // for casual type { string casualTypeName = typeDeclarationName + NameFunc.RefinePropertyName(propertyName); CodeTypeDeclaration casualTypeDeclaration = AddTypeToClassNamespace(casualTypeName, ns); //stay with the namespace of the host class AddProperties(casualTypeDeclaration, arrayItemsSchema, currentTypeName, ns); return(Tuple.Create(ComponentsHelper.CreateArrayOfCustomTypeReference(casualTypeName, 1), propertyName)); //casualTypeName } Type clrType = TypeRefHelper.PrimitiveSwaggerTypeToClrType(arrayType, null); return(Tuple.Create(TypeRefHelper.CreateArrayTypeReference(clrType, 1), String.Empty)); } }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace nspace = new CodeNamespace("NSPC"); nspace.Imports.Add(new CodeNamespaceImport("System")); cu.Namespaces.Add(nspace); CodeTypeDeclaration cd = new CodeTypeDeclaration("TestFields"); cd.IsClass = true; nspace.Types.Add(cd); // GENERATES (C#): // public static int UseStaticPublicField(int i) { // ClassWithFields.StaticPublicField = i; // return ClassWithFields.StaticPublicField; // CodeMemberMethod cmm; if (Supports(provider, GeneratorSupport.PublicStaticMembers)) { AddScenario("CheckUseStaticPublicField"); cmm = new CodeMemberMethod(); cmm.Name = "UseStaticPublicField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression( new CodeTypeReferenceExpression("ClassWithFields"), "StaticPublicField"), new CodeArgumentReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ClassWithFields"), "StaticPublicField"))); cd.Members.Add(cmm); } // GENERATES (C#): // public static int UseNonStaticPublicField(int i) { // ClassWithFields variable = new ClassWithFields(); // variable.NonStaticPublicField = i; // return variable.NonStaticPublicField; // } AddScenario("CheckUseNonStaticPublicField"); cmm = new CodeMemberMethod(); cmm.Name = "UseNonStaticPublicField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWithFields", "variable", new CodeObjectCreateExpression("ClassWithFields"))); cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("variable"), "NonStaticPublicField"), new CodeArgumentReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("variable"), "NonStaticPublicField"))); cd.Members.Add(cmm); // GENERATES (C#): // public static int UseNonStaticInternalField(int i) { // ClassWithFields variable = new ClassWithFields(); // variable.NonStaticInternalField = i; // return variable.NonStaticInternalField; // } if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) { cmm = new CodeMemberMethod(); AddScenario("CheckUseNonStaticInternalField"); cmm.Name = "UseNonStaticInternalField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWithFields", "variable", new CodeObjectCreateExpression("ClassWithFields"))); cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("variable"), "NonStaticInternalField"), new CodeArgumentReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("variable"), "NonStaticInternalField"))); cd.Members.Add(cmm); } // GENERATES (C#): // public static int UseInternalField(int i) { // ClassWithFields.InternalField = i; // return ClassWithFields.InternalField; // } if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) { AddScenario("CheckUseInternalField"); cmm = new CodeMemberMethod(); cmm.Name = "UseInternalField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ClassWithFields"), "InternalField"), new CodeArgumentReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ClassWithFields"), "InternalField"))); cd.Members.Add(cmm); } // GENERATES (C#): // public static int UseConstantField(int i) { // return ClassWithFields.ConstantField; // } AddScenario("CheckUseConstantField"); cmm = new CodeMemberMethod(); cmm.Name = "UseConstantField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ClassWithFields"), "ConstantField"))); cd.Members.Add(cmm); // code a new class to test that the protected field can be accessed by classes that inherit it // GENERATES (C#): // public class TestProtectedField : ClassWithFields { // public static int UseProtectedField(int i) { // ProtectedField = i; // return ProtectedField; // } // } cd = new CodeTypeDeclaration("TestProtectedField"); cd.BaseTypes.Add(new CodeTypeReference("ClassWithFields")); cd.IsClass = true; nspace.Types.Add(cd); cmm = new CodeMemberMethod(); AddScenario("CheckUseProtectedField"); cmm.Name = "UseProtectedField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); CodeFieldReferenceExpression reference = new CodeFieldReferenceExpression(); reference.FieldName = "ProtectedField"; reference.TargetObject = new CodeTypeReferenceExpression("ClassWithFields"); cmm.Statements.Add(new CodeAssignStatement(reference, new CodeArgumentReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(reference)); cd.Members.Add(cmm); // declare class with fields // GENERATES (C#): // public class ClassWithFields { // public static int StaticPublicField = 5; // /*FamANDAssem*/ internal static int InternalField = 0; // public const int ConstantField = 0; // protected static int ProtectedField = 0; // private static int PrivateField = 5; // public int NonStaticPublicField = 5; // /*FamANDAssem*/ internal int NonStaticInternalField = 0; // public static int UsePrivateField(int i) { // PrivateField = i; // return PrivateField; // } // } cd = new CodeTypeDeclaration ("ClassWithFields"); cd.IsClass = true; nspace.Types.Add (cd); CodeMemberField field; if (Supports (provider, GeneratorSupport.PublicStaticMembers)) { field = new CodeMemberField (); field.Name = "StaticPublicField"; field.Attributes = MemberAttributes.Public | MemberAttributes.Static; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (5); cd.Members.Add (field); } if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) { field = new CodeMemberField (); field.Name = "InternalField"; field.Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Static; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (0); cd.Members.Add (field); } field = new CodeMemberField (); field.Name = "ConstantField"; field.Attributes = MemberAttributes.Public | MemberAttributes.Const; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (0); cd.Members.Add (field); field = new CodeMemberField (); field.Name = "ProtectedField"; field.Attributes = MemberAttributes.Family | MemberAttributes.Static; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (0); cd.Members.Add (field); field = new CodeMemberField (); field.Name = "PrivateField"; field.Attributes = MemberAttributes.Private | MemberAttributes.Static; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (5); cd.Members.Add (field); field = new CodeMemberField (); field.Name = "NonStaticPublicField"; field.Attributes = MemberAttributes.Public | MemberAttributes.Final; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (5); cd.Members.Add (field); if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) { field = new CodeMemberField (); field.Name = "NonStaticInternalField"; field.Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Final; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (0); cd.Members.Add (field); } // create a method to test access to private field AddScenario ("CheckUsePrivateField"); cmm = new CodeMemberMethod (); cmm.Name = "UsePrivateField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); CodeFieldReferenceExpression fieldref = new CodeFieldReferenceExpression (); fieldref.TargetObject = new CodeTypeReferenceExpression("ClassWithFields"); fieldref.FieldName = "PrivateField"; cmm.Statements.Add (new CodeAssignStatement (fieldref, new CodeArgumentReferenceExpression ("i"))); cmm.Statements.Add (new CodeMethodReturnStatement (fieldref)); cd.Members.Add (cmm); }
/// <summary> /// Mostly used in ParametersRefBuilder. /// </summary> /// <param name="propertySchema"></param> /// <param name="actionName"></param> /// <param name="propertyName"></param> /// <returns></returns> /// <remarks>This shares similar navigation of schema like those in AddProperty().</remarks> public CodeTypeReference PropertySchemaToCodeTypeReference(OpenApiSchema propertySchema, string actionName, string propertyName) { string schemaType = propertySchema.Type; bool isPrimitiveType = TypeRefHelper.IsPrimitiveTypeOfOA(schemaType); if (String.IsNullOrEmpty(schemaType)) { if (propertySchema.Reference != null) { string propertyTypeNs = NameFunc.GetNamespaceOfClassName(propertySchema.Reference.Id); string propertyTypeName = NameFunc.RefineTypeName(propertySchema.Reference.Id, propertyTypeNs); string propertyTypeWithNs = NameFunc.CombineNamespaceWithClassName(propertyTypeNs, propertyTypeName); return(ComponentsHelper.TranslateTypeNameToClientTypeReference(propertyTypeWithNs)); } else { if (propertySchema.Enum.Count > 0) //for casual enum { var r = GenerateCasualEnum(propertySchema, actionName, propertyName, null); return(r.Item1); } else { Tuple <CodeTypeReference, bool> r = CreateCodeTypeReferenceSchemaOf(propertySchema, actionName, propertyName); return(r.Item1); } } } else { if (schemaType == "array") // for array { var r = CreateArrayCodeTypeReference(propertySchema, actionName, propertyName, null, null); return(r.Item1); } else if (propertySchema.Enum.Count == 0 && propertySchema.Reference != null && !isPrimitiveType) // for complex type { CodeTypeReference complexCodeTypeReference = CreateComplexCodeTypeReference(propertySchema); return(complexCodeTypeReference); } else if (propertySchema.Reference == null && propertySchema.Properties != null && propertySchema.Properties.Count > 0) // for casual type { string casualTypeName = actionName + NameFunc.RefinePropertyName(propertyName); var found = FindTypeDeclarationInNamespaces(casualTypeName, null); //It could happenen when generating sync and async functions in C# if (found == null) { CodeTypeDeclaration casualTypeDeclaration = AddTypeToClassNamespace(casualTypeName, null); //stay with the namespace of the host class AddProperties(casualTypeDeclaration, propertySchema, casualTypeName, null); } return(TypeRefHelper.TranslateToClientTypeReference(casualTypeName)); } else if (schemaType == "object" && propertySchema.AdditionalProperties != null) // for dictionary { CodeTypeReference dicKeyTypeRef = TypeRefHelper.TranslateToClientTypeReference(typeof(string)); CodeTypeReference dicValueTypeRef = PropertySchemaToCodeTypeReference(propertySchema.AdditionalProperties, actionName, propertyName); return(new CodeTypeReference(typeof(Dictionary <,>).FullName, dicKeyTypeRef, dicValueTypeRef)); //for client codes, Dictionary is better than IDictionary, no worry of different implementation of IDictionary } else if (propertySchema.Enum.Count == 0) // for primitive type { Type t = TypeRefHelper.PrimitiveSwaggerTypeToClrType(schemaType, propertySchema.Format); return(new CodeTypeReference(t)); } else if (propertySchema.Enum.Count > 0 && schemaType == "string") // for enum { string[] enumMemberNames; try { enumMemberNames = (String.IsNullOrEmpty(propertySchema.Type) || propertySchema.Type == "string") ? propertySchema.Enum.Cast <OpenApiString>().Select(m => m.Value).ToArray() : propertySchema.Enum.Cast <OpenApiInteger>().Select(m => "_" + m.Value.ToString()).ToArray(); } catch (InvalidCastException ex) { throw new CodeGenException($"When dealing with {propertyName} of {schemaType}, error: {ex.Message}"); } CodeTypeDeclaration existingDeclaration = FindEnumDeclaration(enumMemberNames); if (existingDeclaration != null) { string existingTypeName = existingDeclaration.Name; CodeTypeReference enumReference = TypeRefHelper.TranslateToClientTypeReference(existingTypeName); return(enumReference); } else { var r = GenerateCasualEnum(propertySchema, actionName, propertyName, null); return(r.Item1); } } else if (schemaType != "string" && TypeAliasDic.TryGet(schemaType, out string aliasTypeName)) //check TypeAliasDic { return(new CodeTypeReference(aliasTypeName)); } else if (propertySchema.Reference != null) { CodeTypeReference complexCodeTypeReference = CreateComplexCodeTypeReference(propertySchema); return(complexCodeTypeReference); } else // for casual enum { var r = GenerateCasualEnum(propertySchema, actionName, propertyName, null); return(r.Item1); } } }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { #if WHIDBEY if (!(provider is JScriptCodeProvider)) { // GENERATES (C#): // // #region Compile Unit Region // // namespace Namespace1 { // // // #region Outer Type Region // // Outer Type Comment // public class Class1 { // // // Field 1 Comment // private string field1; // // public void Method1() { // this.Event1(this, System.EventArgs.Empty); // } // // #region Constructor Region // public Class1() { // #region Statements Region // this.field1 = "value1"; // this.field2 = "value2"; // #endregion // } // #endregion // // public string Property1 { // get { // return this.field1; // } // } // // public static void Main() { // } // // public event System.EventHandler Event1; // // public class NestedClass1 { // } // // public delegate void nestedDelegate1(object sender, System.EventArgs e); // // // // #region Field Region // private string field2; // #endregion // // #region Method Region // // Method 2 Comment // // #line 500 "MethodLinePragma.txt" // public void Method2() { // this.Event2(this, System.EventArgs.Empty); // } // // #line default // #line hidden // #endregion // // public Class1(string value1, string value2) { // } // // #region Property Region // public string Property2 { // get { // return this.field2; // } // } // #endregion // // #region Type Constructor Region // static Class1() { // } // #endregion // // #region Event Region // public event System.EventHandler Event2; // #endregion // // #region Nested Type Region // // Nested Type Comment // // #line 400 "NestedTypeLinePragma.txt" // public class NestedClass2 { // } // // #line default // #line hidden // #endregion // // #region Delegate Region // public delegate void nestedDelegate2(object sender, System.EventArgs e); // #endregion // // #region Snippet Region // // #endregion // } // #endregion // } // #endregion CodeNamespace ns = new CodeNamespace ("Namespace1"); cu.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Compile Unit Region")); cu.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); cu.Namespaces.Add (ns); CodeTypeDeclaration cd = new CodeTypeDeclaration ("Class1"); ns.Types.Add (cd); cd.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Outer Type Region")); cd.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); cd.Comments.Add (new CodeCommentStatement ("Outer Type Comment")); CodeMemberField field1 = new CodeMemberField (typeof (String), "field1"); CodeMemberField field2 = new CodeMemberField (typeof (String), "field2"); field1.Comments.Add (new CodeCommentStatement ("Field 1 Comment")); field2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Field Region")); field2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeMemberEvent evt1 = new CodeMemberEvent (); evt1.Name = "Event1"; evt1.Type = new CodeTypeReference (typeof (System.EventHandler)); evt1.Attributes = (evt1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; CodeMemberEvent evt2 = new CodeMemberEvent (); evt2.Name = "Event2"; evt2.Type = new CodeTypeReference (typeof (System.EventHandler)); evt2.Attributes = (evt2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; evt2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Event Region")); evt2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeMemberMethod method1 = new CodeMemberMethod (); method1.Name = "Method1"; method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; if (provider.Supports (GeneratorSupport.DeclareEvents)) { method1.Statements.Add ( new CodeDelegateInvokeExpression ( new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "Event1"), new CodeExpression[] { new CodeThisReferenceExpression(), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty") })); } CodeMemberMethod method2 = new CodeMemberMethod (); method2.Name = "Method2"; method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; if (provider.Supports (GeneratorSupport.DeclareEvents)) { method2.Statements.Add ( new CodeDelegateInvokeExpression ( new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "Event2"), new CodeExpression[] { new CodeThisReferenceExpression(), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty") })); } method2.LinePragma = new CodeLinePragma ("MethodLinePragma.txt", 500); method2.Comments.Add (new CodeCommentStatement ("Method 2 Comment")); method2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Method Region")); method2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeMemberProperty property1 = new CodeMemberProperty (); property1.Name = "Property1"; property1.Type = new CodeTypeReference (typeof (string)); property1.Attributes = (property1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; property1.GetStatements.Add ( new CodeMethodReturnStatement ( new CodeFieldReferenceExpression ( new CodeThisReferenceExpression (), "field1"))); CodeMemberProperty property2 = new CodeMemberProperty (); property2.Name = "Property2"; property2.Type = new CodeTypeReference (typeof (string)); property2.Attributes = (property2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; property2.GetStatements.Add ( new CodeMethodReturnStatement ( new CodeFieldReferenceExpression ( new CodeThisReferenceExpression (), "field2"))); property2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Property Region")); property2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeConstructor constructor1 = new CodeConstructor (); constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; CodeStatement conState1 = new CodeAssignStatement ( new CodeFieldReferenceExpression ( new CodeThisReferenceExpression (), "field1"), new CodePrimitiveExpression ("value1")); conState1.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Statements Region")); constructor1.Statements.Add (conState1); CodeStatement conState2 = new CodeAssignStatement ( new CodeFieldReferenceExpression ( new CodeThisReferenceExpression (), "field2"), new CodePrimitiveExpression ("value2")); conState2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); constructor1.Statements.Add (conState2); constructor1.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Constructor Region")); constructor1.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeConstructor constructor2 = new CodeConstructor (); constructor2.Attributes = (constructor2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; constructor2.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "value1")); constructor2.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "value2")); CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor (); typeConstructor2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Type Constructor Region")); typeConstructor2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeEntryPointMethod methodMain = new CodeEntryPointMethod (); CodeTypeDeclaration nestedClass1 = new CodeTypeDeclaration ("NestedClass1"); CodeTypeDeclaration nestedClass2 = new CodeTypeDeclaration ("NestedClass2"); nestedClass2.LinePragma = new CodeLinePragma ("NestedTypeLinePragma.txt", 400); nestedClass2.Comments.Add (new CodeCommentStatement ("Nested Type Comment")); nestedClass2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Nested Type Region")); nestedClass2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeTypeDelegate delegate1 = new CodeTypeDelegate (); delegate1.Name = "nestedDelegate1"; delegate1.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.Object"), "sender")); delegate1.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.EventArgs"), "e")); CodeTypeDelegate delegate2 = new CodeTypeDelegate (); delegate2.Name = "nestedDelegate2"; delegate2.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.Object"), "sender")); delegate2.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.EventArgs"), "e")); delegate2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Delegate Region")); delegate2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeSnippetTypeMember snippet1 = new CodeSnippetTypeMember (); CodeSnippetTypeMember snippet2 = new CodeSnippetTypeMember (); CodeRegionDirective regionStart = new CodeRegionDirective (CodeRegionMode.End, ""); regionStart.RegionText = "Snippet Region"; regionStart.RegionMode = CodeRegionMode.Start; snippet2.StartDirectives.Add (regionStart); snippet2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); cd.Members.Add (field1); cd.Members.Add (method1); cd.Members.Add (constructor1); cd.Members.Add (property1); cd.Members.Add (methodMain); if (Supports (provider, GeneratorSupport.DeclareEvents)) { cd.Members.Add (evt1); } if (Supports (provider, GeneratorSupport.NestedTypes)) { cd.Members.Add (nestedClass1); if (Supports (provider, GeneratorSupport.DeclareDelegates)) { cd.Members.Add (delegate1); } } cd.Members.Add (snippet1); cd.Members.Add (field2); cd.Members.Add (method2); cd.Members.Add (constructor2); cd.Members.Add (property2); if (Supports (provider, GeneratorSupport.StaticConstructors)) { cd.Members.Add (typeConstructor2); } if (Supports (provider, GeneratorSupport.DeclareEvents)) { cd.Members.Add (evt2); } if (Supports (provider, GeneratorSupport.NestedTypes)) { cd.Members.Add (nestedClass2); if (Supports (provider, GeneratorSupport.DeclareDelegates)) { cd.Members.Add (delegate2); } } cd.Members.Add (snippet2); } #endif }
private Assembly BuildAssemblyFromWsdl(string strWsdl) { // Use an XmlTextReader to get the Web Service description StringReader wsdlStringReader = new StringReader(strWsdl); XmlTextReader tr = new XmlTextReader(wsdlStringReader); ServiceDescription sd = ServiceDescription.Read(tr); tr.Close(); // WSDL service description importer CodeNamespace cns = new CodeNamespace("OW.Tools.WebServices.DynamicProxy"); sdi = new ServiceDescriptionImporter(); //sdi.AddServiceDescription(sd, null, null); // check for optional imports in the root WSDL CheckForImports(wsdl); sdi.ProtocolName = protocolName; sdi.Import(cns, null); // change the base class CodeTypeDeclaration ctDecl = cns.Types[0]; cns.Types.Remove(ctDecl); ctDecl.BaseTypes[0] = new CodeTypeReference("OW.Tools.WebServices.SoapHttpClientProtocolEx"); cns.Types.Add(ctDecl); // source code generation CSharpCodeProvider cscp = new CSharpCodeProvider(); ICodeGenerator icg = cscp.CreateGenerator(); StringBuilder srcStringBuilder = new StringBuilder(); StringWriter sw = new StringWriter(srcStringBuilder); icg.GenerateCodeFromNamespace(cns, sw, null); proxySource = srcStringBuilder.ToString(); sw.Close(); // assembly compilation CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Xml.dll"); cp.ReferencedAssemblies.Add("System.Web.Services.dll"); cp.ReferencedAssemblies.Add("System.Data.dll"); cp.ReferencedAssemblies.Add(Assembly. GetExecutingAssembly().Location); cp.GenerateExecutable = false; cp.GenerateInMemory = false; cp.IncludeDebugInformation = false; ICodeCompiler icc = cscp.CreateCompiler(); CompilerResults cr = icc.CompileAssemblyFromSource(cp, proxySource); if (cr.Errors.Count > 0) { throw new Exception(string.Format(@"Build failed: {0} errors", cr.Errors.Count)); } ass = cr.CompiledAssembly; //rename temporary assembly in order to cache it for later use RenameTempAssembly(cr.PathToAssembly); // create proxy instance proxyInstance = CreateInstance(typeName); return(ass); }