private static CodeTypeMember CreateStaticConstructor() { var constructor = new CodeTypeConstructor(); _sceneRegistration = constructor.Statements; return(constructor); }
private bool HandleDynamic(CodeTypeConstructor obj, Context ctx) { return(HandleIfTrue(() => { HandleTypeConstructor(obj, ctx); }, obj, ctx, CanHandleTypeConstructor, MemberTypes.Constructor)); }
public CodeCompileUnit InitialiseCompileUnit(GLSLAssembly assembly) { var contentUnit = new CodeCompileUnit(); SetVersionNumber(contentUnit, assembly.Version); string nameSpace = assembly.Namespace; if (string.IsNullOrWhiteSpace(nameSpace)) { nameSpace = System.IO.Path.GetFileNameWithoutExtension(assembly.OutputAssembly); } var contentNs = new CodeNamespace(nameSpace); contentUnit.Namespaces.Add(contentNs); var uniforms = CreateClass(contentNs, "Uniforms"); var defaultConstructor = new CodeTypeConstructor(); defaultConstructor.Attributes = MemberAttributes.Public | MemberAttributes.Final; uniforms.Members.Add(defaultConstructor); defaultConstructor.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "testInt", new CodePrimitiveExpression(0))); foreach (var block in mExtractor.Blocks) { AddStruct(contentNs, uniforms, block); } return(contentUnit); }
private static void PrintTypeConstructor(TextWriter output, CodeTypeConstructor typeConstructor) { output.WriteLine("typeconstructor"); foreach (CodeAttributeDeclaration cad in typeConstructor.CustomAttributes) { output.Write(" customattribute "); PrintCustomAttributeDeclaration(output, cad); output.WriteLine(); } output.WriteLine("begin"); for (int i = 0; i < typeConstructor.Statements.Count; ++i) { output.Write(" "); PrintStatement(output, typeConstructor.Statements[i]); if (i + 1 < typeConstructor.Statements.Count) { output.WriteLine(';'); } else { output.WriteLine(); } } output.WriteLine("end"); }
private static void DumpLexicalAnalyzer_GetKeywordList( RegulationList grammar, string grammarId, CodeTypeDeclaration lexiType) { { // private static readonly List<Keyword> keywords = new List<Keyword>(); var field = new CodeMemberField(typeof(List <Keyword>), "keywords"); field.Attributes = MemberAttributes.Private | MemberAttributes.Static; field.InitExpression = new CodeObjectCreateExpression(typeof(List <Keyword>)); lexiType.Members.Add(field); } { // protected override IEnumerable<Keyword> GetKeywords() var method = new CodeMemberMethod(); method.Name = "GetKeywords"; method.Attributes = MemberAttributes.Public | MemberAttributes.Override; method.ReturnType = new CodeTypeReference(typeof(IEnumerable <Keyword>)); var returnKeywords = new CodeMethodReturnStatement( new CodeVariableReferenceExpression("keywords")); method.Statements.Add(returnKeywords); lexiType.Members.Add(method); } { // static DemoLexicalAnalyzer() var method = new CodeTypeConstructor(); method.Name = GetLexicalAnalyzerName(grammarId); method.Attributes = MemberAttributes.Static; //{ // // List<Keyword> keyword = new List<Keyword>(); // var keyword = new CodeVariableDeclarationStatement("List<Keyword>", "keyword"); // keyword.InitExpression = new CodeObjectCreateExpression("List<Keyword>"); // method.Statements.Add(keyword); //} var convertor = new TreeNodeType2TokenType(); foreach (var node in grammar.GetAllTreeNodeLeaveTypes()) { // keywords.Add(new Keyword("__x", "x")); if (node.IsIdentifier()) { TokenType tokenType = convertor.GetTokenType(node); var ctor = new CodeObjectCreateExpression(typeof(Keyword), new CodePrimitiveExpression(tokenType.Type), new CodePrimitiveExpression(tokenType.Content)); var add = new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("keywords"), "Add", ctor); method.Statements.Add(add); } } //{ // // DemoLexicalAnalyzer.keywords = keywords; // var assign = new CodeAssignStatement( // new CodeFieldReferenceExpression( // new CodeSnippetExpression(GetLexicalAnalyzerName(grammarId)), "keywords"), // new CodeVariableReferenceExpression("keywords")); // method.Statements.Add(assign); //} lexiType.Members.Add(method); } }
// Remove private constructor in F#. // Add static constructor. (but ignored in F#) void AdjustConstructor(bool isFSharp, CodeTypeDeclaration type) { if (isFSharp) { foreach (CodeTypeMember tm in type.Members) { if (tm is CodeConstructor) { type.Members.Remove(tm); break; } } } var staticCtor = new CodeTypeConstructor() { Attributes = MemberAttributes.Static }; staticCtor.Statements.Add( new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeTypeReferenceExpression( new CodeTypeReference( "Android.Runtime.ResourceIdManager", CodeTypeReferenceOptions.GlobalReference)), "UpdateIdValues"))); type.Members.Add(staticCtor); }
public CodeStatementCollection WriteStaticConstructor() { CodeTypeConstructor constructor = new CodeTypeConstructor(); constructor.Attributes = MemberAttributes.Public | MemberAttributes.Static; m_currentType.Members.Add(constructor); return(constructor.Statements); }
private void ValidateTypeConstructor(CodeTypeConstructor e) { if (!(IsCurrentClass || IsCurrentStruct)) { return; } ValidateStatements(e.Statements); }
protected override void GenerateTypeConstructor (CodeTypeConstructor e) { Output.WriteLine("Shared Sub New "); ++Indent; GenerateStatements(e.Statements); --Indent; Output.WriteLine("End Sub"); }
private static CodeMemberMethod CreateStaticConstructorMethod(CodeTypeDeclaration inputClass) { CodeTypeConstructor method = new CodeTypeConstructor(); method.Attributes = MemberAttributes.Static; inputClass.Members.Add(method); return(method); }
protected override void GenerateTypeConstructor (CodeTypeConstructor e) { Output.Write("static "); OutputIdentifier(CurrentTypeName); Output.Write("()"); StartBlock(); GenerateStatements(e.Statements); EndBlock(); }
public void Init() { this.functionalConstructor = null; this.staticConstructor = null; this.hasElementWildCards = false; this.contentModelExpression = null; if (this.propertyNameTypeTable != null) { this.propertyNameTypeTable.Clear(); } }
private void AddStaticCtor() { CodeTypeConstructor constructor = new CodeTypeConstructor(); //constructor.Attributes = MemberAttributes.Public | MemberAttributes.Static; foreach (var kv in _fieldsDictionary) { CodeFieldReferenceExpression left = new CodeFieldReferenceExpression(null, kv.Item1); CodeObjectCreateExpression right = new CodeObjectCreateExpression(); right.CreateType = new CodeTypeReference(kv.Item3); if (kv.Item4 != null) { foreach (object param in kv.Item4) { if (param is Enum) { CodeFieldReferenceExpression codeEnum = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(param.GetType().Name), ((Enum)param).ToString()); right.Parameters.Add(codeEnum); } else { right.Parameters.Add(new CodePrimitiveExpression(param)); } } } constructor.Statements.Add(new CodeAssignStatement(left, right)); } _targetClass.Members.Add(constructor); //// Declare constructor //CodeConstructor constructor = new CodeConstructor(); //constructor.Attributes = MemberAttributes.Public | MemberAttributes.Static; //// Add parameters. //foreach (var kv in _fieldsDictionary) //{ // constructor.Parameters.Add(new CodeParameterDeclarationExpression(kv.Key, kv.Value)); //} //// Add field initialization logic //foreach (var kv in _fieldsDictionary) //{ // CodeFieldReferenceExpression reference = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), kv.Value); // constructor.Statements.Add(new CodeAssignStatement(reference, new CodeArgumentReferenceExpression(kv.Value))); //} //_targetClass.Members.Add(constructor); }
public static CodeTypeConstructor DeclareConstructorStatic(this CodeTypeDeclaration type, Action <CodeTypeConstructor> ctor) { CodeTypeConstructor method = new CodeTypeConstructor(); type.Members.Add(method); ctor(method); return(method); }
public CXChildVisitResult Visit(CXCursor cursor, CXCursor parent) { if (!cursor.Location.IsFromMainFile) { return(CXChildVisitResult.CXChildVisit_Continue); } if (this.nativeMethods == null) { var name = this.generator.Name + "NativeMethods"; this.nativeMethods = new CodeTypeDeclaration(); this.nativeMethods.Name = name; this.nativeMethods.Attributes = /*MemberAttributes.Static |*/ MemberAttributes.Public | MemberAttributes.Final; this.nativeMethods.IsPartial = true; this.nativeMethods.Members.Add( new CodeMemberField(typeof(string), "LibraryName") { Attributes = MemberAttributes.Const | MemberAttributes.Public, InitExpression = new CodePrimitiveExpression(this.libraryName) }); var constructor = new CodeTypeConstructor(); constructor.Statements.Add( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression("LibraryResolver"), "EnsureRegistered"))); this.nativeMethods.Members.Add(constructor); this.generator.Types.Add(new CodeDomGeneratedType(this.nativeMethods)); } CXCursorKind curKind = cursor.Kind; // look only at function decls /* * if (curKind == CXCursorKind.CXCursor_FirstDecl) * { * return CXChildVisitResult.CXChildVisit_Recurse; * }*/ if (curKind == CXCursorKind.CXCursor_UnexposedDecl) { return(CXChildVisitResult.CXChildVisit_Recurse); } if (curKind == CXCursorKind.CXCursor_FunctionDecl) { var function = this.WriteFunctionInfoHelper(cursor); this.nativeMethods.Members.Add(function); return(CXChildVisitResult.CXChildVisit_Continue); } return(CXChildVisitResult.CXChildVisit_Continue); }
public CodeMemberMethod declTypeCtor(MemberAttributes attributes, params object[] parameters) { statStack.Clear(); CodeMemberMethod method = new CodeTypeConstructor(); statPush(method.Statements); method.Attributes = attributes; AddParameters(method.Parameters, parameters); AddMember(method); currMethod = method; return(method); }
protected override void GenerateTypeConstructor( CodeTypeConstructor constructor) { Output.WriteLine("static constructor() :"); Indent++; GenerateStatements(constructor.Statements); if ((constructor.Statements.Count) == 0) { Output.WriteLine("pass"); } Indent--; }
protected override void GenerateTypeConstructor(CodeTypeConstructor constructor) { if (IsCurrentDelegate || IsCurrentEnum || IsCurrentInterface) { return; } Output.Write("static " + GetSafeName(CurrentTypeName)); OutputStartBrace(); Indent++; GenerateStatements(constructor.Statements); Indent--; Output.WriteLine('}'); }
protected string GenerateTypeConstructor(CodeGeneratorOptions options) { TypeDeclaration.Name = "Test1"; CodeTypeConstructor typeCtor = new CodeTypeConstructor(); // access, scope and vtable modifiers should be ignored typeCtor.Attributes |= MemberAttributes.Public | MemberAttributes.Abstract | MemberAttributes.Const | MemberAttributes.Final | MemberAttributes.New | MemberAttributes.Overloaded | MemberAttributes.Override | MemberAttributes.Static; TypeDeclaration.Members.Add(typeCtor); // custom attributes CodeAttributeDeclaration attrDec = new CodeAttributeDeclaration(); attrDec.Name = "A"; typeCtor.CustomAttributes.Add(attrDec); attrDec = new CodeAttributeDeclaration(); attrDec.Name = "B"; typeCtor.CustomAttributes.Add(attrDec); // parameter should be ignored CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression( typeof(object), "value1"); typeCtor.Parameters.Add(param); // implementation types should be ignored on type ctors typeCtor.ImplementationTypes.Add(new CodeTypeReference("IPolicy")); // private immplementation type should be ignored on type ctors typeCtor.PrivateImplementationType = new CodeTypeReference(typeof(int)); // return type should be ignored on type ctors typeCtor.ReturnType = new CodeTypeReference(typeof(int)); // return TypeDeclaration custom attributes attrDec = new CodeAttributeDeclaration(); attrDec.Name = "A"; attrDec.Arguments.Add(new CodeAttributeArgument("A1", new CodePrimitiveExpression(false))); attrDec.Arguments.Add(new CodeAttributeArgument("A2", new CodePrimitiveExpression(true))); typeCtor.ReturnTypeCustomAttributes.Add(attrDec); return(GenerateCodeFromType(TypeDeclaration, options)); }
protected override void GenerateTypeConstructor(CodeTypeConstructor constructor) { if (IsCurrentDelegate || IsCurrentEnum || IsCurrentInterface) { return; } OutputAttributes(constructor.CustomAttributes, null, false); Output.Write("static "); OutputStartBrace(); Indent++; GenerateStatements(constructor.Statements); Indent--; Output.WriteLine('}'); }
private void Generate(CodeTypeDeclaration type, CodeTypeConstructor member) { this.WriteDocumentation(member.Comments); this.Write("static "); this.WriteName(type.Name); this.WriteLine("()"); this.WriteLine("{"); this.Indent++; this.Generate(member.Statements); this.Indent--; this.WriteLine("}"); }
private void GenerateTypeConstructors(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeTypeConstructor) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } CodeTypeConstructor imp = (CodeTypeConstructor)current; GenerateTypeConstructor(imp); } } }
// Remove private constructor in F#. // Add static constructor. (but ignored in F#) void AdjustConstructor(CodeTypeDeclaration type) { var staticCtor = new CodeTypeConstructor() { Attributes = MemberAttributes.Static }; staticCtor.Statements.Add( new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeTypeReferenceExpression( new CodeTypeReference( "Android.Runtime.ResourceIdManager", CodeTypeReferenceOptions.GlobalReference)), "UpdateIdValues"))); type.Members.Add(staticCtor); }
protected virtual void BuildPageClass(CodeTypeDeclaration codeType) { this.PageTypeReferenceExpression = new CodeTypeReferenceExpression(new CodeTypeReference(codeType.Name)); AddPageBaseTypes(codeType.BaseTypes); AddPageFields(codeType.Members); AddPageProperties(codeType.Members); CodeTypeConstructor cctor = new CodeTypeConstructor(); cctor.CustomAttributes.Add(new CodeAttributeDeclaration(DebuggerNonUserCodeTypeReference)); AddPageTypeCtorStatements(cctor.Statements); if (cctor.Statements.Count > 0) { codeType.Members.Add(cctor); } AddPageMethods(codeType.Members); }
public static CodeTypeConstructor Static(this CodeConstructor ctor) { var cctor = new CodeTypeConstructor( ) { Attributes = MemberAttributes.Static, CustomAttributes = ctor.CustomAttributes, LinePragma = ctor.LinePragma }; cctor.StartDirectives.AddRange(ctor.StartDirectives); cctor.Comments.AddRange(ctor.Comments); cctor.Statements.AddRange(ctor.Statements); cctor.EndDirectives.AddRange(ctor.EndDirectives); foreach (System.Collections.DictionaryEntry entry in ctor.UserData) { cctor.UserData.Add(entry.Key, entry.Value); } return(cctor); }
public CodeTypeConstructor ParseTypeConstructor() { CodeTypeConstructor ctor = new CodeTypeConstructor(); ExpectKeyword("typeconstructor"); ExpectKeyword("begin"); while (!IsKeyword("end") && TokenType != CDILToken.EOF) { ctor.Statements.Add(ParseStatement()); if (TokenType == CDILToken.Semicolon) { Expect(CDILToken.Semicolon); } else { break; } } ExpectKeyword("end"); return(ctor); }
public static CodeTypeConstructor TypeConstructor( MemberAttributes attributes, CodeParameterDeclarationExpression[] parameters, CodeStatement[] statements, CodeCommentStatement[] comments, CodeAttributeDeclaration[] customAttributes, CodeDirective[] startDirectives, CodeDirective[] endDirectives, CodeLinePragma linePragma) { var result = new CodeTypeConstructor(); result.Attributes = attributes; result.Parameters.AddRange(parameters); result.Statements.AddRange(statements); result.Comments.AddRange(comments); result.CustomAttributes.AddRange(customAttributes); result.StartDirectives.AddRange(startDirectives); result.EndDirectives.AddRange(endDirectives); result.LinePragma = linePragma; return(result); }
public CodeTypeConstructorExample() { //<Snippet2> // Declares a new type for a static constructor. CodeTypeDeclaration type1 = new CodeTypeDeclaration("Type1"); // Declares a static constructor. CodeTypeConstructor constructor2 = new CodeTypeConstructor(); // Adds the static constructor to the type. type1.Members.Add(constructor2); // A C# code generator produces the following source code for the preceeding example code: // public class Type1 // { // // static Type1() // { // } // } //</Snippet2> }
public void Generate(CodeCompileUnit cunit, string csNamespace) { CodeNamespace ns = new CodeNamespace(csNamespace); cunit.Namespaces.Add(ns); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Xml")); CodeTypeDeclaration persClass = new CodeTypeDeclaration("NamespaceManager"); ns.Types.Add(persClass); persClass.Comments.Add(new CodeCommentStatement("<summary>", true)); persClass.Comments.Add(new CodeCommentStatement("Use the static XmlNamespaceManager Instance of this class to provide namespaces for SelectNodes and SelectSingleNode calls.", true)); persClass.Comments.Add(new CodeCommentStatement("</summary>", true)); CodeMemberField cmf = new CodeMemberField("XmlNamespaceManager", "Instance"); cmf.Attributes = MemberAttributes.Public | MemberAttributes.Static; persClass.Members.Add(cmf); CodeTypeConstructor cc = new CodeTypeConstructor(); persClass.Members.Add(cc); CodeVariableReferenceExpression instance = new CodeVariableReferenceExpression("Instance"); CodeObjectCreateExpression newNameTable = new CodeObjectCreateExpression("NameTable"); CodeObjectCreateExpression newNsManager = new CodeObjectCreateExpression("XmlNamespaceManager", newNameTable); CodeAssignStatement instanceAssign = new CodeAssignStatement(instance, newNsManager); cc.Statements.Add(instanceAssign); foreach (XmlQualifiedName qn in this.namespaceWrapper.QualifiedNames) { CodePrimitiveExpression par1 = new CodePrimitiveExpression(qn.Name); CodePrimitiveExpression par2 = new CodePrimitiveExpression(qn.Namespace); CodeMethodInvokeExpression addNamespace = new CodeMethodInvokeExpression(instance, "AddNamespace", par1, par2); cc.Statements.Add(addNamespace); } }
public void Visit(CodeTypeConstructor o) { g.GenerateTypeConstructor(o); }
private void GenerateTypeConstructor(CodeTypeConstructor e) { if (!(IsCurrentClass)) return; if (e.CustomAttributes.Count > 0) { GenerateAttributes(e.CustomAttributes); } Output.Write("static "); Output.Write(CurrentTypeName); Output.Write("()"); OutputStartingBrace(); Indent++; GenerateStatements(e.Statements); Indent--; Output.WriteLine("}"); }
/// <summary> /// Generate all the necessary logic for serialization of payload types used by grain interfaces. /// </summary> internal static void GenerateSerializationForClass(Type t, CodeNamespace container, HashSet <string> referencedNamespaces, Language language) { var generateSerializers = !CheckForCustomSerialization(t); var generateCopier = !CheckForCustomCopier(t); if (!generateSerializers && !generateCopier) { return; // If the class declares all custom implementations, then we don't need to do anything... } bool notVB = (language != Language.VisualBasic); var openGenerics = notVB ? "<" : "(Of "; var closeGenerics = notVB ? ">" : ")"; // Add the class's namespace to this namespace's imports, as well as some other imports we use container.Imports.Add(new CodeNamespaceImport("System")); container.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); container.Imports.Add(new CodeNamespaceImport("System.Reflection")); container.Imports.Add(new CodeNamespaceImport("Orleans.Serialization")); container.Imports.Add(new CodeNamespaceImport(t.Namespace)); // Create the class declaration, including any required generic parameters // At one time this was a struct, not a class, so all the variable names are "structFoo". Too bad. // Note that we need to replace any periods in the type name with _ to properly handle nested classes var className = TypeUtils.GetSimpleTypeName(TypeUtils.GetFullName(t)); var serializationClassName = className.Replace('.', '_') + SERIALIZER_CLASS_NAME_SUFFIX; var serializationClassOpenName = serializationClassName; var classDecl = new CodeTypeDeclaration(serializationClassName) { IsClass = true }; classDecl.Attributes = (classDecl.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; classDecl.TypeAttributes = TypeAttributes.NotPublic; CodeGeneratorBase.MarkAsGeneratedCode(classDecl); if (!t.IsGenericType) { classDecl.CustomAttributes.Add( new CodeAttributeDeclaration(new CodeTypeReference(typeof(RegisterSerializerAttribute), CodeTypeReferenceOptions.GlobalReference))); } if (t.IsGenericType) { className += openGenerics; serializationClassOpenName += openGenerics; bool first = true; foreach (var genericParameter in t.GetGenericTypeDefinition().GetGenericArguments()) { var param = new CodeTypeParameter(genericParameter.Name); if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint) != GenericParameterAttributes.None) { param.Constraints.Add(" class"); } if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != GenericParameterAttributes.None) { param.Constraints.Add(" struct"); } var constraints = genericParameter.GetGenericParameterConstraints(); foreach (var constraintType in constraints) { param.Constraints.Add(new CodeTypeReference(TypeUtils.GetParameterizedTemplateName(constraintType))); } if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.DefaultConstructorConstraint) != GenericParameterAttributes.None) { param.HasConstructorConstraint = true; } classDecl.TypeParameters.Add(param); if (!first) { className += ", "; serializationClassOpenName += ","; } className += genericParameter.Name; first = false; } className += closeGenerics; serializationClassOpenName += closeGenerics; } // A couple of repeatedly-used CodeDom snippets var classType = new CodeTypeOfExpression(className); var classTypeReference = new CodeTypeReference(className); var objectTypeReference = new CodeTypeReference(typeof(object)); var serMgrRefExp = new CodeTypeReferenceExpression(typeof(SerializationManager)); var currentSerialzationContext = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(SerializationContext)), "Current"); // Static DeepCopyInner method: var copier = new CodeMemberMethod(); if (generateCopier) { classDecl.Members.Add(copier); } copier.Attributes = (copier.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; copier.Attributes = (copier.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; copier.Name = "DeepCopier"; copier.Parameters.Add(new CodeParameterDeclarationExpression(objectTypeReference, "original")); bool shallowCopyable = t.IsOrleansShallowCopyable(); if (shallowCopyable) { copier.Statements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression("original"))); } else { copier.Statements.Add(new CodeVariableDeclarationStatement(classTypeReference, "input", new CodeCastExpression(classTypeReference, new CodeArgumentReferenceExpression("original")))); } copier.ReturnType = objectTypeReference; // Static serializer method: var serializer = new CodeMemberMethod(); if (generateSerializers) { classDecl.Members.Add(serializer); } serializer.Attributes = (serializer.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; serializer.Attributes = (serializer.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; serializer.Name = "Serializer"; serializer.Parameters.Add(new CodeParameterDeclarationExpression(objectTypeReference, "untypedInput")); serializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamWriter), "stream")); serializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected")); serializer.ReturnType = new CodeTypeReference(typeof(void)); serializer.Statements.Add(new CodeVariableDeclarationStatement(classTypeReference, "input", new CodeCastExpression(classTypeReference, new CodeArgumentReferenceExpression("untypedInput")))); // Static deserializer method; note that this will never get called for null values or back references var deserializer = new CodeMemberMethod(); if (generateSerializers) { classDecl.Members.Add(deserializer); } deserializer.Attributes = (deserializer.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; deserializer.Attributes = (deserializer.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; deserializer.Name = "Deserializer"; deserializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected")); deserializer.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(BinaryTokenStreamReader), CodeTypeReferenceOptions.GlobalReference), "stream")); deserializer.ReturnType = objectTypeReference; // Static constructor, which just calls the Init method var staticConstructor = new CodeTypeConstructor(); classDecl.Members.Add(staticConstructor); staticConstructor.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(null, "Register"))); // Init method, which registers the type with the serialization manager, and later may get some static FieldInfo initializers var init = new CodeMemberMethod(); classDecl.Members.Add(init); init.Name = "Register"; init.Attributes = (init.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; init.Attributes = (init.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; if (generateCopier && generateSerializers) { init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType, new CodeMethodReferenceExpression(null, notVB ? "DeepCopier" : "AddressOf DeepCopier"), new CodeMethodReferenceExpression(null, notVB ? "Serializer" : "AddressOf Serializer"), new CodeMethodReferenceExpression(null, notVB ? "Deserializer" : "AddressOf Deserializer"))); } else if (generateCopier) { init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType, new CodeMethodReferenceExpression(null, notVB ? "DeepCopier" : "AddressOf DeepCopier"), null, null)); } else { init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType, null, new CodeMethodReferenceExpression(null, notVB ? "Serializer" : "AddressOf Serializer"), new CodeMethodReferenceExpression(null, notVB ? "Deserializer" : "AddressOf Deserializer"))); } CodeStatement constructor; var consInfo = t.GetConstructor(Type.EmptyTypes); if (consInfo != null) { if (!t.ContainsGenericParameters) { constructor = new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeObjectCreateExpression(t)); } else { var typeName = TypeUtils.GetParameterizedTemplateName(t, tt => tt.Namespace != container.Name && !referencedNamespaces.Contains(tt.Namespace), true); if (language == Language.VisualBasic) { typeName = typeName.Replace("<", "(Of ").Replace(">", ")"); } constructor = new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeObjectCreateExpression(typeName)); } } else if (t.IsValueType) { constructor = !t.ContainsGenericParameters ? new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeDefaultValueExpression(new CodeTypeReference(t))) : new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeDefaultValueExpression(new CodeTypeReference(TypeUtils.GetTemplatedName(t)))); } else { if (!t.ContainsGenericParameters) { constructor = new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeCastExpression(className, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(System.Runtime.Serialization.FormatterServices)), "GetUninitializedObject", new CodeTypeOfExpression(t)))); } else { constructor = new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeCastExpression(className, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(System.Runtime.Serialization.FormatterServices)), "GetUninitializedObject", new CodeTypeOfExpression(TypeUtils.GetTemplatedName(t))))); } } if (!shallowCopyable) { copier.Statements.Add(constructor); copier.Statements.Add(new CodeMethodInvokeExpression(currentSerialzationContext, "RecordObject", new CodeVariableReferenceExpression("original"), new CodeVariableReferenceExpression("result"))); } deserializer.Statements.Add(constructor); // For structs, once we encounter a field that we have to use reflection to set, we need to switch to a boxed representation and reflection // for the rest of the fields in the struct while setting. This flag indicates that we're in that mode. bool usingBoxedReflection = false; // For every field in the class: int counter = 0; List <FieldInfo> fields = GetAllFields(t).ToList(); fields.Sort(new FieldNameComparer()); foreach (var fld in fields) { if (fld.IsNotSerialized || fld.IsLiteral) { continue; } var fldType = fld.FieldType; if (TypeUtilities.IsTypeIsInaccessibleForSerialization(fldType, t.Module)) { ConsoleText.WriteStatus("Skipping generation of serializer for {0} because its field {1} is of a private type.", t.FullName, fld.Name); return; // We cannot deserialize a class with a field of non-public type. Need to add a proper reporting here. } // Import the namespace for the field's type (and any of its parameters), just in case it's not already added ImportFieldNamespaces(fld.FieldType, container.Imports); SerializerGenerationManager.RecordTypeToGenerate(fld.FieldType); counter++; // Add the statements moving to and from a class instance, to the instance creation method and the non-default constructor // Getter and setter for this field's value from a class object CodeExpression getter = null; SetterGenerator setter = null; var name = fld.Name; // Normalize the field name -- strip trailing @ (F#) and look for automatic properties var normalizedName = name.TrimEnd('@'); if (name.StartsWith("<")) { // Backing field for an automatic property; see if it's public so we can use it var propertyName = name.Substring(1, name.IndexOf('>') - 1).TrimEnd('@'); var property = t.GetProperty(propertyName); // If the property is public and not hidden... if ((property != null) && property.DeclaringType == fld.DeclaringType) { if (property.GetGetMethod() != null) { getter = new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("input"), propertyName); } if (!usingBoxedReflection && (property.GetSetMethod() != null)) { setter = value => { var s = new CodeAssignStatement { Left = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("result"), propertyName), Right = value }; return(new CodeStatementCollection(new CodeStatement[] { s })); }; } } } var typeName = TypeUtils.GetTemplatedName(fld.FieldType, _ => !_.IsGenericParameter, language); // See if it's a public field if ((getter == null) || (setter == null)) { if (fld.Attributes.HasFlag(FieldAttributes.Public)) { if (getter == null) { getter = new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("input"), normalizedName); } if (!usingBoxedReflection && (setter == null) && !fld.IsInitOnly) { setter = value => { var s = new CodeAssignStatement { Left = new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("result"), normalizedName), Right = value }; return(new CodeStatementCollection(new CodeStatement[] { s })); }; } } } // Have to use reflection if ((getter == null) || (setter == null)) { // Add a static field for the FieldInfo, and a static constructor string infoName = "fieldInfo" + counter; var info = new CodeMemberField(typeof(FieldInfo), infoName); info.Attributes |= MemberAttributes.Private | MemberAttributes.Static; classDecl.Members.Add(info); CodeTypeOfExpression fieldAccessType; if (fld.DeclaringType == t) { fieldAccessType = classType; } else { FieldInfo fld2 = t.GetField(fld.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if ((fld2 != null) && fld2.DeclaringType == fld.DeclaringType) { fieldAccessType = classType; } else { fieldAccessType = fld.DeclaringType.IsGenericType ? new CodeTypeOfExpression(TypeUtils.GetTemplatedName(fld.DeclaringType)) : new CodeTypeOfExpression(fld.DeclaringType); } } init.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(null, infoName), new CodeMethodInvokeExpression(fieldAccessType, "GetField", new CodePrimitiveExpression(name), new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Instance"), CodeBinaryOperatorType.BitwiseOr, new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Public"), CodeBinaryOperatorType.BitwiseOr, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "NonPublic")))))); // Build the getter and setter if (getter == null) { getter = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeFieldReferenceExpression(null, infoName), "GetValue"), new CodeArgumentReferenceExpression("input")); } if (setter == null) { // If the type is a struct, then the setter becomes somewhat more complicated, so first treat non-structs if (t.IsByRef) { setter = value => { var s = new CodeExpressionStatement { Expression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeFieldReferenceExpression(null, infoName), "SetValue"), new CodeVariableReferenceExpression("result"), value) }; return(new CodeStatementCollection(new CodeStatement[] { s })); }; } else { // If this is the first field to use setting by reflection in a struct, we need to box the struct before we can continue if (!usingBoxedReflection) { usingBoxedReflection = true; // NOTE: object objResult = (object)result; if (!shallowCopyable) { copier.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "objResult", new CodeCastExpression(typeof(object), new CodeVariableReferenceExpression("result")))); } deserializer.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "objResult", new CodeCastExpression(typeof(object), new CodeVariableReferenceExpression("result")))); } var temp = "temp" + counter; setter = value => { var s1 = new CodeVariableDeclarationStatement(typeof(object), temp, value); var s2 = new CodeExpressionStatement { Expression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeFieldReferenceExpression(null, infoName), "SetValue"), new CodeVariableReferenceExpression("objResult"), new CodeVariableReferenceExpression(temp)) }; return(new CodeStatementCollection(new CodeStatement[] { s1, s2 })); }; } } } // Copy this field, if needed if (!shallowCopyable) { if (fld.FieldType.IsOrleansShallowCopyable()) { copier.Statements.AddRange(setter(getter)); } else { copier.Statements.AddRange(fld.FieldType == typeof(object) ? setter(new CodeMethodInvokeExpression(serMgrRefExp, "DeepCopyInner", getter)) : setter(new CodeCastExpression(typeName, new CodeMethodInvokeExpression(serMgrRefExp, "DeepCopyInner", getter)))); } } // Serialize this field serializer.Statements.Add(new CodeMethodInvokeExpression(serMgrRefExp, "SerializeInner", getter, new CodeArgumentReferenceExpression("stream"), new CodeTypeOfExpression(typeName))); // Deserialize this field deserializer.Statements.AddRange(setter(new CodeCastExpression(typeName, new CodeMethodInvokeExpression(serMgrRefExp, "DeserializeInner", new CodeTypeOfExpression(typeName), new CodeArgumentReferenceExpression("stream"))))); } // Add return statements, as needed if (!shallowCopyable) { copier.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(usingBoxedReflection ? "objResult" : "result"))); } deserializer.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(usingBoxedReflection ? "objResult" : "result"))); // Special processing for generic types, necessary so that the appropriate closed types will get generated at run-time if (t.IsGenericType) { var masterClassName = TypeUtils.GetSimpleTypeName(t) + "GenericMaster"; var masterClass = new CodeTypeDeclaration(masterClassName); container.Types.Add(masterClass); masterClass.IsClass = true; masterClass.Attributes |= MemberAttributes.Static | MemberAttributes.Assembly | MemberAttributes.Final; masterClass.TypeAttributes = TypeAttributes.NotPublic; masterClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(RegisterSerializerAttribute), CodeTypeReferenceOptions.GlobalReference))); var masterInit = AddInitMethod(masterClass); masterInit.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", new CodeTypeOfExpression(t), new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericCopier"), new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericSerializer"), new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericDeserializer"))); var initClosed = new CodeMethodInvokeExpression { Method = new CodeMethodReferenceExpression { MethodName = "Invoke", TargetObject = new CodeMethodInvokeExpression( new CodeVariableReferenceExpression ("closed"), "GetMethod", new CodePrimitiveExpression( "Register")) } }; initClosed.Parameters.Add(new CodePrimitiveExpression(null)); initClosed.Parameters.Add(new CodeArrayCreateExpression(typeof(object), 0)); var create = new CodeMemberMethod(); masterClass.Members.Add(create); create.Attributes = (create.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; create.Attributes = (create.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; create.Name = "CreateConcreteType"; create.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type[]), "typeParams")); create.ReturnType = new CodeTypeReference(typeof(Type)); create.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeTypeOfExpression(serializationClassOpenName), "MakeGenericType", new CodeArgumentReferenceExpression("typeParams")))); var cop = new CodeMemberMethod(); masterClass.Members.Add(cop); cop.Attributes = (cop.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cop.Attributes = (cop.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; cop.Name = "GenericCopier"; cop.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj")); cop.ReturnType = new CodeTypeReference(typeof(object)); cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t", new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType", new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("obj"), "GetType"), "GetGenericArguments")))); cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f", new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("DeepCopier")))); cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args", new CodeArrayCreateExpression(typeof(object), new CodeExpression[] { new CodeArgumentReferenceExpression("obj") }))); cop.Statements.Add(new CodeMethodReturnStatement( new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(), new CodeVariableReferenceExpression("args")))); var ser = new CodeMemberMethod(); masterClass.Members.Add(ser); ser.Attributes = (ser.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; ser.Attributes = (ser.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; ser.Name = "GenericSerializer"; ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "input")); ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamWriter), "stream")); ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected")); ser.ReturnType = new CodeTypeReference(typeof(void)); ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t", new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType", new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("input"), "GetType"), "GetGenericArguments")))); ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f", new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("Serializer")))); ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args", new CodeArrayCreateExpression(typeof(object), new CodeExpression[] { new CodeArgumentReferenceExpression("input"), new CodeArgumentReferenceExpression("stream"), new CodeArgumentReferenceExpression("expected") }))); ser.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(), new CodeVariableReferenceExpression("args"))); var deser = new CodeMemberMethod(); masterClass.Members.Add(deser); deser.Attributes = (deser.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; deser.Attributes = (deser.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; deser.Name = "GenericDeserializer"; deser.ReturnType = new CodeTypeReference(typeof(object)); deser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected")); deser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamReader), "stream")); deser.ReturnType = new CodeTypeReference(typeof(object)); deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t", new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType", new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("expected"), "GetGenericArguments")))); deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f", new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("Deserializer")))); deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args", new CodeArrayCreateExpression(typeof(object), new CodeExpression[] { new CodeArgumentReferenceExpression("expected"), new CodeArgumentReferenceExpression("stream") }))); deser.Statements.Add(new CodeMethodReturnStatement( new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(), new CodeVariableReferenceExpression("args")))); } container.Types.Add(classDecl); }
public void ProviderSupports() { CodeDomProvider provider = GetProvider(); CodeCompileUnit cu = new CodeCompileUnit(); CodeNamespace nspace = new CodeNamespace("NSPC"); nspace.Imports.Add(new CodeNamespaceImport("System")); nspace.Imports.Add(new CodeNamespaceImport("System.Drawing")); nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); cu.Namespaces.Add(nspace); CodeTypeDeclaration cd = new CodeTypeDeclaration("TEST"); cd.IsClass = true; nspace.Types.Add(cd); // Arrays of Arrays CodeMemberMethod cmm = new CodeMemberMethod(); cmm.Name = "ArraysOfArrays"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; if (provider.Supports(GeneratorSupport.ArraysOfArrays)) { cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])), "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]), new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)), new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) })))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression( new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0)) , new CodePrimitiveExpression(1)))); } else { throw new Exception("not supported"); } cd.Members.Add(cmm); // assembly attributes if (provider.Supports(GeneratorSupport.AssemblyAttributes)) { CodeAttributeDeclarationCollection 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")))); } CodeTypeDeclaration class1 = new CodeTypeDeclaration(); if (provider.Supports(GeneratorSupport.ChainedConstructorArguments)) { class1.Name = "Test2"; class1.IsClass = true; nspace.Types.Add(class1); class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField")); CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = "accessStringField"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference(typeof(String)); prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "stringField"))); prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "stringField"), new CodePropertySetValueReferenceExpression())); class1.Members.Add(prop); CodeConstructor cctor = new CodeConstructor(); cctor.Attributes = MemberAttributes.Public; cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString")); cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null)); cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null)); class1.Members.Add(cctor); CodeConstructor cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded; cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3")); cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression() , "stringField"), new CodeVariableReferenceExpression("p1"))); class1.Members.Add(cc); // verify chained constructors work cmm = new CodeMemberMethod(); cmm.Name = "ChainedConstructorUse"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(String)); // utilize constructor cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("t"), "accessStringField"))); cd.Members.Add(cmm); } // complex expressions if (provider.Supports(GeneratorSupport.ComplexExpressions)) { cmm = new CodeMemberMethod(); cmm.Name = "ComplexExpressions"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply, new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(3))))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i"))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareEnums)) { CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum"); ce.IsEnum = true; nspace.Types.Add(ce); // things to enumerate for (int k = 0; k < 5; k++) { CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString()); Field.InitExpression = new CodePrimitiveExpression(k); ce.Members.Add(Field); } cmm = new CodeMemberMethod(); cmm.Name = "OutputDecimalEnumVal"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i"); cmm.Parameters.Add(param); CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(3)); CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement( new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3"))); CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(4)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num4"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(2)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num2"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num1"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num0"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); cmm.ReturnType = new CodeTypeReference("System.int32"); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10)))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareInterfaces)) { cmm = new CodeMemberMethod(); cmm.Name = "TestSingleInterface"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp"))); CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t") , "InterfaceMethod"); methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i")); cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke)); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration("InterfaceA"); class1.IsInterface = true; nspace.Types.Add(class1); cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.Public; cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); class1.Members.Add(cmm); if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers)) { CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB"); classDecl.IsInterface = true; nspace.Types.Add(classDecl); cmm = new CodeMemberMethod(); cmm.Name = "InterfaceMethod"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); classDecl.Members.Add(cmm); CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp"); class2.BaseTypes.Add(new CodeTypeReference("System.Object")); class2.BaseTypes.Add(new CodeTypeReference("InterfaceB")); class2.BaseTypes.Add(new CodeTypeReference("InterfaceA")); class2.IsClass = true; nspace.Types.Add(class2); cmm = new CodeMemberMethod(); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA")); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); class2.Members.Add(cmm); cmm = new CodeMemberMethod(); cmm.Name = "TestMultipleInterfaces"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp"))); cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA", new CodeVariableReferenceExpression("t")))); cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB", new CodeVariableReferenceExpression("t")))); methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject") , "InterfaceMethod"); methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i")); CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject") , "InterfaceMethod"); methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i")); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( methodinvoke, CodeBinaryOperatorType.Subtract, methodinvoke2))); cd.Members.Add(cmm); } class1 = new CodeTypeDeclaration("TestSingleInterfaceImp"); class1.BaseTypes.Add(new CodeTypeReference("System.Object")); class1.BaseTypes.Add(new CodeTypeReference("InterfaceA")); class1.IsClass = true; nspace.Types.Add(class1); cmm = new CodeMemberMethod(); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); class1.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareValueTypes)) { CodeTypeDeclaration structA = new CodeTypeDeclaration("structA"); structA.IsStruct = true; CodeTypeDeclaration structB = new CodeTypeDeclaration("structB"); structB.Attributes = MemberAttributes.Public; structB.IsStruct = true; CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1"); firstInt.Attributes = MemberAttributes.Public; structB.Members.Add(firstInt); CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct"); innerStruct.Attributes = MemberAttributes.Public; structA.Members.Add(structB); structA.Members.Add(innerStruct); nspace.Types.Add(structA); CodeMemberMethod nestedStructMethod = new CodeMemberMethod(); nestedStructMethod.Name = "NestedStructMethod"; nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int)); nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA"); nestedStructMethod.Statements.Add(varStructA); nestedStructMethod.Statements.Add ( new CodeAssignStatement ( /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"), /* Expression1 */ new CodePrimitiveExpression(3) ) ); nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"))); cd.Members.Add(nestedStructMethod); } if (provider.Supports(GeneratorSupport.EntryPointMethod)) { CodeEntryPointMethod cep = new CodeEntryPointMethod(); cd.Members.Add(cep); } // goto statements if (provider.Supports(GeneratorSupport.GotoStatements)) { cmm = new CodeMemberMethod(); cmm.Name = "GoToMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i"); cmm.Parameters.Add(param); CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)), new CodeGotoStatement("comehere")); cmm.Statements.Add(condstmt); cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6))); cmm.Statements.Add(new CodeLabeledStatement("comehere", new CodeMethodReturnStatement(new CodePrimitiveExpression(7)))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.NestedTypes)) { cmm = new CodeMemberMethod(); cmm.Name = "CallingPublicNestedScenario"; cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t", new CodeObjectCreateExpression(new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC")))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "publicNestedClassesMethod", new CodeVariableReferenceExpression("i")))); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration("PublicNestedClassA"); class1.IsClass = true; nspace.Types.Add(class1); CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1"); nestedClass.IsClass = true; nestedClass.TypeAttributes = TypeAttributes.NestedPublic; class1.Members.Add(nestedClass); nestedClass = new CodeTypeDeclaration("PublicNestedClassB2"); nestedClass.TypeAttributes = TypeAttributes.NestedPublic; nestedClass.IsClass = true; class1.Members.Add(nestedClass); CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC"); innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic; innerNestedClass.IsClass = true; nestedClass.Members.Add(innerNestedClass); cmm = new CodeMemberMethod(); cmm.Name = "publicNestedClassesMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); innerNestedClass.Members.Add(cmm); } // Parameter Attributes if (provider.Supports(GeneratorSupport.ParameterAttributes)) { CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "MyMethod"; method1.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression 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); cd.Members.Add(method1); } // public static members if (provider.Supports(GeneratorSupport.PublicStaticMembers)) { cmm = new CodeMemberMethod(); cmm.Name = "PublicStaticMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16))); cd.Members.Add(cmm); } // reference parameters if (provider.Supports(GeneratorSupport.ReferenceParameters)) { 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); } if (provider.Supports(GeneratorSupport.ReturnTypeAttributes)) { CodeMemberMethod function1 = new CodeMemberMethod(); function1.Name = "MyFunction"; function1.ReturnType = new CodeTypeReference(typeof(string)); function1.Attributes = MemberAttributes.Public | MemberAttributes.Final; 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"))); cd.Members.Add(function1); } if (provider.Supports(GeneratorSupport.StaticConstructors)) { cmm = new CodeMemberMethod(); cmm.Name = "TestStaticConstructor"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a"); cmm.Parameters.Add(param); // utilize constructor cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4"))); // set then get number cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i") , new CodeVariableReferenceExpression("a"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("t"), "i"))); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration(); class1.Name = "Test4"; class1.IsClass = true; nspace.Types.Add(class1); class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number")); CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = "i"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference(typeof(int)); prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number"))); prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"), new CodePropertySetValueReferenceExpression())); class1.Members.Add(prop); CodeTypeConstructor ctc = new CodeTypeConstructor(); class1.Members.Add(ctc); } if (provider.Supports(GeneratorSupport.TryCatchStatements)) { cmm = new CodeMemberMethod(); cmm.Name = "TryCatchMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a"); cmm.Parameters.Add(param); CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement(); tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(5)))); cmm.Statements.Add(tcfstmt); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareEvents)) { CodeNamespace 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); 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; class1.Members.Add(evt); 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"")> Namespace NSPC Public Class TEST Public Function ArraysOfArrays() As Integer Dim arrayOfArrays()() As Integer = New Integer()() {New Integer() {3, 4}, New Integer() {1}} Return arrayOfArrays(0)(1) End Function Public Shared Function ChainedConstructorUse() As String Dim t As Test2 = New Test2() Return t.accessStringField End Function Public Function ComplexExpressions(ByVal i As Integer) As Integer i = (i _ * (i + 3)) Return i End Function Public Shared Function OutputDecimalEnumVal(ByVal i As Integer) As Integer If (i = 3) Then Return CType(DecimalEnum.Num3,Integer) End If If (i = 4) Then Return CType(DecimalEnum.Num4,Integer) End If If (i = 2) Then Return CType(DecimalEnum.Num2,Integer) End If If (i = 1) Then Return CType(DecimalEnum.Num1,Integer) End If If (i = 0) Then Return CType(DecimalEnum.Num0,Integer) End If Return (i + 10) End Function Public Shared Function TestSingleInterface(ByVal i As Integer) As Integer Dim t As TestSingleInterfaceImp = New TestSingleInterfaceImp() Return t.InterfaceMethod(i) End Function Public Shared Function TestMultipleInterfaces(ByVal i As Integer) As Integer Dim t As TestMultipleInterfaceImp = New TestMultipleInterfaceImp() Dim interfaceAobject As InterfaceA = CType(t,InterfaceA) Dim interfaceBobject As InterfaceB = CType(t,InterfaceB) Return (interfaceAobject.InterfaceMethod(i) - interfaceBobject.InterfaceMethod(i)) End Function Public Shared Function NestedStructMethod() As Integer Dim varStructA As structA varStructA.innerStruct.int1 = 3 Return varStructA.innerStruct.int1 End Function Public Shared Sub Main() End Sub Public Function GoToMethod(ByVal i As Integer) As Integer If (i < 1) Then goto comehere End If Return 6 comehere: Return 7 End Function Public Shared Function CallingPublicNestedScenario(ByVal i As Integer) As Integer Dim t As PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC = New PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC() Return t.publicNestedClassesMethod(i) End Function Public Sub MyMethod(<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal blah As String) End Sub Public Shared Function PublicStaticMethod() As Integer Return 16 End Function 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 Public Function MyFunction() As <System.Xml.Serialization.XmlIgnoreAttribute(), System.Xml.Serialization.XmlRootAttribute([Namespace]:=""Namespace Value"", ElementName:=""Root, hehehe"")> String Return ""Return"" End Function Public Shared Function TestStaticConstructor(ByVal a As Integer) As Integer Dim t As Test4 = New Test4() t.i = a Return t.i End Function Public Shared Function TryCatchMethod(ByVal a As Integer) As Integer Try Finally a = (a + 5) End Try Return a End Function End Class Public Class Test2 Private stringField As String Public Sub New() Me.New(""testingString"", Nothing, Nothing) End Sub Public Sub New(ByVal p1 As String, ByVal p2 As String, ByVal p3 As String) MyBase.New Me.stringField = p1 End Sub Public Property accessStringField() As String Get Return Me.stringField End Get Set Me.stringField = value End Set End Property End Class Public Enum DecimalEnum Num0 = 0 Num1 = 1 Num2 = 2 Num3 = 3 Num4 = 4 End Enum Public Interface InterfaceA Function InterfaceMethod(ByVal a As Integer) As Integer End Interface Public Interface InterfaceB Function InterfaceMethod(ByVal a As Integer) As Integer End Interface Public Class TestMultipleInterfaceImp Inherits Object Implements InterfaceB, InterfaceA Public Function InterfaceMethod(ByVal a As Integer) As Integer Implements InterfaceA.InterfaceMethod , InterfaceB.InterfaceMethod Return a End Function End Class Public Class TestSingleInterfaceImp Inherits Object Implements InterfaceA Public Overridable Function InterfaceMethod(ByVal a As Integer) As Integer Implements InterfaceA.InterfaceMethod Return a End Function End Class Public Structure structA Public innerStruct As structB Public Structure structB Public int1 As Integer End Structure End Structure Public Class PublicNestedClassA Public Class PublicNestedClassB1 End Class Public Class PublicNestedClassB2 Public Class PublicNestedClassC Public Function publicNestedClassesMethod(ByVal a As Integer) As Integer Return a End Function End Class End Class End Class Public Class Test4 Private number As Integer Shared Sub New() End Sub Public Property i() As Integer Get Return number End Get Set number = value End Set End Property End Class End Namespace Namespace MyNamespace 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 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"); }
public void RegionsSnippetsAndLinePragmas() { CodeCompileUnit cu = new CodeCompileUnit(); 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; 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; 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)); var snippet1 = new CodeSnippetTypeMember(); var 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); cd.Members.Add(evt1); cd.Members.Add(nestedClass1); cd.Members.Add(delegate1); cd.Members.Add(snippet1); cd.Members.Add(field2); cd.Members.Add(method2); cd.Members.Add(constructor2); cd.Members.Add(property2); cd.Members.Add(typeConstructor2); cd.Members.Add(evt2); cd.Members.Add(nestedClass2); cd.Members.Add(delegate2); cd.Members.Add(snippet2); AssertEqual(cu, @"#Region ""Compile Unit Region"" '------------------------------------------------------------------------------ ' <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 Namespace Namespace1 #Region ""Outer Type Region"" 'Outer Type Comment Public Class Class1 'Field 1 Comment Private field1 As String #Region ""Field Region"" Private field2 As String #End Region #Region ""Snippet Region"" #End Region #Region ""Type Constructor Region"" Shared Sub New() End Sub #End Region #Region ""Constructor Region"" Public Sub New() MyBase.New Me.field1 = ""value1"" Me.field2 = ""value2"" End Sub #End Region Public Sub New(ByVal value1 As String, ByVal value2 As String) MyBase.New End Sub Public ReadOnly Property Property1() As String Get Return Me.field1 End Get End Property #Region ""Property Region"" Public ReadOnly Property Property2() As String Get Return Me.field2 End Get End Property #End Region Public Event Event1 As System.EventHandler #Region ""Event Region"" Public Event Event2 As System.EventHandler #End Region Public Sub Method1() RaiseEvent Event1(Me, System.EventArgs.Empty) End Sub Public Shared Sub Main() End Sub #Region ""Method Region"" 'Method 2 Comment #ExternalSource(""MethodLinePragma.txt"",500) Public Sub Method2() RaiseEvent Event2(Me, System.EventArgs.Empty) End Sub #End ExternalSource #End Region Public Class NestedClass1 End Class Public Delegate Sub nestedDelegate1(ByVal sender As Object, ByVal e As System.EventArgs) #Region ""Nested Type Region"" 'Nested Type Comment #ExternalSource(""NestedTypeLinePragma.txt"",400) Public Class NestedClass2 End Class #End ExternalSource #End Region #Region ""Delegate Region"" Public Delegate Sub nestedDelegate2(ByVal sender As Object, ByVal e As System.EventArgs) #End Region End Class #End Region End Namespace #End Region"); }
private void ValidateTypeConstructor(CodeTypeConstructor e) { ValidateStatements(e.Statements); }
public void ProviderSupports() { CodeDomProvider provider = GetProvider(); var cu = new CodeCompileUnit(); var nspace = new CodeNamespace("NSPC"); nspace.Imports.Add(new CodeNamespaceImport("System")); nspace.Imports.Add(new CodeNamespaceImport("System.Drawing")); nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); cu.Namespaces.Add(nspace); var cd = new CodeTypeDeclaration("TEST"); cd.IsClass = true; nspace.Types.Add(cd); // Arrays of Arrays var cmm = new CodeMemberMethod(); cmm.Name = "ArraysOfArrays"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; if (provider.Supports(GeneratorSupport.ArraysOfArrays)) { cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])), "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]), new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)), new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) })))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression( new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0)) , new CodePrimitiveExpression(1)))); } else { cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(0))); } cd.Members.Add(cmm); // assembly attributes if (provider.Supports(GeneratorSupport.AssemblyAttributes)) { CodeAttributeDeclarationCollection 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")))); } CodeTypeDeclaration class1 = new CodeTypeDeclaration(); if (provider.Supports(GeneratorSupport.ChainedConstructorArguments)) { class1.Name = "Test2"; class1.IsClass = true; nspace.Types.Add(class1); class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField")); CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = "accessStringField"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference(typeof(String)); prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "stringField"))); prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "stringField"), new CodePropertySetValueReferenceExpression())); class1.Members.Add(prop); CodeConstructor cctor = new CodeConstructor(); cctor.Attributes = MemberAttributes.Public; cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString")); cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null)); cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null)); class1.Members.Add(cctor); CodeConstructor cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded; cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3")); cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression() , "stringField"), new CodeVariableReferenceExpression("p1"))); class1.Members.Add(cc); // verify chained constructors work cmm = new CodeMemberMethod(); cmm.Name = "ChainedConstructorUse"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(String)); // utilize constructor cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("t"), "accessStringField"))); cd.Members.Add(cmm); } // complex expressions if (provider.Supports(GeneratorSupport.ComplexExpressions)) { cmm = new CodeMemberMethod(); cmm.Name = "ComplexExpressions"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply, new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(3))))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i"))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareEnums)) { CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum"); ce.IsEnum = true; nspace.Types.Add(ce); // things to enumerate for (int k = 0; k < 5; k++) { CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString()); Field.InitExpression = new CodePrimitiveExpression(k); ce.Members.Add(Field); } cmm = new CodeMemberMethod(); cmm.Name = "OutputDecimalEnumVal"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i"); cmm.Parameters.Add(param); CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(3)); CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement( new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3"))); CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(4)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num4"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(2)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num2"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num1"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num0"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); cmm.ReturnType = new CodeTypeReference("System.int32"); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10)))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareInterfaces)) { cmm = new CodeMemberMethod(); cmm.Name = "TestSingleInterface"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp"))); CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t") , "InterfaceMethod"); methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i")); cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke)); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration("InterfaceA"); class1.IsInterface = true; nspace.Types.Add(class1); cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.Public; cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); class1.Members.Add(cmm); if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers)) { CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB"); classDecl.IsInterface = true; nspace.Types.Add(classDecl); cmm = new CodeMemberMethod(); cmm.Name = "InterfaceMethod"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); classDecl.Members.Add(cmm); CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp"); class2.BaseTypes.Add(new CodeTypeReference("System.Object")); class2.BaseTypes.Add(new CodeTypeReference("InterfaceB")); class2.BaseTypes.Add(new CodeTypeReference("InterfaceA")); class2.IsClass = true; nspace.Types.Add(class2); cmm = new CodeMemberMethod(); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA")); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); class2.Members.Add(cmm); cmm = new CodeMemberMethod(); cmm.Name = "TestMultipleInterfaces"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp"))); cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA", new CodeVariableReferenceExpression("t")))); cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB", new CodeVariableReferenceExpression("t")))); methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject") , "InterfaceMethod"); methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i")); CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject") , "InterfaceMethod"); methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i")); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( methodinvoke, CodeBinaryOperatorType.Subtract, methodinvoke2))); cd.Members.Add(cmm); } class1 = new CodeTypeDeclaration("TestSingleInterfaceImp"); class1.BaseTypes.Add(new CodeTypeReference("System.Object")); class1.BaseTypes.Add(new CodeTypeReference("InterfaceA")); class1.IsClass = true; nspace.Types.Add(class1); cmm = new CodeMemberMethod(); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); class1.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareValueTypes)) { CodeTypeDeclaration structA = new CodeTypeDeclaration("structA"); structA.IsStruct = true; CodeTypeDeclaration structB = new CodeTypeDeclaration("structB"); structB.Attributes = MemberAttributes.Public; structB.IsStruct = true; CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1"); firstInt.Attributes = MemberAttributes.Public; structB.Members.Add(firstInt); CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct"); innerStruct.Attributes = MemberAttributes.Public; structA.Members.Add(structB); structA.Members.Add(innerStruct); nspace.Types.Add(structA); CodeMemberMethod nestedStructMethod = new CodeMemberMethod(); nestedStructMethod.Name = "NestedStructMethod"; nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int)); nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA"); nestedStructMethod.Statements.Add(varStructA); nestedStructMethod.Statements.Add ( new CodeAssignStatement ( /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"), /* Expression1 */ new CodePrimitiveExpression(3) ) ); nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"))); cd.Members.Add(nestedStructMethod); } if (provider.Supports(GeneratorSupport.EntryPointMethod)) { CodeEntryPointMethod cep = new CodeEntryPointMethod(); cd.Members.Add(cep); } // goto statements if (provider.Supports(GeneratorSupport.GotoStatements)) { cmm = new CodeMemberMethod(); cmm.Name = "GoToMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i"); cmm.Parameters.Add(param); CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)), new CodeGotoStatement("comehere")); cmm.Statements.Add(condstmt); cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6))); cmm.Statements.Add(new CodeLabeledStatement("comehere", new CodeMethodReturnStatement(new CodePrimitiveExpression(7)))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.NestedTypes)) { cmm = new CodeMemberMethod(); cmm.Name = "CallingPublicNestedScenario"; cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t", new CodeObjectCreateExpression(new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC")))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "publicNestedClassesMethod", new CodeVariableReferenceExpression("i")))); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration("PublicNestedClassA"); class1.IsClass = true; nspace.Types.Add(class1); CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1"); nestedClass.IsClass = true; nestedClass.TypeAttributes = TypeAttributes.NestedPublic; class1.Members.Add(nestedClass); nestedClass = new CodeTypeDeclaration("PublicNestedClassB2"); nestedClass.TypeAttributes = TypeAttributes.NestedPublic; nestedClass.IsClass = true; class1.Members.Add(nestedClass); CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC"); innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic; innerNestedClass.IsClass = true; nestedClass.Members.Add(innerNestedClass); cmm = new CodeMemberMethod(); cmm.Name = "publicNestedClassesMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); innerNestedClass.Members.Add(cmm); } // Parameter Attributes if (provider.Supports(GeneratorSupport.ParameterAttributes)) { CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "MyMethod"; method1.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression 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); cd.Members.Add(method1); } // public static members if (provider.Supports(GeneratorSupport.PublicStaticMembers)) { cmm = new CodeMemberMethod(); cmm.Name = "PublicStaticMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16))); cd.Members.Add(cmm); } // reference parameters if (provider.Supports(GeneratorSupport.ReferenceParameters)) { 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); } if (provider.Supports(GeneratorSupport.ReturnTypeAttributes)) { CodeMemberMethod function1 = new CodeMemberMethod(); function1.Name = "MyFunction"; function1.ReturnType = new CodeTypeReference(typeof(string)); function1.Attributes = MemberAttributes.Public | MemberAttributes.Final; 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"))); cd.Members.Add(function1); } if (provider.Supports(GeneratorSupport.StaticConstructors)) { cmm = new CodeMemberMethod(); cmm.Name = "TestStaticConstructor"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a"); cmm.Parameters.Add(param); // utilize constructor cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4"))); // set then get number cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i") , new CodeVariableReferenceExpression("a"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("t"), "i"))); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration(); class1.Name = "Test4"; class1.IsClass = true; nspace.Types.Add(class1); class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number")); CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = "i"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference(typeof(int)); prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number"))); prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"), new CodePropertySetValueReferenceExpression())); class1.Members.Add(prop); CodeTypeConstructor ctc = new CodeTypeConstructor(); class1.Members.Add(ctc); } if (provider.Supports(GeneratorSupport.TryCatchStatements)) { cmm = new CodeMemberMethod(); cmm.Name = "TryCatchMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a"); cmm.Parameters.Add(param); CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement(); tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(5)))); cmm.Statements.Add(tcfstmt); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareEvents)) { CodeNamespace 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); 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; class1.Members.Add(evt); 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> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyTitle(""MyAssembly"")] [assembly: System.Reflection.AssemblyVersion(""1.0.6.2"")] namespace NSPC { using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; public class TEST { public int ArraysOfArrays() { int[][] arrayOfArrays = new int[][] { new int[] { 3, 4}, new int[] { 1}}; return arrayOfArrays[0][1]; } public static string ChainedConstructorUse() { Test2 t = new Test2(); return t.accessStringField; } public int ComplexExpressions(int i) { i = (i * (i + 3)); return i; } public static int OutputDecimalEnumVal(int i) { if ((i == 3)) { return ((int)(DecimalEnum.Num3)); } if ((i == 4)) { return ((int)(DecimalEnum.Num4)); } if ((i == 2)) { return ((int)(DecimalEnum.Num2)); } if ((i == 1)) { return ((int)(DecimalEnum.Num1)); } if ((i == 0)) { return ((int)(DecimalEnum.Num0)); } return (i + 10); } public static int TestSingleInterface(int i) { TestSingleInterfaceImp t = new TestSingleInterfaceImp(); return t.InterfaceMethod(i); } public static int TestMultipleInterfaces(int i) { TestMultipleInterfaceImp t = new TestMultipleInterfaceImp(); InterfaceA interfaceAobject = ((InterfaceA)(t)); InterfaceB interfaceBobject = ((InterfaceB)(t)); return (interfaceAobject.InterfaceMethod(i) - interfaceBobject.InterfaceMethod(i)); } public static int NestedStructMethod() { structA varStructA; varStructA.innerStruct.int1 = 3; return varStructA.innerStruct.int1; } public static void Main() { } public int GoToMethod(int i) { if ((i < 1)) { goto comehere; } return 6; comehere: return 7; } public static int CallingPublicNestedScenario(int i) { PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC t = new PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC(); return t.publicNestedClassesMethod(i); } public void MyMethod([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] string blah) { } public static int PublicStaticMethod() { return 16; } static void Work(ref int i, out int j) { i = (i + 4); j = 5; } public static int CallingWork(int a) { a = 10; int b; TEST.Work(ref a, out b); return (a + b); } [return: System.Xml.Serialization.XmlIgnoreAttribute()] [return: System.Xml.Serialization.XmlRootAttribute(Namespace=""Namespace Value"", ElementName=""Root, hehehe"")] public string MyFunction() { return ""Return""; } public static int TestStaticConstructor(int a) { Test4 t = new Test4(); t.i = a; return t.i; } public static int TryCatchMethod(int a) { try { } finally { a = (a + 5); } return a; } } public class Test2 { private string stringField; public Test2() : this(""testingString"", null, null) { } public Test2(string p1, string p2, string p3) { this.stringField = p1; } public string accessStringField { get { return this.stringField; } set { this.stringField = value; } } } public enum DecimalEnum { Num0 = 0, Num1 = 1, Num2 = 2, Num3 = 3, Num4 = 4, } public interface InterfaceA { int InterfaceMethod(int a); } public interface InterfaceB { int InterfaceMethod(int a); } public class TestMultipleInterfaceImp : object, InterfaceB, InterfaceA { public int InterfaceMethod(int a) { return a; } } public class TestSingleInterfaceImp : object, InterfaceA { public virtual int InterfaceMethod(int a) { return a; } } public struct structA { public structB innerStruct; public struct structB { public int int1; } } public class PublicNestedClassA { public class PublicNestedClassB1 { } public class PublicNestedClassB2 { public class PublicNestedClassC { public int publicNestedClassesMethod(int a) { return a; } } } } public class Test4 { private int number; static Test4() { } public int i { get { return number; } set { number = value; } } } } namespace MyNamespace { using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; public class Test : Form { private Button b = new Button(); public Test() { this.Size = new Size(600, 600); b.Text = ""Test""; b.TabIndex = 0; b.Location = new Point(400, 525); this.MyEvent += new EventHandler(this.b_Click); } public event System.EventHandler MyEvent; private void b_Click(object sender, System.EventArgs e) { } } }"); }
protected override void GenerateTypeConstructor (CodeTypeConstructor e) { Output.WriteLine("Shared Sub New "); ++Indent; GenerateStatements(e.Statements); --Indent; Output.WriteLine("End Sub"); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace nspace = new CodeNamespace ("NSPC"); nspace.Imports.Add (new CodeNamespaceImport ("System")); nspace.Imports.Add (new CodeNamespaceImport ("System.Drawing")); nspace.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms")); nspace.Imports.Add (new CodeNamespaceImport ("System.ComponentModel")); cu.Namespaces.Add (nspace); cu.ReferencedAssemblies.Add ("System.Drawing.dll"); cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll"); cu.ReferencedAssemblies.Add ("System.Xml.dll"); CodeTypeDeclaration cd = new CodeTypeDeclaration ("TEST"); cd.IsClass = true; nspace.Types.Add (cd); CodeMemberMethod cmm; // Arrays of Arrays #if !WHIDBEY // Everett VB code provider doesn't support array of array initialization if (!(provider is Microsoft.VisualBasic.VBCodeProvider)) { #endif if (Supports (provider, GeneratorSupport.ArraysOfArrays)) { AddScenario ("CheckArrayOfArrays"); cmm = new CodeMemberMethod (); cmm.Name = "ArraysOfArrays"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference (typeof (int[][])), "arrayOfArrays", new CodeArrayCreateExpression (typeof (int[][]), new CodeArrayCreateExpression (typeof (int[]), new CodePrimitiveExpression (3), new CodePrimitiveExpression (4)), new CodeArrayCreateExpression (typeof (int[]), new CodeExpression[] {new CodePrimitiveExpression (1)})))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArrayIndexerExpression ( new CodeArrayIndexerExpression (new CodeVariableReferenceExpression ("arrayOfArrays"), new CodePrimitiveExpression (0)), new CodePrimitiveExpression (1)))); cd.Members.Add (cmm); } #if !WHIDBEY } #endif // assembly attributes if (Supports (provider, GeneratorSupport.AssemblyAttributes)) { AddScenario ("CheckAssemblyAttributes"); CodeAttributeDeclarationCollection 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")))); } CodeTypeDeclaration class1 = new CodeTypeDeclaration (); if (Supports (provider, GeneratorSupport.ChainedConstructorArguments)) { AddScenario ("CheckChainedConstructorArgs"); class1.Name = "Test2"; class1.IsClass = true; nspace.Types.Add (class1); class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (String)), "stringField")); CodeMemberProperty prop = new CodeMemberProperty (); prop.Name = "accessStringField"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference (typeof (String)); prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "stringField"))); prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "stringField"), new CodePropertySetValueReferenceExpression ())); class1.Members.Add (prop); CodeConstructor cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.Public; cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression ("testingString")); cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression (null)); cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression (null)); class1.Members.Add (cctor); CodeConstructor cc = new CodeConstructor (); cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded; cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "p1")); cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "p2")); cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "p3")); cc.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression () , "stringField"), new CodeArgumentReferenceExpression ("p1"))); class1.Members.Add (cc); // verify chained constructors work cmm = new CodeMemberMethod (); cmm.Name = "ChainedConstructorUse"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference (typeof (String)); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test2", "t", new CodeObjectCreateExpression ("Test2"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "accessStringField"))); cd.Members.Add (cmm); } // complex expressions if (Supports (provider, GeneratorSupport.ComplexExpressions)) { AddScenario ("CheckComplexExpressions"); cmm = new CodeMemberMethod (); cmm.Name = "ComplexExpressions"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("i"), new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Multiply, new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (3))))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("i"))); cd.Members.Add (cmm); } if (Supports (provider, GeneratorSupport.DeclareEnums)) { AddScenario ("CheckDeclareEnums"); CodeTypeDeclaration ce = new CodeTypeDeclaration ("DecimalEnum"); ce.IsEnum = true; nspace.Types.Add (ce); // things to enumerate for (int k = 0; k < 5; k++) { CodeMemberField Field = new CodeMemberField ("System.Int32", "Num" + (k).ToString ()); Field.InitExpression = new CodePrimitiveExpression (k); ce.Members.Add (Field); } cmm = new CodeMemberMethod (); cmm.Name = "OutputDecimalEnumVal"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i"); cmm.Parameters.Add (param); CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression ( new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (3)); CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement ( new CodeCastExpression (typeof (int), new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num3"))); CodeConditionStatement condstmt = new CodeConditionStatement (eq, truestmt); cmm.Statements.Add (condstmt); eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (4)); truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num4"))); condstmt = new CodeConditionStatement (eq, truestmt); cmm.Statements.Add (condstmt); eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (2)); truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num2"))); condstmt = new CodeConditionStatement (eq, truestmt); cmm.Statements.Add (condstmt); eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (1)); truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num1"))); condstmt = new CodeConditionStatement (eq, truestmt); cmm.Statements.Add (condstmt); eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (0)); truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num0"))); condstmt = new CodeConditionStatement (eq, truestmt); cmm.Statements.Add (condstmt); cmm.ReturnType = new CodeTypeReference ("System.Int32"); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (10)))); cd.Members.Add (cmm); } if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { AddScenario ("CheckDeclareInterfaces"); cmm = new CodeMemberMethod (); cmm.Name = "TestSingleInterface"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add (new CodeVariableDeclarationStatement ("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression ("TestSingleInterfaceImp"))); CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t") , "InterfaceMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (methodinvoke)); cd.Members.Add (cmm); class1 = new CodeTypeDeclaration ("InterfaceA"); class1.IsInterface = true; nspace.Types.Add (class1); cmm = new CodeMemberMethod (); cmm.Attributes = MemberAttributes.Public; cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); class1.Members.Add (cmm); if (Supports (provider, GeneratorSupport.MultipleInterfaceMembers)) { AddScenario ("CheckMultipleInterfaceMembers"); CodeTypeDeclaration classDecl = new CodeTypeDeclaration ("InterfaceB"); classDecl.IsInterface = true; nspace.Types.Add (classDecl); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); classDecl.Members.Add (cmm); CodeTypeDeclaration class2 = new CodeTypeDeclaration ("TestMultipleInterfaceImp"); class2.BaseTypes.Add (new CodeTypeReference ("System.Object")); class2.BaseTypes.Add (new CodeTypeReference ("InterfaceB")); class2.BaseTypes.Add (new CodeTypeReference ("InterfaceA")); class2.IsClass = true; nspace.Types.Add (class2); cmm = new CodeMemberMethod (); cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceA")); cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceB")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); class2.Members.Add (cmm); cmm = new CodeMemberMethod (); cmm.Name = "TestMultipleInterfaces"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add (new CodeVariableDeclarationStatement ("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression ("TestMultipleInterfaceImp"))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("InterfaceA", "interfaceAobject", new CodeCastExpression ("InterfaceA", new CodeVariableReferenceExpression ("t")))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("InterfaceB", "interfaceBobject", new CodeCastExpression ("InterfaceB", new CodeVariableReferenceExpression ("t")))); methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("interfaceAobject") , "InterfaceMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("interfaceBobject") , "InterfaceMethod"); methodinvoke2.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( methodinvoke, CodeBinaryOperatorType.Subtract, methodinvoke2))); cd.Members.Add (cmm); } class1 = new CodeTypeDeclaration ("TestSingleInterfaceImp"); class1.BaseTypes.Add (new CodeTypeReference ("System.Object")); class1.BaseTypes.Add (new CodeTypeReference ("InterfaceA")); class1.IsClass = true; nspace.Types.Add (class1); cmm = new CodeMemberMethod (); cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceA")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); class1.Members.Add (cmm); } /*if (Supports (provider, GeneratorSupport.DeclareValueTypes)) { AddScenario ("CheckDeclareValueTypes"); // create first struct to test nested structs // GENERATE (C#): // public struct structA { // public structB innerStruct; // public struct structB { // public int int1; // } // } CodeTypeDeclaration structA = new CodeTypeDeclaration ("structA"); structA.IsStruct = true; CodeTypeDeclaration structB = new CodeTypeDeclaration ("structB"); structB.TypeAttributes = TypeAttributes.NestedPublic; structB.Attributes = MemberAttributes.Public; structB.IsStruct = true; CodeMemberField firstInt = new CodeMemberField (typeof (int), "int1"); firstInt.Attributes = MemberAttributes.Public; structB.Members.Add (firstInt); CodeMemberField innerStruct = new CodeMemberField ("structB", "innerStruct"); innerStruct.Attributes = MemberAttributes.Public; structA.Members.Add (structB); structA.Members.Add (innerStruct); nspace.Types.Add (structA); CodeMemberMethod nestedStructMethod = new CodeMemberMethod (); nestedStructMethod.Name = "NestedStructMethod"; nestedStructMethod.ReturnType = new CodeTypeReference (typeof (int)); nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement ("structA", "varStructA"); nestedStructMethod.Statements.Add (varStructA); nestedStructMethod.Statements.Add ( new CodeAssignStatement ( new CodeFieldReferenceExpression (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("varStructA"), "innerStruct"), "int1"), new CodePrimitiveExpression (3) ) ); nestedStructMethod.Statements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("varStructA"), "innerStruct"), "int1"))); cd.Members.Add (nestedStructMethod); }*/ if (Supports (provider, GeneratorSupport.EntryPointMethod)) { AddScenario ("CheckEntryPointMethod"); CodeEntryPointMethod cep = new CodeEntryPointMethod (); cd.Members.Add (cep); } // goto statements if (Supports (provider, GeneratorSupport.GotoStatements)) { AddScenario ("CheckGotoStatements"); cmm = new CodeMemberMethod (); cmm.Name = "GoToMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i"); cmm.Parameters.Add (param); CodeConditionStatement condstmt = new CodeConditionStatement (new CodeBinaryOperatorExpression ( new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression (1)), new CodeGotoStatement ("comehere")); cmm.Statements.Add (condstmt); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (6))); cmm.Statements.Add (new CodeLabeledStatement ("comehere", new CodeMethodReturnStatement (new CodePrimitiveExpression (7)))); cd.Members.Add (cmm); } if (Supports (provider, GeneratorSupport.NestedTypes)) { AddScenario ("CheckNestedTypes"); cmm = new CodeMemberMethod (); cmm.Name = "CallingPublicNestedScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t", new CodeObjectCreateExpression (new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC")))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "publicNestedClassesMethod", new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); class1 = new CodeTypeDeclaration ("PublicNestedClassA"); class1.IsClass = true; nspace.Types.Add (class1); CodeTypeDeclaration nestedClass = new CodeTypeDeclaration ("PublicNestedClassB1"); nestedClass.IsClass = true; nestedClass.TypeAttributes = TypeAttributes.NestedPublic; class1.Members.Add (nestedClass); nestedClass = new CodeTypeDeclaration ("PublicNestedClassB2"); nestedClass.TypeAttributes = TypeAttributes.NestedPublic; nestedClass.IsClass = true; class1.Members.Add (nestedClass); CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration ("PublicNestedClassC"); innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic; innerNestedClass.IsClass = true; nestedClass.Members.Add (innerNestedClass); cmm = new CodeMemberMethod (); cmm.Name = "publicNestedClassesMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); innerNestedClass.Members.Add (cmm); } // Parameter Attributes if (Supports (provider, GeneratorSupport.ParameterAttributes)) { AddScenario ("CheckParameterAttributes"); CodeMemberMethod method1 = new CodeMemberMethod (); method1.Name = "MyMethod"; method1.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression 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); cd.Members.Add (method1); } // public static members if (Supports (provider, GeneratorSupport.PublicStaticMembers)) { AddScenario ("CheckPublicStaticMembers"); cmm = new CodeMemberMethod (); cmm.Name = "PublicStaticMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (16))); cd.Members.Add (cmm); } // reference parameters if (Supports (provider, GeneratorSupport.ReferenceParameters)) { AddScenario ("CheckReferenceParameters"); 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 CodeArgumentReferenceExpression ("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 CodeArgumentReferenceExpression ("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 CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression ("b")))); cd.Members.Add (cmm); } if (Supports (provider, GeneratorSupport.ReturnTypeAttributes)) { AddScenario ("CheckReturnTypeAttributes"); CodeMemberMethod function1 = new CodeMemberMethod (); function1.Name = "MyFunction"; function1.ReturnType = new CodeTypeReference (typeof (string)); function1.Attributes = MemberAttributes.Public | MemberAttributes.Final; 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"))); cd.Members.Add (function1); } if (Supports (provider, GeneratorSupport.StaticConstructors)) { AddScenario ("CheckStaticConstructors"); cmm = new CodeMemberMethod (); cmm.Name = "TestStaticConstructor"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference (typeof (int)); CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test4", "t", new CodeObjectCreateExpression ("Test4"))); // set then get number cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i") , new CodeArgumentReferenceExpression ("a"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "i"))); cd.Members.Add (cmm); class1 = new CodeTypeDeclaration (); class1.Name = "Test4"; class1.IsClass = true; nspace.Types.Add (class1); class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (int)), "number")); CodeMemberProperty prop = new CodeMemberProperty (); prop.Name = "i"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference (typeof (int)); prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "number"))); prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "number"), new CodePropertySetValueReferenceExpression ())); class1.Members.Add (prop); CodeTypeConstructor ctc = new CodeTypeConstructor (); class1.Members.Add (ctc); } if (Supports (provider, GeneratorSupport.TryCatchStatements)) { AddScenario ("CheckTryCatchStatements"); cmm = new CodeMemberMethod (); cmm.Name = "TryCatchMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement (); tcfstmt.FinallyStatements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (5)))); cmm.Statements.Add (tcfstmt); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cd.Members.Add (cmm); } if (Supports (provider, GeneratorSupport.DeclareEvents)) { AddScenario ("CheckDeclareEvents"); CodeNamespace 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); 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 CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "Text"), new CodePrimitiveExpression ("Test"))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "TabIndex"), new CodePrimitiveExpression (0))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "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; class1.Members.Add (evt); 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); } if (Supports (provider, GeneratorSupport.MultidimensionalArrays)) { // no codedom language represents declaration of multidimensional arrays } }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { // Namespace to hold test scenarios // GENERATES (C#): // namespace NSPC { // using System; // using System.Drawing; // using System.Windows.Forms; // using System.ComponentModel; // } AddScenario ("FindNamespaceComment"); CodeNamespace nspace = new CodeNamespace ("NSPC"); nspace.Comments.Add (new CodeCommentStatement (new CodeComment ("Namespace to hold test scenarios"))); nspace.Imports.Add (new CodeNamespaceImport ("System")); nspace.Imports.Add (new CodeNamespaceImport ("System.Drawing")); nspace.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms")); nspace.Imports.Add (new CodeNamespaceImport ("System.ComponentModel")); cu.Namespaces.Add (nspace); cu.ReferencedAssemblies.Add ("System.Drawing.dll"); cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll"); // GENERATES (C#): // // Class has a method to test static constructors // public class ClassWithMethod { // // This method is used to test a static constructor // public static int TestStaticConstructor(int a) { // // Testing a line comment // TestClass t = new TestClass(); // t.i = a; // return t.i; // } // } AddScenario ("FindClassComment"); CodeTypeDeclaration class1 = new CodeTypeDeclaration ("ClassWithMethod"); class1.IsClass = true; class1.Comments.Add (new CodeCommentStatement ("Class has a method to test static constructors")); nspace.Types.Add (class1); CodeMemberMethod cmm = new CodeMemberMethod (); cmm.Name = "TestStaticConstructor"; AddScenario ("FindMethodComment"); cmm.Comments.Add (new CodeCommentStatement (new CodeComment ("This method is used to test a static constructor"))); cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (int)); AddScenario ("FindLineComment"); cmm.Statements.Add (new CodeCommentStatement ("Testing a line comment")); CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("TestClass", "t", new CodeObjectCreateExpression ("TestClass"))); // set then get number cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i") , new CodeArgumentReferenceExpression ("a"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i"))); class1.Members.Add (cmm); // GENERATES (C#): // public class TestClass { // // This field is an integer counter // private int number; // static TestClass() { // } // // This property allows us to access the integer counter // // We are able to both get and set the value of the counter // public int i { // get { // return number; // } // set { // number = value; // } // } // } class1 = new CodeTypeDeclaration (); class1.Name = "TestClass"; class1.IsClass = true; nspace.Types.Add (class1); AddScenario ("FindFieldComment"); CodeMemberField mfield = new CodeMemberField (new CodeTypeReference (typeof (int)), "number"); mfield.Comments.Add (new CodeCommentStatement ("This field is an integer counter")); class1.Members.Add (mfield); AddScenario ("FindPropertyComment"); CodeMemberProperty prop = new CodeMemberProperty (); prop.Name = "i"; prop.Comments.Add (new CodeCommentStatement ("This property allows us to access the integer counter")); prop.Comments.Add (new CodeCommentStatement ("We are able to both get and set the value of the counter")); prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference (typeof (int)); prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "number"))); prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "number"), new CodePropertySetValueReferenceExpression ())); class1.Members.Add (prop); CodeTypeConstructor ctc = new CodeTypeConstructor (); class1.Members.Add (ctc); // ************* code a comment on an event ************* if (Supports (provider, GeneratorSupport.DeclareEvents)) { // GENERATES (C#): // public class Test : Form { // private Button b = new Button(); // public Test() { // this.Size = new Size(600, 600); // b.Text = "Test"; // b.TabIndex = 0; // b.Location = new Point(400, 525); // this.MyEvent += new EventHandler(this.b_Click); // } // // This is a comment on an event // public event System.EventHandler MyEvent; // private void b_Click(object sender, System.EventArgs e) { // } // } class1 = new CodeTypeDeclaration ("Test"); class1.IsClass = true; class1.BaseTypes.Add (new CodeTypeReference ("Form")); nspace.Types.Add (class1); 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 CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "Text"), new CodePrimitiveExpression ("Test"))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "TabIndex"), new CodePrimitiveExpression (0))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "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); AddScenario ("FindEventComment"); CodeMemberEvent evt = new CodeMemberEvent (); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference ("System.EventHandler"); evt.Attributes = MemberAttributes.Public; evt.Comments.Add (new CodeCommentStatement ("This is a comment on an event")); class1.Members.Add (evt); 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); } if (Supports (provider, GeneratorSupport.DeclareDelegates)) { // GENERATES (C#): // // // This is a delegate comment // public delegate void Delegate(); AddScenario ("FindDelegateComment"); CodeTypeDelegate del = new CodeTypeDelegate ("Delegate"); del.Comments.Add (new CodeCommentStatement ("This is a delegate comment")); nspace.Types.Add (del); } }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { // GENERATES (C#): // [assembly: System.Reflection.AssemblyTitle("MyAssembly")] // [assembly: System.Reflection.AssemblyVersion("1.0.6.2")] // [assembly: System.CLSCompliantAttribute(false)] // // namespace MyNamespace { // using System; // using System.Drawing; // using System.Windows.Forms; // using System.ComponentModel; // CodeNamespace 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); cu.ReferencedAssemblies.Add ("System.Xml.dll"); cu.ReferencedAssemblies.Add ("System.Drawing.dll"); cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll"); // Assembly Attributes if (Supports (provider, GeneratorSupport.AssemblyAttributes)) { AddScenario ("CheckAssemblyAttributes", "Check that assembly attributes get generated properly."); CodeAttributeDeclarationCollection 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)))); } // GENERATES (C#): // [System.Serializable()] // [System.Obsolete("Don\'t use this Class")] // [System.Windows.Forms.AxHost.ClsidAttribute("Class.ID")] // public class MyClass { // #if !WHIDBEY // Everett versions of C# and VB code providers will never have these generated properly if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) AddScenario ("CheckClassAttributes", "Check that class attributes get generated properly."); #else AddScenario ("CheckClassAttributes", "Check that class attributes get generated properly."); #endif CodeTypeDeclaration class1 = new CodeTypeDeclaration (); class1.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")))); class1.CustomAttributes.Add (new CodeAttributeDeclaration (typeof (System.Windows.Forms.AxHost.ClsidAttribute).FullName, new CodeAttributeArgument (new CodePrimitiveExpression ("Class.ID")))); ns.Types.Add (class1); // GENERATES (C#): // [System.Serializable()] // public class NestedClass { // } if (Supports (provider, GeneratorSupport.NestedTypes)) { #if !WHIDBEY // Everett versions of C# and VB code providers will never have these generated properly if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) AddScenario ("CheckNestedClassAttributes", "Check that nested class attributes get generated properly."); #else AddScenario ("CheckNestedClassAttributes", "Check that nested class attributes get generated properly."); #endif CodeTypeDeclaration nestedClass = new CodeTypeDeclaration ("NestedClass"); nestedClass.TypeAttributes = TypeAttributes.NestedPublic; nestedClass.IsClass = true; nestedClass.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Serializable")); class1.Members.Add (nestedClass); } // GENERATES (C#): // [System.Obsolete("Don\'t use this Method")] // [System.ComponentModel.Editor("This", "That")] // public void MyMethod([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] string blah, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] int[] arrayit) { // } AddScenario ("CheckMyMethodAttributes", "Check that attributes are generated properly on MyMethod()."); CodeMemberMethod method1 = new CodeMemberMethod (); method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method1.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")))); CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression (typeof (string), "blah"); if (Supports (provider, GeneratorSupport.ParameterAttributes)) { AddScenario ("CheckParameterAttributes", "Check that parameter attributes are generated properly."); param1.CustomAttributes.Add ( new CodeAttributeDeclaration ( "System.Xml.Serialization.XmlElement", new CodeAttributeArgument ( "Form", new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument ( "IsNullable", new CodePrimitiveExpression (false)))); } method1.Parameters.Add (param1); CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression (typeof (int[]), "arrayit"); if (Supports (provider, GeneratorSupport.ParameterAttributes)) { param2.CustomAttributes.Add ( new CodeAttributeDeclaration ( "System.Xml.Serialization.XmlElement", new CodeAttributeArgument ( "Form", new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument ( "IsNullable", new CodePrimitiveExpression (false)))); } //param2.CustomAttributes.Add(new CodeAttributeDeclaration("System.ParamArray")); method1.Parameters.Add (param2); class1.Members.Add (method1); // GENERATES (C#): // [System.Obsolete("Don\'t use this Function")] // [return: System.Xml.Serialization.XmlIgnoreAttribute()] // [return: System.Xml.Serialization.XmlRootAttribute(Namespace="Namespace Value", ElementName="Root, hehehe")] // public string MyFunction() { // return "Return"; // } // if (Supports (provider, GeneratorSupport.ReturnTypeAttributes)) { AddScenario ("CheckMyFunctionAttributes", "Check return type attributes."); CodeMemberMethod function1 = new CodeMemberMethod (); function1.Attributes = MemberAttributes.Public; 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); } // GENERATES (C#): // [System.Xml.Serialization.XmlElementAttribute()] // private string myField = "hi!"; // AddScenario ("CheckMyFieldAttributes", "Check that attributes are generated properly on MyField."); CodeMemberField field1 = new CodeMemberField (); field1.Name = "myField"; field1.Attributes = MemberAttributes.Public; field1.Type = new CodeTypeReference (typeof (string)); field1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Xml.Serialization.XmlElementAttribute")); field1.InitExpression = new CodePrimitiveExpression ("hi!"); class1.Members.Add (field1); // GENERATES (C#): // [System.Obsolete("Don\'t use this Property")] // public string MyProperty { // get { // return this.myField; // } // } AddScenario ("CheckMyPropertyAttributes", "Check that attributes are generated properly on MyProperty."); CodeMemberProperty prop1 = new CodeMemberProperty (); prop1.Attributes = MemberAttributes.Public; 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); // GENERATES (C#): // [System.Obsolete("Don\'t use this Constructor")] // public MyClass() { // } if (!(provider is JScriptCodeProvider)) AddScenario ("CheckConstructorAttributes", "Check that attributes are generated properly on the constructor."); CodeConstructor const1 = new CodeConstructor (); const1.Attributes = MemberAttributes.Public; const1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Constructor")))); class1.Members.Add (const1); // GENERATES (C#): // [System.Obsolete("Don\'t use this Constructor")] // static MyClass() { // } if (Supports (provider, GeneratorSupport.StaticConstructors)) { // C#, VB and JScript code providers don't generate this properly. This will // be fixed in Beta2 (with the exception of JScript code provider. JScript doesn't // support static constructor custom attributes) //if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) { AddScenario ("CheckStaticConstructorAttributes", "Check that attributes are generated properly on type constructors."); //} CodeTypeConstructor typecons = new CodeTypeConstructor (); typecons.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Constructor")))); class1.Members.Add (typecons); } // GENERATES (C#): // [System.Obsolete ("Don\'t use this entry point")] // public static void Main () { // } if (Supports (provider, GeneratorSupport.EntryPointMethod)) { // C#, VB and JScript code providers don't generate this properly. This will // be fixed in Beta2 (with the exception of JScript code provider. JScript doesn't // support static constructor custom attributes) ///if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) { AddScenario ("CheckEntryPointMethodAttributes", "Check that attributes are generated properly on entry point methods."); //} CodeEntryPointMethod entpoint = new CodeEntryPointMethod (); entpoint.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this entry point")))); class1.Members.Add (entpoint); } if (Supports (provider, GeneratorSupport.DeclareDelegates)) { AddScenario ("CheckDelegateAttributes"); CodeTypeDelegate del = new CodeTypeDelegate ("MyDelegate"); del.TypeAttributes = TypeAttributes.Public; del.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this delegate")))); ns.Types.Add (del); } if (Supports (provider, GeneratorSupport.DeclareEvents)) { // GENERATES (C#): // public class Test : Form { // // private Button b = new Button(); // // AddScenario ("CheckEventAttributes", "test attributes on an event"); 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); // GENERATES (C#): // public Test() { // this.Size = new Size(600, 600); // b.Text = "Test"; // b.TabIndex = 0; // b.Location = new Point(400, 525); // this.MyEvent += new EventHandler(this.b_Click); // } // 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 CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "Text"), new CodePrimitiveExpression ("Test"))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "TabIndex"), new CodePrimitiveExpression (0))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "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); // GENERATES (C#): // [System.CLSCompliantAttribute(false)] // public event System.EventHandler MyEvent; 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); // GENERATES (C#): // private void b_Click(object sender, System.EventArgs e) { // } // } // } // 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); } }
public void RegionsSnippetsAndLinePragmas() { var cu = new CodeCompileUnit(); 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); var 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; 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; 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)); var snippet1 = new CodeSnippetTypeMember(); var 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); cd.Members.Add(evt1); cd.Members.Add(nestedClass1); cd.Members.Add(delegate1); cd.Members.Add(snippet1); cd.Members.Add(field2); cd.Members.Add(method2); cd.Members.Add(constructor2); cd.Members.Add(property2); cd.Members.Add(typeConstructor2); cd.Members.Add(evt2); cd.Members.Add(nestedClass2); cd.Members.Add(delegate2); cd.Members.Add(snippet2); AssertEqual(cu, @"#region Compile Unit Region //------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ namespace Namespace1 { #region Outer Type Region // Outer Type Comment public class Class1 { // Field 1 Comment private string field1; #region Field Region private string field2; #endregion #region Snippet Region #endregion #region Type Constructor Region static Class1() { } #endregion #region Constructor Region public Class1() { #region Statements Region this.field1 = ""value1""; this.field2 = ""value2""; #endregion } #endregion public Class1(string value1, string value2) { } public string Property1 { get { return this.field1; } } #region Property Region public string Property2 { get { return this.field2; } } #endregion public event System.EventHandler Event1; #region Event Region public event System.EventHandler Event2; #endregion public void Method1() { this.Event1(this, System.EventArgs.Empty); } public static void Main() { } #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 class NestedClass1 { } public delegate void nestedDelegate1(object sender, System.EventArgs e); #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 } #endregion } #endregion"); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { // create a namespace CodeNamespace ns = new CodeNamespace ("NS"); ns.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (ns); // create a class that will be used to test the constructors of other classes CodeTypeDeclaration class1 = new CodeTypeDeclaration (); class1.Name = "Test"; class1.IsClass = true; ns.Types.Add (class1); CodeMemberMethod cmm; // construct a method to test class with chained public constructors // GENERATES (C#): // public static string TestingMethod1() { // Test2 t = new Test2(); // return t.accessStringField; // } if (Supports (provider, GeneratorSupport.ChainedConstructorArguments)) { AddScenario ("CheckTestingMethod01"); cmm = new CodeMemberMethod (); cmm.Name = "TestingMethod1"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (String)); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test2", "t", new CodeObjectCreateExpression ("Test2"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "accessStringField"))); class1.Members.Add (cmm); } // construct a method to test class with base public constructor // GENERATES (C#): // public static string TestingMethod2() { // Test3 t = new Test3(); // return t.accessStringField; // } AddScenario ("CheckTestingMethod02"); cmm = new CodeMemberMethod (); cmm.Name = "TestingMethod2"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (String)); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test3", "t", new CodeObjectCreateExpression ("Test3"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "accessStringField"))); class1.Members.Add (cmm); // construct a method to test class with internal constructor // GENERATES (C#): // public static int TestInternalConstruct(int a) { // ClassWInternalConstruct t = new ClassWInternalConstruct(); // t.i = a; // return t.i; // } CodeParameterDeclarationExpression param = null; #if !WHIDBEY // Everett VB compiler doesn't like this construct if (!(provider is VBCodeProvider)) { #endif AddScenario ("CheckTestInternalConstruct"); cmm = new CodeMemberMethod (); cmm.Name = "TestInternalConstruct"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (int)); param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("ClassWInternalConstruct", "t", new CodeObjectCreateExpression ("ClassWInternalConstruct"))); // set then get number cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i") , new CodeArgumentReferenceExpression ("a"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "i"))); class1.Members.Add (cmm); #if !WHIDBEY } #endif // construct a method to test class with static constructor // GENERATES (C#): // public static int TestStaticConstructor(int a) { // Test4 t = new Test4(); // t.i = a; // return t.i; // } if (Supports (provider, GeneratorSupport.StaticConstructors)) { AddScenario ("CheckTestStaticConstructor"); cmm = new CodeMemberMethod (); cmm.Name = "TestStaticConstructor"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (int)); param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test4", "t", new CodeObjectCreateExpression ("Test4"))); // set then get number cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i") , new CodeArgumentReferenceExpression ("a"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "i"))); class1.Members.Add (cmm); } // *** second class, tests chained, public constructors *** // GENERATES (C#): // public class Test2 { // private string stringField; // public Test2() : // this("testingString", null, null) { // } // public Test2(String p1, String p2, String p3) { // this.stringField = p1; // } // public string accessStringField { // get { // return this.stringField; // } // set { // this.stringField = value; // } // } // } class1 = new CodeTypeDeclaration (); class1.Name = "Test2"; class1.IsClass = true; ns.Types.Add (class1); class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (String)), "stringField")); CodeMemberProperty prop = new CodeMemberProperty (); prop.Name = "accessStringField"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference (typeof (String)); prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "stringField"))); prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "stringField"), new CodePropertySetValueReferenceExpression ())); class1.Members.Add (prop); CodeConstructor cctor; if (Supports (provider, GeneratorSupport.ChainedConstructorArguments)) { cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.Public; cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression ("testingString")); cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression (null)); cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression (null)); class1.Members.Add (cctor); } CodeConstructor cc = new CodeConstructor (); cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded; cc.Parameters.Add (new CodeParameterDeclarationExpression ("String", "p1")); cc.Parameters.Add (new CodeParameterDeclarationExpression ("String", "p2")); cc.Parameters.Add (new CodeParameterDeclarationExpression ("String", "p3")); cc.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression () , "stringField"), new CodeArgumentReferenceExpression ("p1"))); class1.Members.Add (cc); // **** third class tests base constructors **** // GENERATES (C#): // public class Test3 : Test2 { // public Test3() : // base("testingString", null, null) { // } // } class1 = new CodeTypeDeclaration (); class1.Name = "Test3"; class1.IsClass = true; class1.BaseTypes.Add (new CodeTypeReference ("Test2")); ns.Types.Add (class1); cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.Public; cctor.BaseConstructorArgs.Add (new CodePrimitiveExpression ("testingString")); cctor.BaseConstructorArgs.Add (new CodePrimitiveExpression (null)); cctor.BaseConstructorArgs.Add (new CodePrimitiveExpression (null)); class1.Members.Add (cctor); if (Supports (provider, GeneratorSupport.StaticConstructors)) { // *** fourth class tests static constructors **** // GENERATES (C#): // public class Test4 { // private int number; // static Test4() { // } // public int i { // get { // return number; // } // set { // number = value; // } // } // } class1 = new CodeTypeDeclaration (); class1.Name = "Test4"; class1.IsClass = true; ns.Types.Add (class1); class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (int)), "number")); prop = new CodeMemberProperty (); prop.Name = "i"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference (typeof (int)); prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "number"))); prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "number"), new CodePropertySetValueReferenceExpression ())); class1.Members.Add (prop); CodeTypeConstructor ctc = new CodeTypeConstructor (); class1.Members.Add (ctc); } // ******* class tests internal constructors ********** // GENERATES (C#): // public class ClassWInternalConstruct { // private int number; // /*FamANDAssem*/ internal ClassWInternalConstruct() { // } // public int i { // get { // return number; // } // set { // number = value; // } // } // } class1 = new CodeTypeDeclaration (); class1.Name = "ClassWInternalConstruct"; class1.IsClass = true; ns.Types.Add (class1); class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (int)), "number")); prop = new CodeMemberProperty (); prop.Name = "i"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference (typeof (int)); prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "number"))); prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "number"), new CodePropertySetValueReferenceExpression ())); class1.Members.Add (prop); if (!(provider is JScriptCodeProvider)) { cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.FamilyOrAssembly; class1.Members.Add (cctor); } // ******** class tests private constructors ********** // GENERATES (C#): // public class ClassWPrivateConstruct { // static int number; // private ClassWPrivateConstruct() { // } // } class1 = new CodeTypeDeclaration (); class1.Name = "ClassWPrivateConstruct"; class1.IsClass = true; ns.Types.Add (class1); cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.Private; class1.Members.Add (cctor); // ******* class tests protected constructors ************** // GENERATES (C#): // public class ClassWProtectedConstruct { // protected ClassWProtectedConstruct() { // } // } class1 = new CodeTypeDeclaration (); class1.Name = "ClassWProtectedConstruct"; class1.IsClass = true; ns.Types.Add (class1); cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.Family; class1.Members.Add (cctor); // class that inherits protected constructor // GENERATES (C#): // public class InheritsProtectedConstruct : ClassWProtectedConstruct { // } class1 = new CodeTypeDeclaration (); class1.Name = "InheritsProtectedConstruct"; class1.IsClass = true; class1.BaseTypes.Add (new CodeTypeReference ("ClassWProtectedConstruct")); ns.Types.Add (class1); }
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 }
protected abstract void GenerateTypeConstructor(CodeTypeConstructor e);
protected override void GenerateTypeConstructor (CodeTypeConstructor e) { Output.Write("static "); OutputIdentifier(CurrentTypeName); Output.Write("()"); StartBlock(); GenerateStatements(e.Statements); EndBlock(); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { #if WHIDBEY CodeNamespace ns = new CodeNamespace("Namespace1"); cu.Namespaces.Add(ns); CodeTypeDeclaration cd = new CodeTypeDeclaration ("Class1"); ns.Types.Add(cd); cd.Comments.Add(new CodeCommentStatement("Outer Type Comment")); CodeMemberField field1 = new CodeMemberField(typeof(String), "field1"); CodeMemberField field2 = new CodeMemberField(typeof(String), "field2"); field2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Foo")); field2.EndDirectives.Add(new CodeRegionDirective (CodeRegionMode.End, String.Empty)); field1.Comments.Add(new CodeCommentStatement("Field 1 Comment")); 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; CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "Method1"; method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; if (Supports(provider, 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 (Supports(provider, 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")); 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"))); CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; constructor1.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "field1"), new CodePrimitiveExpression("value1"))); constructor1.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "field2"), new CodePrimitiveExpression("value2"))); 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(); 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")); 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")); cd.Members.Add(field1); cd.Members.Add(method1); cd.Members.Add(constructor1); cd.Members.Add(property1); if (Supports (provider, GeneratorSupport.EntryPointMethod)) 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(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); } } #endif }