private static CodeMemberMethod CreateOperationCompletedMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeTypeDeclaration operationCompletedEventArgsType, CodeMemberEvent operationCompletedEvent) { CodeObjectCreateExpression expression; CodeMemberMethod method = new CodeMemberMethod(); method.Attributes = MemberAttributes.Private; method.Name = NamingHelper.GetUniqueName(GetOperationCompletedMethodName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations); method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(objectType), "state")); method.ReturnType = new CodeTypeReference(voidType); CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(invokeAsyncCompletedEventArgsTypeName, "e"); statement.InitExpression = new CodeCastExpression(invokeAsyncCompletedEventArgsTypeName, new CodeArgumentReferenceExpression(method.Parameters[0].Name)); CodeVariableReferenceExpression targetObject = new CodeVariableReferenceExpression(statement.Name); if (operationCompletedEventArgsType != null) { expression = new CodeObjectCreateExpression(operationCompletedEventArgsType.Name, new CodeExpression[] { new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[0]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[1]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[2]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[3]) }); } else { expression = new CodeObjectCreateExpression(asyncCompletedEventArgsType, new CodeExpression[] { new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[1]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[2]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[3]) }); } CodeEventReferenceExpression expression3 = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), operationCompletedEvent.Name); CodeDelegateInvokeExpression expression4 = new CodeDelegateInvokeExpression(expression3, new CodeExpression[] { new CodeThisReferenceExpression(), expression }); CodeConditionStatement statement2 = new CodeConditionStatement(new CodeBinaryOperatorExpression(expression3, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), new CodeStatement[] { statement, new CodeExpressionStatement(expression4) }); method.Statements.Add(statement2); clientType.Members.Add(method); return method; }
protected abstract void GenerateEvent(CodeMemberEvent ev, CodeTypeDeclaration d);
/// <summary> /// 默认生成init和clear方法。 /// </summary> protected virtual void genMembers() { _initMethod = genMethod(MemberAttributes.Public | MemberAttributes.Final, typeof(void), getInitMethodName()); _clearMethod = genMethod(MemberAttributes.Public | MemberAttributes.Final, typeof(void), getClearMethodName()); if (controllerType == CTRL_TYPE_LIST || controllerType == CTRL_TYPE_BUTTON_LIST) { //ItemPool类型 CodeTypeDeclaration itemPoolType = new CodeTypeDeclaration(); _type.Members.Add(itemPoolType); itemPoolType.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(SerializableAttribute).Name)); itemPoolType.Attributes = MemberAttributes.Public | MemberAttributes.Final; itemPoolType.IsClass = true; itemPoolType.Name = "ItemPool"; //itemPoolType.BaseTypes.Add(new CodeTypeReference(typeof(ComponentPool<>).Name, new CodeTypeReference(listItemTypeName))); //构造器 CodeConstructor itemPoolTypeConstructor = new CodeConstructor(); itemPoolType.Members.Add(itemPoolTypeConstructor); itemPoolTypeConstructor.Attributes = MemberAttributes.Public | MemberAttributes.Final; itemPoolTypeConstructor.Parameters .append(typeof(Transform).Name, "root") .append(listItemTypeName, "origin"); itemPoolTypeConstructor.BaseConstructorArgs .appendArg("root") .appendArg("origin"); //ItemPool字段 CodeMemberField itemPool = genField(itemPoolType.Name, FIELD_NAME_ITEM_POOL, false); itemPool.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(SerializeField).Name)); //onItemClick事件 CodeMemberEvent onItemClick = null; if (controllerType == CTRL_TYPE_BUTTON_LIST) { onItemClick = genEvent(typeof(Action).Name, "onItemClick", Codo.type(listItemTypeName)); } //itemClickCallback方法 CodeMemberMethod itemClickCallback = null; if (controllerType == CTRL_TYPE_BUTTON_LIST) { itemClickCallback = genMethod(MemberAttributes.Private | MemberAttributes.Final, typeof(void), "itemClickCallback"); itemClickCallback.Parameters.append(listItemTypeName, "item"); itemClickCallback.Statements.append(new CodeConditionStatement( Codo.op(Codo.This.getEvent(onItemClick.Name), CodeBinaryOperatorType.IdentityInequality, Codo.Null), Codo.This.getEvent(onItemClick.Name).invoke(Codo.arg("item")).statement())); } //onItemCreate方法 if (controllerType == CTRL_TYPE_BUTTON_LIST) { genMethod(MemberAttributes.Private | MemberAttributes.Final, typeof(void), "onItemCreate") .appendParam(listItemTypeName, "item") .appendStatement(Codo.arg("item").getMethod("autoReg").invoke()) .appendStatement(Codo.arg("item").getEvent("onClick").attach(Codo.This.getMethod(itemClickCallback.Name))); } else { genPartialMethod("void", "onItemCreate", Codo.parameter(listItemTypeName, "item")); } //onItemRemove方法 if (controllerType == CTRL_TYPE_BUTTON_LIST) { genMethod(MemberAttributes.Private | MemberAttributes.Final, typeof(void), "onItemRemove") .appendParam(listItemTypeName, "item") .appendStatement(Codo.arg("item").getMethod("autoUnreg").invoke()) .appendStatement(Codo.arg("item").getEvent("onClick").remove(Codo.This.getMethod(itemClickCallback.Name))); } else { genPartialMethod("void", "onItemRemove", Codo.parameter(listItemTypeName, "item")); } //initPool方法 var initPool = genMethod(MemberAttributes.Private | MemberAttributes.Final, typeof(void), METHOD_NAME_LIST_INIT_POOL); _initMethod.Statements.Add(Codo.This.getMethod(initPool.Name).invoke().statement()); const string VAR_NAME_ITEM = "item"; initPool.Statements.append(Codo.decVar(listItemTypeName, VAR_NAME_ITEM, string.IsNullOrEmpty(listItemTypeName) ?//有无指定脚本类型? Codo.This.getField(FIELD_NAME_ORIGIN) as CodeExpression : Codo.This.getField(FIELD_NAME_ORIGIN).getMethod(NAME_OF_ADDCOMPO, Codo.type(listItemTypeName)).invoke())); initPool.Statements.Add(Codo.This.getField(FIELD_NAME_ORIGIN).getProp(NAME_OF_GAMEOBJECT).getMethod(NAME_OF_SET_ACTIVE).invoke(Codo.False)); initPool.Statements.Add(Codo.assign(Codo.This.getField(itemPool.Name), Codo.New(itemPoolType.Name, Codo.This.getProp("transform"), Codo.Var(VAR_NAME_ITEM)))); initPool.Statements.Add(Codo.This.getField(itemPool.Name).getEvent("onCreate").attach(Codo.This.getMethod("onItemCreate"))); initPool.Statements.Add(Codo.This.getField(itemPool.Name).getEvent("onRemove").attach(Codo.This.getMethod("onItemRemove"))); //setCount方法 CodeMemberMethod setCount = genMethod(MemberAttributes.Public | MemberAttributes.Final, typeof(void), "setCount"); setCount.Parameters.append(typeof(int), "count"); setCount.Statements.Add(Codo.This.getField(itemPool.Name).getMethod("setCount").invoke(Codo.arg("count"))); //indexer CodeMemberProperty indexer = genIndexer(Codo.type(listItemTypeName)); indexer.Parameters.append(typeof(int), "index"); indexer.HasGet = true; indexer.GetStatements.Add(Codo.Return(Codo.This.getField(itemPool.Name).index(Codo.arg("index")))); //indexOf方法 CodeMemberMethod indexOf = genMethod(MemberAttributes.Public | MemberAttributes.Final, typeof(int), "indexOf"); indexOf.Parameters.append(listItemTypeName, "item"); indexOf.Statements.append(Codo.Return(Codo.This.getField(itemPool.Name).getMethod("indexOf").invoke(Codo.arg("item")))); } }
public static string GenerateWrapper(WrapperClass wrapperClass, Language language) { // Namespace CodeNamespace _namespace = new CodeNamespace(wrapperClass.Namespace); // Comments string comment = @"------------------------------------------------------------------------------" + Environment.NewLine + @" <auto-generated>" + Environment.NewLine + @" This code was generated by '.NET Wrapper Class Generator'" + Environment.NewLine + @" Product Version:" + Assembly.GetExecutingAssembly().GetName().Version + Environment.NewLine + Environment.NewLine + @" Changes to this file may cause incorrect behavior and will be lost if" + Environment.NewLine + @" the code is regenerated." + Environment.NewLine + @" </auto-generated>" + Environment.NewLine + @" ------------------------------------------------------------------------------"; _namespace.Comments.Add(new CodeCommentStatement(comment)); // Class CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration(wrapperClass.ClassName); classDeclaration.IsPartial = wrapperClass.Partial; if (wrapperClass.Sealed) { classDeclaration.TypeAttributes |= TypeAttributes.Sealed; } _namespace.Types.Add(classDeclaration); // Initialization CodeParameterDeclarationExpressionCollection initializationParameters = null; CodeStatementCollection initiazationStatements = null; if (wrapperClass.Partial) { // Initialization method CodeMemberMethod initializer = new CodeMemberMethod(); classDeclaration.Members.Add(initializer); initializer.Name = "InitializeWrapper"; initializer.Attributes = MemberAttributes.Private; { comment = @"***************************************************************" + Environment.NewLine + @" This method should be called by the user-provided constructor!" + Environment.NewLine + @"***************************************************************"; initializer.Comments.Add(new CodeCommentStatement(comment)); } initializationParameters = initializer.Parameters; initiazationStatements = initializer.Statements; } else { // Constructor CodeConstructor constructor = new CodeConstructor(); classDeclaration.Members.Add(constructor); constructor.Attributes = MemberAttributes.Public; initializationParameters = constructor.Parameters; initiazationStatements = constructor.Statements; } // Iterate over the wrapped types foreach (WrappedType wrappedType in wrapperClass.WrappedTypes) { // Fields CodeMemberField field = new CodeMemberField(wrappedType.Type, wrappedType.FieldName); if (wrappedType.Acquisition != Acquisition.UserManaged) { classDeclaration.Members.Add(field); } string memberPrefix = string.Empty; if (wrappedType.PrefixMembers) { memberPrefix = wrappedType.FieldName; memberPrefix = memberPrefix.Substring(0, 1).ToUpper() + memberPrefix.Substring(1); } CodeFieldReferenceExpression fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), wrappedType.FieldName); if (wrappedType.Acquisition == Acquisition.Construct) { // Instantiation CodeObjectCreateExpression instantiation = new CodeObjectCreateExpression(wrappedType.Type); CodeAssignStatement instanceAssignment = new CodeAssignStatement(fieldReference, instantiation); initiazationStatements.Add(instanceAssignment); } else if (wrappedType.Acquisition == Acquisition.Parameter) { // Pass as parameter initializationParameters.Add(new CodeParameterDeclarationExpression(wrappedType.Type, wrappedType.FieldName)); initiazationStatements.Add(new CodeAssignStatement(fieldReference, new CodeVariableReferenceExpression(wrappedType.FieldName))); } else if (wrappedType.Acquisition == Acquisition.Property) { // Set as property CodeMemberProperty property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public; property.HasGet = property.HasSet = true; property.Type = new CodeTypeReference(wrappedType.Type); property.Name = wrappedType.Type.Name; property.GetStatements.Add(new CodeMethodReturnStatement(fieldReference)); property.SetStatements.Add(new CodeAssignStatement(fieldReference, new CodeVariableReferenceExpression("value"))); classDeclaration.Members.Add(property); } // Methods foreach (WrappedMethod wrappedMethod in wrappedType.WrappedMethods) { // Method CodeMemberMethod method = new CodeMemberMethod(); classDeclaration.Members.Add(method); method.Name = memberPrefix + wrappedMethod.Method.Name; method.ReturnType = new CodeTypeReference(wrappedMethod.Method.ReturnType); Generator.SetMember(method, wrappedMethod); if (!string.IsNullOrEmpty(wrappedMethod.Interface)) { method.PrivateImplementationType = new CodeTypeReference(wrappedMethod.Interface); } // Parameters List <CodeExpression> arguments = Generator.SetParameters(method, wrappedMethod.Method.GetParameters()); // Statement CodeMethodInvokeExpression invocation = null; if (!wrappedMethod.Method.IsStatic) { invocation = new CodeMethodInvokeExpression(fieldReference, wrappedMethod.Method.Name, arguments.ToArray()); } else { invocation = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(wrappedType.Type), wrappedMethod.Method.Name, arguments.ToArray()); method.Attributes |= MemberAttributes.Static; } if (wrappedMethod.Method.ReturnType == typeof(void)) { method.Statements.Add(invocation); } else { method.Statements.Add(new CodeMethodReturnStatement(invocation)); } } // Properties foreach (WrappedProperty wrappedProperty in wrappedType.WrappedProperties) { // Property CodeMemberProperty property = new CodeMemberProperty(); classDeclaration.Members.Add(property); property.Name = memberPrefix + wrappedProperty.Property.Name; property.Type = new CodeTypeReference(wrappedProperty.Property.PropertyType); Generator.SetMember(property, wrappedProperty); if (!string.IsNullOrEmpty(wrappedProperty.Interface)) { property.PrivateImplementationType = new CodeTypeReference(wrappedProperty.Interface); } CodePropertyReferenceExpression invocation = null; if (true) // TODO: check if property is static { invocation = new CodePropertyReferenceExpression(fieldReference, wrappedProperty.Property.Name); } else { } // Get statement if (wrappedProperty.Get) { property.GetStatements.Add(new CodeMethodReturnStatement(invocation)); } // Set statement if (wrappedProperty.Set) { property.SetStatements.Add(new CodeAssignStatement(invocation, new CodeVariableReferenceExpression("value"))); } } // Events foreach (WrappedEvent wrappedEvent in wrappedType.WrappedEvents) { // Event MethodInfo eventDelegate = wrappedEvent.Event.EventHandlerType.GetMethod("Invoke"); CodeMemberEvent _event = new CodeMemberEvent(); classDeclaration.Members.Add(_event); _event.Name = memberPrefix + wrappedEvent.Event.Name; _event.Type = new CodeTypeReference(wrappedEvent.Event.EventHandlerType); Generator.SetMember(_event, wrappedEvent); if (!string.IsNullOrEmpty(wrappedEvent.Interface)) { _event.PrivateImplementationType = new CodeTypeReference(wrappedEvent.Interface); } // Event handler/raiser CodeMemberMethod eventHandler = new CodeMemberMethod(); classDeclaration.Members.Add(eventHandler); eventHandler.Name = string.Format("On{0}", _event.Name); eventHandler.ReturnType = new CodeTypeReference(eventDelegate.ReturnType); eventHandler.Attributes = MemberAttributes.Private; List <CodeExpression> arguments = Generator.SetParameters(eventHandler, eventDelegate.GetParameters()); CodeEventReferenceExpression eventReference = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), _event.Name); CodeConditionStatement conditional = new CodeConditionStatement(); eventHandler.Statements.Add(conditional); conditional.Condition = new CodeBinaryOperatorExpression(eventReference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)); CodeDelegateInvokeExpression eventInvocation = new CodeDelegateInvokeExpression(eventReference, arguments.ToArray()); if (eventDelegate.ReturnType == typeof(void)) { conditional.TrueStatements.Add(eventInvocation); } else { conditional.TrueStatements.Add(new CodeMethodReturnStatement(eventInvocation)); } // Event registration CodeEventReferenceExpression wrappedEventReference = new CodeEventReferenceExpression(fieldReference, wrappedEvent.Event.Name); CodeMethodReferenceExpression eventRaiserReference = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), eventHandler.Name); CodeAttachEventStatement eventRegistration = new CodeAttachEventStatement(wrappedEventReference, eventRaiserReference); initiazationStatements.Add(eventRegistration); } } // Generate the code StringWriter stringWriter = new StringWriter(); CodeDomProvider codeProvider = null; if (language == Language.CSharp) { codeProvider = new CSharpCodeProvider(); } else if (language == Language.VBNet) { codeProvider = new VBCodeProvider(); } else { throw new ArgumentException("Specified language is not supported: " + language); } CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BracingStyle = "C"; codeProvider.GenerateCodeFromNamespace(_namespace, stringWriter, options); return(stringWriter.ToString()); }
protected override void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c) { }
protected override void GenerateEvent (CodeMemberEvent e, CodeTypeDeclaration c) { // Bail out if not a class, struct, or interface. if(!IsCurrentClass && !IsCurrentStruct && !IsCurrentInterface) { return; } // Output the event definition. OutputAttributeDeclarations(e.CustomAttributes); if(e.PrivateImplementationType == null) { OutputMemberAccessModifier(e.Attributes); OutputMemberScopeModifier(e.Attributes); Output.Write("event "); OutputTypeNamePair(e.Type, e.Name); } else { Output.Write("event "); OutputTypeNamePair (e.Type, e.PrivateImplementationType + "." + e.Name); } Output.WriteLine(";"); }
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"); }
protected virtual void VisitEvent(CodeMemberEvent member) { }
private static string [] GetStaticEventDefinitionPath(CodeDomProvider codeDomProvider, CodeMemberEvent @event) { var isStatic = @event.Attributes.HasBitMask(MemberAttributes.Static) && @event.PrivateImplementationType == null; if (!isStatic) { return(null); } var path = new List <string> ( ); switch (@event.Attributes & MemberAttributes.AccessMask) { case MemberAttributes.Assembly: path.Add("internal "); break; case MemberAttributes.FamilyAndAssembly: path.Add("internal "); break; case MemberAttributes.Family: path.Add("protected "); break; case MemberAttributes.FamilyOrAssembly: path.Add("protected internal "); break; case MemberAttributes.Private: path.Add("private "); break; case MemberAttributes.Public: path.Add("public "); break; } path.Add("event "); path.Add(codeDomProvider.GetTypeOutput(@event.Type)); path.Add(" "); path.Add(codeDomProvider.CreateEscapedIdentifier(@event.Name)); return(path.ToArray( )); }
void AddAsyncMembers(string messageName, CodeMemberMethod method) { CodeThisReferenceExpression ethis = new CodeThisReferenceExpression(); CodePrimitiveExpression enull = new CodePrimitiveExpression(null); CodeMemberField codeField = new CodeMemberField(typeof(System.Threading.SendOrPostCallback), messageName + "OperationCompleted"); codeField.Attributes = MemberAttributes.Private; CodeTypeDeclaration.Members.Add(codeField); // Event arguments class string argsClassName = classNames.AddUnique(messageName + "CompletedEventArgs", null); CodeTypeDeclaration argsClass = new CodeTypeDeclaration(argsClassName); argsClass.Attributes |= MemberAttributes.Public; #if NET_2_0 argsClass.IsPartial = true; #endif argsClass.BaseTypes.Add(new CodeTypeReference("System.ComponentModel.AsyncCompletedEventArgs")); CodeMemberField resultsField = new CodeMemberField(typeof(object[]), "results"); resultsField.Attributes = MemberAttributes.Private; argsClass.Members.Add(resultsField); CodeConstructor cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Assembly; cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object[]), "results")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(System.Exception), "exception")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "cancelled")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState")); cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("exception")); cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("cancelled")); cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("userState")); CodeExpression thisResults = new CodeFieldReferenceExpression(ethis, "results"); cc.Statements.Add(new CodeAssignStatement(thisResults, new CodeVariableReferenceExpression("results"))); argsClass.Members.Add(cc); int ind = 0; if (method.ReturnType.BaseType != "System.Void") { argsClass.Members.Add(CreateArgsProperty(method.ReturnType, "Result", ind++)); } foreach (CodeParameterDeclarationExpression par in method.Parameters) { if (par.Direction == FieldDirection.Out || par.Direction == FieldDirection.Ref) { argsClass.Members.Add(CreateArgsProperty(par.Type, par.Name, ind++)); } } bool needsArgsClass = (ind > 0); if (needsArgsClass) { asyncTypes.Add(argsClass); } else { argsClassName = "System.ComponentModel.AsyncCompletedEventArgs"; } // Event delegate type CodeTypeDelegate delegateType = new CodeTypeDelegate(messageName + "CompletedEventHandler"); delegateType.Attributes |= MemberAttributes.Public; delegateType.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender")); delegateType.Parameters.Add(new CodeParameterDeclarationExpression(argsClassName, "args")); // Event member CodeMemberEvent codeEvent = new CodeMemberEvent(); codeEvent.Attributes = codeEvent.Attributes & ~MemberAttributes.AccessMask | MemberAttributes.Public; codeEvent.Name = messageName + "Completed"; codeEvent.Type = new CodeTypeReference(delegateType.Name); CodeTypeDeclaration.Members.Add(codeEvent); // Async method (without user state param) CodeMemberMethod am = new CodeMemberMethod(); am.Attributes = MemberAttributes.Public | MemberAttributes.Final; am.Name = method.Name + "Async"; am.ReturnType = new CodeTypeReference(typeof(void)); CodeMethodInvokeExpression inv; inv = new CodeMethodInvokeExpression(ethis, am.Name); am.Statements.Add(inv); // On...Completed method CodeMemberMethod onCompleted = new CodeMemberMethod(); onCompleted.Name = "On" + messageName + "Completed"; onCompleted.Attributes = MemberAttributes.Private | MemberAttributes.Final; onCompleted.ReturnType = new CodeTypeReference(typeof(void)); onCompleted.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "arg")); CodeConditionStatement anIf = new CodeConditionStatement(); CodeExpression eventField = new CodeEventReferenceExpression(ethis, codeEvent.Name); anIf.Condition = new CodeBinaryOperatorExpression(eventField, CodeBinaryOperatorType.IdentityInequality, enull); CodeExpression castedArg = new CodeCastExpression(typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), new CodeVariableReferenceExpression("arg")); CodeStatement invokeArgs = new CodeVariableDeclarationStatement(typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), "invokeArgs", castedArg); anIf.TrueStatements.Add(invokeArgs); CodeDelegateInvokeExpression delegateInvoke = new CodeDelegateInvokeExpression(); delegateInvoke.TargetObject = eventField; delegateInvoke.Parameters.Add(ethis); CodeObjectCreateExpression argsInstance = new CodeObjectCreateExpression(argsClassName); CodeExpression invokeArgsVar = new CodeVariableReferenceExpression("invokeArgs"); if (needsArgsClass) { argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Results")); } argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Error")); argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Cancelled")); argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "UserState")); delegateInvoke.Parameters.Add(argsInstance); anIf.TrueStatements.Add(delegateInvoke); onCompleted.Statements.Add(anIf); // Async method CodeMemberMethod asyncMethod = new CodeMemberMethod(); asyncMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; asyncMethod.Name = method.Name + "Async"; asyncMethod.ReturnType = new CodeTypeReference(typeof(void)); CodeExpression delegateField = new CodeFieldReferenceExpression(ethis, codeField.Name); anIf = new CodeConditionStatement(); anIf.Condition = new CodeBinaryOperatorExpression(delegateField, CodeBinaryOperatorType.IdentityEquality, enull);; CodeExpression delegateRef = new CodeMethodReferenceExpression(ethis, onCompleted.Name); CodeExpression newDelegate = new CodeObjectCreateExpression(typeof(System.Threading.SendOrPostCallback), delegateRef); CodeAssignStatement cas = new CodeAssignStatement(delegateField, newDelegate); anIf.TrueStatements.Add(cas); asyncMethod.Statements.Add(anIf); CodeArrayCreateExpression paramsArray = new CodeArrayCreateExpression(typeof(object)); // Assign parameters CodeIdentifiers paramsIds = new CodeIdentifiers(); foreach (CodeParameterDeclarationExpression par in method.Parameters) { paramsIds.Add(par.Name, null); if (par.Direction == FieldDirection.In || par.Direction == FieldDirection.Ref) { CodeParameterDeclarationExpression inpar = new CodeParameterDeclarationExpression(par.Type, par.Name); am.Parameters.Add(inpar); asyncMethod.Parameters.Add(inpar); inv.Parameters.Add(new CodeVariableReferenceExpression(par.Name)); paramsArray.Initializers.Add(new CodeVariableReferenceExpression(par.Name)); } } inv.Parameters.Add(enull); string userStateName = paramsIds.AddUnique("userState", null); asyncMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), userStateName)); CodeExpression userStateVar = new CodeVariableReferenceExpression(userStateName); asyncMethod.Statements.Add(BuildInvokeAsync(messageName, paramsArray, delegateField, userStateVar)); CodeTypeDeclaration.Members.Add(am); CodeTypeDeclaration.Members.Add(asyncMethod); CodeTypeDeclaration.Members.Add(onCompleted); asyncTypes.Add(delegateType); }
private void ValidateEvent(CodeMemberEvent e) { if (e.CustomAttributes.Count > 0) { ValidateAttributes(e.CustomAttributes); } if (e.PrivateImplementationType != null) { ValidateTypeReference(e.Type); ValidateIdentifier(e, nameof(e.Name), e.Name); } ValidateTypeReferences(e.ImplementationTypes); }
public static CodeTypeDeclaration end(this CodeMemberEvent method) { return(method.UserData["Decleration"] as CodeTypeDeclaration); }
public static IMember GetCompatibleMemberInClass(ProjectDom ctx, IType cls, CodeTypeMember member) { //check for identical property names foreach (IProperty prop in cls.Properties) { if (string.Compare(prop.Name, member.Name, StringComparison.OrdinalIgnoreCase) == 0) { EnsureClassExists(ctx, prop.ReturnType.FullName, GetValidRegion(prop)); CodeMemberProperty memProp = member as CodeMemberProperty; if (memProp == null || !IsTypeCompatible(ctx, prop.ReturnType.FullName, memProp.Type.BaseType)) { throw new MemberExistsException(cls.FullName, MemberType.Property, member, GetValidRegion(prop), cls.CompilationUnit.FileName); } return(prop); } } //check for identical method names foreach (IMethod meth in cls.Methods) { if (string.Compare(meth.Name, member.Name, StringComparison.OrdinalIgnoreCase) == 0) { EnsureClassExists(ctx, meth.ReturnType.FullName, GetValidRegion(meth)); CodeMemberMethod memMeth = member as CodeMemberMethod; if (memMeth == null || !IsTypeCompatible(ctx, meth.ReturnType.FullName, memMeth.ReturnType.BaseType)) { throw new MemberExistsException(cls.FullName, MemberType.Method, member, GetValidRegion(meth), cls.CompilationUnit.FileName); } return(meth); } } //check for identical event names foreach (IEvent ev in cls.Events) { if (string.Compare(ev.Name, member.Name, StringComparison.OrdinalIgnoreCase) == 0) { EnsureClassExists(ctx, ev.ReturnType.FullName, GetValidRegion(ev)); CodeMemberEvent memEv = member as CodeMemberEvent; if (memEv == null || !IsTypeCompatible(ctx, ev.ReturnType.FullName, memEv.Type.BaseType)) { throw new MemberExistsException(cls.FullName, MemberType.Event, member, GetValidRegion(ev), cls.CompilationUnit.FileName); } return(ev); } } //check for identical field names foreach (IField field in cls.Fields) { if (string.Compare(field.Name, member.Name, StringComparison.OrdinalIgnoreCase) == 0) { EnsureClassExists(ctx, field.ReturnType.FullName, GetValidRegion(field)); CodeMemberField memField = member as CodeMemberField; if (memField == null || !IsTypeCompatible(ctx, field.ReturnType.FullName, memField.Type.BaseType)) { throw new MemberExistsException(cls.FullName, MemberType.Field, member, GetValidRegion(field), cls.CompilationUnit.FileName); } return(field); } } //walk down into base classes, if any foreach (IReturnType baseType in cls.BaseTypes) { IType c = ctx.GetType(baseType); if (c == null) { throw new TypeNotFoundException(baseType.FullName, cls.BodyRegion, cls.CompilationUnit.FileName); } IMember mem = GetCompatibleMemberInClass(ctx, c, member); if (mem != null) { return(mem); } } //return null if no match return(null); }
private void TypeGeneratedEventHandler(object sender, TypeGeneratedEventArgs eventArgs) { if (!this.UseDataServiceCollection) { return; } if (eventArgs.TypeSource.BuiltInTypeKind != BuiltInTypeKind.EntityType && eventArgs.TypeSource.BuiltInTypeKind != BuiltInTypeKind.ComplexType) { return; } if (eventArgs.TypeSource.BuiltInTypeKind == BuiltInTypeKind.EntityType) { // Generate EntitySetAttribute only if there is exactly one entity set associated // with the entity type. The DataServiceEntitySetAttribute is not generated for ComplexType(s). EntitySetBase entitySet = this.GetUniqueEntitySetForType((EntityType)eventArgs.TypeSource); if (entitySet != null) { List <CodeAttributeDeclaration> additionalAttributes = eventArgs.AdditionalAttributes; CodeAttributeDeclaration attribute = new CodeAttributeDeclaration( new CodeTypeReference(typeof(System.Data.Services.Common.EntitySetAttribute), CodeTypeReferenceOptions.GlobalReference), new CodeAttributeArgument(new CodePrimitiveExpression(entitySet.Name))); additionalAttributes.Add(attribute); } } //// Determine if type being generated has a base type if (eventArgs.BaseType != null && !String.IsNullOrEmpty(eventArgs.BaseType.BaseType)) { if (this.GetSourceTypes().Where(x => x.BuiltInTypeKind == BuiltInTypeKind.EntityType).Where(x => ((EntityType)x).Name == eventArgs.BaseType.BaseType).Count() != 0) { //// Don't generate the PropertyChanged event and OnPropertyChanged method for derived type classes return; } } //// Add the INotifyPropertyChanged interface List <Type> additionalInterfaces = eventArgs.AdditionalInterfaces; additionalInterfaces.Add(typeof(System.ComponentModel.INotifyPropertyChanged)); //// Add the implementation of the INotifyPropertyChanged interface //// Generate this code: //// //// CSharp: //// //// public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; //// //// protected virtual void OnPropertyChanged(string property) { //// if ((this.PropertyChanged != null)) { //// this.PropertyChanged(this, new global::System.ComponentModel.PropertyChangedEventArgs(property)); //// } //// } //// //// Visual Basic: //// //// Public Event PropertyChanged As Global.System.ComponentModel.PropertyChangedEventHandler Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged //// Protected Overridable Sub OnPropertyChanged(ByVal [property] As String) //// If (Not (Me.PropertyChangedEvent) Is Nothing) Then //// RaiseEvent PropertyChanged(Me, New Global.System.ComponentModel.PropertyChangedEventArgs([property])) //// End If //// End Sub CodeMemberEvent propertyChangedEvent = new CodeMemberEvent(); propertyChangedEvent.Type = new CodeTypeReference(typeof(System.ComponentModel.PropertyChangedEventHandler), CodeTypeReferenceOptions.GlobalReference); propertyChangedEvent.Name = "PropertyChanged"; propertyChangedEvent.Attributes = MemberAttributes.Public; propertyChangedEvent.ImplementationTypes.Add(typeof(System.ComponentModel.INotifyPropertyChanged)); AttributeEmitter.AddGeneratedCodeAttribute(propertyChangedEvent); eventArgs.AdditionalMembers.Add(propertyChangedEvent); CodeMemberMethod propertyChangedMethod = new CodeMemberMethod(); propertyChangedMethod.Name = "OnPropertyChanged"; propertyChangedMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(System.String), CodeTypeReferenceOptions.GlobalReference), "property")); propertyChangedMethod.ReturnType = new CodeTypeReference(typeof(void)); AttributeEmitter.AddGeneratedCodeAttribute(propertyChangedMethod); propertyChangedMethod.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "PropertyChanged"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), new CodeExpressionStatement( new CodeDelegateInvokeExpression( new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "PropertyChanged"), new CodeExpression[] { new CodeThisReferenceExpression(), new CodeObjectCreateExpression(new CodeTypeReference(typeof(System.ComponentModel.PropertyChangedEventArgs), CodeTypeReferenceOptions.GlobalReference), new CodeArgumentReferenceExpression("property")) })))); propertyChangedMethod.Attributes = MemberAttributes.Family; eventArgs.AdditionalMembers.Add(propertyChangedMethod); }
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"); }
/* I want this to be generated : * * public delegate void NumberPressedEventHandler(object sender,NumberPressedEventArgs e); * public event NumberPressedEventHandler NumberPressedEvent; * */ private void CreateCodeTypeDelegate(CodeTypeDeclaration feederCode, EventType evt, bool specificArgs = true, string invokerParam = "e") { string id = evt.id; string eid = evt.id + "Event"; string eidh = eid + "Handler"; string eidArgs = eid + "Args"; CodeTypeDelegate cd = new CodeTypeDelegate(eidh); //add object sender CodeParameterDeclarationExpression sender = new CodeParameterDeclarationExpression("System.Object", "sender"); cd.Parameters.Add(sender); cd.Comments.Add(new CodeCommentStatement("DELEGATE for :" + eid)); cd.Attributes = MemberAttributes.Public; if (evt.parameter != null) { foreach (ParameterType param in evt.parameter) { if (!param.type.Contains(evt.id)) { //specific if parameters are different from the event id CodeParameterDeclarationExpression ee = new CodeParameterDeclarationExpression( param.type, param.name); cd.Parameters.Add(ee); } else { if (param.type.Contains("Args")) { CodeParameterDeclarationExpression ee = new CodeParameterDeclarationExpression( eidArgs, invokerParam); cd.Parameters.Add(ee); } //passes that add EventArgs to the type generated in the .... if (param.type == id) { param.type += "EventArgs"; //add event args to the type (goal: Quickly model argument by just pasting the same id,param e, name to an event CodeParameterDeclarationExpression ee = new CodeParameterDeclarationExpression( eidArgs, invokerParam); cd.Parameters.Add(ee); } } } } else { eidArgs = "Event" + "Args"; //Standard event args for no param events CodeParameterDeclarationExpression ee = new CodeParameterDeclarationExpression( eidArgs, invokerParam); cd.Parameters.Add(ee); } feederCode.Members.Add(cd); //generate the code event /* * I want : * public event NumberPressedEventHandler NumberPressedEvent; * */ CodeMemberEvent cme = new CodeMemberEvent(); cme.Type = new CodeTypeReference(eidh); cme.Name = eid; cme.Comments.Add(new CodeCommentStatement("use to register event " + eid)); cme.Attributes = MemberAttributes.Public; feederCode.Members.Add(cme); }
public void MetadataAttributes() { var cu = new CodeCompileUnit(); var ns = new CodeNamespace(); ns.Name = "MyNamespace"; ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Drawing")); ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); cu.Namespaces.Add(ns); var attrs = cu.AssemblyCustomAttributes; attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly")))); attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2")))); attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false)))); var class1 = new CodeTypeDeclaration() { Name = "MyClass" }; class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable")); class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class")))); ns.Types.Add(class1); var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic }; nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable")); class1.Members.Add(nestedClass); var method1 = new CodeMemberMethod() { Name = "MyMethod" }; method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method")))); method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That")))); var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah"); param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute", new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false)))); method1.Parameters.Add(param1); var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit"); param2.CustomAttributes.Add( new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute", new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false)))); method1.Parameters.Add(param2); class1.Members.Add(method1); var function1 = new CodeMemberMethod(); function1.Name = "MyFunction"; function1.ReturnType = new CodeTypeReference(typeof(string)); function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function")))); function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute")); function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe")))); function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return"))); class1.Members.Add(function1); CodeMemberMethod function2 = new CodeMemberMethod(); function2.Name = "GlobalKeywordFunction"; function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function")))); CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference); CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef); function2.ReturnTypeCustomAttributes.Add(codeAttrib); class1.Members.Add(function2); CodeMemberField field1 = new CodeMemberField(); field1.Name = "myField"; field1.Type = new CodeTypeReference(typeof(string)); field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute")); field1.InitExpression = new CodePrimitiveExpression("hi!"); class1.Members.Add(field1); CodeMemberProperty prop1 = new CodeMemberProperty(); prop1.Name = "MyProperty"; prop1.Type = new CodeTypeReference(typeof(string)); prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property")))); prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField"))); class1.Members.Add(prop1); CodeConstructor const1 = new CodeConstructor(); const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor")))); class1.Members.Add(const1); class1 = new CodeTypeDeclaration("Test"); class1.IsClass = true; class1.BaseTypes.Add(new CodeTypeReference("Form")); ns.Types.Add(class1); CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b"); mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button")); class1.Members.Add(mfield); CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Public; ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"), new CodePrimitiveExpression(600), new CodePrimitiveExpression(600)))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "Text"), new CodePrimitiveExpression("Test"))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "TabIndex"), new CodePrimitiveExpression(0))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"), new CodePrimitiveExpression(400), new CodePrimitiveExpression(525)))); ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler") , new CodeThisReferenceExpression(), "b_Click"))); class1.Members.Add(ctor); CodeMemberEvent evt = new CodeMemberEvent(); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference("System.EventHandler"); evt.Attributes = MemberAttributes.Public; evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false)))); class1.Members.Add(evt); var 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"")] [assembly: System.CLSCompliantAttribute(false)] namespace MyNamespace { using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; [System.Serializable()] [System.Obsolete(""Don\'t use this Class"")] public class MyClass { [System.Xml.Serialization.XmlElementAttribute()] private string myField = ""hi!""; [System.Obsolete(""Don\'t use this Constructor"")] private MyClass() { } [System.Obsolete(""Don\'t use this Property"")] private string MyProperty { get { return this.myField; } } [System.Obsolete(""Don\'t use this Method"")] [System.ComponentModel.Editor(""This"", ""That"")] private 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) { } [System.Obsolete(""Don\'t use this Function"")] [return: System.Xml.Serialization.XmlIgnoreAttribute()] [return: System.Xml.Serialization.XmlRootAttribute(Namespace=""Namespace Value"", ElementName=""Root, hehehe"")] private string MyFunction() { return ""Return""; } [global::System.ObsoleteAttribute(""Don\'t use this Function"")] [return: global::System.Xml.Serialization.XmlIgnoreAttribute()] private void GlobalKeywordFunction() { } [System.Serializable()] public class NestedClass { } } 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); } [System.CLSCompliantAttribute(false)] public event System.EventHandler MyEvent; private void b_Click(object sender, System.EventArgs e) { } } }"); }
public CodeAttachEventStatementExample() { //<Snippet2> // Declares a type to contain the delegate and constructor method. CodeTypeDeclaration type1 = new CodeTypeDeclaration("AttachEventTest"); // Declares an event that needs no custom event arguments class. CodeMemberEvent event1 = new CodeMemberEvent(); event1.Name = "TestEvent"; event1.Type = new CodeTypeReference("System.EventHandler"); // Adds the event to the type members. type1.Members.Add(event1); // Declares a method that matches the System.EventHandler method signature. CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "TestMethod"; method1.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender")); method1.Parameters.Add(new CodeParameterDeclarationExpression("System.EventArgs", "e")); // Adds the method to the type members. type1.Members.Add(method1); // Defines a constructor that attaches a TestDelegate delegate pointing to // the TestMethod method to the TestEvent event. CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; //<Snippet3> // Defines a delegate creation expression that creates an EventHandler delegate pointing to a method named TestMethod. CodeDelegateCreateExpression createDelegate1 = new CodeDelegateCreateExpression( new CodeTypeReference("System.EventHandler"), new CodeThisReferenceExpression(), "TestMethod"); // Attaches an EventHandler delegate pointing to TestMethod to the TestEvent event. CodeAttachEventStatement attachStatement1 = new CodeAttachEventStatement(new CodeThisReferenceExpression(), "TestEvent", createDelegate1); // A C# code generator produces the following source code for the preceeding example code: // this.TestEvent += new System.EventHandler(this.TestMethod); //</Snippet3> // Adds the constructor statements to the construtor. constructor1.Statements.Add(attachStatement1); // Adds the construtor to the type members. type1.Members.Add(constructor1); // A C# code generator produces the following source code for the preceeding example code: // public class AttachEventTest // { // // public AttachEventTest() // { // this.TestEvent += new System.EventHandler(this.TestMethod); // } // // private event System.EventHandler TestEvent; // // private void TestMethod(object sender, System.EventArgs e) // { // } // } //</Snippet2> }
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 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.Obsolete("Don\'t use this Method")] // [System.ComponentModel.Editor("This", "That")] // public void MyMethod(string blah, 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"); method1.Parameters.Add (param1); CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression (typeof (int[]), "arrayit"); method1.Parameters.Add (param2); class1.Members.Add (method1); // 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); 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); } }
private void WriteCodeTypeDelegate(CodeTypeDeclaration feederCode, EventType evt, bool specificArgs = true, string invokerParam = "e") { string id = evt.id; string eid = evt.id + "Event"; string eidh = eid + "Handler"; string eidArgs = eid + "Args"; CodeTypeDelegate cd = new CodeTypeDelegate(eidh); WriteStatePropPlaceholder(cd); //add object sender CodeParameterDeclarationExpression sender = new CodeParameterDeclarationExpression("System.Object", "sender"); cd.Parameters.Add(sender); cd.Comments.Add(new CodeCommentStatement("DELEGATE for :" + eid)); cd.Attributes = MemberAttributes.Public; if (evt.parameter != null) { foreach (ParameterType param in evt.parameter) { if (!param.type.Contains(evt.id)) { //specific if parameters are different from the event id CodeParameterDeclarationExpression ee = new CodeParameterDeclarationExpression( param.type, param.name); cd.Parameters.Add(ee); } else //the Param type name has the Event Id in it, we assume we want to do some more when that happens... { if (param.type.Contains("Args")) { CodeParameterDeclarationExpression ee = new CodeParameterDeclarationExpression( eidArgs, invokerParam); cd.Parameters.Add(ee); } //-------------------------------------------- //TODO See if this section is still relevant and explain what it does more clearly. #region passes to clarify about param type and Event Id. //passes that add EventArgs to the type generated in the .... if (param.type == id) { param.type += OptionsStatic.EventMessageSuffix; //"EventArgs"; //add event args to the type (goal: Quickly model argument by just pasting the same id,param e, name to an event //What does that do?? CodeParameterDeclarationExpression ee = new CodeParameterDeclarationExpression( eidArgs, invokerParam); cd.Parameters.Add(ee); } } #endregion } } else { eidArgs = "Event" + "Args"; //Standard event args for no param events CodeParameterDeclarationExpression ee = new CodeParameterDeclarationExpression( eidArgs, invokerParam); cd.Parameters.Add(ee); } feederCode.Members.Add(cd); //generate the code event /* * I want : * public event NumberPressedEventHandler NumberPressedEvent; * */ CodeMemberEvent cme = new CodeMemberEvent(); cme.Type = new CodeTypeReference(eidh); cme.Name = eid; cme.Comments.Add(new CodeCommentStatement("use to register event " + eid)); cme.Attributes = MemberAttributes.Public; feederCode.Members.Add(cme); }
public void MetadataAttributes() { var cu = new CodeCompileUnit(); var ns = new CodeNamespace(); ns.Name = "MyNamespace"; ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Drawing")); ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); cu.Namespaces.Add(ns); var attrs = cu.AssemblyCustomAttributes; attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly")))); attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2")))); attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false)))); var class1 = new CodeTypeDeclaration() { Name = "MyClass" }; class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable")); class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class")))); ns.Types.Add(class1); var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic }; nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable")); class1.Members.Add(nestedClass); var method1 = new CodeMemberMethod() { Name = "MyMethod" }; method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method")))); method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That")))); var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah"); param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute", new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false)))); method1.Parameters.Add(param1); var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit"); param2.CustomAttributes.Add( new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute", new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false)))); method1.Parameters.Add(param2); class1.Members.Add(method1); var function1 = new CodeMemberMethod(); function1.Name = "MyFunction"; function1.ReturnType = new CodeTypeReference(typeof(string)); function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function")))); function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute")); function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe")))); function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return"))); class1.Members.Add(function1); CodeMemberMethod function2 = new CodeMemberMethod(); function2.Name = "GlobalKeywordFunction"; function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function")))); CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference); CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef); function2.ReturnTypeCustomAttributes.Add(codeAttrib); class1.Members.Add(function2); CodeMemberField field1 = new CodeMemberField(); field1.Name = "myField"; field1.Type = new CodeTypeReference(typeof(string)); field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute")); field1.InitExpression = new CodePrimitiveExpression("hi!"); class1.Members.Add(field1); CodeMemberProperty prop1 = new CodeMemberProperty(); prop1.Name = "MyProperty"; prop1.Type = new CodeTypeReference(typeof(string)); prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property")))); prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField"))); class1.Members.Add(prop1); CodeConstructor const1 = new CodeConstructor(); const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor")))); class1.Members.Add(const1); class1 = new CodeTypeDeclaration("Test"); class1.IsClass = true; class1.BaseTypes.Add(new CodeTypeReference("Form")); ns.Types.Add(class1); CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b"); mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button")); class1.Members.Add(mfield); CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Public; ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"), new CodePrimitiveExpression(600), new CodePrimitiveExpression(600)))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "Text"), new CodePrimitiveExpression("Test"))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "TabIndex"), new CodePrimitiveExpression(0))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"), new CodePrimitiveExpression(400), new CodePrimitiveExpression(525)))); ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler") , new CodeThisReferenceExpression(), "b_Click"))); class1.Members.Add(ctor); CodeMemberEvent evt = new CodeMemberEvent(); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference("System.EventHandler"); evt.Attributes = MemberAttributes.Public; evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false)))); class1.Members.Add(evt); CodeMemberMethod cmm = new CodeMemberMethod(); cmm.Name = "b_Click"; cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender")); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e")); class1.Members.Add(cmm); AssertEqual(cu, @"'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict Off Option Explicit On Imports System Imports System.ComponentModel Imports System.Drawing Imports System.Windows.Forms <Assembly: System.Reflection.AssemblyTitle(""MyAssembly""), _ Assembly: System.Reflection.AssemblyVersion(""1.0.6.2""), _ Assembly: System.CLSCompliantAttribute(false)> Namespace MyNamespace <System.Serializable(), _ System.Obsolete(""Don't use this Class"")> _ Public Class [MyClass] <System.Xml.Serialization.XmlElementAttribute()> _ Private myField As String = ""hi!"" <System.Obsolete(""Don't use this Constructor"")> _ Private Sub New() MyBase.New End Sub <System.Obsolete(""Don't use this Property"")> _ Private ReadOnly Property MyProperty() As String Get Return Me.myField End Get End Property <System.Obsolete(""Don't use this Method""), _ System.ComponentModel.Editor(""This"", ""That"")> _ Private Sub MyMethod(<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal blah As String, <System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal arrayit() As Integer) End Sub <System.Obsolete(""Don't use this Function"")> _ Private Function MyFunction() As <System.Xml.Serialization.XmlIgnoreAttribute(), System.Xml.Serialization.XmlRootAttribute([Namespace]:=""Namespace Value"", ElementName:=""Root, hehehe"")> String Return ""Return"" End Function <Global.System.ObsoleteAttribute(""Don't use this Function"")> _ Private Sub GlobalKeywordFunction() End Sub <System.Serializable()> _ Public Class NestedClass End Class End Class Public Class Test Inherits Form Private b As Button = New Button() Public Sub New() MyBase.New Me.Size = New Size(600, 600) b.Text = ""Test"" b.TabIndex = 0 b.Location = New Point(400, 525) AddHandler MyEvent, AddressOf Me.b_Click End Sub <System.CLSCompliantAttribute(false)> _ Public Event MyEvent As System.EventHandler Private Sub b_Click(ByVal sender As Object, ByVal e As System.EventArgs) End Sub End Class End Namespace"); }
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 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.Obsolete("Don\'t use this Method")] // [System.ComponentModel.Editor("This", "That")] // public void MyMethod(string blah, 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"); method1.Parameters.Add(param1); CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit"); method1.Parameters.Add(param2); class1.Members.Add(method1); // 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); 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); } }
protected override void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c) { Output.Write("event"); }
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 }
public void Visit(CodeMemberEvent o) { g.GenerateEvent(o, g.CurrentClass); }
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); } }
/// <summary> /// Generates the proxy class events. /// </summary> /// <param name="genClass">The generated class.</param> /// <param name="constructor">The generated class constructor.</param> /// <param name="interfaceType">Type of the interface.</param> /// <param name="sourceType">Type of the source.</param> private static void GenerateProxyClassEvents(CodeTypeDeclaration genClass, CodeConstructor constructor, Type interfaceType, Type sourceType) { foreach (EventInfo eventInfo in interfaceType.GetEvents()) { // Event Definition CodeMemberEvent genEvent = new CodeMemberEvent(); genEvent.Attributes = MemberAttributes.Public | MemberAttributes.Final; genEvent.Name = eventInfo.Name; genEvent.Type = new CodeTypeReference(eventInfo.EventHandlerType); genClass.Members.Add(genEvent); // Create event handler CodeMemberMethod genMethod = new CodeMemberMethod(); genMethod.Name = "On" + eventInfo.Name; genMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final; genMethod.ReturnType = new CodeTypeReference(typeof(void)); CodeDelegateInvokeExpression genEventDalegate = new CodeDelegateInvokeExpression(new CodeVariableReferenceExpression("eventDelegate")); foreach (ParameterInfo paramInfo in eventInfo.EventHandlerType.GetMethod("Invoke").GetParameters()) { FieldDirection dir = FieldDirection.In; Type paramType; if (paramInfo.ParameterType.IsByRef) { paramType = paramInfo.ParameterType.GetElementType(); if (paramInfo.IsOut) { dir = FieldDirection.Out; } else { dir = FieldDirection.Ref; } } else { paramType = paramInfo.ParameterType; } genMethod.Parameters.Add(new CodeParameterDeclarationExpression(paramType, paramInfo.Name) { Direction = dir }); if (paramInfo.ParameterType == typeof(object) && paramInfo.Name == "sender" && !paramInfo.ParameterType.IsByRef) { genEventDalegate.Parameters.Add(new CodeThisReferenceExpression()); } else { genEventDalegate.Parameters.Add(new CodeDirectionExpression(dir, new CodeArgumentReferenceExpression(paramInfo.Name))); } } genMethod.Statements.Add(new CodeVariableDeclarationStatement(eventInfo.EventHandlerType, "eventDelegate", new CodeVariableReferenceExpression(eventInfo.Name))); genMethod.Statements.Add(new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("eventDelegate"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeExpressionStatement(genEventDalegate) )); genClass.Members.Add(genMethod); // Subscribe to source event constructor.Statements.Add( new CodeAttachEventStatement( new CodeEventReferenceExpression( new CodeVariableReferenceExpression("_obj"), eventInfo.Name), new CodeMethodReferenceExpression( new CodeThisReferenceExpression(), genMethod.Name ))); } }
public static object CreateDynamicObjectExperimentBinding(string NameClassExperiment, Dictionary <string, object> vars) { object returnData = null; CodeDomProvider codeProvider = new CSharpCodeProvider(); CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace _NameSpace = new CodeNamespace("Tempur"); // Add the new namespace to the compile unit. compileUnit.Namespaces.Add(_NameSpace); // Add the new namespace import for the System namespace. _NameSpace.Imports.Add(new CodeNamespaceImport("System")); _NameSpace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); _NameSpace.Imports.Add(new CodeNamespaceImport("System.Reflection")); _NameSpace.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); CodeTypeDeclaration _ClassTemp = new CodeTypeDeclaration(NameClassExperiment); _ClassTemp.BaseTypes.Add(new CodeTypeReference(typeof(INotifyPropertyChanged))); // Add the new type to the namespace type collection. _NameSpace.Types.Add(_ClassTemp); foreach (KeyValuePair <string, object> variable in vars) { CodeMemberField field = new CodeMemberField(variable.Value.GetType(), "_" + variable.Key); field.Attributes = MemberAttributes.Private; CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = variable.Key; prop.Type = new CodeTypeReference(variable.Value.GetType()); prop.Attributes = MemberAttributes.Public; prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_" + variable.Key))); prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_" + variable.Key), new CodePropertySetValueReferenceExpression())); prop.SetStatements.Add(new CodeSnippetStatement("if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(" + '"' + variable.Key + '"' + "));")); _ClassTemp.Members.Add(field); _ClassTemp.Members.Add(prop); } CodeMemberEvent even = new CodeMemberEvent(); even.Name = "PropertyChanged"; even.Attributes = MemberAttributes.Public; even.Type = new CodeTypeReference(typeof(PropertyChangedEventHandler)); _ClassTemp.Members.Add(even); //IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(NameClassExperiment, false), " "); //// Generate source code using the code generator. //codeProvider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); //// Close the output file. //tw.Close(); //string PathDir = Environment.CurrentDirectory + "\\Script\\" + NameClassScript + ".dll"; CompilerParameters parameters = new CompilerParameters { GenerateInMemory = true }; parameters.ReferencedAssemblies.Add("System.dll"); CompilerResults results = codeProvider.CompileAssemblyFromDom(parameters, new CodeCompileUnit[] { compileUnit }); if (results.Errors.Count > 0) { //var errorMessage = new StringBuilder(); //foreach (CompilerError error in results.Errors) //{ // errorMessage.AppendFormat("{0} {1}", error.Line, // error.ErrorText); //} returnData = null; //returnData = errorMessage.ToString(); } else { Assembly _Assembly = results.CompiledAssembly; Type classType = _Assembly.GetType("Tempur." + NameClassExperiment);; returnData = classType.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null); } return(returnData); }
private static CodeMemberEvent CreateOperationCompletedEvent(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeTypeDeclaration operationCompletedEventArgsType) { CodeMemberEvent event2 = new CodeMemberEvent(); event2.Attributes = MemberAttributes.Public; event2.Type = new CodeTypeReference(eventHandlerType); if (operationCompletedEventArgsType == null) { event2.Type.TypeArguments.Add(asyncCompletedEventArgsType); } else { event2.Type.TypeArguments.Add(operationCompletedEventArgsType.Name); } event2.Name = NamingHelper.GetUniqueName(GetOperationCompletedEventName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations); clientType.Members.Add(event2); return event2; }
static CodeMemberMethod createStatementMethod1(CodeMemberMethod m2, CodeDomProvider cdp, CodeMemberEvent cme, CodeTypeDelegate ctd2, CodeTypeDeclaration ctd) { CodeMemberMethod m = new CodeMemberMethod(); /* * System.CodeDom.CodeArgumentReferenceExpression * System.CodeDom.CodeArrayCreateExpression * System.CodeDom.CodeArrayIndexerExpression * System.CodeDom.CodeBaseReferenceExpression * System.CodeDom.CodeCastExpression * System.CodeDom.CodeDefaultValueExpression * System.CodeDom.CodeDelegateCreateExpression * System.CodeDom.CodeDelegateInvokeExpression * System.CodeDom.CodeDirectionExpression * System.CodeDom.CodeIndexerExpression * System.CodeDom.CodeParameterDeclarationExpression * System.CodeDom.CodePropertyReferenceExpression * * System.CodeDom.CodeSnippetExpression * System.CodeDom.CodeTypeOfExpression * System.CodeDom.CodeTypeReferenceExpression * */ m.ReturnType = new CodeTypeReference(typeof(bool)); m.Name = "test"; m.Attributes = 0; m.Attributes = MemberAttributes.FamilyAndAssembly; m.Attributes = MemberAttributes.FamilyOrAssembly; m.Statements.AddRange(generateStatements1(new CodeVariableReferenceExpression("i"))); generateGotoStuff(cdp, m); // add CodeSnippetExpression generateEventCalls(cdp, cme, m, ctd, m2, ctd2); m.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(false))); return(m); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { // GENERATES (C#): // [assembly: System.CLSCompliantAttribute(false)] // // 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); // this.MyEvent -= new EventHandler(this.b_Click); // } // // [System.CLSCompliantAttribute(false)] // public event System.EventHandler MyEvent; // // private void b_Click(object sender, System.EventArgs e) { // } // } // } // namespace SecondNamespace { // 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); // } // // private event System.EventHandler MyEvent; // // private void b_Click(object sender, System.EventArgs e) { // } // } // } // namespace ThirdNamespace { // 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); // } // // [System.CLSCompliantAttribute(false)] // protected event System.EventHandler MyEvent; // // private void b_Click(object sender, System.EventArgs e) { // } // } // } // namespace FourthNamespace { // 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); // } // // /*FamANDAssem*/ internal event System.EventHandler MyEvent; // // private void b_Click(object sender, System.EventArgs e) { // } // } // } if (Supports (provider, GeneratorSupport.DeclareEvents)) { // ********************************* // public 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.Drawing.dll"); cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll"); // Assembly Attributes if (Supports (provider, GeneratorSupport.AssemblyAttributes)) { CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes; attrs.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new CodeAttributeArgument (new CodePrimitiveExpression (false)))); } CodeTypeDeclaration 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 CodePropertyReferenceExpression (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"))); ctor.Statements.Add (new CodeRemoveEventStatement (new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "MyEvent"), new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler") , new CodeThisReferenceExpression (), "b_Click"))); class1.Members.Add (ctor); CodeMemberEvent evt = new CodeMemberEvent (); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference ("System.EventHandler"); evt.Attributes = MemberAttributes.Public; evt.CustomAttributes.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new CodeAttributeArgument (new CodePrimitiveExpression (false)))); class1.Members.Add (evt); CodeMemberMethod cmm = new CodeMemberMethod (); cmm.Name = "b_Click"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender")); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e")); class1.Members.Add (cmm); // ********************************* // private ns = new CodeNamespace (); ns.Name = "SecondNamespace"; 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); mfield = new CodeMemberField (new CodeTypeReference ("Button"), "b"); mfield.InitExpression = new CodeObjectCreateExpression (new CodeTypeReference ("Button")); class1.Members.Add (mfield); ctor = new CodeConstructor (); ctor.Attributes = MemberAttributes.Public; ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (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)))); CodeAttachEventStatement addevt = new CodeAttachEventStatement (new CodeThisReferenceExpression (), "MyEvent", new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler") , new CodeThisReferenceExpression (), "b_Click")); ctor.Statements.Add (addevt); // remove event statement CodeRemoveEventStatement rem = new CodeRemoveEventStatement (new CodeThisReferenceExpression (), "MyEvent", new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler"), new CodeThisReferenceExpression (), "b_Click")); ctor.Statements.Add (rem); class1.Members.Add (ctor); evt = new CodeMemberEvent (); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference ("System.EventHandler"); evt.Attributes = MemberAttributes.Private; 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); // ********************************* // protected ns = new CodeNamespace (); ns.Name = "ThirdNamespace"; 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); mfield = new CodeMemberField (new CodeTypeReference ("Button"), "b"); mfield.InitExpression = new CodeObjectCreateExpression (new CodeTypeReference ("Button")); class1.Members.Add (mfield); ctor = new CodeConstructor (); ctor.Attributes = MemberAttributes.Public; ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (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)))); addevt = new CodeAttachEventStatement (); addevt.Event = new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "MyEvent"); addevt.Listener = new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler"), new CodeThisReferenceExpression (), "b_Click"); ctor.Statements.Add (addevt); // remove event rem = new CodeRemoveEventStatement (); rem.Event = new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "MyEvent"); rem.Listener = new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler"), new CodeThisReferenceExpression (), "b_Click"); ctor.Statements.Add (rem); class1.Members.Add (ctor); evt = new CodeMemberEvent (); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference ("System.EventHandler"); evt.Attributes = MemberAttributes.Family; evt.CustomAttributes.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new CodeAttributeArgument (new CodePrimitiveExpression (false)))); 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); // ********************************* // internal ns = new CodeNamespace (); ns.Name = "FourthNamespace"; 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); mfield = new CodeMemberField (new CodeTypeReference ("Button"), "b"); mfield.InitExpression = new CodeObjectCreateExpression (new CodeTypeReference ("Button")); class1.Members.Add (mfield); ctor = new CodeConstructor (); ctor.Attributes = MemberAttributes.Public; ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (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); evt = new CodeMemberEvent (); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference ("System.EventHandler"); evt.Attributes = MemberAttributes.FamilyAndAssembly; 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); } }
private void GenerateType(CodeTypeDeclaration type) { this.currentType = type; #if NET_2_0 if (type.StartDirectives.Count > 0) { GenerateDirectives(type.StartDirectives); } #endif foreach (CodeCommentStatement statement in type.Comments) { GenerateCommentStatement(statement); } if (type.LinePragma != null) { GenerateLinePragmaStart(type.LinePragma); } GenerateTypeStart(type); CodeTypeMember[] members = new CodeTypeMember[type.Members.Count]; type.Members.CopyTo(members, 0); #if NET_2_0 if (!Options.VerbatimOrder) #endif { int[] order = new int[members.Length]; for (int n = 0; n < members.Length; n++) { order[n] = Array.IndexOf(memberTypes, members[n].GetType()) * members.Length + n; } Array.Sort(order, members); } // WARNING: if anything is missing in the foreach loop and you add it, add the type in // its corresponding place in CodeTypeMemberComparer class (below) CodeTypeDeclaration subtype = null; foreach (CodeTypeMember member in members) { CodeTypeMember prevMember = this.currentMember; this.currentMember = member; if (prevMember != null && subtype == null) { if (prevMember.LinePragma != null) { GenerateLinePragmaEnd(prevMember.LinePragma); } #if NET_2_0 if (prevMember.EndDirectives.Count > 0) { GenerateDirectives(prevMember.EndDirectives); } #endif } if (options.BlankLinesBetweenMembers) { output.WriteLine(); } subtype = member as CodeTypeDeclaration; if (subtype != null) { GenerateType(subtype); this.currentType = type; continue; } #if NET_2_0 if (currentMember.StartDirectives.Count > 0) { GenerateDirectives(currentMember.StartDirectives); } #endif foreach (CodeCommentStatement statement in member.Comments) { GenerateCommentStatement(statement); } if (member.LinePragma != null) { GenerateLinePragmaStart(member.LinePragma); } CodeMemberEvent eventm = member as CodeMemberEvent; if (eventm != null) { GenerateEvent(eventm, type); continue; } CodeMemberField field = member as CodeMemberField; if (field != null) { GenerateField(field); continue; } CodeEntryPointMethod epmethod = member as CodeEntryPointMethod; if (epmethod != null) { GenerateEntryPointMethod(epmethod, type); continue; } CodeTypeConstructor typeCtor = member as CodeTypeConstructor; if (typeCtor != null) { GenerateTypeConstructor(typeCtor); continue; } CodeConstructor ctor = member as CodeConstructor; if (ctor != null) { GenerateConstructor(ctor, type); continue; } CodeMemberMethod method = member as CodeMemberMethod; if (method != null) { GenerateMethod(method, type); continue; } CodeMemberProperty property = member as CodeMemberProperty; if (property != null) { GenerateProperty(property, type); continue; } CodeSnippetTypeMember snippet = member as CodeSnippetTypeMember; if (snippet != null) { GenerateSnippetMember(snippet); continue; } this.currentMember = prevMember; } // Hack because of previous continue usage if (currentMember != null && !(currentMember is CodeTypeDeclaration)) { if (currentMember.LinePragma != null) { GenerateLinePragmaEnd(currentMember.LinePragma); } #if NET_2_0 if (currentMember.EndDirectives.Count > 0) { GenerateDirectives(currentMember.EndDirectives); } #endif } this.currentType = type; GenerateTypeEnd(type); if (type.LinePragma != null) { GenerateLinePragmaEnd(type.LinePragma); } #if NET_2_0 if (type.EndDirectives.Count > 0) { GenerateDirectives(type.EndDirectives); } #endif }
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 GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c) { Output.WriteLine("[CodeMemberEvent: {0}]", e.ToString()); }
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 }
protected virtual CodeTypeDeclaration GenerateTableClass(Table table) { var _class = new CodeTypeDeclaration() { IsClass = true, IsPartial = true, Name = table.Member, TypeAttributes = TypeAttributes.Public }; _class.CustomAttributes.Add(new CodeAttributeDeclaration("Table", new CodeAttributeArgument("Name", new CodePrimitiveExpression(table.Name)))); // Implement Constructor var constructor = new CodeConstructor() { Attributes = MemberAttributes.Public }; constructor.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "OnCreated"))); _class.Members.Add(constructor); // todo: implement INotifyPropertyChanging // Implement INotifyPropertyChanged _class.BaseTypes.Add(typeof(INotifyPropertyChanged)); var propertyChangedEvent = new CodeMemberEvent() { Type = new CodeTypeReference(typeof(PropertyChangedEventHandler)), Name = "PropertyChanged", Attributes = MemberAttributes.Public }; _class.Members.Add(propertyChangedEvent); var sendPropertyChangedMethod = new CodeMemberMethod() { Attributes = MemberAttributes.Family, Name = "SendPropertyChanged", Parameters = { new CodeParameterDeclarationExpression(typeof(System.String), "propertyName") } }; sendPropertyChangedMethod.Statements.Add ( new CodeConditionStatement ( new CodeSnippetExpression(propertyChangedEvent.Name + " != null"), // todo: covert this to CodeBinaryOperatorExpression new CodeExpressionStatement ( new CodeMethodInvokeExpression ( new CodeMethodReferenceExpression(thisReference, propertyChangedEvent.Name), thisReference, new CodeObjectCreateExpression(typeof(PropertyChangedEventArgs), new CodeArgumentReferenceExpression("propertyName")) ) ) ) ); _class.Members.Add(sendPropertyChangedMethod); // CodeDom does not currently support partial methods. This will be a problem for VB. Will probably be fixed in .net 4 _class.Members.Add(new CodeSnippetTypeMember("\tpartial void OnCreated();")); // todo: add these when the actually get called //partial void OnLoaded(); //partial void OnValidate(System.Data.Linq.ChangeAction action); // columns foreach (Column column in table.Type.Columns) { var type = new CodeTypeReference(column.Type); var columnMember = column.Member ?? column.Name; var field = new CodeMemberField(type, "_" + columnMember); _class.Members.Add(field); var fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name); // CodeDom does not currently support partial methods. This will be a problem for VB. Will probably be fixed in .net 4 string onChangingPartialMethodName = String.Format("On{0}Changing", columnMember); _class.Members.Add(new CodeSnippetTypeMember(String.Format("\tpartial void {0}({1} instance);", onChangingPartialMethodName, column.Type))); string onChangedPartialMethodName = String.Format("On{0}Changed", columnMember); _class.Members.Add(new CodeSnippetTypeMember(String.Format("\tpartial void {0}();", onChangedPartialMethodName))); var property = new CodeMemberProperty(); property.Type = type; property.Name = columnMember; property.Attributes = MemberAttributes.Public | MemberAttributes.Final; property.CustomAttributes.Add ( new CodeAttributeDeclaration ( "Column", new CodeAttributeArgument("Storage", new CodePrimitiveExpression(column.Storage)), new CodeAttributeArgument("Name", new CodePrimitiveExpression(column.Name)), new CodeAttributeArgument("DbType", new CodePrimitiveExpression(column.DbType)), new CodeAttributeArgument("CanBeNull", new CodePrimitiveExpression(column.CanBeNull)), new CodeAttributeArgument("IsPrimaryKey", new CodePrimitiveExpression(column.IsPrimaryKey)) ) ); property.CustomAttributes.Add(new CodeAttributeDeclaration("DebuggerNonUserCode")); property.GetStatements.Add(new CodeMethodReturnStatement(fieldReference)); property.SetStatements.Add ( new CodeConditionStatement ( new CodeSnippetExpression(field.Name + " != value"), // todo: covert this to CodeBinaryOperatorExpression new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, onChangingPartialMethodName, new CodePropertySetValueReferenceExpression())), new CodeAssignStatement(fieldReference, new CodePropertySetValueReferenceExpression()), new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, sendPropertyChangedMethod.Name, new CodePrimitiveExpression(property.Name))), new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, onChangedPartialMethodName)) ) ); _class.Members.Add(property); } // TODO: implement associations // TODO: implement functions / procedures // TODO: Override Equals and GetHashCode return(_class); }
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); } }
private static CodeMemberMethod CreateOperationCompletedMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeTypeDeclaration operationCompletedEventArgsType, CodeMemberEvent operationCompletedEvent) { CodeObjectCreateExpression expression; CodeMemberMethod method = new CodeMemberMethod { Attributes = MemberAttributes.Private, Name = NamingHelper.GetUniqueName(GetOperationCompletedMethodName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations) }; method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(objectType), "state")); method.ReturnType = new CodeTypeReference(voidType); CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(invokeAsyncCompletedEventArgsTypeName, "e") { InitExpression = new CodeCastExpression(invokeAsyncCompletedEventArgsTypeName, new CodeArgumentReferenceExpression(method.Parameters[0].Name)) }; CodeVariableReferenceExpression targetObject = new CodeVariableReferenceExpression(statement.Name); if (operationCompletedEventArgsType != null) { expression = new CodeObjectCreateExpression(operationCompletedEventArgsType.Name, new CodeExpression[] { new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[0]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[1]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[2]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[3]) }); } else { expression = new CodeObjectCreateExpression(asyncCompletedEventArgsType, new CodeExpression[] { new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[1]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[2]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[3]) }); } CodeEventReferenceExpression expression3 = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), operationCompletedEvent.Name); CodeDelegateInvokeExpression expression4 = new CodeDelegateInvokeExpression(expression3, new CodeExpression[] { new CodeThisReferenceExpression(), expression }); CodeConditionStatement statement2 = new CodeConditionStatement(new CodeBinaryOperatorExpression(expression3, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), new CodeStatement[] { statement, new CodeExpressionStatement(expression4) }); method.Statements.Add(statement2); clientType.Members.Add(method); return(method); }
protected abstract void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c);
protected override void GenerateEvent(CodeMemberEvent eventRef, CodeTypeDeclaration declaration) { throw new NotSupportedException(); }
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 CodeDelegateInvokeExpressionExample() { //<Snippet2> // Declares a type to contain the delegate and constructor method. CodeTypeDeclaration type1 = new CodeTypeDeclaration("DelegateInvokeTest"); // Declares an event that accepts a custom delegate type of "TestDelegate". CodeMemberEvent event1 = new CodeMemberEvent(); event1.Name = "TestEvent"; event1.Type = new CodeTypeReference("DelegateInvokeTest.TestDelegate"); type1.Members.Add(event1); // Declares a delegate type called TestDelegate with an EventArgs parameter. CodeTypeDelegate delegate1 = new CodeTypeDelegate("TestDelegate"); delegate1.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender")); delegate1.Parameters.Add(new CodeParameterDeclarationExpression("System.EventArgs", "e")); type1.Members.Add(delegate1); // Declares a method that matches the "TestDelegate" method signature. CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "TestMethod"; method1.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender")); method1.Parameters.Add(new CodeParameterDeclarationExpression("System.EventArgs", "e")); type1.Members.Add(method1); // Defines a constructor that attaches a TestDelegate delegate pointing to the TestMethod method // to the TestEvent event. CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = MemberAttributes.Public; constructor1.Statements.Add(new CodeCommentStatement("Attaches a delegate to the TestEvent event.")); // Creates and attaches a delegate to the TestEvent. CodeDelegateCreateExpression createDelegate1 = new CodeDelegateCreateExpression( new CodeTypeReference("DelegateInvokeTest.TestDelegate"), new CodeThisReferenceExpression(), "TestMethod"); CodeAttachEventStatement attachStatement1 = new CodeAttachEventStatement(new CodeThisReferenceExpression(), "TestEvent", createDelegate1); constructor1.Statements.Add(attachStatement1); constructor1.Statements.Add(new CodeCommentStatement("Invokes the TestEvent event.")); // Invokes the TestEvent. CodeDelegateInvokeExpression invoke1 = new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "TestEvent"), new CodeExpression[] { new CodeThisReferenceExpression(), new CodeObjectCreateExpression("System.EventArgs") }); constructor1.Statements.Add(invoke1); type1.Members.Add(constructor1); // A C# code generator produces the following source code for the preceeding example code: // public class DelegateInvokeTest // { // // public DelegateInvokeTest() // { // // Attaches a delegate to the TestEvent event. // this.TestEvent += new DelegateInvokeTest.TestDelegate(this.TestMethod); // // Invokes the TestEvent event. // this.TestEvent(this, new System.EventArgs()); // } // // private event DelegateInvokeTest.TestDelegate TestEvent; // // private void TestMethod(object sender, System.EventArgs e) // { // } // // public delegate void TestDelegate(object sender, System.EventArgs e); // } //</Snippet2> }
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 }
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 } }