/// <summary> /// Serializes a series of SetChildIndex() statements for each control iln a child control collection in /// reverse order. /// </summary> private void SerializeZOrder(IDesignerSerializationManager manager, CodeStatementCollection statements, Control control) { using (TraceScope("ControlCodeDomSerializer::SerializeZOrder()")) { // Push statements in reverse order so the first guy in the // collection is the last one to be brought to the front. for (int i = control.Controls.Count - 1; i >= 0; i--) { // Only serialize this control if it is (a) sited and // (b) not being privately inherited Control child = control.Controls[i]; if (child.Site is null || child.Site.Container != control.Site.Container) { continue; } InheritanceAttribute attr = (InheritanceAttribute)TypeDescriptor.GetAttributes(child)[typeof(InheritanceAttribute)]; if (attr.InheritanceLevel == InheritanceLevel.InheritedReadOnly) { continue; } // Create the "control.Controls.SetChildIndex" call CodeExpression controlsCollection = new CodePropertyReferenceExpression(SerializeToExpression(manager, control), "Controls"); CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(controlsCollection, "SetChildIndex"); CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); methodInvoke.Method = method; // Fill in parameters CodeExpression childControl = SerializeToExpression(manager, child); methodInvoke.Parameters.Add(childControl); methodInvoke.Parameters.Add(SerializeToExpression(manager, 0)); CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke); statements.Add(statement); } } }
/// <summary> /// Generates an OnChanging-pattern for the given property /// </summary> /// <param name="property">The code property</param> /// <returns></returns> public static CodeStatement CreateOnChangingEventPattern(this CodeMemberProperty property, CodeTypeReference eventType, CodeExpression eventData) { CodeTypeReference handlerType; if (eventType == null) { handlerType = typeof(EventHandler).ToTypeReference(); } else { handlerType = typeof(EventHandler <>).ToTypeReference(eventType); } var changingEvent = new CodeMemberEvent() { Name = property.Name + "Changing", Type = handlerType, Attributes = MemberAttributes.Public | MemberAttributes.Final }; changingEvent.WriteDocumentation(string.Format("Gets fired before the {0} property changes its value", property.Name)); if (eventType == null) { eventType = new CodeTypeReference(typeof(EventArgs).Name); eventData = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(eventType), "Empty"); } var onChanging = CreateRaiseMethod(changingEvent, eventType); var dependent = property.DependentMembers(true); dependent.Add(onChanging); dependent.Add(changingEvent); var onChangedRef = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), onChanging.Name); return(new CodeExpressionStatement(new CodeMethodInvokeExpression(onChangedRef, eventData))); }
public static CodeStatement CreateTryCatchStatement(CodeTypeDeclaration classType, CodeStatement statement, CodeGenerationInfo generationInfo) { var tryStatement = new CodeTryCatchFinallyStatement(); tryStatement.TryStatements.Add(statement); var catchClause = new CodeCatchClause("e"); var methodRefExp = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression($"{generationInfo.BaseNamespace}.CremaData"), "InvokeErrorOccuredEvent"); var methodInvokeExp = new CodeMethodInvokeExpression(methodRefExp, new CodeThisReferenceExpression(), new CodeVariableReferenceExpression("e")); var conditionStatement = new CodeConditionStatement() { Condition = new CodeBinaryOperatorExpression(methodInvokeExp, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(false)) }; conditionStatement.TrueStatements.Add(new CodeThrowExceptionStatement(new CodeVariableReferenceExpression("e"))); catchClause.Statements.Add(conditionStatement); tryStatement.CatchClauses.Add(catchClause); return(tryStatement); }
public void Constructor1() { CodeExpression expression = new CodeExpression(); string methodName = "mono"; CodeMethodReferenceExpression cmre = new CodeMethodReferenceExpression( expression, methodName); Assert.IsNotNull(cmre.MethodName, "#1"); Assert.AreSame(methodName, cmre.MethodName, "#2"); Assert.IsNotNull(cmre.TargetObject, "#3"); Assert.AreSame(expression, cmre.TargetObject, "#4"); Assert.IsNotNull(cmre.TypeArguments, "#5"); Assert.AreEqual(0, cmre.TypeArguments.Count, "#6"); cmre = new CodeMethodReferenceExpression((CodeExpression)null, (string)null); Assert.IsNotNull(cmre.MethodName, "#7"); Assert.AreEqual(string.Empty, cmre.MethodName, "#8"); Assert.IsNull(cmre.TargetObject, "#9"); }
/// <summary> /// Generates the update domain operation entry /// </summary> /// <param name="codeGenContext">The code gen context.></param> /// <param name="businessLogicClass">The business logic class.</param> /// <param name="entity">The entity.</param> protected override void GenerateUpdateMethod(CodeGenContext codeGenContext, CodeTypeDeclaration businessLogicClass, BusinessLogicEntity entity) { string currentParameterName = "current" + entity.ClrType.Name; // public void Update$EntityName$($entityType$ current) CodeMemberMethod method = new CodeMemberMethod(); businessLogicClass.Members.Add(method); LinqToSqlEntity ltsEntity = (LinqToSqlEntity)entity; method.Name = "Update" + CodeGenUtilities.MakeLegalEntityName(entity.Name); method.Attributes = MemberAttributes.Public | MemberAttributes.Final; // final needed to prevent virtual // parameter declaration method.Parameters.Add(new CodeParameterDeclarationExpression(entity.ClrType.Name, currentParameterName)); if (!ltsEntity.HasTimestampMember) { // this.ChangeSet.GetOriginal(current) CodeExpression changeSetRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ChangeSet"); CodeMethodReferenceExpression getOrigMethodRef = new CodeMethodReferenceExpression(changeSetRef, "GetOriginal"); CodeMethodInvokeExpression changeSetGetOrig = new CodeMethodInvokeExpression(getOrigMethodRef, new CodeArgumentReferenceExpression(currentParameterName)); // this.DataContext.$TablePropertyName$.Attach(current, this.ChangeSet.GetOriginal(current)) CodeExpression contextRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "DataContext"); CodeExpression tableRef = new CodePropertyReferenceExpression(contextRef, ltsEntity.TablePropertyName); CodeMethodInvokeExpression attachCall = new CodeMethodInvokeExpression(tableRef, "Attach", new CodeArgumentReferenceExpression(currentParameterName), changeSetGetOrig); method.Statements.Add(attachCall); } else { // this.DataContext.$TablePropertyName$.Attach(current, true) CodeExpression contextRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "DataContext"); CodeExpression tableRef = new CodePropertyReferenceExpression(contextRef, ltsEntity.TablePropertyName); CodeMethodInvokeExpression attachCall = new CodeMethodInvokeExpression(tableRef, "Attach", new CodeArgumentReferenceExpression(currentParameterName), new CodePrimitiveExpression(true)); method.Statements.Add(attachCall); } }
public CodeExpression VisitArgument(Argument a) { Debug.Print(" arg {0}", a); if (a is ListArgument) { return(m.Appl( new CodeVariableReferenceExpression("__flatten___"), new CodeNamedArgument(a.name.Accept(this), null))); } if (a.name == null) { Debug.Assert(a.defval != null); return(a.defval.Accept(this)); } else { var compFor = a.defval as CompFor; if (compFor != null) { var v = compFor.variable.Accept(this); var c = Translate(v, compFor); var mr = new CodeMethodReferenceExpression(c, "Select"); var s = m.Appl(mr, new CodeExpression[] { m.Lambda( new CodeExpression[] { v }, a.name.Accept(this)) }); return(s); } else { return(new CodeNamedArgument( a.name.Accept(this), a.defval != null ? a.defval.Accept(this) : null)); } } }
private static void CreateCreateFromTableMethod(CodeTypeDeclaration classType, TableInfo tableInfo, CodeGenerationInfo generationInfo) { var cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Name = "createFromTable"; cmm.Parameters.Add("reader", "ITable", "table"); cmm.ReturnType = tableInfo.GetCodeType(); // verify hashValue { var css = CreateCompareTypeStatement(classType, tableInfo, generationInfo); var tst = CremaDataClassCreator.CreateTryCatchStatement(classType, css, generationInfo.IsDevmode); cmm.Statements.Add(css); } // create instance; { var create = new CodeObjectCreateExpression(tableInfo.GetCodeType()); cmm.Statements.AddVariableDeclaration(tableInfo.GetCodeType().BaseType, "instance", create); } // invoke readFromFile { var instance = new CodeVariableReferenceExpression("instance"); var table = new CodeVariableReferenceExpression("table"); var readFromTable = new CodeMethodReferenceExpression(instance, "readFromTable"); cmm.Statements.Add(new CodeMethodInvokeExpression(readFromTable, table)); } // return instance; { var instance = new CodeVariableReferenceExpression("instance"); cmm.Statements.AddMethodReturn(instance); } classType.Members.Add(cmm); }
private static void CreateSetChildsMethod(CodeTypeDeclaration classType, TableInfo tableInfo, CodeGenerationInfo generationInfo) { foreach (var item in generationInfo.GetChilds(tableInfo)) { var cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.FamilyAndAssembly | MemberAttributes.Static; cmm.Name = "Set" + item.TableName; cmm.Parameters.Add(tableInfo.GetRowCodeType(), "target"); cmm.Parameters.Add(typeof(string), "childName"); cmm.Parameters.Add(item.GetRowCodeType(), 1, "childs"); // invoke setParent { var target = new CodeVariableReferenceExpression("target"); var childs = new CodeVariableReferenceExpression("childs"); var setParent = new CodeMethodReferenceExpression(tableInfo.GetRowCodeTypeExpression(), "setParent"); setParent.TypeArguments.Add(tableInfo.GetRowCodeType()); setParent.TypeArguments.Add(item.GetRowCodeType()); var invokeSetParent = new CodeMethodInvokeExpression(setParent, target, childs); cmm.Statements.AddExpression(invokeSetParent); } // create and assign child table { var target = new CodeVariableReferenceExpression("target"); var childName = new CodeVariableReferenceExpression("childName"); var childs = new CodeVariableReferenceExpression("childs"); var field = item.GetFieldExpression(target); var createFromRows = new CodeMethodReferenceExpression(item.GetCodeTypeExpression(), "createFromRows"); var InvokeCreateFromRows = new CodeMethodInvokeExpression(createFromRows, childName, childs); cmm.Statements.AddAssign(field, InvokeCreateFromRows); } classType.Members.Add(cmm); } }
private void SerializeZOrder(IDesignerSerializationManager manager, CodeStatementCollection statements, Control control) { for (int i = control.Controls.Count - 1; i >= 0; i--) { Control control2 = control.Controls[i]; if (control2.Site != null && control2.Site.Container == control.Site.Container) { InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(control2)[typeof(InheritanceAttribute)]; if (inheritanceAttribute.InheritanceLevel != InheritanceLevel.InheritedReadOnly) { CodeExpression targetObject = new CodePropertyReferenceExpression(base.SerializeToExpression(manager, control), "Controls"); CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(targetObject, "SetChildIndex"); CodeMethodInvokeExpression codeMethodInvokeExpression = new CodeMethodInvokeExpression(); codeMethodInvokeExpression.Method = method; CodeExpression value = base.SerializeToExpression(manager, control2); codeMethodInvokeExpression.Parameters.Add(value); codeMethodInvokeExpression.Parameters.Add(base.SerializeToExpression(manager, 0)); CodeExpressionStatement value2 = new CodeExpressionStatement(codeMethodInvokeExpression); statements.Add(value2); } } } }
/// <inheritdoc /> protected override bool HandleDynamic(CodeMethodReferenceExpression obj, Context ctx) { if (obj.TargetObject != null) { WrapIfNecessaryAndHandle(obj.TargetObject, ctx); ctx.Writer.Write("."); ctx.Writer.Write(obj.MethodName); } else { ctx.Writer.Write(obj.MethodName.AsVbId()); } if (obj.TypeArguments.Count > 0) { ctx.Writer.Write("(Of "); GeneralUtils.HandleCollectionCommaSeparated(obj.TypeArguments.Cast <CodeTypeReference>(), ctx.HandlerProvider.TypeReferenceHandler, ctx); ctx.Writer.Write(")"); } return(true); }
public void Constructor0() { CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression(); Assert.IsNotNull(cmie.Method, "#1"); Assert.AreEqual(string.Empty, cmie.Method.MethodName, "#2"); Assert.IsNull(cmie.Method.TargetObject, "#3"); Assert.AreEqual(0, cmie.Method.TypeArguments.Count, "#4"); Assert.IsNotNull(cmie.Parameters, "#5"); Assert.AreEqual(0, cmie.Parameters.Count, "#6"); CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(); cmie.Method = method; Assert.IsNotNull(cmie.Method, "#7"); Assert.AreSame(method, cmie.Method, "#8"); cmie.Method = null; Assert.IsNotNull(cmie.Method, "#9"); Assert.AreEqual(string.Empty, cmie.Method.MethodName, "#10"); Assert.IsNull(cmie.Method.TargetObject, "#11"); Assert.AreEqual(0, cmie.Method.TypeArguments.Count, "#12"); }
CodeMemberProperty CreateProperty(Widget widget, string returnType, CodeMemberField backingField, CodeMemberField backingFuncField, CodeMemberMethod creator, CodeExpression parent) { var ensureViewRef = new CodeMethodReferenceExpression(parent, "__EnsureView"); ensureViewRef.TypeArguments.Add(new CodeTypeReference(returnType)); var backingFuncFieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backingFuncField.Name); var ensureViewInvoke = new CodeMethodInvokeExpression( ensureViewRef, new CodeExpression [] { backingFuncFieldReference, new CodeDirectionExpression(FieldDirection.Ref, new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backingField.Name)), } ); var ret = new CodeMemberProperty { Name = widget.Name, HasGet = true, HasSet = false, Type = new CodeTypeReference(returnType), LinePragma = new CodeLinePragma(widget.FileName, widget.Line), Attributes = MemberAttributes.Public | MemberAttributes.Final }; var assignFunc = new CodeAssignStatement( backingFuncFieldReference, new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), creator.Name) ); ret.GetStatements.Add(new CodeConditionStatement( new CodeBinaryOperatorExpression(backingFuncFieldReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)), new CodeStatement [] { assignFunc } )); ret.GetStatements.Add(new CodeMethodReturnStatement(ensureViewInvoke)); return(ret); }
public void GeneratePool(CodeTypeDeclarationCollection typeList, CompileDirectives compileDirectives) { Guid nameExt = Guid.NewGuid(); string name = "pool" + nameExt.ToString("N").ToUpper(); CodeTypeDeclaration type = new CodeTypeDeclaration(name); type.IsClass = true; type.TypeAttributes = System.Reflection.TypeAttributes.Class | System.Reflection.TypeAttributes.Sealed; CodeExpression typeRef = new CodeTypeReferenceExpression(name); typeList.Add(type); int index = 0; //add all the pools to the type. foreach (KeyValuePair <ByteArray, CodeFieldReferenceExpression> item in this.pool) { //create the static member string itemName = "item" + index++; //decompressed in code CodeMethodReferenceExpression decompressMethod = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(ConstantArray.ArrayUtils)), "SimpleDecompress"); CodeExpression dataCode = ShaderBytes.ToArray(item.Key.Array, compileDirectives); CodeMemberField field = new CodeMemberField(typeof(byte[]), itemName); field.Attributes = MemberAttributes.Static | MemberAttributes.Public | MemberAttributes.Final; //assign it inline field.InitExpression = new CodeMethodInvokeExpression(decompressMethod, dataCode); type.Members.Add(field); item.Value.FieldName = itemName; item.Value.TargetObject = typeRef; } }
private static void CreateSetChildsMethod(CodeTypeDeclaration classType, TableInfo tableInfo, CodeGenerationInfo generationInfo) { foreach (var item in generationInfo.GetChilds(tableInfo)) { var cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.FamilyAndAssembly | MemberAttributes.Static; cmm.Name = tableInfo.TableName + "Set" + item.TableName; cmm.Parameters.Add(tableInfo.GetRowCodeType(CodeType.Pointer), "target"); var arrayType = new CodeTypeReference(item.GetRowCodeType(CodeType.Pointer), 1); arrayType.SetCodeType(CodeType.Const | CodeType.Reference); var childNameType = new CodeTypeReference(typeof(string)); childNameType.SetCodeType(CodeType.Const | CodeType.Reference); cmm.Parameters.Add(childNameType, "childName"); cmm.Parameters.Add(arrayType, "childs"); { var methodRefExp = new CodeMethodReferenceExpression(null, "SetParent"); //methodRefExp.TypeArguments.Add(tableInfo.GetRowCodeType()); //methodRefExp.TypeArguments.Add(item.GetRowCodeType()); var methodInvokeExp = new CodeMethodInvokeExpression(methodRefExp, new CodeVariableReferenceExpression("target"), new CodeVariableReferenceExpression("childs")); cmm.Statements.AddExpression(methodInvokeExp); } { var target = new CodeVariablePointerExpression("target"); var childName = new CodeVariablePointerExpression("childName"); var childs = new CodeVariableReferenceExpression("childs"); var targetField = item.GetFieldExpression(target); var targetInstance = new CodeObjectCreateExpression(item.GetCodeType(CodeType.None), childName, childs); cmm.Statements.AddAssign(targetField, targetInstance); } classType.Members.Add(cmm); } }
public static CodeExpression Call( this CodeExpression targetObject, String methodName, Type[] typeParameters, params CodeExpression[] parameters ) { if (targetObject == null) { throw Logger.Fatal.ArgumentNull(nameof(targetObject)); } if (methodName == null) { throw Logger.Fatal.ArgumentNull(nameof(methodName)); } if (typeParameters == null) { typeParameters = new Type[0]; } if (parameters == null) { parameters = new CodeExpression[0]; } var method = new CodeMethodReferenceExpression( targetObject, methodName, typeParameters.Select( t => new CodeTypeReference(t) ).ToArray() ); return(new CodeMethodInvokeExpression(method, parameters)); }
protected override CodeExpression CreateRouteDefinitionsPropertyGetter() { var newRouteDefinition = new CodeObjectCreateExpression(routeDefinition.Name); var defaultForArea = new CodeMethodInvokeExpression(newRouteDefinition, "DefaultForArea"); var areaIs = new CodeMethodInvokeExpression(defaultForArea, "Is", new CodePrimitiveExpression(node.Action.Controller.Area)); var defaultForController = new CodeMethodInvokeExpression(areaIs, "DefaultForController"); var controllerIsRef = new CodeMethodReferenceExpression(defaultForController, "Is", new CodeTypeReference(node.Action.Controller.FullName)); var controllerIs = new CodeMethodInvokeExpression(controllerIsRef); var defaultForAction = new CodeMethodInvokeExpression(controllerIs, "DefaultForAction"); var actionIs = new CodeMethodInvokeExpression(defaultForAction, "Is", new CodePrimitiveExpression(node.Action.Name)); var requiredParameterReferences = new CodeTypeReferenceExpression(routeDefinition.Name + ".RequiredParameters"); var optionalParameterReferences = new CodeTypeReferenceExpression(routeDefinition.Name + ".OptionalParameters"); CodeExpression expression = actionIs; expression = CreateRestrictionInitializers(requiredRouteParameters, requiredParameterReferences, expression); expression = CreateRestrictionInitializers(optionalRouteParameters, optionalParameterReferences, expression); return(new CodeCastExpression(routeDefinition.Name, expression)); }
private void GenerateIntegers(Property property, CodeMemberProperty propertyName) { CodeExpression[] expressionArray; this.GenerateCommon(property, propertyName, "Integer", typeof(int), "Number"); string unformattedText = (property.SwitchName != string.Empty) ? (property.Prefix + property.SwitchName) : property.Name; if (!string.IsNullOrEmpty(property.Min) && !string.IsNullOrEmpty(property.Max)) { expressionArray = new CodeExpression[] { new CodeSnippetExpression(this.SurroundWithQuotes(unformattedText)), new CodePrimitiveExpression(int.Parse(property.Min, CultureInfo.CurrentCulture)), new CodePrimitiveExpression(int.Parse(property.Max, CultureInfo.CurrentCulture)), new CodePropertySetValueReferenceExpression() }; } else if (!string.IsNullOrEmpty(property.Min)) { expressionArray = new CodeExpression[] { new CodeSnippetExpression(this.SurroundWithQuotes(unformattedText)), new CodePrimitiveExpression(int.Parse(property.Min, CultureInfo.CurrentCulture)), new CodeSnippetExpression("Int32.MaxValue"), new CodePropertySetValueReferenceExpression() }; } else if (!string.IsNullOrEmpty(property.Max)) { expressionArray = new CodeExpression[] { new CodeSnippetExpression(this.SurroundWithQuotes(unformattedText)), new CodeSnippetExpression("Int32.MinValue"), new CodePrimitiveExpression(int.Parse(property.Max, CultureInfo.CurrentCulture)), new CodePropertySetValueReferenceExpression() }; } else { expressionArray = new CodeExpression[] { new CodeSnippetExpression(this.SurroundWithQuotes(unformattedText)), new CodeSnippetExpression("Int32.MinValue"), new CodeSnippetExpression("Int32.MaxValue"), new CodePropertySetValueReferenceExpression() }; } CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "ValidateInteger"); CodeConditionStatement statement = new CodeConditionStatement { Condition = new CodeMethodInvokeExpression(method, expressionArray) }; statement.TrueStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("switchToAdd"), "IsValid"), new CodeSnippetExpression("true"))); statement.FalseStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("switchToAdd"), "IsValid"), new CodeSnippetExpression("false"))); propertyName.SetStatements.Add(statement); CodeAssignStatement statement2 = new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("switchToAdd"), "Name"), new CodeSnippetExpression(this.SurroundWithQuotes(property.Name))); propertyName.SetStatements.Add(statement2); this.GenerateAssignToolSwitch(propertyName, "SwitchValue", property.Prefix, property.SwitchName); this.GenerateCommonSetStatements(property, propertyName, "Number"); }
/// <summary> /// This emits a method invoke to ISupportInitialize. /// </summary> private void SerializeSupportInitialize(IDesignerSerializationManager manager, CodeStatementCollection statements, CodeExpression valueExpression, object value, string methodName) { Trace("Emitting {0}", methodName); CodeTypeReference type = new CodeTypeReference(typeof(ISupportInitialize)); CodeCastExpression castExp = new CodeCastExpression(type, valueExpression); CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(castExp, methodName); CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); methodInvoke.Method = method; CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke); if (methodName == "BeginInit") { statement.UserData["statement-ordering"] = "begin"; } else { statement.UserData["statement-ordering"] = "end"; } statements.Add(statement); }
public static void AddDeferredEmbeddedUnmarshalCall(this CodeMemberMethod method, RpcTypeDescriptor descriptor, string unmarshal_name, string var_name, params RpcMarshalArgument[] additional_args) { string method_name = null; List <CodeExpression> args = new List <CodeExpression>(); List <CodeTypeReference> marshal_args = new List <CodeTypeReference>(); marshal_args.Add(descriptor.CodeType); marshal_args.AddRange(descriptor.AdditionalArgs.Select(a => a.CodeType)); marshal_args.AddRange(additional_args.Select(a => a.CodeType)); if (descriptor.Constructed) { method_name = "ReadEmbeddedStructPointer"; } else { if (descriptor.UnmarshalGeneric) { method.ThrowNotImplemented("Can't support generic pointer unmarshal"); return; } method_name = "ReadEmbeddedPointer"; var create_delegate = new CodeDelegateCreateExpression(CreateFuncType(descriptor.CodeType, marshal_args.Skip(1).ToArray()), GetVariable(unmarshal_name), descriptor.UnmarshalMethod); args.Add(create_delegate); } args.AddRange(descriptor.AdditionalArgs.Select(r => r.Expression)); args.AddRange(additional_args.Select(r => r.Expression)); CodeMethodReferenceExpression read_pointer = new CodeMethodReferenceExpression(GetVariable(unmarshal_name), method_name, marshal_args.ToArray()); CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression(read_pointer, args.ToArray()); CodeAssignStatement assign = new CodeAssignStatement(GetVariable(var_name), invoke); method.Statements.Add(assign); }
private static void CreateReadFromRowsMethod(CodeTypeDeclaration classType, TableInfo tableInfo) { if (string.IsNullOrEmpty(tableInfo.ParentName) == true) { return; } var cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.Family; cmm.Name = "readFromRows"; cmm.Parameters.Add(typeof(string), "name"); cmm.Parameters.Add(tableInfo.GetRowCodeType(), 1, "rows"); // invoke super.readFromRows { var name = new CodeVariableReferenceExpression("name"); var rows = new CodeVariableReferenceExpression("rows"); var readFromTable = new CodeMethodReferenceExpression(new CodeBaseReferenceExpression(), "readFromRows"); cmm.Statements.Add(new CodeMethodInvokeExpression(readFromTable, name, rows)); } classType.Members.Add(cmm); }
public void VisitPrint(PrintStatement p) { CodeExpression e= null; if (p.outputStream != null) { e = p.outputStream.Accept(xlat); } else { e = new CodeTypeReferenceExpression("Console"); } e = new CodeMethodReferenceExpression( e, "WriteLine"); gen.SideEffect( gen.Appl( e, p.args.Select(a => xlat.VisitArgument(a)).ToArray())); }
public CodeMethodInvokeExpression(CodeExpression targetObject, string methodName, params CodeExpression[] parameters) { _method = new CodeMethodReferenceExpression(targetObject, methodName); Parameters.AddRange(parameters); }
protected abstract void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e);
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace nspace = new CodeNamespace ("NSPC"); nspace.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (nspace); CodeTypeDeclaration cd = new CodeTypeDeclaration ("TEST"); cd.IsClass = true; nspace.Types.Add (cd); // GENERATES (C#): // public int CallingOverrideScenario(int i) { // ClassWVirtualMethod t = new ClassWOverrideMethod(); // return t.VirtualMethod(i); // } AddScenario ("Check1CallingOverrideScenario", "Check an overridden method."); CodeMemberMethod cmm = new CodeMemberMethod (); cmm.Name = "CallingOverrideScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("ClassWVirtualMethod", "t", new CodeCastExpression(new CodeTypeReference("ClassWVirtualMethod"), new CodeObjectCreateExpression ("ClassWOverrideMethod")))); CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "VirtualMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (methodinvoke)); cd.Members.Add (cmm); // declare a method without parameters cmm = new CodeMemberMethod (); cmm.Name = "NoParamsMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (16))); cd.Members.Add (cmm); // declare a method with multiple parameters cmm = new CodeMemberMethod (); cmm.Name = "MultipleParamsMethod"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "b")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("b")))); cd.Members.Add (cmm); // call method with no parameters, call a method with multiple parameters, // and call a method from a method call // public virtual int CallParamsMethods() { // TEST t = new TEST(); // int val; // val = t.NoParamsMethod (); // return t.MultipleParamsMethod(78, val); // } AddScenario ("CheckCallParamsMethod", "Check CheckCallParamsMethod."); cmm = new CodeMemberMethod (); cmm.Name = "CallParamsMethods"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("TEST"), "t", new CodeObjectCreateExpression ("TEST"))); CodeVariableReferenceExpression cvre = new CodeVariableReferenceExpression (); //To increase code coverage cvre.VariableName = "t"; CodeVariableReferenceExpression valCVRE = new CodeVariableReferenceExpression (); valCVRE.VariableName = "val"; cmm.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "val")); cmm.Statements.Add (new CodeAssignStatement (valCVRE, CDHelper.CreateMethodInvoke (new CodeVariableReferenceExpression ("t"), "NoParamsMethod"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (cvre, "MultipleParamsMethod", new CodePrimitiveExpression (78), valCVRE))); cd.Members.Add (cmm); // method to test the 'new' scenario by calling the 'new' method // GENERATES (C#): // public int CallingNewScenario(int i) { // ClassWVirtualMethod t = new ClassWNewMethod(); // int x1; // int x2; // x1 = ((ClassWNewMethod)(t)).VirtualMethod(i); // x2 = t.VirtualMethod(i); // return (x1 - x2); // } AddScenario ("CheckCallingNewScenario", "Check CheckCallingNewScenario."); cmm = new CodeMemberMethod (); cmm.Name = "CallingNewScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("ClassWVirtualMethod", "t", new CodeCastExpression(new CodeTypeReference("ClassWVirtualMethod"), new CodeObjectCreateExpression ("ClassWNewMethod")))); cmm.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "x1")); cmm.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "x2")); methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "VirtualMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression (new CodeCastExpression ("ClassWNewMethod", new CodeVariableReferenceExpression ("t")), "VirtualMethod"); methodinvoke2.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeAssignStatement (new CodeVariableReferenceExpression ("x1"), methodinvoke2)); cmm.Statements.Add (new CodeAssignStatement (new CodeVariableReferenceExpression ("x2"), methodinvoke)); cmm.Statements.Add (new CodeMethodReturnStatement ( CDHelper.CreateBinaryOperatorExpression ("x1", CodeBinaryOperatorType.Subtract, "x2"))); cd.Members.Add (cmm); // ***************** declare method using new ****************** // first declare a class with a virtual method in it // GENERATES (C#): // public class ClassWVirtualMethod { // public virtual int VirtualMethod(int a) { // return a; // } // } cd = new CodeTypeDeclaration ("ClassWVirtualMethod"); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "VirtualMethod"; 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"))); cd.Members.Add (cmm); // now declare a class that inherits from the previous class and has a 'new' method with the // name VirtualMethod // GENERATES (C#): // public class ClassWNewMethod : ClassWVirtualMethod { // public new virtual int VirtualMethod(int a) { // return (2 * a); // } // } cd = new CodeTypeDeclaration ("ClassWNewMethod"); cd.BaseTypes.Add (new CodeTypeReference ("ClassWVirtualMethod")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "VirtualMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.New; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodePrimitiveExpression (2), CodeBinaryOperatorType.Multiply , new CodeArgumentReferenceExpression ("a")))); cd.Members.Add (cmm); // now declare a class that inherits from the previous class and has a 'new' method with the // name VirtualMethod // GENERATES (C#): // public class ClassWOverrideMethod : ClassWVirtualMethod { // public override int VirtualMethod(int a) { // return (2 * a); // } // } cd = new CodeTypeDeclaration ("ClassWOverrideMethod"); cd.BaseTypes.Add (new CodeTypeReference ("ClassWVirtualMethod")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "VirtualMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodePrimitiveExpression (2), CodeBinaryOperatorType.Multiply , new CodeArgumentReferenceExpression ("a")))); cd.Members.Add (cmm); //*************** overload member function **************** // new class which will include both functions // GENERATES (C#): // public class TEST7 { // public int OverloadedMethod(int a) { // return a; // } // public int OverloadedMethod(int a, int b) { // return (b + a); // } // public int CallingOverloadedMethods(int i) { // int one = OverloadedMethod(i, i); // int two = OverloadedMethod(i); // return (one - two); // } // } AddScenario ("CheckTEST7.CallingOverloadedMethods", "Check CallingOverloadedMethods()"); cd = new CodeTypeDeclaration ("TEST7"); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "OverloadedMethod"; 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"))); cd.Members.Add (cmm); cmm = new CodeMemberMethod (); cmm.Name = "OverloadedMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "b")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodeArgumentReferenceExpression ("b"), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("a")))); cd.Members.Add (cmm); // declare a method that will call both OverloadedMethod functions cmm = new CodeMemberMethod (); cmm.Name = "CallingOverloadedMethods"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public; CodeMethodReferenceExpression methodref = new CodeMethodReferenceExpression (); methodref.MethodName = "OverloadedMethod"; cmm.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "one", new CodeMethodInvokeExpression (methodref, new CodeArgumentReferenceExpression ("i"), new CodeArgumentReferenceExpression ("i")))); cmm.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "two", new CodeMethodInvokeExpression (methodref, new CodeArgumentReferenceExpression ("i")))); cmm.Statements.Add (new CodeMethodReturnStatement ( CDHelper.CreateBinaryOperatorExpression ("one", CodeBinaryOperatorType.Subtract, "two"))); cd.Members.Add (cmm); // GENERATES (C#): // // namespace NSPC2 { // // // public class TEST { // // public virtual int CallingOverrideScenario(int i) { // NSPC.ClassWVirtualMethod t = new NSPC.ClassWOverrideMethod(); // return t.VirtualMethod(i); // } // } // } nspace = new CodeNamespace ("NSPC2"); cu.Namespaces.Add (nspace); cd = new CodeTypeDeclaration ("TEST"); cd.IsClass = true; nspace.Types.Add (cd); AddScenario ("Check2CallingOverrideScenario", "Check CallingOverrideScenario()"); cmm = new CodeMemberMethod (); cmm.Name = "CallingOverrideScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("NSPC.ClassWVirtualMethod", "t", new CodeCastExpression(new CodeTypeReference("NSPC.ClassWVirtualMethod"), new CodeObjectCreateExpression ("NSPC.ClassWOverrideMethod")))); methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "VirtualMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (methodinvoke)); cd.Members.Add (cmm); }
private static void CreateConstructor(CodeTypeDeclaration classType, TableInfo tableInfo, CodeGenerationInfo generationInfo) { var cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Public; cc.Parameters.Add(generationInfo.ReaderNamespace, "irow&", "row"); cc.Parameters.Add(tableInfo.GetCodeType(CodeType.Pointer), "table"); cc.AddConstructorStatement(string.Format("{0}(row)", CodeGenerationInfo.CremaRowName)); //cc.AddConstructorStatement("Table(*table)"); //foreach (var item in tableInfo.Columns) //{ // CodeBinaryOperatorExpression cbor = new CodeBinaryOperatorExpression(); // cbor.Left = new CodeVariableReferenceExpression("propertyName"); // cbor.Operator = CodeBinaryOperatorType.ValueEquality; // cbor.Right = new CodePrimitiveExpression(item.Name); // CodeConditionStatement ccs = new CodeConditionStatement(item.GetHasValueMethodExpression()); // CodeAssignStatement cas = new CodeAssignStatement(); // cas.Left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), item.Name); // cas.Right = item.GetGetValueMethodExpression(); // ccs.TrueStatements.Add(cas); // cc.Statements.Add(ccs); //} //var query = from item in tableInfo.Columns // where item.IsKey // select item; ////method.AddStatement(string.Format("cremarow::initialize(row, iniutil::generate_hash({0}, {1}));", query.Count(), string.Join(", ", query))); //CodeMethodInvokeExpression generate_hashExp = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("iniutil"), "generate_hash"); //foreach (var item in query) //{ // CodeFieldReferenceExpression fieldExp = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), item.Name); // if (item.IsCustomType() == false) // generate_hashExp.Parameters.Add(fieldExp); // else // generate_hashExp.Parameters.Add(new CodeCastExpression(new CodeTypeReference(typeof(int)), fieldExp)); //} // assign table { var tableField = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Table"); var tableVar = new CodeVariableReferenceExpression("table"); cc.Statements.AddAssign(tableField, tableVar); } // assign fields { int index = 0; foreach (var item in tableInfo.Columns) { var cas = new CodeAssignStatement(); cas.Left = item.GetFieldExpression(); cas.Right = item.GetGetValueMethodExpression(index, false); if (item.IsKey == false) { var ccs = new CodeConditionStatement(item.GetHasValueMethodExpression(index, false)); ccs.TrueStatements.Add(cas); cc.Statements.Add(ccs); } else { cc.Statements.Add(cas); } index++; } } //CodeMethodInvokeExpression methodExp = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("cremarow"), "initialize"); //methodExp.Parameters.Add(new CodeVariableReferenceExpression("row")); //methodExp.Parameters.Add(generate_hashExp); //cc.Statements.Add(new CodeExpressionStatement(methodExp)); //var query = from item in columns // where item.IsKey // select item.Name; //method.AddStatement(string.Format("cremarow::initialize(row, iniutil::generate_hash({0}, {1}));", query.Count(), string.Join(", ", query))); foreach (var item in generationInfo.GetChilds(tableInfo)) { // check null and return defaultField { var state = new CodeConditionStatement(); var condition = new CodeBinaryOperatorExpression(item.GetFieldExpression(), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)); state.Condition = condition; var codeTypeRef = new CodeTypeReferenceExpression(tableInfo.GetRowCodeType(CodeType.None)); var staticField = new CodeFieldReferenceExpression(codeTypeRef, item.GetFieldName() + "Empty"); state.TrueStatements.AddAssignReference(item.GetFieldExpression(), staticField); cc.Statements.Add(state); } // return field; //{ // var fieldExp = item.GetFieldExpression(); // cmp.GetStatements.AddMethodReturn(fieldExp, CodeType.None); //} //classType.Members.Add(cmp); } // invoke SetKey method { var methodRefExp = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "SetKey"); var methodInvokeExp = new CodeMethodInvokeExpression(methodRefExp); foreach (var item in tableInfo.Columns) { if (item.IsKey == true) { methodInvokeExp.Parameters.Add(item.GetFieldExpression()); } } cc.Statements.Add(methodInvokeExp); } classType.Members.Add(cc); }
protected override void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e) { }
public void BuildCustomClass(string strClassName) { unit = null; customerclass = null; tableClass = null; configTable = null; m_filed.Clear(); m_typeSave.Clear(); unit = new CodeCompileUnit(); customNameSpace = new CodeNamespace("XWorld.DataConfig"); customNameSpace.Imports.Add(new CodeNamespaceImport("UnityEngine")); customNameSpace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); customNameSpace.Imports.Add(new CodeNamespaceImport("System")); unit.Namespaces.Add(customNameSpace); //自定义的同名数据类成员 tableClass = new CodeTypeDeclaration(strClassName); tableClass.BaseTypes.Add(new CodeTypeReference("System.ICloneable")); tableClass.IsClass = true; tableClass.TypeAttributes = TypeAttributes.Public; customNameSpace.Types.Add(tableClass); setMethod_manager = new CodeMemberMethod(); setMethod_manager.Attributes = MemberAttributes.Public | MemberAttributes.Final; setMethod_manager.Name = "Clone"; setMethod_manager.ReturnType = new CodeTypeReference(typeof(object).ToString()); tableClass.Members.Add(setMethod_manager); setMethod_manager.Statements.Add(new CodeVariableReferenceExpression("return this.MemberwiseClone();")); //根据txt生成的同名文件 customerclass = new CodeTypeDeclaration("Table" + strClassName); customerclass.IsClass = true; customerclass.TypeAttributes = TypeAttributes.Public; customerclass.BaseTypes.Add(new CodeTypeReference("XWorld.DataConfig.TableBase")); customNameSpace.Types.Add(customerclass); //生成List configTable = new CodeMemberField("List<" + tableClass.Name + ">", "m_configList"); configTable.Attributes = MemberAttributes.Public; configTable.InitExpression = new CodeObjectCreateExpression("List<" + tableClass.Name + ">"); customerclass.Members.Add(configTable); //定义类方法 setMethod = new CodeMemberMethod(); setMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; customerclass.Members.Add(setMethod); setMethod.Name = "LoadData"; CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression("XWorld.DataConfig." + strClassName, "codeValue"); setMethod.Parameters.Add(param1); CodeMethodReferenceExpression codeRefExp = new CodeMethodReferenceExpression(); codeRefExp.MethodName = configTable.Name + ".Add"; CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression( codeRefExp, new CodeVariableReferenceExpression("codeValue") ); setMethod.Statements.Add(invoke); }
//// TODO: we need to refactor this to comply with FxCop private CodeTypeDeclaration GenEntityContainerInnerClass(CodeTypeDeclaration proxyClass, IEnumerable <Type> entityTypes, DomainServiceDescription domainServiceDescription) { // ---------------------------------------------------------------- // class xxxEntityContainer : EntityContainer // ---------------------------------------------------------------- string containingNamespace = this.ClientProxyGenerator.GetNamespace(proxyClass).Name; var innerClass = CodeGenUtilities.CreateTypeDeclaration(proxyClass.Name + "EntityContainer", containingNamespace); innerClass.BaseTypes.Add(CodeGenUtilities.GetTypeReference(TypeConstants.EntityContainerTypeFullName, containingNamespace, false)); innerClass.TypeAttributes = TypeAttributes.NotPublic | TypeAttributes.Sealed; proxyClass.Members.Add(innerClass); // ---------------------------------------------------------------- // ctor // ---------------------------------------------------------------- var ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Public; innerClass.Members.Add(ctor); // Convert to a set for faster lookups. HashSet <Type> entityTypesToUse = new HashSet <Type>(); foreach (Type entityType in entityTypes) { entityTypesToUse.Add(entityType); } // ---------------------------------------------------------------- // each entity type gets 'CreateEntitySet<entityType>()' statement in ctor // ---------------------------------------------------------------- foreach (Type entityType in entityTypes.OrderBy(t => t.FullName)) { // Skip entity types which have base classes. if (entityTypesToUse.Any(t => t != entityType && t.IsAssignableFrom(entityType))) { continue; } // ---------------------------------------------------------------- // Build EntitySetOperations enum value // ---------------------------------------------------------------- var enumTypeReference = CodeGenUtilities.GetTypeReference(TypeConstants.EntitySetOperationsTypeFullName, containingNamespace, false); CodeExpression entitySetOperations = null; // Check to see what update operations are supported, and build up the EntitySetOperations flags expression bool canInsert = domainServiceDescription.IsOperationSupported(entityType, DomainOperation.Insert); bool canEdit = domainServiceDescription.IsOperationSupported(entityType, DomainOperation.Update); bool canDelete = domainServiceDescription.IsOperationSupported(entityType, DomainOperation.Delete); CodeTypeReferenceExpression enumTypeReferenceExp = new CodeTypeReferenceExpression(enumTypeReference); if (!canInsert && !canEdit && !canDelete) { // if no update operations are supported, set to 'None' entitySetOperations = new CodeFieldReferenceExpression(enumTypeReferenceExp, "None"); } else if (canInsert && canEdit && canDelete) { // if all operations are supported, set to 'All' entitySetOperations = new CodeFieldReferenceExpression(enumTypeReferenceExp, "All"); } else { if (canInsert) { entitySetOperations = new CodeFieldReferenceExpression(enumTypeReferenceExp, "Add"); } if (canEdit) { CodeFieldReferenceExpression setOp = new CodeFieldReferenceExpression(enumTypeReferenceExp, "Edit"); if (entitySetOperations == null) { entitySetOperations = setOp; } else { entitySetOperations = new CodeBinaryOperatorExpression(entitySetOperations, CodeBinaryOperatorType.BitwiseOr, setOp); } } if (canDelete) { CodeFieldReferenceExpression setOp = new CodeFieldReferenceExpression(enumTypeReferenceExp, "Remove"); if (entitySetOperations == null) { entitySetOperations = setOp; } else { entitySetOperations = new CodeBinaryOperatorExpression(entitySetOperations, CodeBinaryOperatorType.BitwiseOr, setOp); } } } // ---------------------------------------------------------------- // method call: this.CreateEntitySet<entityType> // ---------------------------------------------------------------- var entityTypeReference = CodeGenUtilities.GetTypeReference(entityType, this.ClientProxyGenerator, proxyClass); var methodRef = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "CreateEntitySet", entityTypeReference); var methodCall = new CodeMethodInvokeExpression(methodRef, entitySetOperations); ctor.Statements.Add(methodCall); } return(innerClass); }
public void VisitMethodReference(CodeMethodReferenceExpression m) { if (m.TargetObject != null) { m.TargetObject.Accept(this); writer.Write("."); } writer.WriteName(m.MethodName); }
private static CodeMemberMethod CreateEndOperationMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeMemberMethod endMethod) { CodeMemberMethod method = new CodeMemberMethod(); method.Attributes = MemberAttributes.Private; method.ReturnType = new CodeTypeReference(objectArrayType); method.Name = NamingHelper.GetUniqueName(GetEndOperationMethodName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations); int asyncResultParamIndex = GetAsyncResultParamIndex(endMethod); CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), endMethod.Name, new CodeExpression[0]); CodeArrayCreateExpression expression2 = new CodeArrayCreateExpression(); expression2.CreateType = new CodeTypeReference(objectArrayType); for (int i = 0; i < endMethod.Parameters.Count; i++) { if (i == asyncResultParamIndex) { method.Parameters.Add(new CodeParameterDeclarationExpression(endMethod.Parameters[i].Type, endMethod.Parameters[i].Name)); expression.Parameters.Add(new CodeVariableReferenceExpression(endMethod.Parameters[i].Name)); } else { CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(endMethod.Parameters[i].Type, endMethod.Parameters[i].Name); CodeMethodReferenceExpression expression3 = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), getDefaultValueForInitializationMethodName, new CodeTypeReference[] { endMethod.Parameters[i].Type }); statement.InitExpression = new CodeMethodInvokeExpression(expression3, new CodeExpression[0]); method.Statements.Add(statement); expression.Parameters.Add(new CodeDirectionExpression(endMethod.Parameters[i].Direction, new CodeVariableReferenceExpression(statement.Name))); expression2.Initializers.Add(new CodeVariableReferenceExpression(statement.Name)); } } if (endMethod.ReturnType.BaseType != voidTypeRef.BaseType) { CodeVariableDeclarationStatement statement2 = new CodeVariableDeclarationStatement(); statement2.Type = endMethod.ReturnType; statement2.Name = NamingHelper.GetUniqueName("retVal", new NamingHelper.DoesNameExist(ClientClassGenerator.DoesParameterNameExist), endMethod); statement2.InitExpression = expression; expression2.Initializers.Add(new CodeVariableReferenceExpression(statement2.Name)); method.Statements.Add(statement2); } else { method.Statements.Add(expression); } if (expression2.Initializers.Count > 0) { method.Statements.Add(new CodeMethodReturnStatement(expression2)); } else { method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null))); } clientType.Members.Add(method); return method; }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace nspace = new CodeNamespace ("NSPC"); nspace.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (nspace); CodeTypeDeclaration cd = new CodeTypeDeclaration ("TEST"); cd.IsClass = true; nspace.Types.Add (cd); if (Supports (provider, GeneratorSupport.ReferenceParameters)) { //************** static internal method with parameters with out and ref directions, ************** //************** and void return type ************** // GENERATES (C#): // /*FamANDAssem*/ internal static void Work(ref int i, out int j) { // i = (i + 4); // j = 5; // } CodeMemberMethod cmm1 = new CodeMemberMethod (); cmm1.Name = "Work"; cmm1.ReturnType = new CodeTypeReference ("System.void"); cmm1.Attributes = MemberAttributes.Static | MemberAttributes.FamilyAndAssembly; // add parameter with ref direction CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i"); param.Direction = FieldDirection.Ref; cmm1.Parameters.Add (param); // add parameter with out direction param = new CodeParameterDeclarationExpression (typeof (int), "j"); param.Direction = FieldDirection.Out; cmm1.Parameters.Add (param); cmm1.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("i"), new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (4)))); cmm1.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("j"), new CodePrimitiveExpression (5))); cd.Members.Add (cmm1); } // ********* pass by value using a protected method ****** // GENERATES (C#): // protected static int ProtectedMethod(int a) { // return a; // } CodeMemberMethod cmm = new CodeMemberMethod (); cmm.Name = "ProtectedMethod"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Family | MemberAttributes.Static; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cmm.ReturnType = new CodeTypeReference (typeof (int)); cd.Members.Add (cmm); // declare a method to test the protected method with new attribute // GENERATES (C#): // public static int CallProtected(int a) { // return (a + ProtectedMethod(a)); // } AddScenario ("CheckCallProtected"); cmm = new CodeMemberMethod (); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Name = "CallProtected"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; CodeMethodReferenceExpression meth = new CodeMethodReferenceExpression (); meth.MethodName = "ProtectedMethod"; meth.TargetObject = new CodeTypeReferenceExpression("TEST2"); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodeMethodInvokeExpression (meth, new CodeArgumentReferenceExpression ("a"))))); cd.Members.Add (cmm); // GENERATES (C#): // public static void Main() { // } if (Supports (provider, GeneratorSupport.EntryPointMethod)) { CodeEntryPointMethod cep = new CodeEntryPointMethod (); cd.Members.Add (cep); } // add a second class cd = new CodeTypeDeclaration ("TEST2"); cd.BaseTypes.Add (new CodeTypeReference ("TEST")); cd.IsClass = true; nspace.Types.Add (cd); if (Supports (provider, GeneratorSupport.ReferenceParameters)) { // GENERATES (C#): // public static int CallingWork(int a) { // a = 10; // int b; // TEST.Work(ref a, out b); // return (a + b); // } AddScenario ("CheckCallingWork"); cmm = new CodeMemberMethod (); cmm.Name = "CallingWork"; cmm.Attributes = MemberAttributes.Public; 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 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); } // ***** declare a private method with value return type ****** // GENERATES (C#): // private static int PrivateMethod() { // return 5; // } cmm = new CodeMemberMethod (); cmm.Name = "PrivateMethod"; cmm.Attributes = MemberAttributes.Private | MemberAttributes.Static; cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (5))); cmm.ReturnType = new CodeTypeReference (typeof (int)); cd.Members.Add (cmm); // declare a method to test the private method // GENERATES (C#): // public static int CallPrivateMethod(int a) { // return (a + PrivateMethod()); // } AddScenario ("CheckCallPrivateMethod"); cmm = new CodeMemberMethod (); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Name = "CallPrivateMethod"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; meth = new CodeMethodReferenceExpression (); meth.TargetObject = new CodeTypeReferenceExpression("TEST2"); meth.MethodName = "PrivateMethod"; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodeMethodInvokeExpression (meth)))); cd.Members.Add (cmm); // ********* pass by value using a protected static method ****** // this class needs to inherit from the first class so that we can call the protected method from here and call the // public method that calls the protected method from that class // declare a method to test the protected method // GENERATES (C#): // public static int CallProtectedAndPublic(int a) { // return (CallProtected(a) + ProtectedMethod(a)); // } AddScenario ("CheckCallProtectedAndPublic"); cmm = new CodeMemberMethod (); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Name = "CallProtectedAndPublic"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; meth = new CodeMethodReferenceExpression (); meth.MethodName = "ProtectedMethod"; meth.TargetObject = new CodeTypeReferenceExpression("TEST2"); CodeMethodReferenceExpression meth2 = new CodeMethodReferenceExpression (); meth2.MethodName = "CallProtected"; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeMethodInvokeExpression (meth2, new CodeArgumentReferenceExpression ("a")), CodeBinaryOperatorType.Add, new CodeMethodInvokeExpression (meth, new CodeArgumentReferenceExpression ("a"))))); cd.Members.Add (cmm); if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { // ******** implement a single public interface *********** // declare an interface // GENERATES (C#): // public interface TEST3 { // int InterfaceMethod(int a); // } cd = new CodeTypeDeclaration ("TEST3"); cd.IsInterface = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cd.Members.Add (cmm); // implement the interface // GENERATES (C#): // public class TEST3b : object, TEST3 { // public virtual int InterfaceMethod(int a) { // return a; // } // } cd = new CodeTypeDeclaration ("TEST3b"); cd.BaseTypes.Add (new CodeTypeReference ("System.Object")); cd.BaseTypes.Add (new CodeTypeReference ("TEST3")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.ImplementationTypes.Add (new CodeTypeReference ("TEST3")); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cd.Members.Add (cmm); // ********implement two interfaces with overloading method name******* // declare the second interface // GENERATES (C#): // public interface TEST4 { // int InterfaceMethod(int a); // } cd = new CodeTypeDeclaration ("TEST4"); cd.IsInterface = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cd.Members.Add (cmm); // implement both of the interfaces // GENERATES (C#): // public class TEST4b : object, TEST3, TEST4 { // public int InterfaceMethod(int a) { // return a; // } // } cd = new CodeTypeDeclaration ("TEST4b"); cd.BaseTypes.Add (new CodeTypeReference ("System.Object")); cd.BaseTypes.Add (new CodeTypeReference ("TEST3")); cd.BaseTypes.Add (new CodeTypeReference ("TEST4")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ImplementationTypes.Add (new CodeTypeReference ("TEST3")); cmm.ImplementationTypes.Add (new CodeTypeReference ("TEST4")); 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"))); cd.Members.Add (cmm); } // create a class which will have a method to call the method name that was overloaded // this class will also call a method in the class that implements the private implements testcase cd = new CodeTypeDeclaration ("TEST5"); cd.IsClass = true; nspace.Types.Add (cd); if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { // GENERATES (C#): // public static int TestMultipleInterfaces(int i) { // TEST4b t = new TEST4b(); // TEST3 TEST3 = ((TEST3)(t)); // TEST4 TEST4 = ((TEST4)(t)); // return (TEST3.InterfaceMethod(i) - TEST4.InterfaceMethod(i)); // } AddScenario ("CheckTestMultipleInterfaces"); cmm = new CodeMemberMethod (); cmm.Name = "TestMultipleInterfaces"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST4b", "t", new CodeObjectCreateExpression ("TEST4b"))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST3", "TEST3", new CodeCastExpression ("TEST3", new CodeVariableReferenceExpression ("t")))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST4", "TEST4", new CodeCastExpression ("TEST4", new CodeVariableReferenceExpression ("t")))); CodeMethodInvokeExpression methodinvoking = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST3") , "InterfaceMethod"); methodinvoking.Parameters.Add (new CodeArgumentReferenceExpression ("i")); CodeMethodInvokeExpression methodinvoking2 = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST4") , "InterfaceMethod"); methodinvoking2.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( methodinvoking, CodeBinaryOperatorType.Subtract, methodinvoking2))); cd.Members.Add (cmm); // GENERATES (C#): // public static int PrivateImplements(int i) { // TEST6 t = new TEST6(); // TEST3 TEST3 = ((TEST3)(t)); // TEST4 TEST4 = ((TEST4)(t)); // return (TEST3.InterfaceMethod(i) - TEST4.InterfaceMethod(i)); // } AddScenario ("CheckPrivateImplements"); cmm = new CodeMemberMethod (); cmm.Name = "PrivateImplements"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST6", "t", new CodeObjectCreateExpression ("TEST6"))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST3", "TEST3", new CodeCastExpression ("TEST3", new CodeVariableReferenceExpression ("t")))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST4", "TEST4", new CodeCastExpression ("TEST4", new CodeVariableReferenceExpression ("t")))); methodinvoking = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST3") , "InterfaceMethod"); methodinvoking.Parameters.Add (new CodeArgumentReferenceExpression ("i")); methodinvoking2 = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST4") , "InterfaceMethod"); methodinvoking2.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( methodinvoking, CodeBinaryOperatorType.Subtract, methodinvoking2))); cd.Members.Add (cmm); //******************* private implements *************************** // implement both of the interfaces // GENERATES (C#): // public class TEST6 : object, TEST3, TEST4 { // int TEST3.InterfaceMethod(int a) { // return a; // } // int TEST4.InterfaceMethod(int a) { // return (5 * a); // } // } CodeTypeDeclaration ctd = new CodeTypeDeclaration ("TEST6"); ctd.BaseTypes.Add (new CodeTypeReference ("System.Object")); ctd.BaseTypes.Add (new CodeTypeReference ("TEST3")); ctd.BaseTypes.Add (new CodeTypeReference ("TEST4")); ctd.IsClass = true; nspace.Types.Add (ctd); // make a seperate implementation for each base // first for TEST3 base cmm = new CodeMemberMethod (); 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"))); cmm.PrivateImplementationType = new CodeTypeReference ("TEST3"); ctd.Members.Add (cmm); // now implement for TEST4 base cmm = new CodeMemberMethod (); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.PrivateImplementationType = new CodeTypeReference ("TEST4"); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodePrimitiveExpression (5), CodeBinaryOperatorType.Multiply, new CodeArgumentReferenceExpression ("a")))); ctd.Members.Add (cmm); } // method to test the 'new' scenario by calling the 'new' method // GENERATES (C#): // public int CallingNewScenario(int i) { // ClassWVirtualMethod t = new ClassWNewMethod(); // return (((ClassWNewMethod)(t)).VirtualMethod(i) - t.VirtualMethod(i)); // } CodeMethodInvokeExpression methodinvoke; #if !FSHARP AddScenario ("CheckCallingNewScenario"); cmm = new CodeMemberMethod (); cmm.Name = "CallingNewScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("ClassWVirtualMethod", "t", new CodeCastExpression(new CodeTypeReference("ClassWVirtualMethod"), new CodeObjectCreateExpression ("ClassWNewMethod")))); CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "VirtualMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression (new CodeCastExpression ("ClassWNewMethod", new CodeVariableReferenceExpression ("t")), "VirtualMethod"); methodinvoke2.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( methodinvoke2, CodeBinaryOperatorType.Subtract, methodinvoke))); cd.Members.Add (cmm); #endif // similar to the 'new' test, write a method to complete testing of the 'override' scenario // GENERATES (C#): // public static int CallingOverrideScenario(int i) { // ClassWVirtualMethod t = new ClassWOverrideMethod(); // return t.VirtualMethod(i); // } AddScenario ("CheckCallingOverrideScenario"); cmm = new CodeMemberMethod (); cmm.Name = "CallingOverrideScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWVirtualMethod", "t", new CodeCastExpression(new CodeTypeReference("ClassWVirtualMethod"), new CodeObjectCreateExpression("ClassWOverrideMethod")))); methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "VirtualMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (methodinvoke)); cd.Members.Add (cmm); //*************** overload member function **************** // new class which will include both functions // GENERATES (C#): // public class TEST7 { // public static int OverloadedMethod(int a) { // return a; // } // public static int OverloadedMethod(int a, int b) { // return (b + a); // } // public static int CallingOverloadedMethods(int i) { // return (OverloadedMethod(i, i) - OverloadedMethod(i)); // } // } cd = new CodeTypeDeclaration ("TEST7"); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "OverloadedMethod"; 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"))); cd.Members.Add (cmm); cmm = new CodeMemberMethod (); cmm.Name = "OverloadedMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "b")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodeArgumentReferenceExpression ("b"), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("a")))); cd.Members.Add (cmm); // declare a method that will call both OverloadedMethod functions AddScenario ("CheckCallingOverloadedMethods"); cmm = new CodeMemberMethod (); cmm.Name = "CallingOverloadedMethods"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public; CodeMethodReferenceExpression methodref = new CodeMethodReferenceExpression (); methodref.MethodName = "OverloadedMethod"; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodeMethodInvokeExpression (methodref, new CodeArgumentReferenceExpression ("i"), new CodeArgumentReferenceExpression ("i")) , CodeBinaryOperatorType.Subtract, new CodeMethodInvokeExpression (methodref, new CodeArgumentReferenceExpression ("i"))))); cd.Members.Add (cmm); // ***************** declare method using new ****************** // first declare a class with a virtual method in it // GENERATES (C#): // public class ClassWVirtualMethod { // public virtual int VirtualMethod(int a) { // return a; // } // } cd = new CodeTypeDeclaration ("ClassWVirtualMethod"); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "VirtualMethod"; 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"))); cd.Members.Add (cmm); #if !FSHARP // now declare a class that inherits from the previous class and has a 'new' method with the // name VirtualMethod // GENERATES (C#): // public class ClassWNewMethod : ClassWVirtualMethod { // public new virtual int VirtualMethod(int a) { // return (2 * a); // } // } cd = new CodeTypeDeclaration ("ClassWNewMethod"); cd.BaseTypes.Add (new CodeTypeReference ("ClassWVirtualMethod")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "VirtualMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.New; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodePrimitiveExpression (2), CodeBinaryOperatorType.Multiply , new CodeArgumentReferenceExpression ("a")))); cd.Members.Add (cmm); #endif // *************** declare a method using override ****************** // now declare a class that inherits from the previous class and has a 'new' method with the // name VirtualMethod // GENERATES (C#): // public class ClassWOverrideMethod : ClassWVirtualMethod { // public override int VirtualMethod(int a) { // return (2 * a); // } // } cd = new CodeTypeDeclaration ("ClassWOverrideMethod"); cd.BaseTypes.Add (new CodeTypeReference ("ClassWVirtualMethod")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "VirtualMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodePrimitiveExpression (2), CodeBinaryOperatorType.Multiply , new CodeArgumentReferenceExpression ("a")))); cd.Members.Add (cmm); }
public CodeMethodInvokeExpression(CodeMethodReferenceExpression method, CodeExpression[] parameters) {}
public void CallingMethods() { var ns = new CodeNamespace("MyNamespace"); var cd = new CodeTypeDeclaration("TEST") { IsClass = true }; CodeMemberMethod cmm = new CodeMemberMethod(); cmm.Name = "CallingOverrideScenario"; 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("ClassWVirtualMethod", "t", new CodeObjectCreateExpression("ClassWOverrideMethod"))); CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "VirtualMethod"); methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i")); cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke)); cd.Members.Add(cmm); // declare a method without parameters cmm = new CodeMemberMethod(); cmm.Name = "NoParamsMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16))); cd.Members.Add(cmm); // declare a method with multiple parameters cmm = new CodeMemberMethod(); cmm.Name = "MultipleParamsMethod"; cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "b")); cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b")))); cd.Members.Add(cmm); // call method with no parameters, call a method with multiple parameters, // and call a method from a method call cmm = new CodeMemberMethod(); cmm.Name = "CallParamsMethods"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("TEST"), "t", new CodeObjectCreateExpression("TEST"))); CodeVariableReferenceExpression cvre = new CodeVariableReferenceExpression(); //To increase code coverage cvre.VariableName = "t"; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(cvre, "MultipleParamsMethod", new CodePrimitiveExpression(78), new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "NoParamsMethod")))); cd.Members.Add(cmm); // method to test the 'new' scenario by calling the 'new' method cmm = new CodeMemberMethod(); cmm.Name = "CallingNewScenario"; 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("ClassWVirtualMethod", "t", new CodeObjectCreateExpression("ClassWNewMethod"))); methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "VirtualMethod"); methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i")); CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeCastExpression("ClassWNewMethod", new CodeVariableReferenceExpression("t")), "VirtualMethod"); methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i")); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( methodinvoke2, CodeBinaryOperatorType.Subtract, methodinvoke))); cd.Members.Add(cmm); // first declare a class with a virtual method in it cd = new CodeTypeDeclaration("ClassWVirtualMethod"); cd.IsClass = true; ns.Types.Add(cd); cmm = new CodeMemberMethod(); cmm.Name = "VirtualMethod"; 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"))); cd.Members.Add(cmm); // now declare a class that inherits from the previous class and has a 'new' method with the cd = new CodeTypeDeclaration("ClassWNewMethod"); cd.BaseTypes.Add(new CodeTypeReference("ClassWVirtualMethod")); cd.IsClass = true; ns.Types.Add(cd); cmm = new CodeMemberMethod(); cmm.Name = "VirtualMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.New; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( new CodePrimitiveExpression(2), CodeBinaryOperatorType.Multiply, new CodeVariableReferenceExpression("a")))); cd.Members.Add(cmm); // now declare a class that inherits from the previous class and has a 'new' method with the cd = new CodeTypeDeclaration("ClassWOverrideMethod"); cd.BaseTypes.Add(new CodeTypeReference("ClassWVirtualMethod")); cd.IsClass = true; ns.Types.Add(cd); cmm = new CodeMemberMethod(); cmm.Name = "VirtualMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( new CodePrimitiveExpression(2), CodeBinaryOperatorType.Multiply, new CodeVariableReferenceExpression("a")))); cd.Members.Add(cmm); // new class which will include both functions cd = new CodeTypeDeclaration("TEST7"); cd.IsClass = true; ns.Types.Add(cd); cmm = new CodeMemberMethod(); cmm.Name = "OverloadedMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); cd.Members.Add(cmm); cmm = new CodeMemberMethod(); cmm.Name = "OverloadedMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "b")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("b"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("a")))); cd.Members.Add(cmm); // declare a method that will call both OverloadedMethod functions cmm = new CodeMemberMethod(); cmm.Name = "CallingOverloadedMethods"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeMethodReferenceExpression methodref = new CodeMethodReferenceExpression(); methodref.MethodName = "OverloadedMethod"; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( new CodeMethodInvokeExpression(methodref, new CodeVariableReferenceExpression("i"), new CodeVariableReferenceExpression("i")) , CodeBinaryOperatorType.Subtract, new CodeMethodInvokeExpression(methodref, new CodeVariableReferenceExpression("i"))))); cd.Members.Add(cmm); AssertEqual(ns, @"Namespace MyNamespace Public Class ClassWVirtualMethod Public Overridable Function VirtualMethod(ByVal a As Integer) As Integer Return a End Function End Class Public Class ClassWNewMethod Inherits ClassWVirtualMethod Public Shadows Overridable Function VirtualMethod(ByVal a As Integer) As Integer Return (2 * a) End Function End Class Public Class ClassWOverrideMethod Inherits ClassWVirtualMethod Public Overrides Function VirtualMethod(ByVal a As Integer) As Integer Return (2 * a) End Function End Class Public Class TEST7 Public Overloads Shared Function OverloadedMethod(ByVal a As Integer) As Integer Return a End Function Public Overloads Shared Function OverloadedMethod(ByVal a As Integer, ByVal b As Integer) As Integer Return (b + a) End Function Public Shared Function CallingOverloadedMethods(ByVal i As Integer) As Integer Return (OverloadedMethod(i, i) - OverloadedMethod(i)) End Function End Class End Namespace"); }
/// <summary> /// Create a method entry point for a function import yielding an entity reader. /// </summary> /// <param name="functionImport">SOM for function import; must not be null and must yield /// an entity reader.</param> /// <returns>Method definition.</returns> private CodeMemberMethod CreateFunctionImportStructuralTypeReaderMethod(EdmFunction functionImport) { // Trying to get: // ///// <summary> ///// Documentation ///// </summary> //public ObjectQueryResult<MyType> MyFunctionImport(Nullable<int> id, string foo) //{ // ObjectParameter idParameter; // if (id.HasValue) // { // idParameter = new ObjectParameter("id", id); // } // else // { // idParameter = new ObjectParameter("id", typeof(int)); // } // ObjectParameter fooParameter; // if (null != foo) // { // fooParameter = new ObjectParameter("foo", foo); // } // else // { // fooParameter = new ObjectParameter("foo", typeof(string)); // } // return base.ExecuteFunction<MyType>("MyFunctionImport", idParameter, fooParameter); //} Debug.Assert(null != functionImport); CodeMemberMethod method = new CodeMemberMethod(); Generator.AttributeEmitter.EmitGeneratedCodeAttribute(method); method.Name = functionImport.Name; method.Attributes = GetFunctionImportAccessibility(functionImport) | MemberAttributes.Final; UniqueIdentifierService uniqueIdentifierService = new UniqueIdentifierService( this.Generator.IsLanguageCaseSensitive, s => Utils.FixParameterName(s)); // determine element return type EdmType returnType = GetReturnTypeFromFunctionImport(functionImport); if (Helper.IsCollectionType(returnType)) { // get the type in the collection returnType = ((CollectionType)returnType).TypeUsage.EdmType; } CodeTypeReference elementType = Generator.GetLeastPossibleQualifiedTypeReference(returnType); method.ReturnType = TypeReference.ObjectResult(elementType); // generate <summary> comments based on CSDL Documentation element CommentEmitter.EmitSummaryComments(functionImport, method.Comments); // build up list of arguments to ExecuteFunction List <CodeExpression> executeArguments = new List <CodeExpression>(); executeArguments.Add(new CodePrimitiveExpression(functionImport.Name)); // first argument is the name of the function foreach (FunctionParameter parameter in functionImport.Parameters) { CreateFunctionArgument(method, uniqueIdentifierService, parameter); } // add fields representing object parameters foreach (FunctionParameter parameter in functionImport.Parameters) { if (parameter.Mode == ParameterMode.In) { CodeExpression variableReference = CreateFunctionParameter(method, uniqueIdentifierService, parameter); executeArguments.Add(variableReference); } else { // the parameter is already being passed in as an argument; just remember it and // pass it in as an argument string adjustedParameterName; if (!uniqueIdentifierService.TryGetAdjustedName(parameter, out adjustedParameterName)) { Debug.Fail("parameter must be registered in identifier service"); } executeArguments.Add(new CodeVariableReferenceExpression(adjustedParameterName)); } } // Add call to ExecuteFunction // return ExecuteFunction<elementType>("FunctionImportName", { object parameters }); CodeMethodReferenceExpression executeFunctionMethod = new CodeMethodReferenceExpression( new CodeBaseReferenceExpression(), "ExecuteFunction", new CodeTypeReference[] { elementType }); method.Statements.Add( new CodeMethodReturnStatement( new CodeMethodInvokeExpression(executeFunctionMethod, executeArguments.ToArray()) ) ); // invoke the ExecuteFunction method passing in parameters return(method); }
/// <summary> /// Serializes the given object into a CodeDom object. This uses the stock /// resource serialization scheme and retains the expression it provides. /// </summary> public override object Serialize(IDesignerSerializationManager manager, object value) { PropertyDescriptor desc = (PropertyDescriptor)manager.Context[typeof(PropertyDescriptor)]; ExpressionContext tree = (ExpressionContext)manager.Context[typeof(ExpressionContext)]; bool isSerializable = (value is not null) ? GetReflectionTypeHelper(manager, value).IsSerializable : true; // If value is not serializable, we have no option but to call the original serializer, // since we cannot push this into resources. bool callExistingSerializer = !isSerializable; // Compat: If we are serializing content, we need to skip property reflection to preserve compatibility, // since tools like WinRes expect items in collections (like TreeNodes and ListViewItems) // to be serialized as binary blobs. bool serializingContent = (desc is not null && desc.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content)); // We also skip back to the original serializer if there is a preset value for this object. if (!callExistingSerializer) { callExistingSerializer = tree is not null && tree.PresetValue is not null && tree.PresetValue == value; } if (_model == CodeDomLocalizationModel.PropertyReflection && !serializingContent && !callExistingSerializer) { // For a property reflecting model, we need to do more work. Here we need to find // the object we are serializing against and inject an "ApplyResources" method // against the object and its name. If any of this machinery fails we will // just return the existing expression which will default to the original behavior. CodeStatementCollection statements = (CodeStatementCollection)manager.Context[typeof(CodeStatementCollection)]; // In the case of extender properties, we don't want to serialize using the property // reflecting model. In this case we'll skip it and fall through to the // property assignment model. bool skipPropertyReflect = false; if (desc is not null) { var attr = desc.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute; if (attr is not null && attr.ExtenderProperty is not null) { skipPropertyReflect = true; } } if (!skipPropertyReflect && tree is not null && statements is not null) { string name = manager.GetName(tree.Owner); CodeExpression ownerExpression = SerializeToExpression(manager, tree.Owner); if (name is not null && ownerExpression is not null) { RootContext rootCtx = manager.Context[typeof(RootContext)] as RootContext; if (rootCtx is not null && rootCtx.Value == tree.Owner) { name = "$this"; } // Ok, if we got here it means we have enough data to emit // using the reflection model. SerializeToResourceExpression(manager, value, false); if (EmitApplyMethod(manager, tree.Owner)) { ResourceManager rm = manager.Context[typeof(ResourceManager)] as ResourceManager; Debug.Assert(rm is not null, "No resource manager available in context."); CodeExpression rmExpression = GetExpression(manager, rm); Debug.Assert(rmExpression is not null, "No expression available for resource manager."); CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression(rmExpression, "ApplyResources"); CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); methodInvoke.Method = methodRef; methodInvoke.Parameters.Add(ownerExpression); methodInvoke.Parameters.Add(new CodePrimitiveExpression(name)); statements.Add(methodInvoke); } return(null); // we have already worked our statements into the tree. } } } if (callExistingSerializer) { return(_currentSerializer.Serialize(manager, value)); } return(SerializeToResourceExpression(manager, value)); }
public void BuildCustomClassStepLoad(string strClassName, string[] typeNames, string[] memberNames, bool bDescTips) { //Get Row Count CodeMemberMethod rowMethod = new CodeMemberMethod(); rowMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; rowMethod.Name = "GetRowCount"; rowMethod.ReturnType = new CodeTypeReference(typeof(int).ToString()); customerclass.Members.Add(rowMethod); rowMethod.Statements.Add(new CodeVariableReferenceExpression("return " + memberNames.Length.ToString())); //GetDataCount CodeMemberMethod dataCountMethod = new CodeMemberMethod(); dataCountMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; dataCountMethod.Name = "GetDataCount"; dataCountMethod.ReturnType = new CodeTypeReference(typeof(int)); CodeVariableReferenceExpression dataCountCheck = new CodeVariableReferenceExpression(configTable.Name.ToString() + " == null"); CodeConditionStatement codeStateDataCount = new CodeConditionStatement(); codeStateDataCount.Condition = dataCountCheck; codeStateDataCount.TrueStatements.Add(new CodeVariableReferenceExpression("return 0")); dataCountMethod.Statements.Add(codeStateDataCount); dataCountMethod.Statements.Add(new CodeVariableReferenceExpression("return " + configTable.Name.ToString() + ".Count")); customerclass.Members.Add(dataCountMethod); //GetData CodeMemberMethod getDataMethod = new CodeMemberMethod(); getDataMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; getDataMethod.Name = "GetData"; getDataMethod.ReturnType = new CodeTypeReference(strClassName); CodeParameterDeclarationExpression paramGetData1 = new CodeParameterDeclarationExpression(typeof(int), "rowIdx"); getDataMethod.Parameters.Add(paramGetData1); CodeVariableReferenceExpression getDataCheckCode = new CodeVariableReferenceExpression(configTable.Name.ToString() + " != null && " + "rowIdx >= 0 && rowIdx < " + configTable.Name.ToString() + ".Count"); CodeConditionStatement codstateGet = new CodeConditionStatement(); codstateGet.Condition = getDataCheckCode; codstateGet.TrueStatements.Add(new CodeVariableReferenceExpression("return " + configTable.Name.ToString() + "[rowIdx]")); getDataMethod.Statements.Add(codstateGet); getDataMethod.Statements.Add(new CodeVariableReferenceExpression("return null")); customerclass.Members.Add(getDataMethod); //Load Data setMethod = new CodeMemberMethod(); setMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override; customerclass.Members.Add(setMethod); setMethod.Name = "LoadData"; CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(string), "content"); setMethod.Parameters.Add(param1); // setMethod.Statements.Add(new CodeTypeReferenceExpression("content = content.Trim(ClientConfigManager.CMD_CHAR)")); CodeMethodReferenceExpression codeRefExp = new CodeMethodReferenceExpression(); codeRefExp.MethodName = @"string[] values = content.Split"; CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression( codeRefExp, new CodeVariableReferenceExpression("\"\\r\"[0]") ); setMethod.Statements.Add(invoke); int initLineNum = 2; if (bDescTips) { initLineNum = 3; } CodeIterationStatement its = new CodeIterationStatement(); // 初始化条件 its.InitStatement = new CodeVariableDeclarationStatement(typeof(int), "i", new CodePrimitiveExpression(initLineNum)); // 条件检查 its.TestExpression = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodeTypeReferenceExpression("values.Length")); // 每一轮循环后对条件的更改 its.IncrementStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))); // 循环体 { CodeAssignStatement ass = new CodeAssignStatement(); ass.Left = new CodeArgumentReferenceExpression(strClassName + " data"); ass.Right = new CodeArgumentReferenceExpression("new " + strClassName + "()"); its.Statements.Add(ass); its.Statements.Add(new CodeTypeReferenceExpression("int j = 0")); codeRefExp = new CodeMethodReferenceExpression(); codeRefExp.MethodName = @"string[] subValues = values[i].TrimStart('\n').Split"; invoke = new CodeMethodInvokeExpression( codeRefExp, new CodeVariableReferenceExpression("ClientConfigManager.CMD_STRING"), new CodeVariableReferenceExpression("StringSplitOptions.None") ); its.Statements.Add(invoke); // 生成判断条件的表达式 CodeVariableReferenceExpression codexp = new CodeVariableReferenceExpression("subValues != null && subValues.Length == GetRowCount()"); // 分支语句 CodeConditionStatement codstatement = new CodeConditionStatement(); codstatement.Condition = codexp; // 条件成立时 // codstatement.TrueStatements.Add(new CodeTypeReferenceExpression()); its.Statements.Add(codstatement); for (int i = 0; i < typeNames.Length; i++) { string typeName = typeNames[i]; string memberName = memberNames[i]; codeRefExp = new CodeMethodReferenceExpression(); codeRefExp.MethodName = @"data." + memberName + " = " + GetConvertByType(typeName); invoke = new CodeMethodInvokeExpression( codeRefExp, new CodeVariableReferenceExpression("subValues[j]") ); // its.Statements.Add(invoke); codstatement.TrueStatements.Add(invoke); ass = new CodeAssignStatement(); ass.Left = new CodeArgumentReferenceExpression("j"); ass.Right = new CodeArgumentReferenceExpression("j + 1"); // its.Statements.Add(ass); codstatement.TrueStatements.Add(ass); } codeRefExp = new CodeMethodReferenceExpression(); codeRefExp.MethodName = @"m_configList.Add"; invoke = new CodeMethodInvokeExpression( codeRefExp, new CodeVariableReferenceExpression("data") ); codstatement.TrueStatements.Add(invoke); } setMethod.Statements.Add(its); }
private void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e) { if (e.TargetObject != null) { if (e.TargetObject is CodeBinaryOperatorExpression) { Output.Write("("); GenerateExpression(e.TargetObject); Output.Write(")"); } else { GenerateExpression(e.TargetObject); } Output.Write("."); } OutputIdentifier(e.MethodName); if (e.TypeArguments.Count > 0) { Output.Write(GetTypeArgumentsOutput(e.TypeArguments)); } }
public CodeMethodInvokeExpression(CodeMethodReferenceExpression method, params CodeExpression[] parameters) { _method = method; Parameters.AddRange(parameters); }
public CodeTypeDeclaration GenerateClass(Generator g, CodeTypeDeclaration libDecl, string libFieldName) { var decl = new CodeTypeDeclaration (Name); decl.IsPartial = true; if (BaseClasses.Count > 0) decl.BaseTypes.Add (new CodeTypeReference (BaseClasses [0].Name)); else decl.BaseTypes.Add (new CodeTypeReference ("ICppObject")); bool hasBase = BaseClasses.Count > 0; var layout = new CodeTypeDeclaration ("_" + Name); layout.IsStruct = true; layout.TypeAttributes = TypeAttributes.NotPublic; decl.Members.Add (layout); foreach (var f in Fields) { CodeMemberField field = new CodeMemberField { Name = f.Name, Type = g.CppTypeToCodeDomType (f.Type) }; layout.Members.Add (field); } var iface = new CodeTypeDeclaration ("I" + Name); iface.IsInterface = true; layout.TypeAttributes = TypeAttributes.NotPublic; iface.BaseTypes.Add (new CodeTypeReference ("ICppClassOverridable", new CodeTypeReference [] { new CodeTypeReference (decl.Name) })); decl.Members.Add (iface); var layoutField = new CodeMemberField (new CodeTypeReference (typeof (Type)), "native_layout"); layoutField.Attributes = MemberAttributes.Private|MemberAttributes.Static; layoutField.InitExpression = new CodeTypeOfExpression (layout.Name); decl.Members.Add (layoutField); var implField = new CodeMemberField (new CodeTypeReference (iface.Name), "impl"); implField.Attributes = MemberAttributes.Private|MemberAttributes.Static; var getclass = new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (libDecl.Name), libFieldName), "GetClass", new CodeTypeReference [] { new CodeTypeReference (iface.Name), new CodeTypeReference (layout.Name), new CodeTypeReference (decl.Name) }); implField.InitExpression = new CodeMethodInvokeExpression (getclass, new CodeExpression [] { new CodePrimitiveExpression (Name) }); decl.Members.Add (implField); //private static IClass impl = global::CppTests.Libs.Test.GetClass <IClass, _Class, Class>("Class"); if (!hasBase) { var ptrField = new CodeMemberField (new CodeTypeReference ("CppInstancePtr"), "native_ptr"); ptrField.Attributes = MemberAttributes.Family; decl.Members.Add (ptrField); } var allocCtor = new CodeConstructor () { }; allocCtor.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("CppLibrary"), "dummy")); allocCtor.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "native_ptr"), new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (null, "impl"), "Alloc"), new CodeExpression [] { new CodeThisReferenceExpression () }))); if (hasBase) { var implTypeInfo = new CodeFieldReferenceExpression (new CodeFieldReferenceExpression { FieldName = "impl" }, "TypeInfo"); allocCtor.BaseConstructorArgs.Add (implTypeInfo); } decl.Members.Add (allocCtor); var subclassCtor = new CodeConstructor () { Attributes = MemberAttributes.Family }; subclassCtor.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("CppTypeInfo"), "subClass")); subclassCtor.Statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeArgumentReferenceExpression ("subClass"), "AddBase"), new CodeExpression [] { new CodeFieldReferenceExpression (new CodeFieldReferenceExpression (null, "impl"), "TypeInfo") }))); if (hasBase) { var implTypeInfo = new CodeFieldReferenceExpression (new CodeFieldReferenceExpression { FieldName = "impl" }, "TypeInfo"); subclassCtor.BaseConstructorArgs.Add (implTypeInfo); } decl.Members.Add (subclassCtor); if (!hasBase) { var nativeProperty = new CodeMemberProperty () { Name = "Native", Type = new CodeTypeReference ("CppInstancePtr"), Attributes = MemberAttributes.Public|MemberAttributes.Final }; nativeProperty.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "native_ptr"))); decl.Members.Add (nativeProperty); } var disposeMethod = new CodeMemberMethod () { Name = "Dispose", Attributes = MemberAttributes.Public }; if (Methods.Any (m => m.IsDestructor)) disposeMethod.Statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (null, "impl"), "Destruct"), new CodeExpression [] { new CodeFieldReferenceExpression (null, "Native") }))); disposeMethod.Statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (null, "Native"), "Dispose")))); decl.Members.Add (disposeMethod); foreach (Method m in Methods) { iface.Members.Add (m.GenerateIFaceMethod (g)); if (m.GenWrapperMethod) { var cm = m.GenerateWrapperMethod (g); if (m.IsConstructor && hasBase) { var implTypeInfo = new CodeFieldReferenceExpression (new CodeFieldReferenceExpression { FieldName = "impl" }, "TypeInfo"); (cm as CodeConstructor).BaseConstructorArgs.Add (implTypeInfo); } decl.Members.Add (cm); } } foreach (Property p in Properties) { decl.Members.Add (p.GenerateProperty (g)); } return decl; }
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); }
public void Visit(CodeMethodReferenceExpression o) { g.GenerateMethodReferenceExpression(o); }
public StatementBuilder InvokeMethod(ITarget methodSource, CodeMethodReferenceExpression method, ParamBuilder parameters) { var invokeMethod = new CodeMethodInvokeExpression(methodSource.Expression, method.MethodName, parameters); Expressions.Add(new CodeExpressionStatement(invokeMethod)); return this; }
protected override void GenerateMethodReferenceExpression (CodeMethodReferenceExpression e) { if(e.TargetObject != null) { GenerateExpression(e.TargetObject); Output.Write("."); } OutputIdentifier(e.MethodName); }
private static void AddEntityOptionSetEnumDeclaration(CodeTypeDeclarationCollection types) { var enumClass = new CodeTypeDeclaration("EntityOptionSetEnum") { IsClass = true, TypeAttributes = TypeAttributes.Sealed | TypeAttributes.NotPublic, }; // public static int? GetEnum(Microsoft.Xrm.Sdk.Entity entity, string attributeLogicalName) var get = new CodeMemberMethod { Name = "GetEnum", ReturnType = new CodeTypeReference(typeof(int?)), // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags Attributes = System.CodeDom.MemberAttributes.Static | System.CodeDom.MemberAttributes.Public, }; get.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Microsoft.Xrm.Sdk.Entity), "entity")); get.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "attributeLogicalName")); // entity.Attributes.ContainsKey(attributeLogicalName) var entityAttributesContainsKey = new CodeMethodReferenceExpression( new CodePropertyReferenceExpression( new CodeArgumentReferenceExpression("entity"), "Attributes"), "ContainsKey"); var invokeContainsKey = new CodeMethodInvokeExpression(entityAttributesContainsKey, new CodeArgumentReferenceExpression("attributeLogicalName")); // Microsoft.Xrm.Sdk.OptionSetValue value = entity.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>(attributeLogicalName).Value; var declareAndSetValue = new CodeVariableDeclarationStatement { Type = new CodeTypeReference(typeof(OptionSetValue)), Name = "value", InitExpression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeArgumentReferenceExpression("entity"), "GetAttributeValue", new CodeTypeReference(typeof(OptionSetValue))), new CodeArgumentReferenceExpression("attributeLogicalName")) }; // value != null var valueNeNull = new CodeSnippetExpression("value != null"); // value.Value var invokeValueGetValue = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("value"), "Value"); // if(invokeContainsKey){return invokeGetAttributeValue;}else{return null} get.Statements.Add(new CodeConditionStatement(invokeContainsKey, new CodeStatement[] { declareAndSetValue, new CodeConditionStatement(valueNeNull, new CodeMethodReturnStatement(invokeValueGetValue)) })); // return null; get.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null))); enumClass.Members.Add(get); types.Add(enumClass); }
private void ValidateMethodReferenceExpression(CodeMethodReferenceExpression e) { if (e.TargetObject != null) { ValidateExpression(e.TargetObject); } ValidateIdentifier(e, nameof(e.MethodName), e.MethodName); ValidateTypeReferences(e.TypeArguments); }