public void Constructor1_Deny_Unrestricted () { CodeTypeDelegate ctd = new CodeTypeDelegate ("mono"); Assert.AreEqual (0, ctd.Parameters.Count, "Parameters"); Assert.AreEqual ("System.Void", ctd.ReturnType.BaseType, "ReturnType"); ctd.ReturnType = new CodeTypeReference ("System.Int32"); }
// Builds a codedom delegate expression and attaches it to the given codedom namespace. public static void Emit(CodeNamespace codeNamespace, DelegateDeclaration del) { // Create the codedom delegate and attach it to the namespace. var codeDelegate = new CodeTypeDelegate(); codeNamespace.Types.Add(codeDelegate); // Assign the name of the delegate codeDelegate.Name = del.Name; // Set the type of the delegate: make sure to check for null if (del.ReturnTypeName == "void") codeDelegate.ReturnType = null; else codeDelegate.ReturnType = new CodeTypeReference(del.ReturnTypeName); // Translate the accessibililty of the delegate MemberAttributes attributes = MemberAttributes.Public; switch(del.Accessibility) { case Accessibility.Public: attributes = MemberAttributes.Public; break; case Accessibility.Protected: attributes = MemberAttributes.Family; break; case Accessibility.Private: attributes = MemberAttributes.Private; break; case Accessibility.Internal: attributes = MemberAttributes.FamilyAndAssembly; break; } // Shared = static if (del.IsShared) attributes |= MemberAttributes.Static; codeDelegate.Attributes = attributes; // Translate the parameters of the delegate. foreach (Expression p in del.Parameters) { if (p is SimpleParameter) // ex "int i" codeDelegate.Parameters.Add(new CodeParameterDeclarationExpression((p as SimpleParameter).TypeName, (p as SimpleParameter).Name)); if (p is DirectionedParameter) // ex "ref int t" { var codeParameter = new CodeParameterDeclarationExpression((p as DirectionedParameter).TypeName, (p as DirectionedParameter).Name); switch ((p as DirectionedParameter).Direction) { case ParameterDirection.Out: codeParameter.Direction = FieldDirection.Out; break; case ParameterDirection.Ref: codeParameter.Direction = FieldDirection.Ref; break; } codeDelegate.Parameters.Add(codeParameter); } } }
public CodeTypeMember ToCodeDom() { CodeTypeDelegate d = new CodeTypeDelegate(); d.Name = this.Name; foreach(ParameterDeclaration p in signature.Parameters) d.Parameters.Add(p.ToCodeDom()); d.ReturnType = signature.ReturnType.TypeReference; base.ToCodeDom(d); return d; }
public void DefaultReturnType () { CodeTypeDelegate delegateType = new CodeTypeDelegate ((string) null); Assert.AreEqual (typeof(void).FullName, delegateType.ReturnType.BaseType); }
public override void AttributesAndTypeTest () { CodeTypeDelegate delegateDecl = new CodeTypeDelegate (); delegateDecl.ReturnType = new CodeTypeReference (typeof (int)); _typeDeclaration = delegateDecl; string code = GenerateAttributesAndType (Options); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<A(), _{0}" + " B()> _{0}" + "Public Delegate Function Test1() As Integer{0}", NewLine), code); }
private static CodeTypeDeclaration CreateDelegateDeclaration(TypeDefinition publicType) { var invokeMethod = publicType.Methods.Single(m => m.Name == "Invoke"); var name = publicType.Name; var index = name.IndexOf('`'); if (index != -1) name = name.Substring(0, index); var declaration = new CodeTypeDelegate(name) { Attributes = MemberAttributes.Public, CustomAttributes = CreateCustomAttributes(publicType), ReturnType = CreateCodeTypeReference(invokeMethod.ReturnType), }; // CodeDOM. No support. Return type attributes. PopulateCustomAttributes(invokeMethod.MethodReturnType, declaration.CustomAttributes, type => ModifyCodeTypeReference(type, "return:")); PopulateGenericParameters(publicType, declaration.TypeParameters); PopulateMethodParameters(invokeMethod, declaration.Parameters); // Of course, CodeDOM doesn't support generic type parameters for delegates. Of course. if (declaration.TypeParameters.Count > 0) { var parameterNames = from parameterType in declaration.TypeParameters.Cast<CodeTypeParameter>() select parameterType.Name; declaration.Name = string.Format("{0}<{1}>", declaration.Name, string.Join(", ", parameterNames)); } return declaration; }
/// ------------------------------------------------------------------------------------ /// <summary> /// Declares the coclass creator class. /// </summary> /// <param name="type">The type name.</param> /// <param name="nameSpace">The name space.</param> /// <param name="attributes">The attributes.</param> /// <returns>coclass creator class declaration.</returns> /// ------------------------------------------------------------------------------------ public CodeTypeDeclaration DeclareCoClassCreator(CodeTypeDeclaration type, CodeNamespace nameSpace, IDictionary attributes) { CodeTypeDeclaration coClassCreator = new CodeTypeDeclaration(type.Name + "Class"); coClassCreator.TypeAttributes = TypeAttributes.Public; coClassCreator.Attributes = MemberAttributes.Static; // .NET 2.0 allows static classes, but unfortunately the C# code generator // doesn't have a way to generate code that way directly yet, so we add a userdata // property and deal with that in our custom code generator. coClassCreator.UserData.Add("static", true); // add delegate declaration string delegateName = coClassCreator.Name + "Delegate"; CodeTypeReference returnType = new CodeTypeReference(type.Name); CodeTypeDelegate deleg = new CodeTypeDelegate(delegateName); deleg.ReturnType = returnType; // There's no way to cause the code generator to put the keyword "private" in front - // all we can do is ommit "public". deleg.TypeAttributes = TypeAttributes.NestedPrivate; coClassCreator.Members.Add(deleg); // add the Create() method declaration CodeMemberMethod createMethod = new CodeMemberMethod(); createMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public; createMethod.Name = "Create"; createMethod.ReturnType = returnType; // Now add this code: // if (Application.OpenForms.Count > 0) //{ // Form form = Application.OpenForms[0]; // if (form.InvokeRequired) // { // return (ITsPropsBldr)form.Invoke(new CreateTsPropsBldrClassDelegate(Create)); // } //} CodeConditionStatement ifStatement = new CodeConditionStatement(); // ENHANCE: this doesn't work very well if we ever want to generate in a language // other then C#. // if (Application.OpenForms.Count > 0) ifStatement.Condition = new CodeBinaryOperatorExpression( new CodeSnippetExpression("Application.OpenForms.Count"), CodeBinaryOperatorType.GreaterThan, new CodePrimitiveExpression(0)); ifStatement.TrueStatements.Add( new CodeSnippetExpression("Form form = Application.OpenForms[0]")); CodeConditionStatement nestedIf = new CodeConditionStatement(); nestedIf.Condition = new CodeSnippetExpression("form.InvokeRequired"); nestedIf.TrueStatements.Add(new CodeMethodReturnStatement( new CodeSnippetExpression( string.Format("({0})form.Invoke(new {1}(Create))", returnType.BaseType, delegateName)))); ifStatement.TrueStatements.Add(nestedIf); createMethod.Statements.Add(ifStatement); createMethod.Statements.Add(new CodeMethodReturnStatement( new CodeObjectCreateExpression(GetCoClassObjectName(type)))); coClassCreator.Members.Add(createMethod); coClassCreator.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); Dictionary<string, IdhCommentProcessor.CommentInfo> childMethods = new Dictionary<string, IdhCommentProcessor.CommentInfo>(); childMethods.Add("Create", new IdhCommentProcessor.CommentInfo("Creates a new " + type.Name + " object", null, 0)); IDLImporter.s_MoreComments.Add(coClassCreator.Name, new IdhCommentProcessor.CommentInfo("Helper class used to create a new instance of the " + type.Name + " COM object", childMethods, 0)); return coClassCreator; }
private CodeTypeDeclaration GetCodeTypeDelegate(TypeDefinition typeDefinition) { if(typeDefinition.IsClass && typeDefinition.BaseType.FullName == "System.MulticastDelegate") { CodeTypeDelegate codeTypeDelegate = new CodeTypeDelegate() { Name = GetTypeName(typeDefinition) }; if(typeDefinition.IsPublic || typeDefinition.IsNestedPublic) { codeTypeDelegate.TypeAttributes = TypeAttributes.Public; } FillCustomAttribute(codeTypeDelegate.CustomAttributes, typeDefinition.CustomAttributes); FillGenericParameters(codeTypeDelegate.TypeParameters, typeDefinition.GenericParameters); MethodDefinition methodDefinition = typeDefinition.Methods.First(i => i.Name == "Invoke"); codeTypeDelegate.ReturnType = new CodeTypeReference(GetTypeReferenceName(methodDefinition.ReturnType)); codeTypeDelegate.Parameters.AddRange(methodDefinition.Parameters.Select(i => GetParameterExpression(i)).ToArray()); if(typeDefinition.HasGenericParameters) { string sign = string.Join(",", typeDefinition.GenericParameters.Select(i => i.FullName)); codeTypeDelegate.Name += '<' + sign + '>'; } return codeTypeDelegate; } return null; }
public void Run () { // using decls cns.Imports.Add (new CodeNamespaceImport ("System")); cns.Imports.Add (new CodeNamespaceImport ("System.Collections")); cns.Imports.Add (new CodeNamespaceImport ("System.ComponentModel")); cns.Imports.Add (new CodeNamespaceImport ("System.Data")); cns.Imports.Add (new CodeNamespaceImport ("System.Runtime.Serialization")); cns.Imports.Add (new CodeNamespaceImport ("System.Xml")); CodeTypeDeclaration dsType = GenerateDataSetType (); cns.Types.Add (dsType); foreach (DataTable dt in ds.Tables) { // 1. table types ([foo]DataTable) // 2. row types ([foo]Row) // 3. delegates ([foo]RowChangedEventHandler) // 4. eventargs ([foo]RowChangeEventArgs) CodeTypeDeclaration dtType = GenerateDataTableType (dt); CodeTypeDeclaration dtRow = GenerateDataRowType (dt); CodeTypeDelegate dtDelegate = new CodeTypeDelegate (opts.TableDelegateName (dt.TableName)); dtDelegate.Parameters.Add (Param (typeof (object), "o")); dtDelegate.Parameters.Add (Param (opts.EventArgsName (dt.TableName), "e")); CodeTypeDeclaration dtEventType = GenerateEventType (dt); // Add types to either DataSet or CodeNamespace if (opts.MakeClassesInsideDataSet) { dsType.Members.Add (dtType); dsType.Members.Add (dtRow); dsType.Members.Add (dtDelegate); dsType.Members.Add (dtEventType); } else { cns.Types.Add (dtType); cns.Types.Add (dtRow); cns.Types.Add (dtDelegate); cns.Types.Add (dtEventType); } } #if NET_2_0 if (cunit == null) return; TableAdapterSchemaInfo adapterInfo = ds.TableAdapterSchemaData; if (adapterInfo != null) { // #325464 debugging //Console.WriteLine (opts.TableAdapterNSName(opts.DataSetName (ds.DataSetName))); CodeNamespace cnsTA = new CodeNamespace (opts.TableAdapterNSName(opts.DataSetName (ds.DataSetName))); CodeTypeDeclaration dtAdapter = GenerateTableAdapterType (adapterInfo); cnsTA.Types.Add (dtAdapter); cunit.Namespaces.Add (cnsTA); } #endif }
internal static void AddDelegate(CodeTypeDeclarationCollection codeClasses, string handlerType, string handlerArgs) { CodeTypeDelegate delegate2 = new CodeTypeDelegate(handlerType); delegate2.CustomAttributes.Add(GeneratedCodeAttribute); delegate2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender")); delegate2.Parameters.Add(new CodeParameterDeclarationExpression(handlerArgs, "e")); delegate2.Comments.Add(new CodeCommentStatement(Res.GetString("CodeRemarks"), true)); codeClasses.Add(delegate2); }
internal static CodeTypeDelegate NewDelegate(string name, CodeTypeReference returnType, string comment, params CodeParameterDeclarationExpression[] parameters) { CodeTypeDelegate dlgt = new CodeTypeDelegate(name); dlgt.ReturnType = returnType; CreateCommont(dlgt.Comments, comment); foreach (CodeParameterDeclarationExpression parameter in parameters) dlgt.Parameters.Add(parameter); return dlgt; }
public static void ReadMetadata(IClass c, out string filePath) { if (c == null) { filePath = null; return; } CodeCompileUnit compileUnit = new CodeCompileUnit(); // add namespace CodeNamespace generatedNamespace = new CodeNamespace(c.Namespace); generatedNamespace.Imports.Add(new CodeNamespaceImport("System")); compileUnit.Namespaces.Add(generatedNamespace); // add type var targetClass = new CodeTypeDeclaration(c.Name); // write attributes AddAttributes(c, targetClass); // write class definition if (c.IsPublic) targetClass.TypeAttributes |= System.Reflection.TypeAttributes.Public; if (c.IsSealed) targetClass.TypeAttributes |= System.Reflection.TypeAttributes.Sealed; // static class limitation - c.IsStatic: https://connect.microsoft.com/VisualStudio/feedback/details/93653/codedom-unable-to-generate-static-events-and-classes targetClass.IsPartial = c.IsPartial; switch (c.ClassType) { case ClassType.Class: targetClass.IsClass = true; break; case ClassType.Enum: targetClass.IsEnum = true; break; case ClassType.Interface: targetClass.IsInterface = true; break; case ClassType.Struct: targetClass.IsStruct = true; break; } // generics foreach (var typeParameter in c.TypeParameters) { var tp = new CodeTypeParameter(typeParameter.Name); foreach (var con in typeParameter.Constraints) { tp.Constraints.Add(con.Name); } targetClass.TypeParameters.Add(tp); } // base types foreach (var basetype in c.BaseTypes) { if (basetype.FullyQualifiedName.Equals("System.Object", StringComparison.OrdinalIgnoreCase)) continue; var baseType = AddGenericBaseTypes(basetype); targetClass.BaseTypes.Add(baseType); } // field members foreach (var f in c.Fields) { if (!f.IsPublic && !f.IsProtected) continue; CodeMemberField field = new CodeMemberField() { Name = f.Name, Attributes = MemberAttributes.Public }; AddDefinition(f, field); AddAttributes(f, field); AddDocumentation(f, field); field.Type = new CodeTypeReference(f.ReturnType.FullyQualifiedName); targetClass.Members.Add(field); } // event members foreach (var e in c.Events) { if (!e.IsPublic && !e.IsProtected) continue; CodeMemberEvent ev = new CodeMemberEvent() { Name = e.Name, Attributes = MemberAttributes.Public, Type = new CodeTypeReference(e.ReturnType.FullyQualifiedName) }; AddDefinition(e, ev); AddDocumentation(e, ev); targetClass.Members.Add(ev); } // properties foreach (var property in c.Properties) { if (!property.IsPublic && !property.IsProtected) continue; CodeMemberProperty p = new CodeMemberProperty() { Name = property.Name, Attributes = MemberAttributes.Public, Type = new CodeTypeReference(property.ReturnType.FullyQualifiedName), HasGet = property.CanGet, HasSet = property.CanSet }; AddAttributes(property, p); AddDefinition(property, p); AddDocumentation(property, p); if (property.IsIndexer) { p.Parameters.Add(new CodeParameterDeclarationExpression("System.Int32", "index")); } targetClass.Members.Add(p); } // methods and constructors foreach (var method in c.Methods) { if (!method.IsPublic && !method.IsProtected) continue; if (method.IsConstructor) { CodeConstructor constructor = new CodeConstructor() { Name = c.Name, Attributes = MemberAttributes.Public }; AddAttributes(method, constructor); AddDefinition(method, constructor); AddParameters(method, constructor); AddDocumentation(method, constructor); targetClass.Members.Add(constructor); } else { CodeMemberMethod m = new CodeMemberMethod() { Name = method.Name, Attributes = MemberAttributes.Public, ReturnType = new CodeTypeReference(method.ReturnType.FullyQualifiedName), }; AddAttributes(method, m); AddDefinition(method, m); AddParameters(method, m); AddDocumentation(method, m); targetClass.Members.Add(m); } } // delegates foreach (var inner in c.InnerClasses) { if (inner.ClassType == ClassType.Delegate) { IMethod invoker = inner.Methods.Where(method => method.Name == "Invoke").FirstOrDefault(); CodeTypeDelegate del = new CodeTypeDelegate(inner.Name) { Attributes = MemberAttributes.Public, ReturnType = new CodeTypeReference(invoker.ReturnType.FullyQualifiedName) }; AddDocumentation(invoker, del); foreach (var p in invoker.Parameters) del.Parameters.Add(new CodeParameterDeclarationExpression(p.ReturnType.FullyQualifiedName, p.Name)); targetClass.Members.Add(del); } } // add class generatedNamespace.Types.Add(targetClass); filePath = WriteTempFile(c.Name, compileUnit); }
/// <summary> /// Visits a <see cref="CodeTypeDelegate"/>. /// </summary> /// <param name="codeTypeDelegate">The <see cref="CodeTypeDelegate"/> to visit.</param> protected virtual void VisitCodeTypeDelegate(CodeTypeDelegate codeTypeDelegate) { if (codeTypeDelegate == null) { return; } this.VisitCodeTypeReference(codeTypeDelegate.ReturnType); this.VisitCodeParameterDeclarationExpressionCollection(codeTypeDelegate.Parameters); this.VisitCodeTypeReferenceCollection(codeTypeDelegate.BaseTypes); this.VisitCodeTypeMemberCollection(codeTypeDelegate.Members); this.VisitCodeTypeParameterCollection(codeTypeDelegate.TypeParameters); this.VisitCodeAttributeDeclarationCollection(codeTypeDelegate.CustomAttributes); this.VisitCodeLinePragma(codeTypeDelegate.LinePragma); this.VisitCodeCommentStatementCollection(codeTypeDelegate.Comments); this.VisitCodeDirectiveCollection(codeTypeDelegate.StartDirectives); this.VisitCodeDirectiveCollection(codeTypeDelegate.EndDirectives); }
public void Run () { // using decls cns.Imports.Add (new CodeNamespaceImport ("System")); cns.Imports.Add (new CodeNamespaceImport ("System.Collections")); cns.Imports.Add (new CodeNamespaceImport ("System.ComponentModel")); cns.Imports.Add (new CodeNamespaceImport ("System.Data")); cns.Imports.Add (new CodeNamespaceImport ("System.Runtime.Serialization")); cns.Imports.Add (new CodeNamespaceImport ("System.Xml")); CodeTypeDeclaration dsType = GenerateDataSetType (); cns.Types.Add (dsType); foreach (DataTable dt in ds.Tables) { // 1. table types ([foo]DataTable) // 2. row types ([foo]Row) // 3. delegates ([foo]RowChangedEventHandler) // 4. eventargs ([foo]RowChangeEventArgs) CodeTypeDeclaration dtType = GenerateDataTableType (dt); CodeTypeDeclaration dtRow = GenerateDataRowType (dt); CodeTypeDelegate dtDelegate = new CodeTypeDelegate (opts.TableDelegateName (dt.TableName, gen)); dtDelegate.Parameters.Add (Param (typeof (object), "o")); dtDelegate.Parameters.Add (Param (opts.EventArgsName (dt.TableName, gen), "e")); CodeTypeDeclaration dtEventType = GenerateEventType (dt); // Add types to either DataSet or CodeNamespace if (opts.MakeClassesInsideDataSet) { dsType.Members.Add (dtType); dsType.Members.Add (dtRow); dsType.Members.Add (dtDelegate); dsType.Members.Add (dtEventType); } else { cns.Types.Add (dtType); cns.Types.Add (dtRow); cns.Types.Add (dtDelegate); cns.Types.Add (dtEventType); } } }
private CodeTypeDelegate CreateTypedRowEventHandler(DataTable table) { CodeTypeDelegate delegate2; string str = this.RowClassName(table); delegate2 = new CodeTypeDelegate(str + "ChangeEventHandler") { TypeAttributes = delegate2.TypeAttributes | TypeAttributes.Public }; delegate2.Parameters.Add(ParameterDecl(typeof(object), "sender")); delegate2.Parameters.Add(ParameterDecl(str + "ChangeEvent", "e")); return delegate2; }
}// CreateTypedRowEvent private CodeTypeDelegate CreateTypedRowEventHandler(DataTable table) { string stRowClassName = RowClassName(table); //\\ public delegate void <RowClassName>ChangeEventHandler(object sender, <RowClassName>ChangeEvent e); CodeTypeDelegate delegateClass = new CodeTypeDelegate(stRowClassName + "ChangeEventHandler"); { delegateClass.TypeAttributes |= System.Reflection.TypeAttributes.Public; delegateClass.Parameters.Add(ParameterDecl(typeof(object), "sender")); delegateClass.Parameters.Add(ParameterDecl(stRowClassName + "ChangeEvent", "e")); } return delegateClass; }// CreateTypedRowEventHandler
public override void AttributesAndTypeTest () { CodeTypeDelegate delegateDecl = new CodeTypeDelegate (); delegateDecl.ReturnType = new CodeTypeReference (typeof (int)); _typeDeclaration = delegateDecl; string code = GenerateAttributesAndType (Options); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "[A()]{0}" + "[B()]{0}" + "public delegate int Test1();{0}", NewLine), code); }
public static void ReadFunctionSpecs( string file, out List<CodeTypeDelegate> delegates, out List<CodeMemberMethod> functions) { StreamReader sr = OpenSpecFile(file); Console.WriteLine("Reading function specs from file: {0}", file); functions = new List<CodeMemberMethod>(); delegates = new List<CodeTypeDelegate>(); do { string line = NextValidLine(sr); if (String.IsNullOrEmpty(line)) break; // Get next OpenGL function while (line.Contains("(") && !sr.EndOfStream) { CodeTypeDelegate d = new CodeTypeDelegate(); d.Attributes = MemberAttributes.Static; d.CustomAttributes.Add(new CodeAttributeDeclaration("System.Security.SuppressUnmanagedCodeSecurity")); // Get function name: d.Name = line.Split(SpecTranslator.Separators, StringSplitOptions.RemoveEmptyEntries)[0]; if (IsExtension(d.Name)) { d.UserData.Add("Extension", true); } else { d.UserData.Add("Extension", false); } //d.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, d.Name)); //d.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, d.Name)); // Get function parameters and return value: do { line = sr.ReadLine(); List<string> words = new List<string>( line.Replace('\t', ' ').Split(SpecTranslator.Separators, StringSplitOptions.RemoveEmptyEntries)); if (words.Count == 0) break; // Identify line: switch (words[0]) { case "return": // Line denotes return value CodeTypeReference tr = new CodeTypeReference( words[1] ); //if (tr.BaseType == "GLvoid") // tr.BaseType = "System.Void"; d.ReturnType = tr; break; case "param": // Line denotes parameter CodeParameterDeclarationExpression p = new CodeParameterDeclarationExpression(); p.Name = words[1]; p.Type = new CodeTypeReference(words[2]); p.Direction = words[3] == "in" ? FieldDirection.In : FieldDirection.Out; if (words[3] != "in") p.CustomAttributes.Add(new CodeAttributeDeclaration("In, Out")); p.Type.ArrayRank = words[4] == "array" ? 1 : 0; d.Parameters.Add(p); break; /* version directive is not used. GetTexParameterIivEXT and GetTexParameterIuivEXT define two(!) versions (why?) case "version": // Line denotes function version (i.e. 1.0, 1.2, 1.5) d.UserData.Add("version", words[1]); break; */ } } while (!sr.EndOfStream); List<CodeMemberMethod> wrappers; SpecTranslator.TranslateDelegate(d, out wrappers); delegates.Add(d); functions.AddRange(wrappers.ToArray()); } } while (!sr.EndOfStream); }
private string WriteEventHandlerClass(CodeNamespace ns, MethodInfo mi) { string clsName = this.axctlEventsType.Name + "_" + mi.Name + "EventHandler"; if (!this.ClassAlreadyExistsInNamespace(ns, clsName)) { CodeTypeDelegate cls = new CodeTypeDelegate { Name = clsName }; cls.Parameters.Add(this.CreateParamDecl(typeof(object).FullName, "sender", false)); cls.Parameters.Add(this.CreateParamDecl(this.axctlEventsType.Name + "_" + mi.Name + "Event", "e", false)); cls.ReturnType = new CodeTypeReference(mi.ReturnType); this.AddClassToNamespace(ns, cls); } return clsName; }
private DelegateNode TranslateToDelegate(CodeTypeDelegate typeDec, Identifier nameSpace, TypeNode declaringType){ Debug.Assert(typeDec != null); DelegateNode d = new DelegateNode(); d.Attributes = this.Translate(typeDec.CustomAttributes, null); d.DeclaringModule = this.targetModule; d.DeclaringType = declaringType; d.Name = Identifier.For(typeDec.Name); d.Namespace = nameSpace; d.Parameters = this.Translate(typeDec.Parameters); d.ReturnType = this.TranslateToTypeNode(typeDec.ReturnType); this.SetTypeFlags(d, typeDec.TypeAttributes); d.Flags |= TypeFlags.Sealed; if (declaringType != null) declaringType.Members.Add(d); return d; }
private CodeTypeDeclaration GetDelegateType () { CodeTypeDeclaration type = new CodeTypeDelegate (); return type; }
protected virtual CodeTypeDelegate Rewrite(CodeTypeDelegate source, ref bool didRewrite) { if (source == null) { return source; } bool didChildRewrite = false; CodeTypeDelegate result = new CodeTypeDelegate(); result.ReturnType = this.Rewrite(source.ReturnType, ref didChildRewrite); this.Rewrite(result.Parameters, source.Parameters, ref didChildRewrite); result.TypeAttributes = source.TypeAttributes; this.Rewrite(result.BaseTypes, source.BaseTypes, ref didChildRewrite); result.IsClass = source.IsClass; result.IsStruct = source.IsStruct; result.IsEnum = source.IsEnum; result.IsInterface = source.IsInterface; result.IsPartial = source.IsPartial; this.Rewrite(result.Members, source.Members, ref didChildRewrite); this.Rewrite(result.TypeParameters, source.TypeParameters, ref didChildRewrite); result.Name = source.Name; result.Attributes = this.Rewrite(source.Attributes, ref didChildRewrite); this.Rewrite(result.CustomAttributes, source.CustomAttributes, ref didChildRewrite); result.LinePragma = this.Rewrite(source.LinePragma, ref didChildRewrite); this.Rewrite(result.Comments, source.Comments, ref didChildRewrite); this.Rewrite(result.StartDirectives, source.StartDirectives, ref didChildRewrite); this.Rewrite(result.EndDirectives, source.EndDirectives, ref didChildRewrite); this.Rewrite(result.UserData, source.UserData, ref didChildRewrite); if (didChildRewrite) { didRewrite = true; return result; } else { return source; } }
/// <summary> /// Main driving routine for building a class /// </summary> void BuildClass(string expression, Dictionary<string, double> vars, bool bSimpleAssign, bool bRetArray, int arrayLen) { // need a string to put the code into _source = new StringBuilder(); StringWriter sw = new StringWriter(_source); //Declare provider and generator CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeGenerator generator = codeProvider.CreateGenerator(sw); CodeGeneratorOptions codeOpts = new CodeGeneratorOptions(); CodeNamespace myNamespace = new CodeNamespace("ExpressionEvaluator"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); //myNamespace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); //Build the class declaration and member variables CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration(); classDeclaration.IsClass = true; classDeclaration.Name = "Calculator"; classDeclaration.Attributes = MemberAttributes.Public; classDeclaration.Members.Add(FieldVariable("ans", typeof(double), MemberAttributes.Private)); classDeclaration.Members.Add(FieldVariable("arrAns", typeof(double[]), MemberAttributes.Private)); foreach (KeyValuePair<string, double> k in vars) classDeclaration.Members.Add(FieldVariable(k.Key, typeof(double), MemberAttributes.Private)); //default constructor CodeConstructor defaultConstructor = new CodeConstructor(); defaultConstructor.Attributes = MemberAttributes.Public; defaultConstructor.Comments.Add(new CodeCommentStatement("Default Constructor for class", true)); classDeclaration.Members.Add(defaultConstructor); CodeTypeDelegate dg = new CodeTypeDelegate("FN1"); dg.ReturnType = new CodeTypeReference(typeof(double)); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p0")); classDeclaration.Members.Add(dg); dg = new CodeTypeDelegate("FN2"); dg.ReturnType = new CodeTypeReference(typeof(double)); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p0")); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p1")); classDeclaration.Members.Add(dg); dg = new CodeTypeDelegate("FN3"); dg.ReturnType = new CodeTypeReference(typeof(double)); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p0")); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p1")); dg.Parameters.Add(new CodeParameterDeclarationExpression(typeof(double), "p2")); classDeclaration.Members.Add(dg); //property classDeclaration.Members.Add(this.MakeProperty("Ans", "ans", typeof(double))); classDeclaration.Members.Add(this.MakeProperty("ArrAns", "arrAns", typeof(double[]))); //Our Calculate Method CodeMemberMethod myMethod = new CodeMemberMethod(); myMethod.Name = "Calculate"; myMethod.Attributes = MemberAttributes.Public; if (bRetArray) { myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("arrAns"), new CodeSnippetExpression("new double["+arrayLen.ToString(CultureInfo.InvariantCulture)+"]"))); myMethod.ReturnType = new CodeTypeReference(typeof(double[])); } else { myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("ans"), new CodeSnippetExpression("0.0"))); myMethod.ReturnType = new CodeTypeReference(typeof(double)); } foreach (KeyValuePair<string, double> k in vars) myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression(k.Key), new CodeSnippetExpression(k.Value.ToString(CultureInfo.InvariantCulture)))); if (bSimpleAssign) //require a full statement? myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression(bRetArray?"arrAns":"ans"), new CodeSnippetExpression(expression))); else myMethod.Statements.Add(new CodeSnippetExpression(expression)); if (bRetArray) myMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "arrAns"))); else myMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Ans"))); classDeclaration.Members.Add(myMethod); //write code myNamespace.Types.Add(classDeclaration); generator.GenerateCodeFromNamespace(myNamespace, sw, codeOpts); sw.Flush(); sw.Close(); }
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.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.Parameters.Add (new CodeParameterDeclarationExpression (typeof(object), "sender")); delegateType.Parameters.Add (new CodeParameterDeclarationExpression (argsClassName, "args")); // Event member CodeMemberEvent codeEvent = new CodeMemberEvent (); 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); }
public void DelegateWithParametersTest () { CodeTypeDelegate type = new CodeTypeDelegate("A"); type.Parameters.Add (new CodeParameterDeclarationExpression ("type", "param")); string code = GenerateCodeFromType (type, Options); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "Public Delegate Sub A(ByVal param As type){0}", NewLine), code); }
private CodeTypeDelegate GenerateTypedRowEventHandler(DesignTable table) { if (table == null) { throw new InternalException("DesignTable should not be null."); } string generatorRowClassName = table.GeneratorRowClassName; CodeTypeDelegate codeTypeDelegate = new CodeTypeDelegate(table.GeneratorRowEvHandlerName); CodeTypeDelegate typeAttributes = codeTypeDelegate; typeAttributes.TypeAttributes = typeAttributes.TypeAttributes | TypeAttributes.Public; codeTypeDelegate.Parameters.Add(CodeGenHelper.ParameterDecl(CodeGenHelper.GlobalType(typeof(object)), "sender")); codeTypeDelegate.Parameters.Add(CodeGenHelper.ParameterDecl(CodeGenHelper.Type(table.GeneratorRowEvArgName), "e")); codeTypeDelegate.CustomAttributes.Add(CodeGenHelper.GeneratedCodeAttributeDecl()); return codeTypeDelegate; }
public override object VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data) { CodeTypeDelegate codeTypeDelegate = new CodeTypeDelegate(delegateDeclaration.Name); codeTypeDelegate.Attributes = ConvMemberAttributes(delegateDeclaration.Modifier); codeTypeDelegate.ReturnType = ConvType(delegateDeclaration.ReturnType); foreach (ParameterDeclarationExpression parameter in delegateDeclaration.Parameters) { codeTypeDelegate.Parameters.Add((CodeParameterDeclarationExpression)VisitParameterDeclarationExpression(parameter, data)); } if (typeDeclarations.Count > 0) { typeDeclarations.Peek().Members.Add(codeTypeDelegate); } else { namespaceDeclarations.Peek().Types.Add(codeTypeDelegate); } return null; }
private void Write(CodeTypeDelegate e){ this.WriteIndent(); TextWriter w = this.writer; switch((e.TypeAttributes & TypeAttributes.VisibilityMask)){ case TypeAttributes.NotPublic: case TypeAttributes.NestedAssembly: w.Write("internal "); break; case TypeAttributes.NestedFamANDAssem: w.Write("/*FamANDAssem*/ internal "); break; case TypeAttributes.NestedFamily: w.Write("protected "); break; case TypeAttributes.NestedFamORAssem: w.Write("protected internal "); break; case TypeAttributes.NestedPrivate: w.Write("private "); break; case TypeAttributes.Public: case TypeAttributes.NestedPublic: w.Write("public "); break; } w.Write("delegate "); this.Write(e.ReturnType); w.Write(' '); this.WriteIdentifier(e.Name); this.Write(e.Parameters); w.WriteLine(';'); }
/// <summary> /// Generates the tracking changes classes. /// </summary> /// <returns></returns> public static IEnumerable<CodeTypeDeclaration> GenerateTrackingChangesClasses() { var classList = new List<CodeTypeDeclaration>(); classList.Add(CreateObjectsToCollectionProperties("ObjectsOriginalFromCollectionProperties", "Dictionary<string, ObjectList>")); classList.Add(CreateObjectsToCollectionProperties("ObjectsAddedToCollectionProperties", "Dictionary<string, ObjectList>")); classList.Add(CreateObjectsToCollectionProperties("ObjectsRemovedFromCollectionProperties", "Dictionary<string, ObjectList>")); classList.Add(CreateObjectsToCollectionProperties("PropertyValueStatesDictionary", "Dictionary<string, PropertyValueState>")); // TrackableCollection var trackableCollectionClass = new CodeTypeDeclaration("TrackableCollection") { IsClass = true, IsPartial = false, TypeAttributes = TypeAttributes.Public, }; trackableCollectionClass.TypeParameters.Add(new CodeTypeParameter("T")); var ctr = new CodeTypeReference("ObservableCollection"); ctr.TypeArguments.Add("T"); trackableCollectionClass.BaseTypes.Add(ctr); var codeTemplate = new CodeSnippetTypeMember(); codeTemplate.Text = Resources.TrackableCollection_cs; trackableCollectionClass.Members.Add(codeTemplate); trackableCollectionClass.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "TrackableCollection class")); trackableCollectionClass.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "TrackableCollection")); classList.Add(trackableCollectionClass); // ObjectChangeTracker class var trackableClass = new CodeTypeDeclaration("ObjectChangeTracker") { IsClass = true, IsPartial = false, TypeAttributes = TypeAttributes.Public, }; trackableClass.BaseTypes.Add(typeof(INotifyPropertyChanged)); var cm = new CodeSnippetTypeMember(); cm.Text = Resources.ObjectChangeTracker_cs; trackableClass.Members.Add(cm); trackableClass.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Tracking changes class")); trackableClass.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "Tracking changes class")); classList.Add(trackableClass); var notifyTrackableDelegate = new CodeTypeDelegate("NotifyTrackableCollectionChangedEventHandler"); notifyTrackableDelegate.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender")); notifyTrackableDelegate.Parameters.Add(new CodeParameterDeclarationExpression("NotifyCollectionChangedEventArgs", "e")); notifyTrackableDelegate.Parameters.Add(new CodeParameterDeclarationExpression("system.string", "propertyName")); notifyTrackableDelegate.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "NotifyTrackableCollectionChangedEventHandler class")); notifyTrackableDelegate.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "NotifyTrackableCollectionChangedEventHandler")); classList.Add(notifyTrackableDelegate); // enum ObjectState var objectStateenum = new CodeTypeDeclaration("ObjectState") { IsEnum = true, TypeAttributes = TypeAttributes.Public }; // Creates the enum member objectStateenum.Members.Add(new CodeMemberField(typeof(int), "Unchanged")); objectStateenum.Members.Add(new CodeMemberField(typeof(int), "Added")); objectStateenum.Members.Add(new CodeMemberField(typeof(int), "Modified")); objectStateenum.Members.Add(new CodeMemberField(typeof(int), "Deleted")); objectStateenum.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "ObjectState enum")); objectStateenum.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "ObjectState")); classList.Add(objectStateenum); // ObjectList class var ObjectListClass = new CodeTypeDeclaration("ObjectList") { IsClass = true, IsPartial = false, TypeAttributes = TypeAttributes.Public, }; ctr = new CodeTypeReference("List"); ctr.TypeArguments.Add(typeof(object)); ObjectListClass.BaseTypes.Add(ctr); ObjectListClass.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "ObjectList class")); ObjectListClass.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "ObjectList")); classList.Add(ObjectListClass); // ObjectStateChangingEventArgs class var objectStateChangingEventArgsClass = new CodeTypeDeclaration("ObjectStateChangingEventArgs") { IsClass = true, IsPartial = false, TypeAttributes = TypeAttributes.Public, }; ctr = new CodeTypeReference("EventArgs"); objectStateChangingEventArgsClass.BaseTypes.Add(ctr); codeTemplate = new CodeSnippetTypeMember(); codeTemplate.Text = Resources.ObjectStateChangingEventArgs_cs; objectStateChangingEventArgsClass.Members.Add(codeTemplate); objectStateChangingEventArgsClass.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "ObjectStateChangingEventArgs class")); objectStateChangingEventArgsClass.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "ObjectStateChangingEventArgs")); classList.Add(objectStateChangingEventArgsClass); // ObjectChangeTracker class var propertyValueStateClass = new CodeTypeDeclaration("PropertyValueState") { IsClass = true, IsPartial = false, TypeAttributes = TypeAttributes.Public, }; cm = new CodeSnippetTypeMember(); cm.Text = Resources.PropertyValueState_cs; propertyValueStateClass.Members.Add(cm); propertyValueStateClass.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "PropertyValueState class")); propertyValueStateClass.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "PropertyValueState class")); classList.Add(propertyValueStateClass); return classList; }
public void BaseTypes () { CodeTypeDelegate delegateType = new CodeTypeDelegate ((string) null); Assert.AreEqual (1, delegateType.BaseTypes.Count); Assert.AreEqual ("System.Delegate", delegateType.BaseTypes[0].BaseType); }