/// <summary> /// 字段 /// <para>eg. public Dictionary<string,string> TestDic = new Dictionary<string,string>();</para> /// </summary> /// <param name="inLeft">字段类型</param> /// <param name="inFieldName"></param> /// <param name="inRight"></param> public ItemField(string inLeft, string inFieldName, string inRight = "", MemberAttributes inAtt = MemberAttributes.Private) { field = new CodeMemberField(inLeft, inFieldName); if (inRight != "") { CodeVariableReferenceExpression right = new CodeVariableReferenceExpression(inRight); field.InitExpression = right; } field.Attributes = inAtt; }
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); }
/// <summary> /// Create serialization method /// </summary> private CodeTypeMember CreateSerializeMethod(Type forType) { var retVal = new CodeMemberMethod() { Name = "Serialize", ReturnType = new CodeTypeReference(typeof(void)), Attributes = MemberAttributes.Public | MemberAttributes.Final }; retVal.Parameters.Add(new CodeParameterDeclarationExpression(typeof(JsonWriter), "w")); retVal.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IdentifiedData), "o")); retVal.Parameters.Add(new CodeParameterDeclarationExpression(typeof(JsonSerializationContext), "context")); var _object = new CodeVariableReferenceExpression("o"); var _writer = new CodeVariableReferenceExpression("w"); var _context = new CodeVariableReferenceExpression("context"); // Verify the object is not null retVal.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(_object, CodeBinaryOperatorType.IdentityEquality, s_null), new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(ArgumentNullException), new CodePrimitiveExpression("o"))))); // Cast var _strongType = new CodeVariableReferenceExpression("_strong"); var _strongKeyReference = new CodePropertyReferenceExpression(_strongType, "Key"); //var _loaded = new CodeVariableReferenceExpression("_loaded"); var _jsonContext = new CodePropertyReferenceExpression(_context, "JsonContext"); retVal.Statements.Add(new CodeVariableDeclarationStatement(forType, "_strong", s_null)); //retVal.Statements.Add(new CodeVariableDeclarationStatement(typeof(JsonSerializationContext), "_jsonContext", s_null)); //retVal.Statements.Add(new CodeVariableDeclarationStatement(typeof(bool), "_loaded", s_false)); retVal.Statements.Add(this.CreateCastTryCatch(forType, _strongType, _object, new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(ArgumentException), this.CreateStringFormatExpression("Invalid type {0} provided, expected {1}", this.CreateGetTypeExpression(_object), new CodeTypeOfExpression(forType)))))); // Iterate through the object constructing the properties foreach (var pi in forType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var jsonName = this.GetPropertyName(pi, true); if (jsonName == null || jsonName.StartsWith("$") || !pi.CanRead) { continue; } // Create an if statement that represents whether we should serialize var shouldSerializeCondition = new CodeConditionStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(_context, "ShouldSerialize"), new CodePrimitiveExpression(jsonName))); retVal.Statements.Add(shouldSerializeCondition); var _propertyReference = new CodePropertyReferenceExpression(_strongType, pi.Name); var writePropertyCall = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(_jsonContext, "WritePropertyUtil"), _writer, new CodePrimitiveExpression(jsonName), _propertyReference, _context); // Check if the property is nullable if (pi.PropertyType.IsClass || pi.PropertyType.StripNullable() != pi.PropertyType) { CodeBinaryOperatorExpression isNullCondition = new CodeBinaryOperatorExpression(_propertyReference, CodeBinaryOperatorType.IdentityEquality, s_null); if (typeof(IList).IsAssignableFrom(pi.PropertyType) && !pi.PropertyType.IsArray) { isNullCondition = new CodeBinaryOperatorExpression(isNullCondition, CodeBinaryOperatorType.BooleanOr, new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(_propertyReference, "Count"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0))); } var nullPropertyValueCondition = new CodeConditionStatement(isNullCondition); shouldSerializeCondition.TrueStatements.Add(nullPropertyValueCondition); // Method expression to call WritePropertyUtil // Should we delay load? if (typeof(IIdentifiedEntity).IsAssignableFrom(pi.PropertyType.StripGeneric())) { CodeExpression wasLoadedExpression = null; CodeConditionStatement shouldForceLoad = null; var _delay = new CodeVariableReferenceExpression("_delay"); if (typeof(IList).IsAssignableFrom(pi.PropertyType) && !pi.PropertyType.IsArray) { var shouldForceLoadCondition = new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(_strongKeyReference, "HasValue"), CodeBinaryOperatorType.BooleanAnd, new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(_context, "ShouldForceLoad"), new CodePrimitiveExpression(jsonName), new CodePropertyReferenceExpression(_strongKeyReference, "Value"))); //if(typeof(IVersionedEntity).IsAssignableFrom(forType)) // shouldForceLoadCondition = new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(_strongType, "VersionKey"), "HasValue"), CodeBinaryOperatorType.BooleanAnd, shouldForceLoadCondition); shouldForceLoad = new CodeConditionStatement(shouldForceLoadCondition); // Check persistence nullPropertyValueCondition.TrueStatements.Add(shouldForceLoad); shouldForceLoad.TrueStatements.Add(new CodeVariableDeclarationStatement(pi.PropertyType, "_delay", s_null)); var _strongKeyReferenceValue = new CodePropertyReferenceExpression(_strongKeyReference, "Value"); if (typeof(ISimpleAssociation).IsAssignableFrom(pi.PropertyType.StripGeneric())) { var codeRef = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(ExtensionMethods)), nameof(ExtensionMethods.LoadCollection), new CodeTypeReference(pi.PropertyType.StripGeneric())); shouldForceLoad.TrueStatements.Add(new CodeAssignStatement(_delay, new CodeMethodInvokeExpression(s_toList, new CodeMethodInvokeExpression(codeRef, _strongType, new CodePrimitiveExpression(pi.Name))))); wasLoadedExpression = new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(_delay, "Count"), CodeBinaryOperatorType.GreaterThan, new CodePrimitiveExpression(0)); } } else { var keyPropertyRef = pi.GetCustomAttribute <SerializationReferenceAttribute>(); if (keyPropertyRef != null) { var _keyPropertyCodeReference = new CodePropertyReferenceExpression(_strongType, keyPropertyRef.RedirectProperty); var shouldForceLoadCondition = new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(_keyPropertyCodeReference, "HasValue"), CodeBinaryOperatorType.BooleanAnd, new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(_context, "ShouldForceLoad"), new CodePrimitiveExpression(jsonName), _strongKeyReference)); //if(typeof(IVersionedEntity).IsAssignableFrom(forType)) // shouldForceLoadCondition = new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(_strongType, "VersionKey"), "HasValue"), CodeBinaryOperatorType.BooleanAnd, shouldForceLoadCondition); shouldForceLoad = new CodeConditionStatement(shouldForceLoadCondition); // Check persistence nullPropertyValueCondition.TrueStatements.Add(shouldForceLoad); shouldForceLoad.TrueStatements.Add(new CodeVariableDeclarationStatement(pi.PropertyType, "_delay", s_null)); var codeRef = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(ExtensionMethods)), nameof(ExtensionMethods.LoadProperty), new CodeTypeReference(pi.PropertyType.StripGeneric())); shouldForceLoad.TrueStatements.Add(new CodeAssignStatement(_delay, new CodeMethodInvokeExpression(codeRef, _strongType, new CodePrimitiveExpression(pi.Name)))); wasLoadedExpression = new CodeBinaryOperatorExpression(_delay, CodeBinaryOperatorType.IdentityInequality, s_null); } } if (wasLoadedExpression != null) { shouldForceLoad.TrueStatements.Add(new CodeConditionStatement(wasLoadedExpression, new CodeStatement[] { new CodeAssignStatement(_propertyReference, _delay), new CodeExpressionStatement(writePropertyCall) }, new CodeStatement[] { new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(_context, "RegisterMissTarget"), new CodePrimitiveExpression(jsonName), new CodeMethodInvokeExpression(_strongKeyReference, "GetValueOrDefault"))) } )); } } nullPropertyValueCondition.FalseStatements.Add(writePropertyCall); } else { shouldSerializeCondition.TrueStatements.Add(writePropertyCall); } } // Do we need to write loaded properties //var _loadStateReference = new CodePropertyReferenceExpression(_strongType, nameof(IdentifiedData.LoadState)); //var _newLoadStateReference = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(LoadState)), nameof(LoadState.New)); //var shouldUpdateCacheExpression = new CodeBinaryOperatorExpression(_loaded, CodeBinaryOperatorType.BooleanAnd, // new CodeBinaryOperatorExpression( // new CodeBinaryOperatorExpression(_newLoadStateReference, CodeBinaryOperatorType.IdentityInequality, _loadStateReference), // CodeBinaryOperatorType.BooleanAnd, // new CodePropertyReferenceExpression(_strongKeyReference, "HasValue") // ) //); //if (typeof(IVersionedEntity).IsAssignableFrom(forType)) // shouldUpdateCacheExpression = new CodeBinaryOperatorExpression(shouldUpdateCacheExpression, CodeBinaryOperatorType.BooleanAnd, new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(_strongType, "VersionKey"), "HasValue")); //retVal.Statements.Add(new CodeConditionStatement(shouldUpdateCacheExpression, // new CodeExpressionStatement(new CodeMethodInvokeExpression( // new CodeMethodReferenceExpression( // new CodeCastExpression(typeof(IDataCachingService), new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(ApplicationServiceContext)), "Current"), "GetService"), new CodeTypeOfExpression(typeof(IDataCachingService)))), "Add"), _strongType)))); return(retVal); }
private static void GenerateProperties(Type t, CodeTypeDeclaration codeType) { foreach (PropertyInfo property in t.GetProperties()) { if (OmittedProperties.ContainsKey(t.FullName) && OmittedProperties[t.FullName].Contains(property.Name)) { continue; } if (property.CustomAttributes.Any(x => x.AttributeType.FullName.Contains("Obsolete"))) { continue; } string propertyType = GetPropertyType(property.PropertyType); bool isGenericCollection = property.PropertyType.IsGenericType && (property.PropertyType.GetGenericTypeDefinition() == typeof(IList <>) || property.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable <>) || property.PropertyType.GetGenericTypeDefinition() == typeof(IReadOnlyList <>)); CodeFieldReferenceExpression wrappedObject = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), OmObject); CodePropertyReferenceExpression wrappedObjectProperty = new CodePropertyReferenceExpression(wrappedObject, property.Name); CodeFieldReferenceExpression fieldReference = null; if (isGenericCollection || OMtoPSClassMappings.ContainsKey(property.PropertyType.FullName)) { // Add a backing field for the property with the same name but using camel case. string fieldName = string.Format("{0}{1}", property.Name.ToLower()[0], property.Name.Substring(1, property.Name.Length - 1)); CodeMemberField backingField = new CodeMemberField(); backingField.Attributes = MemberAttributes.Private; backingField.Name = fieldName; backingField.Type = new CodeTypeReference(propertyType); codeType.Members.Add(backingField); fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName); } CodeMemberProperty codeProperty = new CodeMemberProperty(); codeProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeProperty.Name = property.Name; codeProperty.Type = new CodeTypeReference(propertyType); // For properties with a backing field, the field will not be initialized in the constructor in order to avoid // hitting a run time access constraint from the OM. Instead, the field is initialized on the first access of // the property. if (isGenericCollection) { // Special handling for dict Type argType = property.PropertyType.GetGenericArguments()[0]; bool magicalDictConversion = propertyType == "IDictionary"; string wrapperArgType = argType.FullName.StartsWith("System") || argType.FullName.StartsWith("Microsoft.Azure.Batch.Common") ? argType.FullName : OMtoPSClassMappings[argType.FullName]; string wrapperType = magicalDictConversion ? string.Format("Dictionary<string, string>") : string.Format("List<{0}>", wrapperArgType); string variableName = magicalDictConversion ? "dict" : "list"; if (property.GetMethod != null && property.GetMethod.IsPublic) { // Collections are not kept in sync with the wrapped OM object. Cmdlets will need to sync them before sending // a request to the server. CodeVariableDeclarationStatement declaration = new CodeVariableDeclarationStatement(wrapperType, variableName); CodeVariableReferenceExpression reference = new CodeVariableReferenceExpression(variableName); CodeAssignStatement initialize = new CodeAssignStatement(reference, new CodeObjectCreateExpression(wrapperType)); // CodeDom doesn't support foreach loops very well, so instead explicitly get the enumerator and loop on MoveNext() calls const string enumeratorVariableName = "enumerator"; CodeVariableDeclarationStatement enumeratorDeclaration = new CodeVariableDeclarationStatement(string.Format("IEnumerator<{0}>", argType.FullName), enumeratorVariableName); CodeVariableReferenceExpression enumeratorReference = new CodeVariableReferenceExpression(enumeratorVariableName); CodeAssignStatement initializeEnumerator = new CodeAssignStatement(enumeratorReference, new CodeMethodInvokeExpression(wrappedObjectProperty, "GetEnumerator")); CodeIterationStatement loopStatement = new CodeIterationStatement(); loopStatement.TestExpression = new CodeMethodInvokeExpression(enumeratorReference, "MoveNext"); loopStatement.IncrementStatement = new CodeSnippetStatement(string.Empty); loopStatement.InitStatement = new CodeSnippetStatement(string.Empty); CodePropertyReferenceExpression enumeratorCurrent = new CodePropertyReferenceExpression(enumeratorReference, "Current"); // Fill the list by individually wrapping each item in the loop if (magicalDictConversion) { var keyReference = new CodePropertyReferenceExpression(enumeratorCurrent, OMToPSDictionaryConversionMappings[argType.FullName].Item1); var valueReference = new CodePropertyReferenceExpression(enumeratorCurrent, OMToPSDictionaryConversionMappings[argType.FullName].Item2); CodeMethodInvokeExpression addToList = new CodeMethodInvokeExpression(reference, "Add", keyReference, valueReference); loopStatement.Statements.Add(addToList); } else { // Fill the list by individually wrapping each item in the loop if (wrapperArgType.Contains("System") || wrapperArgType.StartsWith("Microsoft.Azure.Batch.Common")) { CodeMethodInvokeExpression addToList = new CodeMethodInvokeExpression(reference, "Add", enumeratorCurrent); loopStatement.Statements.Add(addToList); } else { CodeObjectCreateExpression createListItem = new CodeObjectCreateExpression(wrapperArgType, enumeratorCurrent); CodeMethodInvokeExpression addToList = new CodeMethodInvokeExpression(reference, "Add", createListItem); loopStatement.Statements.Add(addToList); } } // Initialize the backing field with the built list on first access of the property CodeAssignStatement assignStatement = new CodeAssignStatement(fieldReference, reference); CodePrimitiveExpression nullExpression = new CodePrimitiveExpression(null); CodeBinaryOperatorExpression fieldNullCheck = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityEquality, nullExpression); CodeBinaryOperatorExpression wrappedPropertyNullCheck = new CodeBinaryOperatorExpression(wrappedObjectProperty, CodeBinaryOperatorType.IdentityInequality, nullExpression); CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(fieldNullCheck, CodeBinaryOperatorType.BooleanAnd, wrappedPropertyNullCheck); CodeConditionStatement ifBlock = new CodeConditionStatement(condition, declaration, initialize, enumeratorDeclaration, initializeEnumerator, loopStatement, assignStatement); codeProperty.GetStatements.Add(ifBlock); codeProperty.GetStatements.Add(new CodeMethodReturnStatement(fieldReference)); } if (property.SetMethod != null && property.SetMethod.IsPublic) { // Call the "set" on the OM object to ensure that constraints are enforced. codeProperty.HasSet = true; CodePropertySetValueReferenceExpression valueReference = new CodePropertySetValueReferenceExpression(); CodeBinaryOperatorExpression nullCheck = new CodeBinaryOperatorExpression(valueReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)); CodeAssignStatement nullAssignment = new CodeAssignStatement(wrappedObjectProperty, new CodePrimitiveExpression(null)); CodeAssignStatement nonNullAssignment = new CodeAssignStatement(wrappedObjectProperty, new CodeObjectCreateExpression(string.Format("List<{0}>", argType.FullName))); CodeConditionStatement ifBlock = new CodeConditionStatement(nullCheck, new CodeStatement[] { nullAssignment }, new CodeStatement[] { nonNullAssignment }); codeProperty.SetStatements.Add(ifBlock); codeProperty.SetStatements.Add(new CodeAssignStatement(fieldReference, valueReference)); } } else if (OMtoPSClassMappings.ContainsKey(property.PropertyType.FullName)) { if (property.GetMethod != null && property.GetMethod.IsPublic) { codeProperty.HasGet = true; CodeObjectCreateExpression createFieldObject = new CodeObjectCreateExpression(OMtoPSClassMappings[property.PropertyType.FullName], wrappedObjectProperty); CodeAssignStatement assignStatement = new CodeAssignStatement(fieldReference, createFieldObject); CodePrimitiveExpression nullExpression = new CodePrimitiveExpression(null); CodeBinaryOperatorExpression fieldNullCheck = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityEquality, nullExpression); CodeBinaryOperatorExpression wrappedPropertyNullCheck = new CodeBinaryOperatorExpression(wrappedObjectProperty, CodeBinaryOperatorType.IdentityInequality, nullExpression); CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(fieldNullCheck, CodeBinaryOperatorType.BooleanAnd, wrappedPropertyNullCheck); CodeConditionStatement ifBlock = new CodeConditionStatement(condition, assignStatement); codeProperty.GetStatements.Add(ifBlock); codeProperty.GetStatements.Add(new CodeMethodReturnStatement(fieldReference)); } if (property.SetMethod != null && property.SetMethod.IsPublic) { codeProperty.HasSet = true; CodePropertySetValueReferenceExpression valueReference = new CodePropertySetValueReferenceExpression(); CodeBinaryOperatorExpression nullCheck = new CodeBinaryOperatorExpression(valueReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)); CodeAssignStatement nullAssignment = new CodeAssignStatement(wrappedObjectProperty, new CodePrimitiveExpression(null)); CodePropertyReferenceExpression valueProperty = new CodePropertyReferenceExpression(valueReference, OmObject); CodeAssignStatement nonNullAssignment = new CodeAssignStatement(wrappedObjectProperty, valueProperty); CodeConditionStatement ifBlock = new CodeConditionStatement(nullCheck, new CodeStatement[] { nullAssignment }, new CodeStatement[] { nonNullAssignment }); codeProperty.SetStatements.Add(ifBlock); codeProperty.SetStatements.Add(new CodeAssignStatement(fieldReference, valueReference)); } } else { // By default, just pass through to the wrapped OM object's property. if (property.GetMethod != null && property.GetMethod.IsPublic) { codeProperty.HasGet = true; codeProperty.GetStatements.Add(new CodeMethodReturnStatement(wrappedObjectProperty)); } if (property.SetMethod != null && property.SetMethod.IsPublic) { codeProperty.HasSet = true; codeProperty.SetStatements.Add(new CodeAssignStatement(wrappedObjectProperty, new CodePropertySetValueReferenceExpression())); } } codeType.Members.Add(codeProperty); } }
private CodeExpression[] GetListParameters(bool set, bool constructor) { CodeExpression[] listParameters = null; int paramCount = 2; CodeExpression typeParam = null; CodeExpression nameOrValue = null; if (set) { paramCount++; if (!constructor) { nameOrValue = CodeDomHelper.SetValue(); } else { nameOrValue = new CodeVariableReferenceExpression(this.propertyName); } } if (!this.IsSubstitutionHead) { paramCount++; if (!this.typeRef.IsSimpleType) { typeParam = CodeDomHelper.SingletonTypeManager(); } else { typeParam = this.GetSchemaDatatypeExpression(); if (this.fixedDefaultValue != null) { paramCount++; } } } else { paramCount += this.substitutionMembers.Count; typeParam = CodeDomHelper.SingletonTypeManager(); } listParameters = new CodeExpression[paramCount]; int paramIndex = 0; int num = paramIndex; paramIndex = num + 1; listParameters[num] = CodeDomHelper.This(); int num1 = paramIndex; paramIndex = num1 + 1; listParameters[num1] = typeParam; if (nameOrValue != null) { int num2 = paramIndex; paramIndex = num2 + 1; listParameters[num2] = nameOrValue; } if (!this.IsSubstitutionHead) { int num3 = paramIndex; paramIndex = num3 + 1; listParameters[num3] = this.xNameGetExpression; } else { foreach (XmlSchemaElement elem in this.substitutionMembers) { int num4 = paramIndex; paramIndex = num4 + 1; listParameters[num4] = CodeDomHelper.XNameGetExpression(elem.QualifiedName.Name, elem.QualifiedName.Namespace); } } if (this.fixedDefaultValue != null) { if (this.FixedValue == null) { int num5 = paramIndex; paramIndex = num5 + 1; listParameters[num5] = new CodeFieldReferenceExpression(null, NameGenerator.ChangeClrName(this.propertyName, NameOptions.MakeDefaultValueField)); } else { int num6 = paramIndex; paramIndex = num6 + 1; listParameters[num6] = new CodeFieldReferenceExpression(null, NameGenerator.ChangeClrName(this.propertyName, NameOptions.MakeFixedValueField)); } } return(listParameters); }
private void EmitTupleFieldAssignments(List<Exp> lhs, CodeVariableReferenceExpression tup) { int i = 0; foreach (Exp value in lhs) { ++i; if (value == null || value.Name == "_") continue; var tupleField = gen.Access(tup, "Item" + i); var id = value as Identifier; if (id != null) { EnsureLocalVariable(id.Name, new CodeTypeReference(typeof(object)), false); gen.Assign(new CodeVariableReferenceExpression(id.Name), tupleField); } else { var dst = value.Accept(xlat); gen.Assign(dst, tupleField); } } }
void GenerateEventBasedAsyncSupport(CodeTypeDeclaration type, OperationDescription od, CodeNamespace cns) { var method = FindByName(type, od.Name) ?? FindByName(type, "Begin" + od.Name); var endMethod = method.Name == od.Name ? null : FindByName(type, "End" + od.Name); bool methodAsync = method.Name.StartsWith("Begin", StringComparison.Ordinal); var resultType = endMethod != null ? endMethod.ReturnType : method.ReturnType; var thisExpr = new CodeThisReferenceExpression(); var baseExpr = new CodeBaseReferenceExpression(); var nullExpr = new CodePrimitiveExpression(null); var asyncResultType = new CodeTypeReference(typeof(IAsyncResult)); // OnBeginXxx() implementation var cm = new CodeMemberMethod() { Name = "OnBegin" + od.Name, Attributes = MemberAttributes.Private | MemberAttributes.Final, ReturnType = asyncResultType }; type.Members.Add(cm); AddMethodParam(cm, typeof(object []), "args"); AddMethodParam(cm, typeof(AsyncCallback), "asyncCallback"); AddMethodParam(cm, typeof(object), "userState"); var call = new CodeMethodInvokeExpression( thisExpr, "Begin" + od.Name); for (int idx = 0; idx < method.Parameters.Count - (methodAsync ? 2 : 0); idx++) { var p = method.Parameters [idx]; cm.Statements.Add(new CodeVariableDeclarationStatement(p.Type, p.Name, new CodeCastExpression(p.Type, new CodeArrayIndexerExpression(new CodeArgumentReferenceExpression("args"), new CodePrimitiveExpression(idx))))); call.Parameters.Add(new CodeVariableReferenceExpression(p.Name)); } call.Parameters.Add(new CodeArgumentReferenceExpression("asyncCallback")); call.Parameters.Add(new CodeArgumentReferenceExpression("userState")); cm.Statements.Add(new CodeMethodReturnStatement(call)); // OnEndXxx() implementation cm = new CodeMemberMethod() { Name = "OnEnd" + od.Name, Attributes = MemberAttributes.Private | MemberAttributes.Final, ReturnType = new CodeTypeReference(typeof(object [])) }; type.Members.Add(cm); AddMethodParam(cm, typeof(IAsyncResult), "result"); var outArgRefs = new List <CodeVariableReferenceExpression> (); for (int idx = 0; idx < method.Parameters.Count; idx++) { var p = method.Parameters [idx]; if (p.Direction != FieldDirection.In) { cm.Statements.Add(new CodeVariableDeclarationStatement(p.Type, p.Name)); outArgRefs.Add(new CodeVariableReferenceExpression(p.Name)); // FIXME: should this work? They need "out" or "ref" modifiers. } } call = new CodeMethodInvokeExpression( thisExpr, "End" + od.Name, new CodeArgumentReferenceExpression("result")); call.Parameters.AddRange(outArgRefs.Cast <CodeExpression> ().ToArray()); // questionable var retCreate = new CodeArrayCreateExpression(typeof(object)); if (resultType.BaseType == "System.Void") { cm.Statements.Add(call); } else { cm.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "__ret", call)); retCreate.Initializers.Add(new CodeVariableReferenceExpression("__ret")); } foreach (var outArgRef in outArgRefs) { retCreate.Initializers.Add(new CodeVariableReferenceExpression(outArgRef.VariableName)); } cm.Statements.Add(new CodeMethodReturnStatement(retCreate)); // OnXxxCompleted() implementation cm = new CodeMemberMethod() { Name = "On" + od.Name + "Completed", Attributes = MemberAttributes.Private | MemberAttributes.Final }; type.Members.Add(cm); AddMethodParam(cm, typeof(object), "state"); string argsname = identifiers.AddUnique(od.Name + "CompletedEventArgs", null); var iaargs = new CodeTypeReference("InvokeAsyncCompletedEventArgs"); // avoid messy System.Type instance for generic nested type :| var iaref = new CodeVariableReferenceExpression("args"); var methodEventArgs = new CodeObjectCreateExpression(new CodeTypeReference(argsname), new CodePropertyReferenceExpression(iaref, "Results"), new CodePropertyReferenceExpression(iaref, "Error"), new CodePropertyReferenceExpression(iaref, "Cancelled"), new CodePropertyReferenceExpression(iaref, "UserState")); cm.Statements.Add(new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeEventReferenceExpression(thisExpr, od.Name + "Completed"), CodeBinaryOperatorType.IdentityInequality, nullExpr), new CodeVariableDeclarationStatement(iaargs, "args", new CodeCastExpression(iaargs, new CodeArgumentReferenceExpression("state"))), new CodeExpressionStatement(new CodeMethodInvokeExpression(thisExpr, od.Name + "Completed", thisExpr, methodEventArgs)))); // delegate fields type.Members.Add(new CodeMemberField(new CodeTypeReference("BeginOperationDelegate"), "onBegin" + od.Name + "Delegate")); type.Members.Add(new CodeMemberField(new CodeTypeReference("EndOperationDelegate"), "onEnd" + od.Name + "Delegate")); type.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(SendOrPostCallback)), "on" + od.Name + "CompletedDelegate")); // XxxCompletedEventArgs class var argsType = new CodeTypeDeclaration(argsname); argsType.BaseTypes.Add(new CodeTypeReference(typeof(AsyncCompletedEventArgs))); cns.Types.Add(argsType); var argsCtor = new CodeConstructor() { Attributes = MemberAttributes.Public | MemberAttributes.Final }; argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object []), "results")); argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Exception), "error")); argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "cancelled")); argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState")); argsCtor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("error")); argsCtor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("cancelled")); argsCtor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("userState")); var resultsField = new CodeFieldReferenceExpression(thisExpr, "results"); argsCtor.Statements.Add(new CodeAssignStatement(resultsField, new CodeArgumentReferenceExpression("results"))); argsType.Members.Add(argsCtor); argsType.Members.Add(new CodeMemberField(typeof(object []), "results")); if (resultType.BaseType != "System.Void") { var resultProp = new CodeMemberProperty { Name = "Result", Type = resultType, Attributes = MemberAttributes.Public | MemberAttributes.Final }; resultProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(resultProp.Type, new CodeArrayIndexerExpression(resultsField, new CodePrimitiveExpression(0))))); argsType.Members.Add(resultProp); } // event field var handlerType = new CodeTypeReference(typeof(EventHandler <>)); handlerType.TypeArguments.Add(new CodeTypeReference(argsType.Name)); type.Members.Add(new CodeMemberEvent() { Name = od.Name + "Completed", Type = handlerType, Attributes = MemberAttributes.Public | MemberAttributes.Final }); // XxxAsync() implementations bool hasAsync = false; foreach (int __x in Enumerable.Range(0, 2)) { cm = new CodeMemberMethod(); type.Members.Add(cm); cm.Name = od.Name + "Async"; cm.Attributes = MemberAttributes.Public | MemberAttributes.Final; var inArgs = new List <CodeParameterDeclarationExpression> (); for (int idx = 0; idx < method.Parameters.Count - (methodAsync ? 2 : 0); idx++) { var pd = method.Parameters [idx]; inArgs.Add(pd); cm.Parameters.Add(pd); } // First one is overload without asyncState arg. if (!hasAsync) { call = new CodeMethodInvokeExpression(thisExpr, cm.Name, inArgs.ConvertAll <CodeExpression> (decl => new CodeArgumentReferenceExpression(decl.Name)).ToArray()); call.Parameters.Add(nullExpr); cm.Statements.Add(new CodeExpressionStatement(call)); hasAsync = true; continue; } // Second one is the primary one. cm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState")); // if (onBeginBarOperDelegate == null) onBeginBarOperDelegate = new BeginOperationDelegate (OnBeginBarOper); // if (onEndBarOperDelegate == null) onEndBarOperDelegate = new EndOperationDelegate (OnEndBarOper); // if (onBarOperCompletedDelegate == null) onBarOperCompletedDelegate = new BeginOperationDelegate (OnBarOperCompleted); var beginOperDelegateRef = new CodeFieldReferenceExpression(thisExpr, "onBegin" + od.Name + "Delegate"); var endOperDelegateRef = new CodeFieldReferenceExpression(thisExpr, "onEnd" + od.Name + "Delegate"); var operCompletedDelegateRef = new CodeFieldReferenceExpression(thisExpr, "on" + od.Name + "CompletedDelegate"); var ifstmt = new CodeConditionStatement( new CodeBinaryOperatorExpression(beginOperDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr), new CodeAssignStatement(beginOperDelegateRef, new CodeDelegateCreateExpression(new CodeTypeReference("BeginOperationDelegate"), thisExpr, "OnBegin" + od.Name))); cm.Statements.Add(ifstmt); ifstmt = new CodeConditionStatement( new CodeBinaryOperatorExpression(endOperDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr), new CodeAssignStatement(endOperDelegateRef, new CodeDelegateCreateExpression(new CodeTypeReference("EndOperationDelegate"), thisExpr, "OnEnd" + od.Name))); cm.Statements.Add(ifstmt); ifstmt = new CodeConditionStatement( new CodeBinaryOperatorExpression(operCompletedDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr), new CodeAssignStatement(operCompletedDelegateRef, new CodeDelegateCreateExpression(new CodeTypeReference(typeof(SendOrPostCallback)), thisExpr, "On" + od.Name + "Completed"))); cm.Statements.Add(ifstmt); // InvokeAsync (onBeginBarOperDelegate, inValues, onEndBarOperDelegate, onBarOperCompletedDelegate, userState); inArgs.Add(new CodeParameterDeclarationExpression(typeof(object), "userState")); var args = new List <CodeExpression> (); args.Add(beginOperDelegateRef); args.Add(new CodeArrayCreateExpression(typeof(object), inArgs.ConvertAll <CodeExpression> (decl => new CodeArgumentReferenceExpression(decl.Name)).ToArray())); args.Add(endOperDelegateRef); args.Add(new CodeFieldReferenceExpression(thisExpr, "on" + od.Name + "CompletedDelegate")); args.Add(new CodeArgumentReferenceExpression("userState")); call = new CodeMethodInvokeExpression(baseExpr, "InvokeAsync", args.ToArray()); cm.Statements.Add(new CodeExpressionStatement(call)); } }
private static void BuildLogic(CodeStatementCollection statements, ReadOnlyArrayCollection <ParticleSystemLogicStep> steps, bool addMethod) { Dictionary <string, bool> argsUsed = new Dictionary <string, bool>(); foreach (string arg in memberTranslate.Keys) { argsUsed.Add(arg, false); } argsUsed.Add("rand", false); CodeStatementCollection code = new CodeStatementCollection(); BuildLogic(code, steps, argsUsed, 0); //rand requires a local variable if (argsUsed["rand"]) { statements.Add( new CodeVariableDeclarationStatement( typeof(float), "_tmp", new CodePrimitiveExpression(0.0f))); } for (int i = 0; i < 4; i++) { if (argsUsed["local" + i]) { code.Insert(0, new CodeVariableDeclarationStatement( typeof(float), "local" + i, new CodePrimitiveExpression(0.0f))); } } CodeVariableReferenceExpression ref_i = new CodeVariableReferenceExpression("i"); if (addMethod) // add methods have indices to update... { ref_i.VariableName = "_i"; } CodeIterationStatement loop = new CodeIterationStatement(); loop.InitStatement = new CodeVariableDeclarationStatement(typeof(uint), ref_i.VariableName, new CodePrimitiveExpression(0)); loop.IncrementStatement = new CodeAssignStatement(ref_i, new CodeBinaryOperatorExpression(ref_i, CodeBinaryOperatorType.Add, new CodePrimitiveExpression((uint)1))); loop.TestExpression = new CodeBinaryOperatorExpression(ref_i, CodeBinaryOperatorType.LessThan, new CodeArgumentReferenceExpression("count")); // uint i = indices[_i]; if (addMethod) { loop.Statements.Add(new CodeVariableDeclarationStatement(typeof(uint), "i", new CodeArrayIndexerExpression(new CodeArgumentReferenceExpression("indices"), ref_i))); } else { //put in velocity logic loop.Statements.Add( new CodeAssignStatement(Arg("position.x"), new CodeBinaryOperatorExpression(Arg("position.x"), CodeBinaryOperatorType.Add, new CodeBinaryOperatorExpression(Arg("velocity.x"), CodeBinaryOperatorType.Multiply, Arg("delta_time"))))); loop.Statements.Add( new CodeAssignStatement(Arg("position.y"), new CodeBinaryOperatorExpression(Arg("position.y"), CodeBinaryOperatorType.Add, new CodeBinaryOperatorExpression(Arg("velocity.y"), CodeBinaryOperatorType.Multiply, Arg("delta_time"))))); loop.Statements.Add( new CodeAssignStatement(Arg("position.z"), new CodeBinaryOperatorExpression(Arg("position.z"), CodeBinaryOperatorType.Add, new CodeBinaryOperatorExpression(Arg("velocity.z"), CodeBinaryOperatorType.Multiply, Arg("delta_time"))))); } loop.Statements.AddRange(code); statements.Add(loop); }
public void Visit(CodeVariableReferenceExpression o) { g.GenerateVariableReferenceExpression(o); }
private static CodeMemberMethod CreateBeginOperationMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeMemberMethod beginMethod) { CodeMemberMethod method = new CodeMemberMethod(); method.Attributes = MemberAttributes.Private; method.ReturnType = new CodeTypeReference(asyncResultType); method.Name = NamingHelper.GetUniqueName(GetBeginOperationMethodName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations); CodeParameterDeclarationExpression expression = new CodeParameterDeclarationExpression(); expression.Type = new CodeTypeReference(objectArrayType); expression.Name = NamingHelper.GetUniqueName("inValues", new NamingHelper.DoesNameExist(ClientClassGenerator.DoesParameterNameExist), beginMethod); method.Parameters.Add(expression); CodeMethodInvokeExpression expression2 = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), beginMethod.Name, new CodeExpression[0]); CodeExpression targetObject = new CodeVariableReferenceExpression(expression.Name); for (int i = 0; i < (beginMethod.Parameters.Count - 2); i++) { CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(); statement.Type = beginMethod.Parameters[i].Type; statement.Name = beginMethod.Parameters[i].Name; statement.InitExpression = new CodeCastExpression(statement.Type, new CodeArrayIndexerExpression(targetObject, new CodeExpression[] { new CodePrimitiveExpression(i) })); method.Statements.Add(statement); expression2.Parameters.Add(new CodeDirectionExpression(beginMethod.Parameters[i].Direction, new CodeVariableReferenceExpression(statement.Name))); } for (int j = beginMethod.Parameters.Count - 2; j < beginMethod.Parameters.Count; j++) { method.Parameters.Add(new CodeParameterDeclarationExpression(beginMethod.Parameters[j].Type, beginMethod.Parameters[j].Name)); expression2.Parameters.Add(new CodeVariableReferenceExpression(beginMethod.Parameters[j].Name)); } method.Statements.Add(new CodeMethodReturnStatement(expression2)); clientType.Members.Add(method); return method; }
private static CodeMemberMethod GenerateHelperMethod(CodeTypeReference ifaceType, CodeMemberMethod method) { CodeMemberMethod helperMethod = new CodeMemberMethod(); helperMethod.Name = method.Name; helperMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeCastExpression(ifaceType, new CodeThisReferenceExpression()), method.Name), new CodeExpression[0]); bool flag = false; foreach (CodeParameterDeclarationExpression expression2 in method.Parameters) { CodeTypeDeclaration codeType = ServiceContractGenerator.NamespaceHelper.GetCodeType(expression2.Type); if (codeType != null) { flag = true; CodeVariableReferenceExpression expression3 = new CodeVariableReferenceExpression("inValue"); helperMethod.Statements.Add(new CodeVariableDeclarationStatement(expression2.Type, expression3.VariableName, new CodeObjectCreateExpression(expression2.Type, new CodeExpression[0]))); expression.Parameters.Add(expression3); GenerateParameters(helperMethod, codeType, expression3, FieldDirection.In); } else { helperMethod.Parameters.Add(new CodeParameterDeclarationExpression(expression2.Type, expression2.Name)); expression.Parameters.Add(new CodeArgumentReferenceExpression(expression2.Name)); } } if (method.ReturnType.BaseType == voidTypeRef.BaseType) { helperMethod.Statements.Add(expression); } else { CodeTypeDeclaration codeTypeDeclaration = ServiceContractGenerator.NamespaceHelper.GetCodeType(method.ReturnType); if (codeTypeDeclaration != null) { flag = true; CodeVariableReferenceExpression target = new CodeVariableReferenceExpression("retVal"); helperMethod.Statements.Add(new CodeVariableDeclarationStatement(method.ReturnType, target.VariableName, expression)); CodeMethodReturnStatement statement = GenerateParameters(helperMethod, codeTypeDeclaration, target, FieldDirection.Out); if (statement != null) { helperMethod.Statements.Add(statement); } } else { helperMethod.Statements.Add(new CodeMethodReturnStatement(expression)); helperMethod.ReturnType = method.ReturnType; } } if (flag) { method.PrivateImplementationType = ifaceType; } if (!flag) { return null; } return helperMethod; }
private static CodeMemberMethod CreateOperationCompletedMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeTypeDeclaration operationCompletedEventArgsType, CodeMemberEvent operationCompletedEvent) { CodeObjectCreateExpression expression; CodeMemberMethod method = new CodeMemberMethod(); method.Attributes = MemberAttributes.Private; method.Name = NamingHelper.GetUniqueName(GetOperationCompletedMethodName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations); method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(objectType), "state")); method.ReturnType = new CodeTypeReference(voidType); CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(invokeAsyncCompletedEventArgsTypeName, "e"); statement.InitExpression = new CodeCastExpression(invokeAsyncCompletedEventArgsTypeName, new CodeArgumentReferenceExpression(method.Parameters[0].Name)); CodeVariableReferenceExpression targetObject = new CodeVariableReferenceExpression(statement.Name); if (operationCompletedEventArgsType != null) { expression = new CodeObjectCreateExpression(operationCompletedEventArgsType.Name, new CodeExpression[] { new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[0]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[1]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[2]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[3]) }); } else { expression = new CodeObjectCreateExpression(asyncCompletedEventArgsType, new CodeExpression[] { new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[1]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[2]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[3]) }); } CodeEventReferenceExpression expression3 = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), operationCompletedEvent.Name); CodeDelegateInvokeExpression expression4 = new CodeDelegateInvokeExpression(expression3, new CodeExpression[] { new CodeThisReferenceExpression(), expression }); CodeConditionStatement statement2 = new CodeConditionStatement(new CodeBinaryOperatorExpression(expression3, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), new CodeStatement[] { statement, new CodeExpressionStatement(expression4) }); method.Statements.Add(statement2); clientType.Members.Add(method); return method; }
public void VisitVariableReference(CodeVariableReferenceExpression var) { writer.WriteName(var.Name); }
private void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e) { OutputIdentifier(e.VariableName); }
protected override void CreateConstructor(CodeStatementCollection localVars, CodeStatementCollection trueStmt) { MainDirectiveAttribute <string> masterPageFile = pageParser.MasterPageFile; if (masterPageFile != null && !masterPageFile.IsExpression) { // This is here just to trigger master page build, so that its type // is available when compiling the page itself. BuildManager.GetCompiledType(masterPageFile.Value); } MainDirectiveAttribute <string> clientTarget; clientTarget = pageParser.ClientTarget; if (clientTarget != null) { CodeExpression prop; prop = new CodePropertyReferenceExpression(thisRef, "ClientTarget"); CodeExpression ct = null; if (clientTarget.IsExpression) { var pi = GetFieldOrProperty(typeof(Page), "ClientTarget") as PropertyInfo; if (pi != null) { ct = CompileExpression(pi, pi.PropertyType, clientTarget.UnparsedValue, false); } } if (ct == null) { ct = new CodePrimitiveExpression(clientTarget.Value); } if (localVars == null) { localVars = new CodeStatementCollection(); } localVars.Add(new CodeAssignStatement(prop, ct)); } List <string> deps = pageParser.Dependencies; int depsCount = deps != null ? deps.Count : 0; if (depsCount > 0) { if (localVars == null) { localVars = new CodeStatementCollection(); } if (trueStmt == null) { trueStmt = new CodeStatementCollection(); } CodeAssignStatement assign; localVars.Add( new CodeVariableDeclarationStatement( typeof(string[]), "dependencies") ); CodeVariableReferenceExpression dependencies = new CodeVariableReferenceExpression("dependencies"); trueStmt.Add( new CodeAssignStatement(dependencies, new CodeArrayCreateExpression(typeof(string), depsCount)) ); CodeArrayIndexerExpression arrayIndex; object o; for (int i = 0; i < depsCount; i++) { o = deps [i]; arrayIndex = new CodeArrayIndexerExpression(dependencies, new CodeExpression[] { new CodePrimitiveExpression(i) }); assign = new CodeAssignStatement(arrayIndex, new CodePrimitiveExpression(o)); trueStmt.Add(assign); } CodeMethodInvokeExpression getDepsCall = new CodeMethodInvokeExpression( thisRef, "GetWrappedFileDependencies", new CodeExpression[] { dependencies } ); assign = new CodeAssignStatement(GetMainClassFieldReferenceExpression("__fileDependencies"), getDepsCall); trueStmt.Add(assign); } base.CreateConstructor(localVars, trueStmt); }
public override object Serialize(IDesignerSerializationManager manager, object value) { if (manager == null) { throw new ArgumentNullException("manager"); } object obj2 = null; if (value != null) { CodeStatementCollection statements = null; ExpressionContext context = manager.Context[typeof(ExpressionContext)] as ExpressionContext; if (value.GetType().GetConstructor(new Type[0]) != null) { if (value is ICollection) { ExpressionContext context2 = null; if (context == null) { return(obj2); } if (context.PresetValue != value) { try { statements = new CodeStatementCollection(); CodeVariableReferenceExpression expression = this.AddVariableExpression(manager, statements, value); context2 = new ExpressionContext(expression, value.GetType(), context.Owner, value); manager.Context.Push(context2); obj2 = this.originalSerializer.Serialize(manager, value); if (obj2 is CodeStatementCollection) { statements.AddRange(obj2 as CodeStatementCollection); return(statements); } if (obj2 is CodeStatement) { statements.Add(obj2 as CodeStatement); return(statements); } if (obj2 is CodeExpression) { statements.Add(new CodeAssignStatement(expression, obj2 as CodeExpression)); } return(statements); } finally { if (context2 != null) { manager.Context.Pop(); } } } return(this.originalSerializer.Serialize(manager, value)); } statements = new CodeStatementCollection(); this.AddVariableExpression(manager, statements, value); base.SerializeProperties(manager, statements, value, new Attribute[] { DesignOnlyAttribute.No }); base.SerializeEvents(manager, statements, value, new Attribute[] { DesignOnlyAttribute.No }); return(statements); } if (context != null) { obj2 = this.originalSerializer.Serialize(manager, value); } } return(obj2); }
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 CodeMemberProperty GenerateDLinqPrimitiveProperty(IPropertyMap propertyMap, string propertyName, string fieldName, string typeName) { CodeMemberProperty propertyMember = new CodeMemberProperty(); propertyMember.Name = propertyName; CodeTypeReference typeReference = new CodeTypeReference(typeName); propertyMember.Type = typeReference; propertyMember.Attributes = MemberAttributes.Public; //Column attribute CodeAttributeDeclaration columnAttrib = new CodeAttributeDeclaration("Column"); CodeAttributeArgument columnNameArg = new CodeAttributeArgument("Name", new CodePrimitiveExpression(propertyMap.Column)); columnAttrib.Arguments.Add(columnNameArg); CodeAttributeArgument storageArg = new CodeAttributeArgument("Storage", new CodePrimitiveExpression(fieldName)); columnAttrib.Arguments.Add(storageArg); if (propertyMap.IsIdentity) { CodeAttributeArgument idArg = new CodeAttributeArgument("Id", new CodePrimitiveExpression(true)); columnAttrib.Arguments.Add(idArg); } if (propertyMap.IsAssignedBySource) { CodeAttributeArgument autoGenArg = new CodeAttributeArgument("AutoGen", new CodePrimitiveExpression(true)); columnAttrib.Arguments.Add(autoGenArg); } propertyMember.CustomAttributes.Add(columnAttrib); CodeFieldReferenceExpression fieldExpression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName); CodeVariableReferenceExpression valueVar = new CodeVariableReferenceExpression("value"); CodePrimitiveExpression propNameEpr = new CodePrimitiveExpression(propertyMap.Name); //Getter method CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement(fieldExpression); propertyMember.GetStatements.Add(returnStmt); //Setter method CodeAssignStatement setStmt = new CodeAssignStatement(fieldExpression, valueVar); CodeExpressionStatement onPropertyChangingStmt = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "OnPropertyChanging", new CodeExpression[] { propNameEpr })); CodeExpressionStatement onPropertyChangedStmt = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "OnPropertyChanged", new CodeExpression[] { propNameEpr })); CodeBinaryOperatorExpression ifExpression = new CodeBinaryOperatorExpression(fieldExpression, CodeBinaryOperatorType.IdentityInequality, valueVar); CodeConditionStatement ifStmt = new CodeConditionStatement(ifExpression, new CodeStatement[] { onPropertyChangingStmt, setStmt, onPropertyChangedStmt }); propertyMember.SetStatements.Add(ifStmt); return(propertyMember); }
protected override void GenerateVariableReferenceExpression (CodeVariableReferenceExpression e) { OutputIdentifier(e.VariableName); }
protected override void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e) { Output.Write("variableReferenceExpression"); }
private static void GenerateFilterPropertyMembers(CodeTypeDeclaration genClass, Type entityType) { foreach ( PropertyInfo pi in entityType.GetInstanceProperties().Where(pi => FilterPropertyTypes.Contains(pi.PropertyType))) { string fieldName = string.Format("_Filter{0}", pi.Name); string propertyName = string.Format("Filter{0}", pi.Name); bool isValueType = pi.PropertyType.IsValueType; bool isNullable = (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)); string fieldType = isValueType && !isNullable ? string.Format("System.Nullable<{0}>", pi.PropertyType) : pi.PropertyType.FullName; #region field //generate field var clsMember = new CodeMemberField { Name = string.Format(fieldName), Attributes = MemberAttributes.Private, Type = new CodeTypeReference(fieldType) }; genClass.Members.Add(clsMember); #endregion #region Property //generate property getter and setter var property = new CodeMemberProperty { Name = string.Format(propertyName), Type = new CodeTypeReference(fieldType), Attributes = MemberAttributes.Public }; //Add [Display] Attribute property.DefineDisplayAttribute(null, true); var codeFieldReferenceExpression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName); var codePropertySetValueReferenceExpression = new CodePropertySetValueReferenceExpression(); #region getter property.GetStatements.Add(new CodeMethodReturnStatement(codeFieldReferenceExpression)); #endregion #region setter //if (_PropValue == value) return; property.SetStatements.Add( new CodeConditionStatement(new CodeBinaryOperatorExpression(codeFieldReferenceExpression, CodeBinaryOperatorType.ValueEquality, codePropertySetValueReferenceExpression), new CodeMethodReturnStatement())); var beforeVariableDeclaration = new CodeVariableDeclarationStatement(typeof(object), "before"); var beforeVariableReference = new CodeVariableReferenceExpression("before"); //object before; property.SetStatements.Add(beforeVariableDeclaration); //before = _PropValue; property.SetStatements.Add(new CodeAssignStatement(beforeVariableReference, codeFieldReferenceExpression)); //_PropValue = value; property.SetStatements.Add(new CodeAssignStatement(codeFieldReferenceExpression, codePropertySetValueReferenceExpression)); var onPropertyChangedMethodReference = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "OnPropertyChanged"); //OnPropertyChanged("PropertyName",before,value) property.SetStatements.Add(new CodeMethodInvokeExpression(onPropertyChangedMethodReference, new CodePrimitiveExpression(propertyName), beforeVariableReference, codePropertySetValueReferenceExpression)); #endregion genClass.Members.Add(property); #endregion } }
private static void GenerateApplyFilterMethod(CodeTypeDeclaration genClass, Type entityType) { var method = new CodeMemberMethod { ReturnType = new CodeTypeReference(typeof(void)), Name = "ApplyFilter", Attributes = MemberAttributes.Override | MemberAttributes.Family, }; var codeThisReferenceExpression = new CodeThisReferenceExpression(); //check for QueryNull //if(Query==null) return; method.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodePropertyReferenceExpression(codeThisReferenceExpression, "Query"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(null)), new CodeMethodReturnStatement())); //Expression<Func<T,bool>> condition; method.Statements.Add( new CodeVariableDeclarationStatement( string.Format("System.Linq.Expressions.Expression<System.Func<{0},bool>>", entityType.FullName), "condition")); //condition = c=>true; method.Statements.Add(new CodeSnippetExpression("condition = c=> true")); var conditionVariableReference = new CodeVariableReferenceExpression("condition"); foreach ( PropertyInfo pi in entityType.GetInstanceProperties().Where(pi => FilterPropertyTypes.Contains(pi.PropertyType))) { string propertyName = string.Format("Filter{0}", pi.Name); bool isValueType = pi.PropertyType.IsValueType; var codePropertyReferenceExpression = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), propertyName); if (pi.PropertyType == typeof(string)) { var stament = new CodeSnippetExpression( string.Format( "if (!string.IsNullOrEmpty({1})){{ condition = condition.And(c=>c.{0}.Contains({1})); }};", pi.Name, propertyName)); method.Statements.Add(stament); } else { method.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression(codePropertyReferenceExpression, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), new CodeSnippetStatement(string.Format("condition=condition.And(c=>c.{0} == {1});", pi.Name, propertyName)) )); } } //assign filter expression to _query.Filter var queryFieldReference = new CodeFieldReferenceExpression(new CodeBaseReferenceExpression(), "_query.Filter"); method.Statements.Add(new CodeAssignStatement(queryFieldReference, conditionVariableReference)); genClass.Members.Add(method); }
private static void GenerateMethodBody(IOperation input, CodeMemberMethod output, ITransformationContext context, CodeMemberMethod onCalling, CodeMemberMethod onCalled, CodeMemberField operationField) { CodeTypeReference handlerType = CreateHandlerType(input, output, context); output.Statements.Add(new CodeVariableDeclarationStatement { Name = "handler", Type = handlerType, InitExpression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(OperationBroker).ToTypeReference()), "Instance"), "GetRegisteredDelegate", handlerType), new CodeFieldReferenceExpression(null, operationField.Name)) }); var handlerRef = new CodeVariableReferenceExpression("handler"); var ifNotNull = new CodeConditionStatement(new CodeBinaryOperatorExpression( handlerRef, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression())); output.Statements.Add(ifNotNull); ifNotNull.FalseStatements.Add(new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(InvalidOperationException).ToTypeReference(), new CodePrimitiveExpression($"There is no implementation for method {input.Name} registered. Use the method broker to register a method implementation.")))); var operationVal = new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(null, operationField.Name), "Value"); var inputArgs = output.Parameters.Cast <CodeParameterDeclarationExpression>().Select(p => new CodeArgumentReferenceExpression(p.Name)).ToArray(); var callEventInputs = new CodeExpression[input.Parameters.Count + 2]; callEventInputs[0] = new CodeThisReferenceExpression(); callEventInputs[1] = operationVal; Array.Copy(inputArgs, 0, callEventInputs, 2, inputArgs.Length); output.Statements.Add(new CodeVariableDeclarationStatement { Name = "e", Type = typeof(OperationCallEventArgs).ToTypeReference(), InitExpression = new CodeObjectCreateExpression(typeof(OperationCallEventArgs).ToTypeReference(), callEventInputs) }); var e = new CodeVariableReferenceExpression("e"); var thisRef = new CodeThisReferenceExpression(); output.Statements.Add(new CodeMethodInvokeExpression( thisRef, onCalling.Name, e)); output.Statements.Add(new CodeMethodInvokeExpression( thisRef, "OnBubbledChange", new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(BubbledChangeEventArgs).ToTypeReference()), "OperationCalling", thisRef, operationVal, e))); CodeExpression result = null; var methodCallArgs = new CodeExpression[input.Parameters.Count + 1]; methodCallArgs[0] = thisRef; Array.Copy(inputArgs, 0, methodCallArgs, 1, inputArgs.Length); var methodCall = new CodeMethodInvokeExpression(handlerRef, "Invoke", methodCallArgs); if (input.Type != null) { output.Statements.Add(new CodeVariableDeclarationStatement { Name = "result", Type = output.ReturnType, InitExpression = methodCall }); result = new CodeVariableReferenceExpression("result"); output.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(e, "Result"), result)); } else { output.Statements.Add(methodCall); } output.Statements.Add(new CodeMethodInvokeExpression( thisRef, onCalled.Name, e)); output.Statements.Add(new CodeMethodInvokeExpression( thisRef, "OnBubbledChange", new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(BubbledChangeEventArgs).ToTypeReference()), "OperationCalled", thisRef, operationVal, e))); if (result != null) { output.Statements.Add(new CodeMethodReturnStatement(result)); } }
void AppendVariableReferenceExpression(CodeVariableReferenceExpression expression) { codeBuilder.Append(expression.VariableName); }
public abstract void EmitApply(CodeMemberMethod apply, CodeArgumentReferenceExpression proj, CodeArgumentReferenceExpression declloc, CodeArgumentReferenceExpression log, CodeVariableReferenceExpression pb, CodeVariableReferenceExpression tb);
/// <summary> /// Create a de-serialization method /// </summary> private CodeTypeMember CreateDeserializeMethod(Type forType) { var retVal = new CodeMemberMethod() { Name = "Deserialize", ReturnType = new CodeTypeReference(typeof(Object)), Attributes = MemberAttributes.Public | MemberAttributes.Final }; retVal.Parameters.Add(new CodeParameterDeclarationExpression(typeof(JsonReader), "r")); retVal.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "asType")); retVal.Parameters.Add(new CodeParameterDeclarationExpression(typeof(JsonSerializationContext), "context")); var _reader = new CodeVariableReferenceExpression("r"); var _context = new CodeVariableReferenceExpression("context"); var _jsonContext = new CodePropertyReferenceExpression(_context, "JsonContext"); retVal.Statements.Add(new CodeVariableDeclarationStatement(forType, "_retVal", new CodeObjectCreateExpression(forType))); var _depth = new CodeVariableReferenceExpression("_depth"); var readerDepth = new CodePropertyReferenceExpression(_reader, "Depth"); var readerToken = new CodePropertyReferenceExpression(_reader, "TokenType"); var readerValue = new CodePropertyReferenceExpression(_reader, "Value"); // Depth retVal.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "_depth", readerDepth)); retVal.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(readerToken, CodeBinaryOperatorType.IdentityInequality, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(JsonToken)), "StartObject")), new CodeAssignStatement(_depth, new CodeBinaryOperatorExpression(_depth, CodeBinaryOperatorType.Subtract, new CodePrimitiveExpression(1))))); var jsonPropertyTokenCondition = new CodeConditionStatement(new CodeBinaryOperatorExpression(readerToken, CodeBinaryOperatorType.IdentityEquality, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(JsonToken)), "PropertyName"))); jsonPropertyTokenCondition.FalseStatements.Add(new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression(readerToken, CodeBinaryOperatorType.IdentityEquality, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(JsonToken)), "EndObject")), CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression(readerDepth, CodeBinaryOperatorType.IdentityEquality, _depth) ), new CodeStatement[] { new CodeMethodReturnStatement(s_retVal) }, new CodeStatement[] { new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(JsonSerializationException), new CodePrimitiveExpression("JSON in invalid state"))) } )); var elementLoop = new CodeIterationStatement(new CodeSnippetStatement(), new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(_reader, "Read")), new CodeSnippetStatement(), jsonPropertyTokenCondition); // Switch the object type CodeConditionStatement propertyCondition = new CodeConditionStatement(this.CreateEqualsStatement(new CodePrimitiveExpression("$type"), readerValue)); var _xsiTypeRef = new CodeVariableReferenceExpression("_type"); propertyCondition.TrueStatements.Add(new CodeVariableDeclarationStatement(typeof(Type), "_type", new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(s_fBinder, "BindToType"), new CodePrimitiveExpression(forType.Assembly.FullName), new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(_reader, "ReadAsString"))))); propertyCondition.TrueStatements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(_xsiTypeRef, CodeBinaryOperatorType.IdentityInequality, new CodeTypeOfExpression(forType)), new CodeVariableDeclarationStatement(forType, "_nretVal", new CodeCastExpression(forType, new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(_jsonContext, "GetFormatter"), _xsiTypeRef), "Deserialize"), _reader, _xsiTypeRef, _context))), new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("_nretVal"), "CopyObjectData"), s_retVal)), new CodeMethodReturnStatement(new CodeVariableReferenceExpression("_nretVal")) )); propertyCondition.FalseStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(_reader, "Skip")))); // Loop foreach (var pi in forType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var jsonName = this.GetPropertyName(pi, true); if (jsonName == null || jsonName.StartsWith("$") || !pi.CanWrite) { continue; } propertyCondition = new CodeConditionStatement(this.CreateEqualsStatement(new CodePrimitiveExpression(jsonName), readerValue), new CodeStatement[] { }, new CodeStatement[] { propertyCondition }); propertyCondition.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(_reader, "Read"))); propertyCondition.TrueStatements.Add(new CodeVariableDeclarationStatement(typeof(Object), "_instance", new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(_jsonContext, "ReadElementUtil"), _reader, new CodeTypeOfExpression(pi.PropertyType), new CodeObjectCreateExpression(typeof(JsonSerializationContext), new CodePrimitiveExpression(jsonName), _jsonContext, s_retVal, _context)))); var _instance = new CodeVariableReferenceExpression("_instance"); propertyCondition.TrueStatements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(_instance, CodeBinaryOperatorType.IdentityInequality, s_null), new CodeAssignStatement(new CodePropertyReferenceExpression(s_retVal, pi.Name), new CodeCastExpression(pi.PropertyType, _instance)))); } jsonPropertyTokenCondition.TrueStatements.Add(propertyCondition); retVal.Statements.Add(elementLoop); retVal.Statements.Add(new CodeMethodReturnStatement(s_retVal)); return(retVal); }
protected abstract void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e);
private static void ValidateVariableReferenceExpression(CodeVariableReferenceExpression e) { ValidateIdentifier(e, "VariableName", e.VariableName); }
//[WebMethod(Description=<OperationName>, EnableSession=true)] //public virtual <ReturnType> <OperationName>(<Arguments>) //{ // For No out ref case. // return (<ReturnType>)base.Invoke(<InterfaceType>, <MethodName>, true | false(based on activation), arguments)[0]; // // For out & ref case. // Object[] results = base.Invoke(<InterfaceType>, <MethodName>, true | false(based on activation), arguments); // refParam1 = (RPType)results[1]; // refParam2 = (RPType)results[2]; // outParam3 = (RPType)results[3]; // return (<ReturnType>)results[0]; //} private CodeMemberMethod GetWebServiceMethodDeclaraion(MethodInfo methodInfo, bool isActivation, SupportedLanguages language) { CodeMemberMethod webMethod = new CodeMemberMethod(); webMethod.Attributes = MemberAttributes.Public; webMethod.ReturnType = new CodeTypeReference(methodInfo.ReturnType); webMethod.Name = methodInfo.Name; CodeAttributeDeclaration attrDecl = new CodeAttributeDeclaration("WebMethodAttribute"); attrDecl.Arguments.Add(new CodeAttributeArgument("Description", new CodePrimitiveExpression(methodInfo.Name))); attrDecl.Arguments.Add(new CodeAttributeArgument("EnableSession", new CodePrimitiveExpression(false))); webMethod.CustomAttributes.Add(attrDecl); List <ParameterInfo> outRefParams = new List <ParameterInfo>(); CodeArrayCreateExpression paramArrayCreationExpression = new CodeArrayCreateExpression(); paramArrayCreationExpression.CreateType = new CodeTypeReference(typeof(Object)); foreach (ParameterInfo paramInfo in methodInfo.GetParameters()) { CodeParameterDeclarationExpression paramDecl = new CodeParameterDeclarationExpression(); if (paramInfo.IsOut || paramInfo.ParameterType.IsByRef) { paramDecl.Type = new CodeTypeReference(paramInfo.ParameterType.GetElementType().FullName); paramDecl.Direction = paramInfo.IsOut ? FieldDirection.Out : FieldDirection.Ref; if (paramDecl.Direction == FieldDirection.Out && language == SupportedLanguages.VB) { paramDecl.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(System.Runtime.InteropServices.OutAttribute)))); } outRefParams.Add(paramInfo); } else { paramDecl.Type = new CodeTypeReference(paramInfo.ParameterType.FullName); } paramDecl.Name = paramInfo.Name; webMethod.Parameters.Add(paramDecl); if (!paramInfo.IsOut) { paramArrayCreationExpression.Initializers.Add(new CodeArgumentReferenceExpression(paramInfo.Name)); } } //Emit method body CodeMethodInvokeExpression baseInvokeExpression = new CodeMethodInvokeExpression(); baseInvokeExpression.Method = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "Invoke"); baseInvokeExpression.Parameters.Add(new CodeTypeOfExpression(methodInfo.DeclaringType)); baseInvokeExpression.Parameters.Add(new CodePrimitiveExpression(methodInfo.Name)); baseInvokeExpression.Parameters.Add(new CodePrimitiveExpression(isActivation)); baseInvokeExpression.Parameters.Add(paramArrayCreationExpression); int iStartIndex = (methodInfo.ReturnType == typeof(void)) ? 0 : 1; if (outRefParams.Count != 0) { //Results variable declaration CodeVariableDeclarationStatement resultsDeclaration = new CodeVariableDeclarationStatement(new CodeTypeReference(new CodeTypeReference(typeof(Object)), 1), "results"); resultsDeclaration.InitExpression = baseInvokeExpression; webMethod.Statements.Add(resultsDeclaration); for (int i = 0; i < outRefParams.Count; ++i) { ParameterInfo pinfo = outRefParams[i]; CodeAssignStatement assignStatement = new CodeAssignStatement(); CodeExpression leftExpression = new CodeArgumentReferenceExpression(pinfo.Name); CodeExpression rightExpression = new CodeCastExpression(new CodeTypeReference(pinfo.ParameterType.GetElementType().FullName), new CodeIndexerExpression(new CodeVariableReferenceExpression("results"), new CodePrimitiveExpression(i + iStartIndex))); assignStatement.Left = leftExpression; assignStatement.Right = rightExpression; webMethod.Statements.Add(assignStatement); } } if (methodInfo.ReturnType != typeof(void)) { CodeExpression returnTargetExpression; if (outRefParams.Count != 0) { returnTargetExpression = new CodeVariableReferenceExpression("results"); } else { returnTargetExpression = baseInvokeExpression; } CodeMethodReturnStatement methodReturnStatement = new CodeMethodReturnStatement(new CodeCastExpression(methodInfo.ReturnType, new CodeIndexerExpression(returnTargetExpression, new CodePrimitiveExpression(0)))); webMethod.Statements.Add(methodReturnStatement); } else if (outRefParams.Count == 0 && methodInfo.ReturnType == typeof(void)) { webMethod.Statements.Add(baseInvokeExpression); } return(webMethod); }
void OutputCacheParamsBlock(CodeMemberMethod method) { var statements = new List <CodeStatement> (); var localSettingsDecl = new CodeVariableDeclarationStatement(typeof(OutputCacheParameters), "outputCacheSettings"); var localSettings = new CodeVariableReferenceExpression("outputCacheSettings"); statements.Add(localSettingsDecl); statements.Add( new CodeAssignStatement( localSettings, new CodeObjectCreateExpression(typeof(OutputCacheParameters), new CodeExpression[] {}) ) ); TemplateParser.OutputCacheParsedParams parsed = pageParser.OutputCacheParsedParameters; if ((parsed & TemplateParser.OutputCacheParsedParams.CacheProfile) != 0) { statements.Add(AssignOutputCacheParameter(localSettings, "CacheProfile", pageParser.OutputCacheCacheProfile)); } statements.Add(AssignOutputCacheParameter(localSettings, "Duration", pageParser.OutputCacheDuration)); if ((parsed & TemplateParser.OutputCacheParsedParams.Location) != 0) { statements.Add(AssignOutputCacheParameter(localSettings, "Location", pageParser.OutputCacheLocation)); } if ((parsed & TemplateParser.OutputCacheParsedParams.NoStore) != 0) { statements.Add(AssignOutputCacheParameter(localSettings, "NoStore", pageParser.OutputCacheNoStore)); } if ((parsed & TemplateParser.OutputCacheParsedParams.SqlDependency) != 0) { statements.Add(AssignOutputCacheParameter(localSettings, "SqlDependency", pageParser.OutputCacheSqlDependency)); } if ((parsed & TemplateParser.OutputCacheParsedParams.VaryByContentEncodings) != 0) { statements.Add(AssignOutputCacheParameter(localSettings, "VaryByContentEncoding", pageParser.OutputCacheVaryByContentEncodings)); } if ((parsed & TemplateParser.OutputCacheParsedParams.VaryByControl) != 0) { statements.Add(AssignOutputCacheParameter(localSettings, "VaryByControl", pageParser.OutputCacheVaryByControls)); } if ((parsed & TemplateParser.OutputCacheParsedParams.VaryByCustom) != 0) { statements.Add(AssignOutputCacheParameter(localSettings, "VaryByCustom", pageParser.OutputCacheVaryByCustom)); } if ((parsed & TemplateParser.OutputCacheParsedParams.VaryByHeader) != 0) { statements.Add(AssignOutputCacheParameter(localSettings, "VaryByHeader", pageParser.OutputCacheVaryByHeader)); } statements.Add(AssignOutputCacheParameter(localSettings, "VaryByParam", pageParser.OutputCacheVaryByParam)); CodeFieldReferenceExpression outputCacheSettings = GetMainClassFieldReferenceExpression("__outputCacheSettings"); statements.Add(new CodeAssignStatement(outputCacheSettings, localSettings)); var cond = new CodeConditionStatement( new CodeBinaryOperatorExpression( outputCacheSettings, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null) ), statements.ToArray() ); method.Statements.Add(cond); }
/// <summary> /// Implement interface method by using extension method. /// </summary> /// <param name="typeName">UI type</param> /// <param name="codeTypeEx">Extension type</param> /// <param name="factoryType">Factory</param> /// <param name="implementType">Interface to implement</param> /// <param name="genericCreate">If Create method is generic</param> static void ImplementInterface(string typeName, CodeTypeDeclaration codeTypeEx, Type factoryType, Type implementType, bool genericCreate) { foreach (var memberInfo in implementType.GetMembers()) { if (memberInfo is MethodInfo) { var methodInfo = memberInfo as MethodInfo; var methodName = methodInfo.Name; CodeMemberMethod codeMethod = new CodeMemberMethod() { Name = methodName, Attributes = MemberAttributes.Final | MemberAttributes.Public | MemberAttributes.Static, ReturnType = new CodeTypeReference(methodInfo.ReturnType) }; string varTypeName = char.ToLower(typeName[0]).ToString() + string.Join(string.Empty, typeName.Skip(1).ToArray()); codeTypeEx.Members.Add(codeMethod); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression("this " + typeName, varTypeName)); foreach (var p in methodInfo.GetParameters()) { CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(new CodeTypeReference(p.ParameterType), p.Name); codeMethod.Parameters.Add(parameter); } CodePropertyReferenceExpression endpointField = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(fieldNameApp), PropertyNameEndpoint); CodeMethodInvokeExpression queryMethod = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(varTypeName), PropertyNameApp), PropertyNameEndpoint), EndpointMethodQueryInterfaceName, new CodeTypeReference(factoryType))); CodeMethodReturnStatement queryReturnStatment = new CodeMethodReturnStatement(queryMethod); CodeMethodReferenceExpression codeMethodCreateRef = new CodeMethodReferenceExpression(queryReturnStatment.Expression, PatternFactoryMethodNameCreate); if (genericCreate) { codeMethodCreateRef.TypeArguments.Add(new CodeTypeReference(implementType)); } CodeMethodInvokeExpression createMethod = new CodeMethodInvokeExpression( codeMethodCreateRef, new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(varTypeName), PropertyNameFullExpression)); List <CodeVariableReferenceExpression> varList = new List <CodeVariableReferenceExpression>(); for (int i = 1; i < codeMethod.Parameters.Count; i++) { CodeParameterDeclarationExpression p = codeMethod.Parameters[i]; CodeVariableReferenceExpression varExpr = new CodeVariableReferenceExpression(p.Name); varList.Add(varExpr); } CodeMethodInvokeExpression callMethod = new CodeMethodInvokeExpression( createMethod, methodName, varList.ToArray()); if (methodInfo.ReturnType == typeof(void)) { codeMethod.Statements.Add(callMethod); } else { CodeMethodReturnStatement createReturnStatment = new CodeMethodReturnStatement(callMethod); codeMethod.Statements.Add(createReturnStatment); } } } }
/// <summary> /// Create a static constructor for the data model. /// </summary> /// <param name="dataModelSchema">A description of the data model.</param> public StaticConstructor(DataModelSchema dataModelSchema) { /// <summary> // /// Static Constructor for the DataModel. // /// </summary> // static DataModel() { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(string.Format("Static Constructor for the {0}.", dataModelSchema.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); // DataModel.purgeBufferSize = FluidTrade.Guardian.Properties.Settings.Default.PurgeBufferSize; this.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "purgeBufferSize"), new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(string.Format("{0}.{1}", dataModelSchema.TargetNamespace, "Properties")), "Settings"), "Default"), "PurgeBufferSize"))); // FluidTrade.UnitTest.Server.DataModel.dataSet = new global::System.Data.DataSet(); // FluidTrade.UnitTest.Server.DataModel.dataSet.DataSetName = "DataModel"; // FluidTrade.UnitTest.Server.DataModel.dataSet.CaseSensitive = true; // FluidTrade.UnitTest.Server.DataModel.dataSet.EnforceConstraints = true; this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.DataSet))))); this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), "DataSetName"), new CodePrimitiveExpression(dataModelSchema.Name))); this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), "CaseSensitive"), new CodePrimitiveExpression(true))); this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), "EnforceConstraints"), new CodePrimitiveExpression(true))); // FluidTrade.UnitTest.Server.DataModel.tableConfiguration = new ConfigurationDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableConfiguration); // FluidTrade.UnitTest.Server.DataModel.tableDepartment = new DepartmentDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableDepartment); // FluidTrade.UnitTest.Server.DataModel.tableEmployee = new EmployeeDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableEmployee); // FluidTrade.UnitTest.Server.DataModel.tableEngineer = new EngineerDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableEngineer); // FluidTrade.UnitTest.Server.DataModel.tableManager = new ManagerDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableManager); // FluidTrade.UnitTest.Server.DataModel.tableObject = new ObjectDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableObject); // FluidTrade.UnitTest.Server.DataModel.tableProject = new ProjectDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableProject); // FluidTrade.UnitTest.Server.DataModel.tableProjectMember = new ProjectMemberDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableProjectMember); // FluidTrade.UnitTest.Server.DataModel.tableRace = new RaceDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableRace); foreach (KeyValuePair <string, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("table{0}", keyValuePair.Value.Name)), new CodeObjectCreateExpression(string.Format("{0}DataTable", keyValuePair.Value.Name)))); this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), "Tables"), "Add", new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("table{0}", keyValuePair.Value.Name)))); } // // Enforce the foreign key constraint between Object and Department tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint0 = new System.Data.ForeignKeyConstraint("FK_Object_Department", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableDepartment.Constraints.Add(foreignKeyConstraint0); // // Enforce the foreign key constraint between Department and Employee tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint1 = new System.Data.ForeignKeyConstraint("FK_Department_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.DepartmentIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEmployee.Constraints.Add(foreignKeyConstraint1); // // Enforce the foreign key constraint between Object and Employee tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint2 = new System.Data.ForeignKeyConstraint("FK_Object_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEmployee.Constraints.Add(foreignKeyConstraint2); // // Enforce the foreign key constraint between Race and Employee tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint3 = new System.Data.ForeignKeyConstraint("FK_Race_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableRace.RaceCodeColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.RaceCodeColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEmployee.Constraints.Add(foreignKeyConstraint3); // // Enforce the foreign key constraint between Employee and Engineer tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint4 = new System.Data.ForeignKeyConstraint("FK_Employee_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.EngineerIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEngineer.Constraints.Add(foreignKeyConstraint4); // // Enforce the foreign key constraint between Manager and Engineer tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint5 = new System.Data.ForeignKeyConstraint("FK_Manager_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.ManagerIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEngineer.Constraints.Add(foreignKeyConstraint5); // // Enforce the foreign key constraint between Employee and Manager tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint6 = new System.Data.ForeignKeyConstraint("FK_Employee_Manager", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableManager.Constraints.Add(foreignKeyConstraint6); // // Enforce the foreign key constraint between Object and Project tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint7 = new System.Data.ForeignKeyConstraint("FK_Object_Project", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableProject.Constraints.Add(foreignKeyConstraint7); // // Enforce the foreign key constraint between Employee and ProjectMember tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint8 = new System.Data.ForeignKeyConstraint("FK_Employee_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.EmployeeIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.Constraints.Add(foreignKeyConstraint8); // // Enforce the foreign key constraint between Project and ProjectMember tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint9 = new System.Data.ForeignKeyConstraint("FK_Project_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.ProjectIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.Constraints.Add(foreignKeyConstraint9); int foreignKeyCount = 0; foreach (KeyValuePair <string, TableSchema> tablePair in dataModelSchema.Tables) { foreach (KeyValuePair <string, ConstraintSchema> constraintPair in tablePair.Value.Constraints) { if (constraintPair.Value is ForeignKeyConstraintSchema) { // Construct a foreign key constraint described by this schema. ForeignKeyConstraintSchema foreignKeyConstraintSchema = constraintPair.Value as ForeignKeyConstraintSchema; // FluidTrade.UnitTest.Client.DataModel.relationDepartmentEmployee = new System.Data.DataRelation("FK_Department_Employee", new global::System.Data.DataColumn[] { // FluidTrade.UnitTest.Client.DataModel.tableDepartment.DepartmentIdColumn}, new global::System.Data.DataColumn[] { // FluidTrade.UnitTest.Client.DataModel.tableEmployee.DepartmentIdColumn}, false); // FluidTrade.UnitTest.Client.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Client.DataModel.relationDepartmentEmployee); CodeVariableReferenceExpression foreignKeyConstraintExpression = new CodeVariableReferenceExpression(string.Format("foreignKeyConstraint{0}", foreignKeyCount++)); this.Statements.Add(new CodeVariableDeclarationStatement(new CodeGlobalTypeReference(typeof(System.Data.ForeignKeyConstraint)), foreignKeyConstraintExpression.VariableName, new CodeForeignKeyConstraint(foreignKeyConstraintSchema))); this.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(foreignKeyConstraintExpression.VariableName), "AcceptRejectRule"), new CodeFieldReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.AcceptRejectRule)), "Cascade"))); this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), string.Format("table{0}", tablePair.Value.Name)), "Constraints"), "Add", foreignKeyConstraintExpression)); } } } // // Create a relation between the Department and Employee tables. // FluidTrade.UnitTest.Server.DataModel.relationDepartmentEmployee = new System.Data.DataRelation("FK_Department_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.DepartmentIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationDepartmentEmployee); // // Create a relation between the Employee and Engineer tables. // FluidTrade.UnitTest.Server.DataModel.relationEmployeeEngineer = new System.Data.DataRelation("FK_Employee_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.EngineerIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationEmployeeEngineer); // // Create a relation between the Employee and Manager tables. // FluidTrade.UnitTest.Server.DataModel.relationEmployeeManager = new System.Data.DataRelation("FK_Employee_Manager", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationEmployeeManager); // // Create a relation between the Employee and ProjectMember tables. // FluidTrade.UnitTest.Server.DataModel.relationEmployeeProjectMember = new System.Data.DataRelation("FK_Employee_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.EmployeeIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationEmployeeProjectMember); // // Create a relation between the Manager and Engineer tables. // FluidTrade.UnitTest.Server.DataModel.relationManagerEngineer = new System.Data.DataRelation("FK_Manager_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.ManagerIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationManagerEngineer); // // Create a relation between the Object and Department tables. // FluidTrade.UnitTest.Server.DataModel.relationObjectDepartment = new System.Data.DataRelation("FK_Object_Department", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationObjectDepartment); // // Create a relation between the Object and Employee tables. // FluidTrade.UnitTest.Server.DataModel.relationObjectEmployee = new System.Data.DataRelation("FK_Object_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationObjectEmployee); // // Create a relation between the Object and Project tables. // FluidTrade.UnitTest.Server.DataModel.relationObjectProject = new System.Data.DataRelation("FK_Object_Project", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationObjectProject); // // Create a relation between the Project and ProjectMember tables. // FluidTrade.UnitTest.Server.DataModel.relationProjectProjectMember = new System.Data.DataRelation("FK_Project_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.ProjectIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationProjectProjectMember); // // Create a relation between the Race and Employee tables. // FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee = new System.Data.DataRelation("FK_Race_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableRace.RaceCodeColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.RaceCodeColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee); foreach (KeyValuePair <string, RelationSchema> relationPair in dataModelSchema.Relations) { // The name of the relation is decorated with the relation name when the relation between the child and the parent // isn't unique. string relationName = relationPair.Value.IsDistinctPathToParent ? string.Format("relation{0}{1}", relationPair.Value.ParentTable.Name, relationPair.Value.ChildTable.Name) : string.Format("relation{0}{1}By{2}", relationPair.Value.ParentTable.Name, relationPair.Value.ChildTable.Name, relationPair.Value.Name); // FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee = new System.Data.DataRelation("FK_Race_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableRace.RaceCodeColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.RaceCodeColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee); CodeExpression relationFieldExpression = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), relationName); this.Statements.Add(new CodeAssignStatement(relationFieldExpression, new CodeDataRelation(relationPair.Value))); this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), "Relations"), "Add", relationFieldExpression)); } // FluidTrade.UnitTest.Server.DataModel.Configuration.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Department.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Employee.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Engineer.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Manager.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Object.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Project.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.ProjectMember.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Race.InitializeRelations(); foreach (KeyValuePair <string, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), string.Format("table{0}", keyValuePair.Value.Name)), "InitializeRelations")); } // DataModel.syncUpdate = new global::System.Object(); this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncUpdate"), new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Object))))); // DataModel.syncRoot = new System.Object(); this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncRoot"), new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Object))))); // DataModel.dataSetId = Guid.Empty; this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSetId"), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(Guid)), "Empty"))); // DataModel.sequence = int.MinValue; this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "sequence"), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(Int64)), "MinValue"))); // DataModel.updateBufferMutex = new Mutex(false); this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "updateBufferMutex"), new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Threading.Mutex)), new CodePrimitiveExpression(false)))); // } }
public static void Main(string[] args) { string directory = "../../../Project/Src/Ast/"; string visitorsDir = "../../../Project/Src/Visitors/"; Debug.WriteLine("AST Generator running..."); if (!File.Exists(directory + "INode.cs")) { Debug.WriteLine("did not find output directory"); return; } if (!File.Exists(visitorsDir + "AbstractAstTransformer.cs")) { Debug.WriteLine("did not find visitor output directory"); return; } List <Type> nodeTypes = new List <Type>(); foreach (Type type in typeof(MainClass).Assembly.GetTypes()) { if (type.IsClass && typeof(INode).IsAssignableFrom(type)) { nodeTypes.Add(type); } } nodeTypes.Sort(delegate(Type a, Type b) { return(a.Name.CompareTo(b.Name)); }); CodeCompileUnit ccu = new CodeCompileUnit(); CodeNamespace cns = ccu.AddNamespace("ICSharpCode.NRefactory.Ast"); cns.AddImport("System"); cns.AddImport("System.Collections.Generic"); foreach (Type type in nodeTypes) { if (type.GetCustomAttributes(typeof(CustomImplementationAttribute), false).Length == 0) { CodeTypeDeclaration ctd = cns.AddType(type.Name); if (type.IsAbstract) { ctd.TypeAttributes |= TypeAttributes.Abstract; } ctd.BaseTypes.Add(new CodeTypeReference(type.BaseType.Name)); ProcessType(type, ctd); foreach (object o in type.GetCustomAttributes(false)) { if (o is TypeImplementationModifierAttribute) { (o as TypeImplementationModifierAttribute).ModifyImplementation(cns, ctd, type); } } if (!type.IsAbstract) { CodeMemberMethod method = new CodeMemberMethod(); method.Name = "AcceptVisitor"; method.Attributes = MemberAttributes.Public | MemberAttributes.Override; method.Parameters.Add(new CodeParameterDeclarationExpression("IAstVisitor", "visitor")); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "data")); method.ReturnType = new CodeTypeReference(typeof(object)); CodeExpression ex = new CodeVariableReferenceExpression("visitor"); ex = new CodeMethodInvokeExpression(ex, VisitPrefix + ctd.Name, new CodeThisReferenceExpression(), new CodeVariableReferenceExpression("data")); method.Statements.Add(new CodeMethodReturnStatement(ex)); ctd.Members.Add(method); method = new CodeMemberMethod(); method.Name = "ToString"; method.Attributes = MemberAttributes.Public | MemberAttributes.Override; method.ReturnType = new CodeTypeReference(typeof(string)); method.Statements.Add(new CodeMethodReturnStatement(CreateToString(type))); ctd.Members.Add(method); } } } System.CodeDom.Compiler.CodeGeneratorOptions settings = new System.CodeDom.Compiler.CodeGeneratorOptions(); settings.IndentString = "\t"; settings.VerbatimOrder = true; using (StringWriter writer = new StringWriter()) { new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromCompileUnit(ccu, writer, settings); File.WriteAllText(directory + "Generated.cs", writer.ToString()); } ccu = new CodeCompileUnit(); cns = ccu.AddNamespace("ICSharpCode.NRefactory"); cns.AddImport("System"); cns.AddImport("ICSharpCode.NRefactory.Ast"); cns.Types.Add(CreateAstVisitorInterface(nodeTypes)); using (StringWriter writer = new StringWriter()) { new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromCompileUnit(ccu, writer, settings); File.WriteAllText(visitorsDir + "../IAstVisitor.cs", writer.ToString()); } ccu = new CodeCompileUnit(); cns = ccu.AddNamespace("ICSharpCode.NRefactory.Visitors"); cns.AddImport("System"); cns.AddImport("System.Collections.Generic"); cns.AddImport("System.Diagnostics"); cns.AddImport("ICSharpCode.NRefactory.Ast"); cns.Types.Add(CreateAstVisitorClass(nodeTypes, false)); using (StringWriter writer = new StringWriter()) { new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromCompileUnit(ccu, writer, settings); File.WriteAllText(visitorsDir + "AbstractAstVisitor.cs", writer.ToString()); } ccu = new CodeCompileUnit(); cns = ccu.AddNamespace("ICSharpCode.NRefactory.Visitors"); cns.AddImport("System"); cns.AddImport("System.Collections.Generic"); cns.AddImport("System.Diagnostics"); cns.AddImport("ICSharpCode.NRefactory.Ast"); cns.Types.Add(CreateAstVisitorClass(nodeTypes, true)); using (StringWriter writer = new StringWriter()) { new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromCompileUnit(ccu, writer, settings); File.WriteAllText(visitorsDir + "AbstractAstTransformer.cs", writer.ToString()); } ccu = new CodeCompileUnit(); cns = ccu.AddNamespace("ICSharpCode.NRefactory.Visitors"); cns.AddImport("System"); cns.AddImport("ICSharpCode.NRefactory.Ast"); cns.Types.Add(CreateNodeTrackingAstVisitorClass(nodeTypes)); using (StringWriter writer = new StringWriter()) { new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromCompileUnit(ccu, writer, settings); // CodeDom cannot output "sealed", so we need to use this hack: File.WriteAllText(visitorsDir + "NodeTrackingAstVisitor.cs", writer.ToString().Replace("public override object", "public sealed override object")); } //NotImplementedAstVisitor ccu = new CodeCompileUnit(); cns = ccu.AddNamespace("ICSharpCode.NRefactory.Visitors"); cns.AddImport("System"); cns.AddImport("ICSharpCode.NRefactory.Ast"); cns.Types.Add(CreateNotImplementedAstVisitorClass(nodeTypes)); using (StringWriter writer = new StringWriter()) { new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromCompileUnit(ccu, writer, settings); File.WriteAllText(visitorsDir + "NotImplementedAstVisitor.cs", writer.ToString()); } Debug.WriteLine("AST Generator done!"); }
static void GenerateBindFieldCode(CodeStatementCollection statements, CodeExpression cobj) { // Bind the fields CodeVariableDeclarationStatement varDecIndex = new CodeVariableDeclarationStatement(typeof(int), "n"); varDecIndex.InitExpression = new CodePrimitiveExpression(0); CodeExpression varIndex = new CodeVariableReferenceExpression("n"); CodeVariableDeclarationStatement varDecArray = new CodeVariableDeclarationStatement(typeof(FieldInfo[]), "fields"); varDecArray.InitExpression = new CodeMethodInvokeExpression( new CodeMethodInvokeExpression( cobj, "GetType", new CodeExpression [0] ), "GetFields", bindingFlags ); statements.Add(varDecArray); CodeVariableReferenceExpression varArray = new CodeVariableReferenceExpression("fields"); CodeIterationStatement iteration = new CodeIterationStatement(); statements.Add(iteration); iteration.InitStatement = varDecIndex; iteration.TestExpression = new CodeBinaryOperatorExpression( varIndex, CodeBinaryOperatorType.LessThan, new CodePropertyReferenceExpression(varArray, "Length") ); iteration.IncrementStatement = new CodeAssignStatement( varIndex, new CodeBinaryOperatorExpression( varIndex, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1) ) ); CodeVariableDeclarationStatement varDecField = new CodeVariableDeclarationStatement(typeof(FieldInfo), "field"); varDecField.InitExpression = new CodeArrayIndexerExpression(varArray, new CodeExpression [] { varIndex }); CodeVariableReferenceExpression varField = new CodeVariableReferenceExpression("field"); iteration.Statements.Add(varDecField); CodeVariableDeclarationStatement varDecWidget = new CodeVariableDeclarationStatement(typeof(object), "widget"); iteration.Statements.Add(varDecWidget); varDecWidget.InitExpression = new CodeIndexerExpression( new CodeVariableReferenceExpression("bindings"), new CodePropertyReferenceExpression(varField, "Name") ); CodeVariableReferenceExpression varWidget = new CodeVariableReferenceExpression("widget"); // Make sure the type of the field matches the type of the widget CodeConditionStatement fcond = new CodeConditionStatement(); iteration.Statements.Add(fcond); fcond.Condition = new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression( varWidget, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), CodeBinaryOperatorType.BooleanAnd, new CodeMethodInvokeExpression( new CodePropertyReferenceExpression(varField, "FieldType"), "IsInstanceOfType", varWidget ) ); // Set the variable value fcond.TrueStatements.Add( new CodeMethodInvokeExpression( varField, "SetValue", cobj, varWidget ) ); }
private CodeMemberMethod GenerateSwitchComplexType(bool objIsArray) { var methodDecl = new CodeMemberMethod { Name = methodName + (objIsArray ? "Array" : ""), Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static }; methodDecl.ReturnType = new CodeTypeReference(typeof(Stream)); methodDecl.Parameters.Add( new CodeParameterDeclarationExpression(new CodeTypeReference(type.FullName + (objIsArray ? "[]" : "")), "obj")); methodDecl.Parameters.Add( new CodeParameterDeclarationExpression(new CodeTypeReference("SerializationFormat"), "serializationFormat")); methodDecl.Parameters.Add( new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(System.ServiceModel.Web.WebMessageFormat)), "webMessageFormat")); CodeConditionStatement _if1 = new CodeConditionStatement(); CodeMethodInvokeExpression _invoke1 = new CodeMethodInvokeExpression(); CodePropertyReferenceExpression _prop1 = new CodePropertyReferenceExpression(); _prop1.PropertyName = "DataContract"; CodeVariableReferenceExpression _arg2 = new CodeVariableReferenceExpression(); _arg2.VariableName = "SerializationFormat"; _prop1.TargetObject = _arg2; _invoke1.Parameters.Add(_prop1); CodeMethodReferenceExpression _Equals_method1 = new CodeMethodReferenceExpression(); _Equals_method1.MethodName = "Equals"; CodeVariableReferenceExpression _arg3 = new CodeVariableReferenceExpression(); _arg3.VariableName = "serializationFormat"; _Equals_method1.TargetObject = _arg3; _invoke1.Method = _Equals_method1; _if1.Condition = _invoke1; CodeConditionStatement _if2 = new CodeConditionStatement(); CodeMethodInvokeExpression _invoke2 = new CodeMethodInvokeExpression(); CodePropertyReferenceExpression _prop2 = new CodePropertyReferenceExpression(); _prop2.PropertyName = "Xml"; CodeVariableReferenceExpression _arg5 = new CodeVariableReferenceExpression(); _arg5.VariableName = "System.ServiceModel.Web.WebMessageFormat"; _prop2.TargetObject = _arg5; _invoke2.Parameters.Add(_prop2); CodeMethodReferenceExpression _Equals_method2 = new CodeMethodReferenceExpression(); _Equals_method2.MethodName = "Equals"; CodeVariableReferenceExpression _arg6 = new CodeVariableReferenceExpression(); _arg6.VariableName = "webMessageFormat"; _Equals_method2.TargetObject = _arg6; _invoke2.Method = _Equals_method2; _if2.Condition = _invoke2; _if2.TrueStatements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(null, methodName + "__DataXml", new CodeVariableReferenceExpression("obj")))); CodeConditionStatement _if3 = new CodeConditionStatement(); CodeMethodInvokeExpression _invoke3 = new CodeMethodInvokeExpression(); CodePropertyReferenceExpression _prop3 = new CodePropertyReferenceExpression(); _prop3.PropertyName = "Json"; CodeVariableReferenceExpression _arg7 = new CodeVariableReferenceExpression(); _arg7.VariableName = "System.ServiceModel.Web.WebMessageFormat"; _prop3.TargetObject = _arg7; _invoke3.Parameters.Add(_prop3); CodeMethodReferenceExpression _Equals_method3 = new CodeMethodReferenceExpression(); _Equals_method3.MethodName = "Equals"; CodeVariableReferenceExpression _arg8 = new CodeVariableReferenceExpression(); _arg8.VariableName = "webMessageFormat"; _Equals_method3.TargetObject = _arg8; _invoke3.Method = _Equals_method3; _if3.Condition = _invoke3; _if3.TrueStatements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(null, methodName + "__DataJson", new CodeVariableReferenceExpression("obj")))); CodeThrowExceptionStatement _throw1 = new CodeThrowExceptionStatement(); CodeObjectCreateExpression _new1 = new CodeObjectCreateExpression(); CodeTypeReference _NotSupportedException_type1 = new CodeTypeReference("NotSupportedException"); _new1.CreateType = _NotSupportedException_type1; CodeBinaryOperatorExpression _binop1 = new CodeBinaryOperatorExpression(); CodePrimitiveExpression _value4 = new CodePrimitiveExpression(); _value4.Value = "Unknown WebMessageFormat found: "; _binop1.Left = _value4; _binop1.Operator = CodeBinaryOperatorType.Add; CodeVariableReferenceExpression _arg9 = new CodeVariableReferenceExpression(); _arg9.VariableName = "webMessageFormat"; _binop1.Right = _arg9; _new1.Parameters.Add(_binop1); _throw1.ToThrow = _new1; _if3.FalseStatements.Add(_throw1); _if2.FalseStatements.Add(_if3); _if1.TrueStatements.Add(_if2); CodeConditionStatement _if4 = new CodeConditionStatement(); CodeMethodInvokeExpression _invoke4 = new CodeMethodInvokeExpression(); CodePropertyReferenceExpression _prop4 = new CodePropertyReferenceExpression(); _prop4.PropertyName = "XmlSerializer"; CodeVariableReferenceExpression _arg10 = new CodeVariableReferenceExpression(); _arg10.VariableName = "SerializationFormat"; _prop4.TargetObject = _arg10; _invoke4.Parameters.Add(_prop4); CodeMethodReferenceExpression _Equals_method4 = new CodeMethodReferenceExpression(); _Equals_method4.MethodName = "Equals"; CodeVariableReferenceExpression _arg11 = new CodeVariableReferenceExpression(); _arg11.VariableName = "serializationFormat"; _Equals_method4.TargetObject = _arg11; _invoke4.Method = _Equals_method4; _if4.Condition = _invoke4; CodeConditionStatement _if5 = new CodeConditionStatement(); CodeMethodInvokeExpression _invoke5 = new CodeMethodInvokeExpression(); CodePropertyReferenceExpression _prop5 = new CodePropertyReferenceExpression(); _prop5.PropertyName = "Xml"; CodeVariableReferenceExpression _arg13 = new CodeVariableReferenceExpression(); _arg13.VariableName = "System.ServiceModel.Web.WebMessageFormat"; _prop5.TargetObject = _arg13; _invoke5.Parameters.Add(_prop5); CodeMethodReferenceExpression _Equals_method5 = new CodeMethodReferenceExpression(); _Equals_method5.MethodName = "Equals"; CodeVariableReferenceExpression _arg14 = new CodeVariableReferenceExpression(); _arg14.VariableName = "webMessageFormat"; _Equals_method5.TargetObject = _arg14; _invoke5.Method = _Equals_method5; _if5.Condition = _invoke5; _if5.TrueStatements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(null, methodName + "__XmlXml", new CodeVariableReferenceExpression("obj")))); CodeConditionStatement _if6 = new CodeConditionStatement(); CodeMethodInvokeExpression _invoke6 = new CodeMethodInvokeExpression(); CodePropertyReferenceExpression _prop6 = new CodePropertyReferenceExpression(); _prop6.PropertyName = "Json"; CodeVariableReferenceExpression _arg15 = new CodeVariableReferenceExpression(); _arg15.VariableName = "System.ServiceModel.Web.WebMessageFormat"; _prop6.TargetObject = _arg15; _invoke6.Parameters.Add(_prop6); CodeMethodReferenceExpression _Equals_method6 = new CodeMethodReferenceExpression(); _Equals_method6.MethodName = "Equals"; CodeVariableReferenceExpression _arg16 = new CodeVariableReferenceExpression(); _arg16.VariableName = "webMessageFormat"; _Equals_method6.TargetObject = _arg16; _invoke6.Method = _Equals_method6; _if6.Condition = _invoke6; CodeThrowExceptionStatement _throw2 = new CodeThrowExceptionStatement(); CodeObjectCreateExpression _new2 = new CodeObjectCreateExpression(); CodeTypeReference _NotSupportedException_type2 = new CodeTypeReference("NotSupportedException"); _new2.CreateType = _NotSupportedException_type2; CodePrimitiveExpression _value6 = new CodePrimitiveExpression(); _value6.Value = "WebMessageFormat.Json is not supported in relation with XmlSerializerFormatAttribute"; _new2.Parameters.Add(_value6); _throw2.ToThrow = _new2; _if6.TrueStatements.Add(_throw2); CodeThrowExceptionStatement _throw3 = new CodeThrowExceptionStatement(); CodeObjectCreateExpression _new3 = new CodeObjectCreateExpression(); CodeTypeReference _NotSupportedException_type3 = new CodeTypeReference("NotSupportedException"); _new3.CreateType = _NotSupportedException_type3; CodeBinaryOperatorExpression _binop2 = new CodeBinaryOperatorExpression(); CodePrimitiveExpression _value7 = new CodePrimitiveExpression(); _value7.Value = "Unknown WebMessageFormat found: "; _binop2.Left = _value7; _binop2.Operator = CodeBinaryOperatorType.Add; CodeVariableReferenceExpression _arg17 = new CodeVariableReferenceExpression(); _arg17.VariableName = "webMessageFormat"; _binop2.Right = _arg17; _new3.Parameters.Add(_binop2); _throw3.ToThrow = _new3; _if6.FalseStatements.Add(_throw3); _if5.FalseStatements.Add(_if6); _if4.TrueStatements.Add(_if5); CodeThrowExceptionStatement _throw4 = new CodeThrowExceptionStatement(); CodeObjectCreateExpression _new4 = new CodeObjectCreateExpression(); CodeTypeReference _NotSupportedException_type4 = new CodeTypeReference("NotSupportedException"); _new4.CreateType = _NotSupportedException_type4; CodeBinaryOperatorExpression _binop3 = new CodeBinaryOperatorExpression(); CodePrimitiveExpression _value8 = new CodePrimitiveExpression(); _value8.Value = "Unknown SerializationFormat found: "; _binop3.Left = _value8; _binop3.Operator = CodeBinaryOperatorType.Add; CodeVariableReferenceExpression _arg18 = new CodeVariableReferenceExpression(); _arg18.VariableName = "serializationFormat"; _binop3.Right = _arg18; _new4.Parameters.Add(_binop3); _throw4.ToThrow = _new4; _if4.FalseStatements.Add(_throw4); _if1.FalseStatements.Add(_if4); methodDecl.Statements.Add(_if1); return(methodDecl); }
private static void BuildLogic(CodeStatementCollection statements, ReadOnlyArrayCollection <ParticleSystemLogicStep> steps, Dictionary <string, bool> argUsed, int depth) { for (int i = 0; i < steps.Length; i++) { ParticleSystemLogicStep step = steps[i]; CodeExpression arg0 = Arg(step.arg0); CodeExpression arg1 = Arg(step.arg1); CodeExpression argT = Arg(step.target); CodeExpression target = Arg(step.target); if (arg0 != null && arg0 is CodePrimitiveExpression == false) { argUsed[step.arg0] = true; } if (arg1 != null && arg1 is CodePrimitiveExpression == false) { argUsed[step.arg1] = true; } if (target != null && target is CodePrimitiveExpression == false) { argUsed[step.target] = true; } if (step.Children.Length > 0) { CodeVariableReferenceExpression local = new CodeVariableReferenceExpression("i" + depth); if (step.type == "loop") { CodeIterationStatement iteration = new CodeIterationStatement(); iteration.InitStatement = new CodeVariableDeclarationStatement(typeof(uint), local.VariableName, new CodePrimitiveExpression((uint)0)); iteration.TestExpression = new CodeBinaryOperatorExpression(local, CodeBinaryOperatorType.LessThan, arg0); iteration.IncrementStatement = new CodeAssignStatement(local, new CodeBinaryOperatorExpression(local, CodeBinaryOperatorType.Add, new CodePrimitiveExpression((uint)1))); BuildLogic(iteration.Statements, step.Children, argUsed, depth + 1); statements.Add(iteration); } else { CodeBinaryOperatorType op = CodeBinaryOperatorType.IdentityEquality; //if switch (step.type) { case "if_notequal": op = CodeBinaryOperatorType.IdentityInequality; break; case "if_lessequal": op = CodeBinaryOperatorType.LessThanOrEqual; break; case "if_greaterequal": op = CodeBinaryOperatorType.GreaterThanOrEqual; break; case "if_less": op = CodeBinaryOperatorType.LessThan; break; case "if_greater": op = CodeBinaryOperatorType.GreaterThan; break; } CodeConditionStatement condition = new CodeConditionStatement(); condition.Condition = new CodeBinaryOperatorExpression( arg0, op, arg1); BuildLogic(condition.TrueStatements, step.Children, argUsed, depth + 1); statements.Add(condition); } } else { CodeExpression expression = null; switch (step.type) { case "set": expression = arg0; break; case "add": expression = Op(CodeBinaryOperatorType.Add, argT, arg0, arg1); break; case "sub": expression = Op(CodeBinaryOperatorType.Subtract, argT, arg0, arg1); break; case "mul": expression = Op(CodeBinaryOperatorType.Multiply, argT, arg0, arg1); break; case "div": expression = Op(CodeBinaryOperatorType.Divide, argT, arg0, arg1); break; case "abs": case "sign": case "cos": case "sin": case "acos": case "asin": case "tan": case "atan": case "sqrt": expression = MathOp1(step.type, arg0); break; case "atan2": case "min": case "max": expression = MathOp2(step.type, arg0, arg1); break; case "saturate": expression = MathOp2("max", new CodePrimitiveExpression(0.0f), MathOp2("min", new CodePrimitiveExpression(1.0f), arg0)); break; case "rsqrt": expression = new CodeBinaryOperatorExpression( new CodePrimitiveExpression(1.0f), CodeBinaryOperatorType.Divide, MathOp1("sqrt", arg0)); break; case "madd": expression = new CodeBinaryOperatorExpression(argT, CodeBinaryOperatorType.Add, new CodeBinaryOperatorExpression(arg0, CodeBinaryOperatorType.Multiply, arg1)); break; case "rand": argUsed["rand"] = true; expression = Rand(arg0, arg1, statements); break; case "rand_smooth": argUsed["rand"] = true; expression = RandSmooth(arg0, arg1, statements); break; } if (expression == null) { throw new ArgumentNullException("Unknown statement " + step.type); } statements.Add(new CodeAssignStatement(target, expression)); } } }
private void GenerateTestBody(TestClassGenerationContext generationContext, StepsContainer scenario, CodeMemberMethod testMethod, CodeExpression additionalTagsExpression = null, ParameterSubstitution paramToIdentifier = null) { //call test setup //ScenarioInfo scenarioInfo = new ScenarioInfo("xxxx", tags...); CodeExpression tagsExpression; if (additionalTagsExpression == null) { tagsExpression = GetStringArrayExpression(scenario.GetTags()); } else if (!scenario.HasTags()) { tagsExpression = additionalTagsExpression; } else { // merge tags list // var tags = tags1 // if (tags2 != null) // tags = Enumerable.ToArray(Enumerable.Concat(tags1, tags1)); testMethod.Statements.Add( new CodeVariableDeclarationStatement(typeof(string[]), "__tags", GetStringArrayExpression(scenario.GetTags()))); tagsExpression = new CodeVariableReferenceExpression("__tags"); testMethod.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( additionalTagsExpression, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), new CodeAssignStatement( tagsExpression, new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Enumerable)), "ToArray", new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Enumerable)), "Concat", tagsExpression, additionalTagsExpression))))); } testMethod.Statements.Add( new CodeVariableDeclarationStatement(typeof(ScenarioInfo), "scenarioInfo", new CodeObjectCreateExpression(typeof(ScenarioInfo), new CodePrimitiveExpression(scenario.Name), new CodePrimitiveExpression(scenario.Description), tagsExpression))); AddLineDirective(testMethod.Statements, scenario); testMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), generationContext.ScenarioInitializeMethod.Name, new CodeVariableReferenceExpression("scenarioInfo"))); testMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), generationContext.ScenarioStartMethod.Name)); if (HasFeatureBackground(generationContext.Feature)) { AddLineDirective(testMethod.Statements, generationContext.Feature.Background); testMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), generationContext.FeatureBackgroundMethod.Name)); } foreach (var scenarioStep in scenario.Steps) { GenerateStep(testMethod, scenarioStep, paramToIdentifier); } AddLineDirectiveHidden(testMethod.Statements); // call scenario cleanup testMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), generationContext.ScenarioCleanupMethod.Name)); }
private void GenerateTestBody(TestClassGenerationContext generationContext, Scenario scenario, CodeMemberMethod testMethod, CodeExpression additionalTagsExpression = null, ParameterSubstitution paramToIdentifier = null) { //call test setup //ScenarioInfo scenarioInfo = new ScenarioInfo("xxxx", tags...); CodeExpression tagsExpression; if (additionalTagsExpression == null) { tagsExpression = GetStringArrayExpression(scenario.Tags); } else if (scenario.Tags == null) { tagsExpression = additionalTagsExpression; } else { testMethod.Statements.Add( new CodeVariableDeclarationStatement(typeof(string[]), "__tags", GetStringArrayExpression(scenario.Tags))); tagsExpression = new CodeVariableReferenceExpression("__tags"); testMethod.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( additionalTagsExpression, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), new CodeAssignStatement( tagsExpression, new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Enumerable)), "ToArray", new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Enumerable)), "Concat", tagsExpression, additionalTagsExpression))))); } testMethod.Statements.Add( new CodeVariableDeclarationStatement(typeof(ScenarioInfo), "scenarioInfo", new CodeObjectCreateExpression(typeof(ScenarioInfo), new CodePrimitiveExpression(scenario.Title), tagsExpression))); testMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), generationContext.ScenarioInitializeMethod.Name, new CodeVariableReferenceExpression("scenarioInfo"))); if (HasFeatureBackground(generationContext.Feature)) { testMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), generationContext.FeatureBackgroundMethod.Name)); } foreach (var scenarioStep in scenario.Steps) { GenerateStep(testMethod, scenarioStep, paramToIdentifier); } }
protected void GenerateTupleParameterUnpackers(CodeMemberMethod method) { foreach (var parameter in args.Where(p => p.tuple != null)) { var csTupleParam = mpPyParamToCs[parameter]; var tuplePath = new CodeVariableReferenceExpression(csTupleParam.ParameterName); foreach (var component in parameter.tuple.Select((p, i) => new { p, i = i + 1 })) { GenerateTupleParameterUnpacker(component.p, component.i, tuplePath, method); } } }
void RenderPostOrPutImplementation(bool isPost) { //Create function parameters in prototype var parameters = description.ParameterDescriptions.Select(d => new CodeParameterDeclarationExpression() { Name = d.Name, Type = poco2CsGen.TranslateToClientTypeReference(d.ParameterDescriptor.ParameterType), }).ToArray(); method.Parameters.AddRange(parameters); var uriQueryParameters = description.ParameterDescriptions.Where(d => (!(d.ParameterDescriptor.ParameterBinder == ParameterBinder.FromBody) && TypeHelper.IsSimpleType(d.ParameterDescriptor.ParameterType)) || (TypeHelper.IsComplexType(d.ParameterDescriptor.ParameterType) && d.ParameterDescriptor.ParameterBinder == ParameterBinder.FromUri) || (d.ParameterDescriptor.ParameterType.IsValueType && d.ParameterDescriptor.ParameterBinder == ParameterBinder.FromUri) ).Select(d => new CodeParameterDeclarationExpression() { Name = d.Name, Type = poco2CsGen.TranslateToClientTypeReference(d.ParameterDescriptor.ParameterType), }).ToArray(); var fromBodyParameterDescriptions = description.ParameterDescriptions.Where(d => d.ParameterDescriptor.ParameterBinder == ParameterBinder.FromBody || (TypeHelper.IsComplexType(d.ParameterDescriptor.ParameterType) && (!(d.ParameterDescriptor.ParameterBinder == ParameterBinder.FromUri) || (d.ParameterDescriptor.ParameterBinder == ParameterBinder.None)))).ToArray(); if (fromBodyParameterDescriptions.Length > 1) { throw new CodeGenException("BadApiDef") { Description = String.Format("This API function {0} has more than 1 FromBody bindings in parameters", description.ActionDescriptor.ActionName) }; } var singleFromBodyParameterDescription = fromBodyParameterDescriptions.FirstOrDefault(); Action AddRequestUriWithQueryAssignmentStatement = () => { var jsUriQuery = CreateUriQuery(description.RelativePath, description.ParameterDescriptions); var uriText = jsUriQuery == null ? $"new Uri(this.baseUri, \"{description.RelativePath}\")" : RemoveTrialEmptyString($"new Uri(this.baseUri, \"{jsUriQuery}\")"); method.Statements.Add(new CodeVariableDeclarationStatement( new CodeTypeReference("var"), "requestUri", new CodeSnippetExpression(uriText))); }; Action AddRequestUriAssignmentStatement = () => { var jsUriQuery = CreateUriQuery(description.RelativePath, description.ParameterDescriptions); var uriText = jsUriQuery == null ? $"new Uri(this.baseUri, \"{description.RelativePath}\")" : RemoveTrialEmptyString($"new Uri(this.baseUri, \"{jsUriQuery}\")"); method.Statements.Add(new CodeVariableDeclarationStatement( new CodeTypeReference("var"), "requestUri", new CodeSnippetExpression(uriText))); }; Action <CodeExpression> AddPostStatement = (httpMethodInvokeExpression) => { //Statement: var task = this.client.GetAsync(requestUri.ToString()); method.Statements.Add(new CodeVariableDeclarationStatement( new CodeTypeReference("var"), "responseMessage", httpMethodInvokeExpression)); }; if (uriQueryParameters.Length > 0) { AddRequestUriWithQueryAssignmentStatement(); } else { AddRequestUriAssignmentStatement(); } if (singleFromBodyParameterDescription != null) { method.Statements.Add(new CodeSnippetStatement( @" using (var requestWriter = new System.IO.StringWriter()) { var requestSerializer = JsonSerializer.Create();" )); method.Statements.Add(new CodeMethodInvokeExpression(new CodeSnippetExpression("requestSerializer"), "Serialize", new CodeSnippetExpression("requestWriter"), new CodeSnippetExpression(singleFromBodyParameterDescription.ParameterDescriptor.ParameterName))); method.Statements.Add(new CodeSnippetStatement( @" var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, ""application/json"");" )); if (forAsync) { AddPostStatement( new CodeMethodInvokeExpression(new CodeSnippetExpression("await " + sharedContext.clientReference.FieldName), isPost ? "PostAsync" : "PutAsync", new CodeSnippetExpression("requestUri") , new CodeSnippetExpression("content"))); } else { AddPostStatement(new CodePropertyReferenceExpression( new CodeMethodInvokeExpression(sharedContext.clientReference, isPost ? "PostAsync" : "PutAsync", new CodeSnippetExpression("requestUri") , new CodeSnippetExpression("content")) , "Result")); } } else { if (forAsync) { AddPostStatement( new CodeMethodInvokeExpression(new CodeSnippetExpression("await " + sharedContext.clientReference.FieldName), isPost ? "PostAsync" : "PutAsync" , new CodeSnippetExpression("requestUri") , new CodeSnippetExpression("new StringContent(String.Empty)"))); } else { AddPostStatement(new CodePropertyReferenceExpression( new CodeMethodInvokeExpression(sharedContext.clientReference, isPost ? "PostAsync" : "PutAsync" , new CodeSnippetExpression("requestUri") , new CodeSnippetExpression("new StringContent(String.Empty)")) , "Result")); } } var resultReference = new CodeVariableReferenceExpression("responseMessage"); //Statement: result.EnsureSuccessStatusCode(); method.Statements.Add(new CodeMethodInvokeExpression(resultReference, "EnsureSuccessStatusCode")); //Statement: return something; if (returnType != null) { AddReturnStatement(); } if (singleFromBodyParameterDescription != null) { method.Statements.Add(new CodeSnippetStatement(" }")); } }
private CodeMemberMethod BuildClientProxyMethod(ServiceOp serviceOp, IList <Message> messages, MessageEncodingType encodingType) { string reqElementName = null; string reqTypeName = null; string reqElementNamespace = null; string respElementName = null; string respTypeName = null; string respElementNamespace = null; foreach (Message message in messages) { if (serviceOp.Operation.Messages.Input != null && serviceOp.Operation.Messages.Input.Message.Name == message.Name) { if (message.Parts.Count != 0) { reqElementName = CodeGenUtils.GetMessageElementName(serviceOp.Operation.PortType.ServiceDescription, message); reqTypeName = CodeGenUtils.GetMessageTypeName(serviceOp.Operation.PortType.ServiceDescription, message); reqElementNamespace = message.Parts[0].Element == null ? message.Parts[0].Type.Namespace : message.Parts[0].Element.Namespace; } } else if (serviceOp.Operation.Messages.Output != null && serviceOp.Operation.Messages.Output.Message.Name == message.Name) { if (message.Parts.Count != 0) { respElementName = CodeGenUtils.GetMessageElementName(serviceOp.Operation.PortType.ServiceDescription, message); respTypeName = CodeGenUtils.GetMessageTypeName(serviceOp.Operation.PortType.ServiceDescription, message); respElementNamespace = message.Parts[0].Element == null ? message.Parts[0].Type.Namespace : message.Parts[0].Element.Namespace; } } } // If either element name is null set to default for serializer naming reqElementName = reqElementName == null ? serviceOp.Operation.Name + "Request" : reqElementName; respElementName = respElementName == null ? serviceOp.Operation.Name + "Response" : respElementName; // If either type name is null set to default "void" reqTypeName = reqTypeName == null ? "void" : reqTypeName; respTypeName = respTypeName == null ? "void" : respTypeName; // Set the method name from Action. string methodName = serviceOp.InAction; if (methodName == null) { methodName = serviceOp.Operation.Name; } else { int index = methodName.LastIndexOfAny(new char[] { ':', '/', '\\' }); methodName = (index == -1 || index == (methodName.Length - 1)) ? methodName : methodName.Substring(index + 1); } CodeMemberMethod codeMethod = new CodeMemberMethod(); codeMethod.Name = methodName; codeMethod.Attributes = MemberAttributes.Public; if (respTypeName != "void") { codeMethod.ReturnType = new CodeTypeReference(respTypeName); } else { codeMethod.ReturnType = new CodeTypeReference(typeof(void)); } if (reqTypeName != "void") { codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(reqTypeName, "req")); } codeMethod.Statements.Add(new CodeSnippetStatement("")); codeMethod.Statements.Add(new CodeCommentStatement("Create request header")); // Generated Code: string action; codeMethod.Statements.Add( new CodeVariableDeclarationStatement( "String", "action" ) ); // Generated Code: action = "http://www.nrf-arts.org/IXRetail/namespace/PosPrinter/EventName"; codeMethod.Statements.Add( new CodeAssignStatement( new CodeVariableReferenceExpression("action"), new CodePrimitiveExpression(serviceOp.InAction) ) ); // Generated Code: WsWsaHeader header; codeMethod.Statements.Add( new CodeVariableDeclarationStatement( "WsWsaHeader", "header" ) ); // Generated Code: header = new WsWsaHeader(action, null, EndpointAddress, m_version.AnonymousUri, null, null); codeMethod.Statements.Add( new CodeAssignStatement( new CodeVariableReferenceExpression("header"), new CodeObjectCreateExpression( "WsWsaHeader", new CodeExpression[] { new CodeVariableReferenceExpression("action"), new CodePrimitiveExpression(null), new CodeVariableReferenceExpression("EndpointAddress"), new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("m_version"), "AnonymousUri"), new CodePrimitiveExpression(null), new CodePrimitiveExpression(null), } ) ) ); CodeExpression obj; if (reqTypeName != "void") { obj = new CodeVariableReferenceExpression("req"); } else { obj = new CodePrimitiveExpression(null); } // Generated Code: WsMessage request = new WsMessage(header, req, WsPrefix.None); codeMethod.Statements.Add( new CodeVariableDeclarationStatement("WsMessage", "request", new CodeObjectCreateExpression( "WsMessage", new CodeVariableReferenceExpression("header"), obj, new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("WsPrefix"), "None" ) ) ) ); // If message body is empty skip request seralizer if (reqTypeName != "void") { codeMethod.Statements.Add(new CodeSnippetStatement("")); codeMethod.Statements.Add(new CodeCommentStatement("Create request serializer")); // requestTypeNameDataContractSerializer eventDcs; codeMethod.Statements.Add( new CodeVariableDeclarationStatement( CodeGenUtils.GenerateDcsName(reqTypeName), "reqDcs" ) ); // reqDcs = new requestTypeNameDataContractSerializer("reqTypeName", ServiceNamespace.Namespace); codeMethod.Statements.Add( new CodeAssignStatement( new CodeVariableReferenceExpression("reqDcs"), new CodeObjectCreateExpression( CodeGenUtils.GenerateDcsName(reqTypeName), new CodeExpression[] { new CodePrimitiveExpression(reqElementName), new CodePrimitiveExpression(reqElementNamespace) } ) ) ); // Generated Code: request.Serializer = reqDcs; codeMethod.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("request"), "Serializer"), new CodeVariableReferenceExpression("reqDcs") ) ); } codeMethod.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("request"), "Method"), new CodePrimitiveExpression(methodName) ) ); codeMethod.Statements.Add(new CodeSnippetStatement("")); //codeMethod.Statements.Add(new CodeCommentStatement("Build soap request message")); //// Generated Code: byte[] soapBuffer = SoapMessageBuilder.BuildSoapMessage(header, reqDcs, req); //CodeExpression reqDcsParam; //CodeExpression reqParam; //if (reqTypeName == "void") //{ // reqDcsParam = new CodePrimitiveExpression(null); // reqParam = new CodePrimitiveExpression(null); //} //else //{ // reqDcsParam = new CodeVariableReferenceExpression("reqDcs"); // reqParam = new CodeVariableReferenceExpression("req"); //} //codeMethod.Statements.Add( // new CodeVariableDeclarationStatement( // typeof(byte[]), // "soapBuffer", // new CodeMethodInvokeExpression( // new CodeVariableReferenceExpression("SoapMessageBuilder"), // "BuildSoapMessage", // new CodeExpression[] { // new CodeVariableReferenceExpression("header"), // reqDcsParam, // reqParam // } // ) // ) //); // If this is an mtom message create body parts collection // If the message encoding is Mtom set the mtom encoded flag if (encodingType == MessageEncodingType.Mtom) { codeMethod.Statements.Add(new CodeSnippetStatement("")); codeMethod.Statements.Add(new CodeCommentStatement("Indicate that this message will use Mtom encoding")); // Generated Code: request.BodyParts = new WsMtomBodyParts(); codeMethod.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("request"), "BodyParts"), new CodeObjectCreateExpression("WsMtomBodyParts") ) ); //codeMethod.Statements.Add(new CodeCommentStatement("Build mtom request message and store as first Mtom Bodypart")); //// Generated Code: MessageType = WsMessageType.Mtom; //codeMethod.Statements.Add( // new CodeAssignStatement( // new CodeVariableReferenceExpression("MessageType"), // new CodeFieldReferenceExpression( // new CodeVariableReferenceExpression("WsMessageType"), // "Mtom" // ) // ) //); // WsMtomBodyParts bodyParts = new WsMtomBodyParts(); //codeMethod.Statements.Add( // new CodeVariableDeclarationStatement("WsMtomBodyParts", // "bodyParts", // new CodeObjectCreateExpression("WsMtomBodyParts", new CodeExpression[] {}) // ) //); //// Generated Code: bodyParts.Start = "<soap@soap>"; //codeMethod.Statements.Add( // new CodeAssignStatement( // new CodeFieldReferenceExpression( // new CodeVariableReferenceExpression("bodyParts"), // "Start" // ), // new CodePrimitiveExpression("<soap@soap>") // ) //); //// bodyParts.Add(respDcs.CreateNewBodyPart(soapBuffer, "soap@soap")); //codeMethod.Statements.Add( // new CodeMethodInvokeExpression( // new CodeVariableReferenceExpression("bodyParts"), // "Add", // new CodeExpression[] { // new CodeMethodInvokeExpression( // new CodeVariableReferenceExpression("reqDcs"), // "CreateNewBodyPart", // new CodeExpression[] { // new CodeVariableReferenceExpression("soapBuffer"), // new CodePrimitiveExpression("<soap@soap>") // } // ) // } // ) //); //// bodyParts.Add(reqDcs.BodyParts[0]); //codeMethod.Statements.Add( // new CodeMethodInvokeExpression( // new CodeVariableReferenceExpression("bodyParts"), // "Add", // new CodeExpression[] { // new CodeIndexerExpression( // new CodeFieldReferenceExpression( // new CodeVariableReferenceExpression("reqDcs"), // "BodyParts" // ), // new CodeExpression[] { // new CodePrimitiveExpression(0) // } // ) // } // ) //); } codeMethod.Statements.Add(new CodeSnippetStatement("")); codeMethod.Statements.Add(new CodeCommentStatement("Send service request")); // Generated Code: DpwsSoapResponse response; //codeMethod.Statements.Add( // new CodeVariableDeclarationStatement("DpwsSoapResponse", "response") //); //// Depending on whether this is an mtom request or not //// Generated Code: response = m_httpClient.SendRequest(BodyParts, SimpleService, true, false); //// or //// Generated Code: response = m_httpClient.SendRequest(soapBuffer, SimpleService, true, false); //codeMethod.Statements.Add( // new CodeAssignStatement( // new CodeVariableReferenceExpression("response"), // new CodeMethodInvokeExpression( // new CodeVariableReferenceExpression("m_httpClient"), // "SendRequest", // new CodeExpression[] { // new CodeVariableReferenceExpression(encodingType == MessageEncodingType.Mtom ? "ref bodyParts" : "soapBuffer"), // new CodeVariableReferenceExpression("EndpointAddress"), // new CodePrimitiveExpression(serviceOp.Operation.Messages.Flow == OperationFlow.OneWay || respTypeName == "void" ? true : false), // new CodePrimitiveExpression(false) // } // ) // ) //); // Generated Code: m_requestChannel.Open(); codeMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("m_requestChannel"), "Open" ) ); if (serviceOp.Operation.Messages.Flow == OperationFlow.OneWay || (respTypeName == "void")) { // Generated Code: m_requestChannel.RequestOneWay(request); codeMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("m_requestChannel"), "RequestOneWay", new CodeVariableReferenceExpression("request") ) ); } else { // Generated Code: WsMessage response = m_requestChannel.Request(request); codeMethod.Statements.Add( new CodeVariableDeclarationStatement("WsMessage", "response", new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("m_requestChannel"), "Request", new CodeVariableReferenceExpression("request") ) ) ); } // Generated Code: m_requestChannel.Open(); codeMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("m_requestChannel"), "Close" ) ); if (serviceOp.Operation.Messages.Flow == OperationFlow.RequestResponse || serviceOp.Operation.Messages.Flow == OperationFlow.RequestResponse) { if (respTypeName != "void") { codeMethod.Statements.Add(new CodeSnippetStatement("")); codeMethod.Statements.Add(new CodeCommentStatement("Process response")); // Generated Code: TwoWayResponseDataContractSerializer respDcs; codeMethod.Statements.Add( new CodeVariableDeclarationStatement( CodeGenUtils.GenerateDcsName(respTypeName), "respDcs" ) ); // Generated Code: respDcs = new ResponseDataTypeNameDataContractSerializer("ResponseDataTypeName", "http://schemas.example.org/SimpleService"); codeMethod.Statements.Add( new CodeAssignStatement( new CodeVariableReferenceExpression("respDcs"), new CodeObjectCreateExpression( CodeGenUtils.GenerateDcsName(respTypeName), new CodeExpression[] { new CodePrimitiveExpression(respElementName), new CodePrimitiveExpression(respElementNamespace) } ) ) ); // If the encoding type is mtom copy the body parts content to the response object if (encodingType == MessageEncodingType.Mtom) { // respDcs.BodyParts = bodyParts; codeMethod.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("respDcs"), "BodyParts" ), new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("response"), "BodyParts" ) //new CodeVariableReferenceExpression("bodyParts") ) ); } // Generated Code: TwoWayResponse resp; codeMethod.Statements.Add( new CodeVariableDeclarationStatement(respTypeName, "resp") ); // Generated Code: resp = (TwoWayResponse)respDcs.ReadObject(response.Reader); codeMethod.Statements.Add( new CodeAssignStatement( new CodeVariableReferenceExpression("resp"), new CodeCastExpression( respTypeName, new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("respDcs"), "ReadObject", new CodeExpression[] { new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("response"), "Reader" ) } ) ) ) ); // Add response.Reader.Dispose() method call codeMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("response"), "Reader" ), "Dispose", new CodeExpression[] { } ) ); // reqest.Reader = null; codeMethod.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("response"), "Reader" ), new CodePrimitiveExpression(null) ) ); // return resp; codeMethod.Statements.Add( new CodeMethodReturnStatement( new CodeVariableReferenceExpression("resp") ) ); } else { // return null; codeMethod.Statements.Add( new CodeMethodReturnStatement() ); } } return(codeMethod); }
public void VisitDel(DelStatement d) { var exprList = d.Expressions.AsList() .Select(e => e.Accept(xlat)) .ToList(); if (exprList.Count == 1) { var aref = exprList[0] as CodeArrayIndexerExpression; if (aref != null && aref.Indices.Length == 1) { // del foo[bar] is likely // foo.Remove(bar) gen.SideEffect( gen.Appl( new CodeMethodReferenceExpression( aref.TargetObject, "Remove"), aref.Indices[0])); return; } } var fn = new CodeVariableReferenceExpression("WONKO_del"); foreach (var exp in exprList) { gen.SideEffect(gen.Appl(fn, exp)); } }
private void AddGetStatements(CodeStatementCollection getStatements) { CodeExpression[] simpleTypeClassExpression; if (!this.IsSubstitutionHead) { CodeExpression returnExp = null; if (this.FixedValue == null) { getStatements.Add(this.GetValueMethodCall()); this.CheckOccurrence(getStatements); CodeVariableReferenceExpression returnValueExp = new CodeVariableReferenceExpression("x"); if ((this.IsRef ? true : !this.typeRef.IsSimpleType)) { returnExp = new CodeCastExpression(this.ReturnType, returnValueExp); } else { CodeTypeReference parseType = this.ReturnType; if ((!this.typeRef.IsValueType ? false : this.IsNullable)) { parseType = new CodeTypeReference(this.clrTypeName); } if (!this.IsUnion) { string parseMethodName = null; CodeExpression simpleTypeExpression = this.GetSchemaDatatypeExpression(); if (!this.IsSchemaList) { parseMethodName = "ParseValue"; } else { parseMethodName = "ParseListValue"; parseType = new CodeTypeReference(this.clrTypeName); } CodeTypeReferenceExpression codeTypeReferenceExpression = CodeDomHelper.CreateTypeReferenceExp("XTypedServices"); simpleTypeClassExpression = new CodeExpression[] { returnValueExp, simpleTypeExpression }; returnExp = CodeDomHelper.CreateGenericMethodCall(codeTypeReferenceExpression, parseMethodName, parseType, simpleTypeClassExpression); if (this.DefaultValue != null) { ((CodeMethodInvokeExpression)returnExp).Parameters.Add(new CodeFieldReferenceExpression(null, NameGenerator.ChangeClrName(this.propertyName, NameOptions.MakeDefaultValueField))); } } else { CodeTypeReferenceExpression codeTypeReferenceExpression1 = CodeDomHelper.CreateTypeReferenceExp("XTypedServices"); simpleTypeClassExpression = new CodeExpression[] { returnValueExp, this.GetSimpleTypeClassExpression() }; returnExp = CodeDomHelper.CreateMethodCall(codeTypeReferenceExpression1, "ParseUnionValue", simpleTypeClassExpression); } } getStatements.Add(new CodeMethodReturnStatement(returnExp)); } else { getStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, NameGenerator.ChangeClrName(this.propertyName, NameOptions.MakeFixedValueField)))); } } else { this.AddSubstGetStatements(getStatements); } }
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"); }
private static void ValidateVariableReferenceExpression(CodeVariableReferenceExpression e) { ValidateIdentifier(e, nameof(e.VariableName), e.VariableName); }