Inheritance: System.CodeDom.CodeExpression
		public void Constructor1 ()
		{
			CodeTypeReference type1 = new CodeTypeReference ("mono1");
			CodeExpression expression1 = new CodeExpression ();

			CodeCastExpression cce = new CodeCastExpression (type1, expression1);
			Assert.IsNotNull (cce.Expression, "#1");
			Assert.AreSame (expression1, cce.Expression, "#2");
			Assert.IsNotNull (cce.TargetType, "#3");
			Assert.AreSame (type1, cce.TargetType, "#4");

			cce.Expression = null;
			Assert.IsNull (cce.Expression, "#5");

			CodeExpression expression2 = new CodeExpression ();
			cce.Expression = expression2;
			Assert.IsNotNull (cce.Expression, "#6");
			Assert.AreSame (expression2, cce.Expression, "#7");

			cce.TargetType = null;
			Assert.IsNotNull (cce.TargetType, "#8");
			Assert.AreEqual (typeof (void).FullName, cce.TargetType.BaseType, "#9");

			CodeTypeReference type2 = new CodeTypeReference ("mono2");
			cce.TargetType = type2;
			Assert.IsNotNull (cce.TargetType, "#10");
			Assert.AreSame (type2, cce.TargetType, "#11");

			cce = new CodeCastExpression ((CodeTypeReference) null, (CodeExpression) null);
			Assert.IsNull (cce.Expression, "#12");
			Assert.IsNotNull (cce.TargetType, "#13");
			Assert.AreEqual (typeof (void).FullName, cce.TargetType.BaseType, "#14");
		}
		CodeMemberMethod CreateMethod()
		{
			CodeMemberMethod method = new CodeMemberMethod();
			
			// BeginInit method call.
			CodeExpressionStatement statement = new CodeExpressionStatement();
			CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression();
			statement.Expression = methodInvoke;
			
			CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression();
			methodRef.MethodName = "BeginInit";
			
			CodeCastExpression cast = new CodeCastExpression();
			cast.TargetType = new CodeTypeReference();
			cast.TargetType.BaseType = "System.ComponentModel.ISupportInitialize";
			
			CodeFieldReferenceExpression fieldRef = new CodeFieldReferenceExpression();
			fieldRef.FieldName = "pictureBox1";
			fieldRef.TargetObject = new CodeThisReferenceExpression();
			cast.Expression = fieldRef;

			methodRef.TargetObject = cast;
			methodInvoke.Method = methodRef;

			method.Statements.Add(statement);
			return method;
		}
Beispiel #3
0
        protected CodeExpression ConvertTo(string value, Type type)
        {
            var valueExpression = new CodePrimitiveExpression(value);

            var converter = TypeDescriptor.GetConverter(type);

            if (type == typeof(string) || type == typeof(object))
                return valueExpression;

            if (type == typeof(double))
                return new CodePrimitiveExpression(double.Parse(value, CultureInfo.InvariantCulture));

            if (type == typeof(BindingBase))
            {
                var bindingParser = new BindingParser(State);
                var bindingVariableName = bindingParser.Parse(value);
                return new CodeVariableReferenceExpression(bindingVariableName);
            }

            // there is no conversion availabe, the generated code won't compile, but there is nothing we can do about that
            if (converter == null)
                return valueExpression;

            var conversion = new CodeCastExpression(
                type.Name,
                new CodeMethodInvokeExpression(
                    new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("TypeDescriptor"), "GetConverter",
                                                   new CodeTypeOfExpression(type.Name)), "ConvertFromInvariantString",
                    new CodePrimitiveExpression(value)));

            return conversion;
        }
Beispiel #4
0
 private CodeStatement GenerateCallStatementC2J(GMethod method, CodeExpression invokeExpression)
 {
     CodeStatement call;
     if (method.IsConstructor || method.IsVoid)
     {
         call = new CodeExpressionStatement(invokeExpression);
     }
     else
     {
         if (method.ReturnType.IsPrimitive)
         {
             if (method.ReturnType.JVMSubst != null)
             {
                 invokeExpression = new CodeCastExpression(method.ReturnType.CLRReference, invokeExpression);
             }
             call = new CodeMethodReturnStatement(invokeExpression);
         }
         else
         {
             CodeMethodInvokeExpression conversionExpression = CreateConversionExpressionJ2CParam(method.ReturnType,
                                                                                             invokeExpression);
             call = new CodeMethodReturnStatement(conversionExpression);
         }
     }
     return call;
 }
Beispiel #5
0
		public void Constructor0_Deny_Unrestricted ()
		{
			CodeCastExpression cce = new CodeCastExpression ();
			Assert.IsNull (cce.Expression, "Expression");
			cce.Expression = new CodeExpression ();
			Assert.AreEqual ("System.Void", cce.TargetType.BaseType, "TargetType.BaseType");
			cce.TargetType = new CodeTypeReference ("System.Void");
		}
 public static CodeCastExpression Clone(this CodeCastExpression expression)
 {
     if (expression == null) return null;
     CodeCastExpression e = new CodeCastExpression();
     e.Expression = expression.Expression.Clone();
     e.TargetType = expression.TargetType.Clone();
     e.UserData.AddRange(expression.UserData);
     return e;
 }
Beispiel #7
0
 protected override void GenerateCastExpression(System.CodeDom.CodeCastExpression e)
 {
     Output.Write("(");
     OutputType(e.TargetType);
     Output.Write("(");
     GenerateExpression(e.Expression);
     Output.Write("))");
     //throw new Exception("The method or operation is not implemented.");
 }
Beispiel #8
0
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeTypeReference target = new CodeTypeReference ("System.Int32");
			CodeExpression expression = new CodeExpression ();
			CodeCastExpression cce = new CodeCastExpression (target, expression);
			Assert.AreSame (expression, cce.Expression, "Expression");
			cce.Expression = new CodeExpression ();
			Assert.AreEqual ("System.Int32", cce.TargetType.BaseType, "TargetType.BaseType");
			cce.TargetType = new CodeTypeReference ("System.Void");
		}
 public TypescriptCastExpression(
     IExpressionFactory expressionFactory,
     CodeCastExpression codeExpression, 
     CodeGeneratorOptions options,
     ITypescriptTypeMapper typescriptTypeMapper)
 {
     _expressionFactory = expressionFactory;
     _codeExpression = codeExpression;
     _options = options;
     _typescriptTypeMapper = typescriptTypeMapper;
     System.Diagnostics.Debug.WriteLine("TypescriptCastExpression Created");
 }
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {

            CodeExpression expression = new CodePrimitiveExpression(value);

            if (value == null
                || value is bool
                || value is char
                || value is int
                || value is float
                || value is double)
            {

                // work aroundf for J#, since they don't support auto-boxing of value types yet.
                CodeDomProvider codeProvider = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
                if (codeProvider != null && String.Equals(codeProvider.FileExtension, JSharpFileExtension))
                {
                    // See if we are boxing - if so, insert a cast.
                    ExpressionContext cxt = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
                    //Debug.Assert(cxt != null, "No expression context on stack - J# boxing cast will not be inserted");
                    if (cxt != null)
                    {
                        if (cxt.ExpressionType == typeof(object))
                        {
                            expression = new CodeCastExpression(value.GetType(), expression);
                            expression.UserData.Add("CastIsBoxing", true);
                        }
                    }
                }
                return expression;
            }

            String stringValue = value as string;
            if (stringValue != null)
            {
                // WinWS: The commented code breaks us when we have long strings
                //if (stringValue.Length > 200)
                //{
                // return SerializeToResourceExpression(manager, stringValue);
                //}
                //else 
                return expression;
            }

            // generate a cast for non-int types because we won't parse them properly otherwise because we won't know to convert
            // them to the narrow form.
            //
            return new CodeCastExpression(new CodeTypeReference(value.GetType()), expression);
        }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     CodeExpression left = null;
     using (CodeDomSerializerBase.TraceScope("EnumCodeDomSerializer::Serialize"))
     {
         Enum[] enumArray;
         if (!(value is Enum))
         {
             return left;
         }
         bool flag = false;
         TypeConverter converter = TypeDescriptor.GetConverter(value);
         if ((converter != null) && converter.CanConvertTo(typeof(Enum[])))
         {
             enumArray = (Enum[]) converter.ConvertTo(value, typeof(Enum[]));
             flag = enumArray.Length > 1;
         }
         else
         {
             enumArray = new Enum[] { (Enum) value };
             flag = true;
         }
         CodeTypeReferenceExpression targetObject = new CodeTypeReferenceExpression(value.GetType());
         TypeConverter converter2 = new EnumConverter(value.GetType());
         foreach (Enum enum2 in enumArray)
         {
             string str = (converter2 != null) ? converter2.ConvertToString(enum2) : null;
             CodeExpression right = !string.IsNullOrEmpty(str) ? new CodeFieldReferenceExpression(targetObject, str) : null;
             if (right != null)
             {
                 if (left == null)
                 {
                     left = right;
                 }
                 else
                 {
                     left = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.BitwiseOr, right);
                 }
             }
         }
         if ((left != null) && flag)
         {
             left = new CodeCastExpression(value.GetType(), left);
         }
     }
     return left;
 }
        public void Visit(InsertIntoDirectoryStatement statement)
        {
            if (statement.Select.Args.Length != 2) //can only select one thing into a directory
            {
                Errors.Add(new OnlyTwoSelectParamForDirectory(new Semantic.LineInfo(statement.Line.Line, statement.Line.CharacterPosition)));
                return;
            }

            var domArg = VisitChild(statement.Select);

            CodeMemberMethod method = new CodeMemberMethod();
            method.Name = "InsertIntoDir_" + domArg.MethodIdentifier;
            method.Attributes = MemberAttributes.Private;

            ((Action)domArg.Tag)();

            //needs to foreach around the returned table from select like the other inserts

            method.Statements.Add(new CodeVariableDeclarationStatement(domArg.Scope.CodeDomReference,
                "resultRows",
                domArg.CodeExpression));

            var cast = new CodeCastExpression(typeof(string),
                new CodeIndexerExpression(new CodeIndexerExpression(new CodeVariableReferenceExpression("resultRows"),
                    new CodePrimitiveExpression(0)), new CodePrimitiveExpression(0)));

            method.Statements.Add(new CodeVariableDeclarationStatement(typeof(string), "filename", cast));

            cast = new CodeCastExpression(typeof(byte[]),
                new CodeIndexerExpression(new CodeIndexerExpression(new CodeVariableReferenceExpression("resultRows"),
                    new CodePrimitiveExpression(0)), new CodePrimitiveExpression(1)));

            method.Statements.Add(new CodeVariableDeclarationStatement(typeof(byte[]), "bytes", cast));

            var directoryArgs = VisitChild(statement.Directory);

            method.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("bytes"), "WriteFile",
                directoryArgs.CodeExpression, new CodeVariableReferenceExpression("filename")));

            _mainType.Type.Members.Add(method);

            var methodcall = new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(null, method.Name));

            _codeStack.Peek().ParentStatements.Add(methodcall);
            _codeStack.Peek().CodeExpression = methodcall;
        }
Beispiel #13
0
		protected internal override void CreateMethods ()
		{
			base.CreateMethods ();

			Type type = parser.MasterType;
			if (type != null) {
				CodeMemberProperty mprop = new CodeMemberProperty ();
				mprop.Name = "Master";
				mprop.Type = new CodeTypeReference (parser.MasterType);
				mprop.Attributes = MemberAttributes.Public | MemberAttributes.New;
				CodeExpression prop = new CodePropertyReferenceExpression (new CodeBaseReferenceExpression (), "Master");
				prop = new CodeCastExpression (parser.MasterType, prop);
				mprop.GetStatements.Add (new CodeMethodReturnStatement (prop));
				mainClass.Members.Add (mprop);
				AddReferencedAssembly (type.Assembly);
			}
		}
Beispiel #14
0
        public CodeTypeDeclaration ToClass()
        {
            var cs = new CodeTypeDeclaration(this.Name);
            var iname = "I" + cs.Name;
            if (cs.Name.Contains('`'))
            {
                cs.Name = cs.Name.Substring(0, cs.Name.Length - 2);

                if (cs.Name.EndsWith("Base"))
                {
                    iname = "I" + cs.Name.Substring(0, cs.Name.Length - 4);
                }
                cs.Name += "<T>";
            }
            if (iname != null)
            {
                cs.BaseTypes.Add(new CodeTypeReference(iname));
            }

            cs.IsPartial = true;

            foreach (var p in Properties)
            {
                if (p.IsInherited) continue;
                var prop = new CodeMemberProperty();
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                prop.Name = p.Name;
                prop.Type = new CodeTypeReference(p.Type);

                prop.HasGet = true;
                prop.HasSet = false;

                var indexer = new CodeIndexerExpression(new CodeThisReferenceExpression(), new CodePrimitiveExpression(p.Name));

                var cast = new CodeCastExpression(prop.Type, indexer);

                prop.GetStatements.Add(new CodeMethodReturnStatement(cast));

                cs.Members.Add(prop);
            }

            return cs;
        }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     CodeExpression expression = new CodePrimitiveExpression(value);
     if ((((value == null) || (value is bool)) || ((value is char) || (value is int))) || ((value is float) || (value is double)))
     {
         CodeDomProvider service = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
         if ((service != null) && string.Equals(service.FileExtension, JSharpFileExtension))
         {
             ExpressionContext context = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
             if ((context != null) && (context.ExpressionType == typeof(object)))
             {
                 expression = new CodeCastExpression(value.GetType(), expression);
                 expression.UserData.Add("CastIsBoxing", true);
             }
         }
         return expression;
     }
     if (value is string)
     {
         return expression;
     }
     return new CodeCastExpression(new CodeTypeReference(value.GetType()), expression);
 }
Beispiel #16
0
		public void Constructor0 ()
		{
			CodeCastExpression cce = new CodeCastExpression ();
			Assert.IsNull (cce.Expression, "#1");
			Assert.IsNotNull (cce.TargetType, "#2");
			Assert.AreEqual (typeof (void).FullName, cce.TargetType.BaseType, "#3");

			CodeExpression expression = new CodeExpression ();
			cce.Expression = expression;
			Assert.IsNotNull (cce.Expression, "#4");
			Assert.AreSame (expression, cce.Expression, "#5");

			cce.Expression = null;
			Assert.IsNull (cce.Expression, "#6");

			CodeTypeReference type = new CodeTypeReference ("mono");
			cce.TargetType = type;
			Assert.IsNotNull (cce.TargetType, "#7");
			Assert.AreSame (type, cce.TargetType, "#8");

			cce.TargetType = null;
			Assert.IsNotNull (cce.TargetType, "#9");
			Assert.AreEqual (typeof (void).FullName, cce.TargetType.BaseType, "#10");
		}
		protected override void GenerateCastExpression(CodeCastExpression e)
		{
			Output.Write("[CodeCastExpression: {0}]", e.ToString());
		}
Beispiel #18
0
		/// <summary>
		/// Creates a new body in stlye of an Ado.net Constructor and attaches it to the <paramref name="target"/>
		/// </summary>
		/// <param name="properties"></param>
		/// <param name="settings"></param>
		/// <param name="importNameSpace"></param>
		/// <param name="container"></param>
		/// <param name="target"></param>
		public static void GenerateBody(Dictionary<string, DbPropertyInfoCache> properties,
			FactoryHelperSettings settings,
			CodeNamespace importNameSpace,
			CodeMemberMethod container,
			CodeExpression target)
		{
			foreach (var propertyInfoCache in properties.Values)
			{
				propertyInfoCache.Refresh();

				var columnName = propertyInfoCache.DbName;

				if (settings.EnforcePublicPropertys)
				{
					if (propertyInfoCache.Getter.MethodInfo.IsPrivate)
						throw new AccessViolationException(string.Format(
							"The Getter of {0} is private. Full creation cannot be enforced", propertyInfoCache.PropertyName));
					if (propertyInfoCache.Setter.MethodInfo.IsPrivate)
						throw new AccessViolationException(string.Format(
							"The Setter of {0} is private. Full creation cannot be enforced", propertyInfoCache.PropertyName));
				}

				var codeIndexerExpression = new CodeIndexerExpression(new CodeVariableReferenceExpression("record"),
					new CodePrimitiveExpression(columnName));

				var variableName = columnName.ToLower();
				CodeVariableDeclarationStatement bufferVariable = null;

				//var propertyRef = new CodeVariableReferenceExpression(propertyInfoCache.PropertyName);

				var refToProperty = new CodeFieldReferenceExpression(target, propertyInfoCache.PropertyName);

				var attributes = propertyInfoCache.Attributes;
				var valueConverterAttributeModel =
					attributes.FirstOrDefault(s => s.Attribute is ValueConverterAttribute);
				var isXmlProperty = attributes.FirstOrDefault(s => s.Attribute is FromXmlAttribute);
				CodeVariableReferenceExpression uncastLocalVariableRef = null;

				if (isXmlProperty != null)
				{
					bufferVariable = new CodeVariableDeclarationStatement(typeof(object), variableName);
					container.Statements.Add(bufferVariable);
					uncastLocalVariableRef = new CodeVariableReferenceExpression(variableName);
					var buffAssignment = new CodeAssignStatement(uncastLocalVariableRef, codeIndexerExpression);
					container.Statements.Add(buffAssignment);

					var checkXmlForNull = new CodeConditionStatement();
					checkXmlForNull.Condition = new CodeBinaryOperatorExpression(
						new CodeVariableReferenceExpression(variableName),
						CodeBinaryOperatorType.IdentityInequality,
						new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("System.DBNull"), "Value"));
					container.Statements.Add(checkXmlForNull);

					var xmlRecordType = new CodeTypeReferenceExpression(typeof(XmlDataRecord));
					importNameSpace.Imports.Add(new CodeNamespaceImport(typeof(DbClassInfoCache).Namespace));
					importNameSpace.Imports.Add(new CodeNamespaceImport(typeof(DataConverterExtensions).Namespace));
					importNameSpace.Imports.Add(new CodeNamespaceImport(typeof(DbConfigHelper).Namespace));

					if (propertyInfoCache.CheckForListInterface())
					{
						var typeArgument = propertyInfoCache.PropertyInfo.PropertyType.GetGenericArguments().FirstOrDefault();
						var codeTypeOfListArg = new CodeTypeOfExpression(typeArgument);

						var instanceHelper = new CodeMethodInvokeExpression(
							new CodeTypeReferenceExpression(typeof(NonObservableDbCollection<>).MakeGenericType(typeArgument)),
							"FromXml",
							new CodeCastExpression(typeof(string), new CodeVariableReferenceExpression(variableName)));

						//var tryParse = new CodeMethodInvokeExpression(xmlRecordType,
						//	"TryParse",
						//	new CodeCastExpression(typeof(string), uncastLocalVariableRef),
						//	codeTypeOfListArg,
						//	new CodePrimitiveExpression(false));

						//var xmlDataRecords = new CodeMethodInvokeExpression(tryParse, "CreateListOfItems");
						//var getClassInfo = new CodeMethodInvokeExpression(codeTypeOfListArg, "GetClassInfo");

						//var xmlRecordsToObjects = new CodeMethodInvokeExpression(xmlDataRecords, "Select",
						//	new CodeMethodReferenceExpression(getClassInfo, "SetPropertysViaReflection"));

						//CodeObjectCreateExpression collectionCreate;
						//if (typeArgument != null && (typeArgument.IsClass && typeArgument.GetInterface("INotifyPropertyChanged") != null))
						//{
						//	collectionCreate = new CodeObjectCreateExpression(typeof(DbCollection<>).MakeGenericType(typeArgument),
						//		xmlRecordsToObjects);
						//}
						//else
						//{
						//	collectionCreate = new CodeObjectCreateExpression(typeof(NonObservableDbCollection<>).MakeGenericType(typeArgument),
						//		xmlRecordsToObjects);
						//}

						var setExpr = new CodeAssignStatement(refToProperty, instanceHelper);
						checkXmlForNull.TrueStatements.Add(setExpr);
					}
					else
					{
						var typeofProperty = new CodeTypeOfExpression(propertyInfoCache.PropertyType);
						var getClassInfo = new CodeMethodInvokeExpression(typeofProperty, "GetClassInfo");

						var tryParse = new CodeMethodInvokeExpression(xmlRecordType,
							"TryParse",
							new CodeCastExpression(typeof(string), uncastLocalVariableRef),
							typeofProperty,
							new CodePrimitiveExpression(true));

						var setProps = new CodeMethodInvokeExpression(getClassInfo, "SetPropertysViaReflection", tryParse,
							new CodeSnippetExpression("null"),
							new CodeSnippetExpression("null"));
						var setExpr = new CodeAssignStatement(refToProperty,
							new CodeCastExpression(propertyInfoCache.PropertyType, setProps));
						checkXmlForNull.TrueStatements.Add(setExpr);
					}
				}
				else
				{
					//Should the SQL value be converted
					if (valueConverterAttributeModel != null)
					{
						//create object buff123;
						bufferVariable = new CodeVariableDeclarationStatement(typeof(object), variableName);
						container.Statements.Add(bufferVariable);
						//Assing buff123 = record[x]
						uncastLocalVariableRef = new CodeVariableReferenceExpression(variableName);
						var buffAssignment = new CodeAssignStatement(uncastLocalVariableRef, codeIndexerExpression);
						container.Statements.Add(buffAssignment);

						var converter = valueConverterAttributeModel.Attribute as ValueConverterAttribute;
						//Create the converter and then convert the value before everything else

						importNameSpace.Imports.Add(new CodeNamespaceImport(converter.Converter.Namespace));
						var converterCall = new CodeObjectCreateExpression(converter.Converter);
						var converterInstanceCall = new CodeMethodInvokeExpression(converterCall, "Convert",
							new CodeVariableReferenceExpression(variableName),
							new CodeTypeOfExpression(propertyInfoCache.PropertyType),
							new CodePrimitiveExpression(converter.Parameter),
							new CodeVariableReferenceExpression("System.Globalization.CultureInfo.CurrentCulture"));
						var codeAssignment = new CodeAssignStatement(new CodeVariableReferenceExpression(variableName),
							converterInstanceCall);
						container.Statements.Add(codeAssignment);
					}
					else
					{
						if (propertyInfoCache.PropertyType.IsEnum)
						{
							bufferVariable = new CodeVariableDeclarationStatement(typeof(object), variableName);
							container.Statements.Add(bufferVariable);
							uncastLocalVariableRef = new CodeVariableReferenceExpression(variableName);
							var setToValue = new CodeAssignStatement(refToProperty,
							new CodeCastExpression(
								new CodeTypeReference(propertyInfoCache.PropertyType, CodeTypeReferenceOptions.GenericTypeParameter),
									uncastLocalVariableRef));
							container.Statements.Add(setToValue);
						}
					}

					var isNullable = false;

					var baseType = Nullable.GetUnderlyingType(propertyInfoCache.PropertyType);

					if (baseType != null)
						isNullable = true;

					if (propertyInfoCache.PropertyType == typeof(string))
					{
						baseType = typeof(string);
					}
					else if (propertyInfoCache.PropertyType.IsArray)
					{
						baseType = propertyInfoCache.PropertyType;
					}

					if (baseType != null)
					{
						if (bufferVariable == null)
						{
							bufferVariable = new CodeVariableDeclarationStatement(typeof(object), variableName);
							container.Statements.Add(bufferVariable);
							uncastLocalVariableRef = new CodeVariableReferenceExpression(variableName);
							var buffAssignment = new CodeAssignStatement(uncastLocalVariableRef, codeIndexerExpression);
							container.Statements.Add(buffAssignment);
						}

						var checkForDbNull = new CodeConditionStatement
						{
							Condition = new CodeBinaryOperatorExpression(uncastLocalVariableRef,
								CodeBinaryOperatorType.IdentityEquality,
								new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("System.DBNull"), "Value"))
						};

						CodeAssignStatement setToNull;
						if (!isNullable && baseType != typeof(string))
						{
							setToNull = new CodeAssignStatement(refToProperty,
							new CodeDefaultValueExpression(
								CreateShortCodeTypeReference(baseType, importNameSpace.Imports)));
						}
						else
						{
							setToNull = new CodeAssignStatement(refToProperty, new CodePrimitiveExpression(null));
						}

						var setToValue = new CodeAssignStatement(refToProperty,
							new CodeCastExpression(
								new CodeTypeReference(baseType, CodeTypeReferenceOptions.GenericTypeParameter),
								uncastLocalVariableRef));
						checkForDbNull.TrueStatements.Add(setToNull);
						checkForDbNull.FalseStatements.Add(setToValue);
						container.Statements.Add(checkForDbNull);
					}
					else
					{
						if (bufferVariable != null)
						{
							CodeExpression castExp = new CodeCastExpression(
						new CodeTypeReference(propertyInfoCache.PropertyType, CodeTypeReferenceOptions.GenericTypeParameter),
						new CodeVariableReferenceExpression(bufferVariable.Name));
							var setExpr = new CodeAssignStatement(refToProperty, castExp);
							container.Statements.Add(setExpr);
						}
						else
						{
							CodeExpression castExp = new CodeCastExpression(
		new CodeTypeReference(propertyInfoCache.PropertyType, CodeTypeReferenceOptions.GenericTypeParameter),
		codeIndexerExpression);
							var setExpr = new CodeAssignStatement(refToProperty, castExp);
							container.Statements.Add(setExpr);
						}

					}
				}
			}
		}
Beispiel #19
0
        private static string AddExpressionEvaluation(CodeTypeDeclaration declaration, CodeExpression root, ref int methodSuffix)
        {
            int currentMethodSuffix = methodSuffix;
            CodeMemberMethod method = new CodeMemberMethod();
            method.Name = string.Format("Eval{0}", currentMethodSuffix);
            method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
            method.ReturnType = new CodeTypeReference(typeof(object));
            method.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    typeof(object[]),
                    "e"));

            if (root is CodeBinaryOperatorExpression)
            {
                CodeBinaryOperatorExpression binaryRoot = (CodeBinaryOperatorExpression)root;

                CodeExpression left = null;
                if (binaryRoot.Left is CodePrimitiveExpression)
                {
                    left = binaryRoot.Left;
                }
                else
                {
                    methodSuffix++;
                    Type expressionType = GetType(binaryRoot.Left, true);
                    if (expressionType == null)
                        return null;
                    left =
                        new CodeCastExpression(expressionType,
                            new CodeMethodInvokeExpression(
                                new CodeThisReferenceExpression(),
                                AddExpressionEvaluation(declaration, binaryRoot.Left, ref methodSuffix),
                                new CodeVariableReferenceExpression("e")));

                }

                CodeExpression right = null;
                if (binaryRoot.Right is CodePrimitiveExpression)
                {
                    right = binaryRoot.Right;
                }
                else
                {
                    methodSuffix++;
                    right =
                        new CodeCastExpression(GetType(binaryRoot.Right, true),
                            new CodeMethodInvokeExpression(
                                new CodeThisReferenceExpression(),
                                AddExpressionEvaluation(declaration, binaryRoot.Right, ref methodSuffix),
                                new CodeVariableReferenceExpression("e")));
                }

                method.Statements.Add(
                    new CodeConditionStatement(
                        new CodeMethodInvokeExpression(
                            new CodeThisReferenceExpression(),
                            "IsEmpty",
                            new CodeArrayIndexerExpression(
                                new CodeVariableReferenceExpression("e"),
                                new CodePrimitiveExpression(currentMethodSuffix))),
                        new CodeStatement[] {
                            new CodeMethodReturnStatement(
                                new CodeBinaryOperatorExpression(
                                    left,
                                    binaryRoot.Operator,
                                    right)) },
                        new CodeStatement[] {
                            new CodeMethodReturnStatement(
                                new CodeArrayIndexerExpression(
                                    new CodeVariableReferenceExpression("e"),
                                    new CodePrimitiveExpression(currentMethodSuffix))) }));
            }
            else
            {
                method.Statements.Add(
                    new CodeConditionStatement(
                        new CodeMethodInvokeExpression(
                            new CodeThisReferenceExpression(),
                            "IsEmpty",
                            new CodeArrayIndexerExpression(
                                new CodeVariableReferenceExpression("e"),
                                new CodePrimitiveExpression(currentMethodSuffix))),
                        new CodeStatement[] {
                            new CodeThrowExceptionStatement(
                                new CodeObjectCreateExpression(
                                    typeof(ArgumentException),
                                    new CodePrimitiveExpression("Cannot have an empty parameter for a non-binary expression"),
                                    new CodePrimitiveExpression("e[" + currentMethodSuffix + "]"))) },
                        new CodeStatement[] {
                            new CodeMethodReturnStatement(
                                new CodeArrayIndexerExpression(
                                    new CodeVariableReferenceExpression("e"),
                                    new CodePrimitiveExpression(currentMethodSuffix))) }));
            }
            declaration.Members.Add(method);

            SetParameterIndex(root, currentMethodSuffix);
            return method.Name;
        }
        public void GenerateProperties(CodeTypeDeclaration ctd, ClassInfo ci)
        {
            CodeMemberProperty prop;

            foreach (FieldInfo fi in classInfo.LocalFields)
            {
                if (fi.References != null)
                    continue;

                if (fi.IsNullable)
                {
                    if (options.NullableRepresentation == PrimitiveRepresentation.RawWithIsNull)
                    {
                        ctd.Members.Add(_IsNull(fi));
                        if (!ci.ReadOnly)
                        {
                            ctd.Members.Add(_SetNull(fi));
                        }
                    }
                }
                else
                {
                    if (options.NotNullRepresentation == PrimitiveRepresentation.RawWithIsNull)
                    {
                        if (!ci.ReadOnly)
                        {
                            // if it's read-only, not-null means not-null and there's no
                            // exception
                            ctd.Members.Add(_IsNull(fi));
                        }
                    }
                }
            }

            int primaryKeyComponentNumber = 0;

            foreach (FieldInfo fi in classInfo.LocalFields)
            {
                PrimitiveRepresentation actualNullableRepresentation = options.NullableRepresentation;
                PrimitiveRepresentation actualNotNullRepresentation = options.NotNullRepresentation;

                if (fi.GetNullableFieldHandler().GetSqlType() == null)
                {
                    if (actualNotNullRepresentation == PrimitiveRepresentation.SqlType)
                        actualNotNullRepresentation = PrimitiveRepresentation.Raw;

                    if (actualNullableRepresentation == PrimitiveRepresentation.SqlType)
                        actualNullableRepresentation = PrimitiveRepresentation.Raw;
                }

                CodeTypeReference returnType;

                //if (fi.Name == ci.PrimaryKeyFieldName)
                //{
                //  returnType = GetReturnType(PrimitiveRepresentation.Raw, fi.DataType);
                //}
                //else
                if (fi.References != null)
                {
                    returnType = new CodeTypeReference(fi.References);
                }
                else if (fi.IsNullable)
                {
                    returnType = GetReturnType(actualNullableRepresentation, fi);
                }
                else
                {
                    returnType = GetReturnType(actualNotNullRepresentation, fi);
                }

                prop = new CodeMemberProperty();
                prop.Name = fi.Name;
                prop.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                prop.Type = returnType;
                //prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, "_FieldNames")));
                if (fi.Description != null)
                {
                    prop.Comments.Add(new CodeCommentStatement("<summary>", true));
                    prop.Comments.Add(new CodeCommentStatement(fi.Description, true));
                    prop.Comments.Add(new CodeCommentStatement("</summary>", true));
                }
                ctd.Members.Add(prop);

                if (fi.Size != -1)
                {
                    CodeAttributeDeclaration cad = new CodeAttributeDeclaration("Sooda.SoodaFieldSizeAttribute");
                    cad.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(fi.Size)));
                    prop.CustomAttributes.Add(cad);
                }

                if (fi.IsPrimaryKey)
                {
                    CodeExpression getPrimaryKeyValue = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "GetPrimaryKeyValue");

                    if (classInfo.GetPrimaryKeyFields().Length > 1)
                    {
                        getPrimaryKeyValue = new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(typeof(SoodaTuple)), "GetValue", getPrimaryKeyValue, new CodePrimitiveExpression(primaryKeyComponentNumber));
                    }

                    if (fi.References != null)
                    {
                        prop.GetStatements.Add(
                            new CodeMethodReturnStatement(
                            new CodeMethodInvokeExpression(
                                LoaderClass(fi.ReferencedClass),
                                "GetRef",
                                GetTransaction(),
                                new CodeCastExpression(
                                    GetReturnType(actualNotNullRepresentation, fi),
                                    getPrimaryKeyValue
                            ))));
                    }
                    else
                    {
                        prop.GetStatements.Add(
                            new CodeMethodReturnStatement(
                            new CodeCastExpression(
                            prop.Type,
                            getPrimaryKeyValue
                            )));
                    }

                    if (!classInfo.ReadOnly && !fi.ReadOnly)
                    {
                        if (classInfo.GetPrimaryKeyFields().Length == 1)
                        {
                            prop.SetStatements.Add(
                                new CodeExpressionStatement(
                                new CodeMethodInvokeExpression(
                                new CodeThisReferenceExpression(), "SetPrimaryKeyValue",
                                new CodePropertySetValueReferenceExpression())));
                        }
                        else
                        {
                            CodeExpression plainValue = new CodePropertySetValueReferenceExpression();
                            if (fi.References != null)
                                plainValue = new CodeMethodInvokeExpression(plainValue, "GetPrimaryKeyValue");
                            prop.SetStatements.Add(
                                new CodeExpressionStatement(
                                new CodeMethodInvokeExpression(
                                new CodeThisReferenceExpression(), "SetPrimaryKeySubValue",
                                plainValue,
                                new CodePrimitiveExpression(primaryKeyComponentNumber),
                                new CodePrimitiveExpression(classInfo.GetPrimaryKeyFields().Length))));
                        }
                    }
                    primaryKeyComponentNumber++;
                    continue;
                }

                if (options.NullPropagation && (fi.References != null || fi.IsNullable) && actualNullableRepresentation != PrimitiveRepresentation.Raw)
                {
                    CodeExpression retVal = new CodePrimitiveExpression(null);

                    if (fi.References == null && actualNullableRepresentation == PrimitiveRepresentation.SqlType)
                    {
                        retVal = new CodePropertyReferenceExpression(
                            new CodeTypeReferenceExpression(fi.GetNullableFieldHandler().GetSqlType()), "Null");
                    }

                    prop.GetStatements.Add(
                        new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(
                        new CodeThisReferenceExpression(),
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePrimitiveExpression(null)),
                        new CodeStatement[]
                            {
                                new CodeMethodReturnStatement(retVal)
                            },
                        new CodeStatement[]
                            {
                            }));
                }

                if (fi.References != null)
                {
                    // reference field getter
                    //
                    CodeExpression pk = new CodeVariableReferenceExpression("pk");
                    Type pkType;
                    CodeExpression isFieldNotNull;
                    CodeExpression getRef;
                    if (fi.ParentClass.GetDataSource().EnableDynamicFields)
                    {
                        pkType = typeof(object);
                        isFieldNotNull = new CodeBinaryOperatorExpression(
                            pk,
                            CodeBinaryOperatorType.IdentityInequality,
                            new CodePrimitiveExpression(null));
                        getRef = new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(typeof(SoodaObject)),
                            "GetRefHelper",
                            GetTransaction(),
                            Factory(fi.References),
                            pk);
                    }
                    else
                    {
                        pkType = fi.GetNullableFieldHandler().GetSqlType();
                        isFieldNotNull = new CodeBinaryOperatorExpression(
                            new CodePropertyReferenceExpression(pk, "IsNull"),
                            CodeBinaryOperatorType.ValueEquality,
                            new CodePrimitiveExpression(false));
                        getRef = new CodeMethodInvokeExpression(
                            LoaderClass(fi.ReferencedClass),
                            "GetRef",
                            GetTransaction(),
                            new CodePropertyReferenceExpression(pk, "Value"));
                    }
                    prop.GetStatements.Add(
                            new CodeConditionStatement(
                                new CodeBinaryOperatorExpression(
                                    RefCacheExpression(ci, fi),
                                    CodeBinaryOperatorType.IdentityEquality,
                                    new CodePrimitiveExpression(null)),
                                new CodeStatement[]
                                {
                                new CodeVariableDeclarationStatement(pkType, "pk", GetFieldValueForRead(fi)),
                                new CodeConditionStatement(
                                    isFieldNotNull,
                                    new CodeStatement[]
                                    {
                                    new CodeAssignStatement(
                                        RefCacheExpression(ci, fi),
                                        getRef)
                                    })
                                }
                    ));


                    prop.GetStatements.Add(
                            new CodeMethodReturnStatement(
                                new CodeCastExpression(returnType,
                                    RefCacheExpression(ci, fi))));

                    // reference field setter
                    if (!classInfo.ReadOnly && !fi.ReadOnly)
                    {
                        prop.SetStatements.Add(
                                new CodeExpressionStatement(

                                    new CodeMethodInvokeExpression(
                                        new CodeTypeReferenceExpression(typeof(Sooda.ObjectMapper.SoodaObjectImpl)), "SetRefFieldValue",

                                        // parameters
                                        new CodeThisReferenceExpression(),
                                        new CodePrimitiveExpression(fi.Table.OrdinalInClass),
                                        new CodePrimitiveExpression(fi.Name),
                                        new CodePrimitiveExpression(fi.ClassUnifiedOrdinal),
                                        new CodePropertySetValueReferenceExpression(),
                                        RefCacheArray(),
                                        new CodePrimitiveExpression(GetFieldRefCacheIndex(ci, fi)),
                                        Factory(returnType.BaseType)
                                        )));
                    }
                }
                else
                {
                    // plain field getter

                    CodeExpression fieldValue = GetFieldValueForRead(fi);
                    if (fi.ParentClass.GetDataSource().EnableDynamicFields)
                    {
                        switch (fi.IsNullable ? actualNullableRepresentation : actualNotNullRepresentation)
                        {
                            case PrimitiveRepresentation.Boxed:
                                break;

                            case PrimitiveRepresentation.SqlType:
                            case PrimitiveRepresentation.RawWithIsNull:
                            case PrimitiveRepresentation.Raw:
                                fieldValue = new CodeCastExpression(new CodeTypeReference(fi.GetNullableFieldHandler().GetFieldType()), fieldValue);
                                break;

                            case PrimitiveRepresentation.Nullable:
                                fieldValue = new CodeCastExpression(new CodeTypeReference(fi.GetNullableFieldHandler().GetNullableType()), fieldValue);
                                break;

                            default:
                                throw new NotImplementedException("Unknown PrimitiveRepresentation");
                        }
                    }
                    prop.GetStatements.Add(new CodeMethodReturnStatement(fieldValue));

                    if (!classInfo.ReadOnly && !fi.ReadOnly)
                    {
                        // plain field setter

                        CodeExpression beforeDelegate = new CodePrimitiveExpression(null);
                        CodeExpression afterDelegate = new CodePrimitiveExpression(null);

                        if (classInfo.Triggers)
                        {
                            beforeDelegate = new CodeDelegateCreateExpression(new CodeTypeReference(typeof(SoodaFieldUpdateDelegate)),
                                    new CodeThisReferenceExpression(), "BeforeFieldUpdate_" + fi.Name);
                            afterDelegate = new CodeDelegateCreateExpression(new CodeTypeReference(typeof(SoodaFieldUpdateDelegate)),
                                    new CodeThisReferenceExpression(), "AfterFieldUpdate_" + fi.Name);
                        }

                        prop.SetStatements.Add(
                                new CodeExpressionStatement(
                                    new CodeMethodInvokeExpression(
                                        new CodeTypeReferenceExpression(typeof(Sooda.ObjectMapper.SoodaObjectImpl)), "SetPlainFieldValue",

                                        // parameters
                                        new CodeThisReferenceExpression(),
                                        new CodePrimitiveExpression(fi.Table.OrdinalInClass),
                                        new CodePrimitiveExpression(fi.Name),
                                        new CodePrimitiveExpression(fi.ClassUnifiedOrdinal),
                                        Box(new CodePropertySetValueReferenceExpression()),
                                        beforeDelegate,
                                        afterDelegate
                                        )));
                    }
                }
            }


            if (classInfo.Collections1toN != null)
            {
                foreach (CollectionOnetoManyInfo coli in classInfo.Collections1toN)
                {
                    prop = new CodeMemberProperty();
                    prop.Name = coli.Name;
                    prop.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                    prop.Type = GetCollectionPropertyType(coli.ClassName);

                    prop.GetStatements.Add(
                        new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(
                        new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name),
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePrimitiveExpression(null)), new CodeStatement[]
                            {
                                new CodeAssignStatement(
                                new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name),
                                new CodeObjectCreateExpression(GetCollectionWrapperType(coli.ClassName),
                                new CodeObjectCreateExpression(new CodeTypeReference(typeof(Sooda.ObjectMapper.SoodaObjectOneToManyCollection)),
                                new CodeExpression[] {
                                    new CodeMethodInvokeExpression(This, "GetTransaction"),
                                    new CodeTypeOfExpression(new CodeTypeReference(coli.ClassName)),
                                    new CodeThisReferenceExpression(),
                                    new CodePrimitiveExpression(coli.ForeignFieldName),
                                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(coli.ClassName + "_Factory"), "TheClassInfo"),
                                    new CodeFieldReferenceExpression(null, "_collectionWhere_" + coli.Name),
                                    new CodePrimitiveExpression(coli.Cache)
                            }))),
                    }, new CodeStatement[] { }));

                    prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name)));
                    ctd.Members.Add(prop);

#if DOTNET35
                    CodeExpression whereExpression = new CodeMethodInvokeExpression(
                        new CodeTypeReferenceExpression(typeof(Sooda.QL.Soql)),
                        "FieldEquals",
                        new CodePrimitiveExpression(coli.ForeignFieldName),
                        This);
                    if (!string.IsNullOrEmpty(coli.Where))
                    {
                        whereExpression = new CodeObjectCreateExpression(
                            typeof(Sooda.QL.SoqlBooleanAndExpression),
                            whereExpression,
                            new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(null, "_collectionWhere_" + coli.Name), "WhereExpression"));
                    }
                    prop = GetCollectionLinqQuery(coli, whereExpression);
                    ctd.Members.Add(prop);
#endif
                }
            }

            if (classInfo.CollectionsNtoN != null)
            {
                foreach (CollectionManyToManyInfo coli in classInfo.CollectionsNtoN)
                {
                    RelationInfo relationInfo = coli.GetRelationInfo();
                    // FieldInfo masterField = relationInfo.Table.Fields[1 - coli.MasterField];

                    string relationTargetClass = relationInfo.Table.Fields[coli.MasterField].References;

                    prop = new CodeMemberProperty();
                    prop.Name = coli.Name;
                    prop.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                    prop.Type = GetCollectionPropertyType(relationTargetClass);

                    prop.GetStatements.Add(
                        new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(
                        new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name),
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePrimitiveExpression(null)), new CodeStatement[] {
                                                                                    new CodeAssignStatement(
                                                                                    new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name),
                                                                                    new CodeObjectCreateExpression(GetCollectionWrapperType(relationTargetClass),
                                                                                    new CodeObjectCreateExpression(new CodeTypeReference(typeof(Sooda.ObjectMapper.SoodaObjectManyToManyCollection)),
                                                                                    new CodeExpression[] {
                                                                                                             new CodeMethodInvokeExpression(This, "GetTransaction"),
                                                                                                             new CodePrimitiveExpression(coli.MasterField),
                                                                                                             new CodeMethodInvokeExpression(This, "GetPrimaryKeyValue"),
                                                                                                             new CodeTypeOfExpression(relationInfo.Name + "_RelationTable"),
                                                                                                             new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(relationInfo.Name + "_RelationTable"), "theRelationInfo")

                                                                                                         }))
                                                                                    ),
                    }
                        , new CodeStatement[] { }));

                    prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name)));

                    ctd.Members.Add(prop);

#if DOTNET35
                    CodeExpression whereExpression = new CodeMethodInvokeExpression(
                        new CodeTypeReferenceExpression(typeof(Sooda.QL.Soql)),
                        "CollectionFor",
                        new CodeMethodInvokeExpression(
                                new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(classInfo.Name + "_Factory"), "TheClassInfo"),
                                "FindCollectionManyToMany",
                                new CodePrimitiveExpression(coli.Name)),
                        This);
                    prop = GetCollectionLinqQuery(coli, whereExpression);
                    ctd.Members.Add(prop);
#endif
                }
            }
        }
		CodeMemberMethod GenerateMethod (CodeIdentifiers memberIds, SoapOperationBinding soapOper, SoapBodyBinding bodyBinding, XmlMembersMapping inputMembers, XmlMembersMapping outputMembers)
		{
			CodeIdentifiers pids = new CodeIdentifiers ();
			CodeMemberMethod method = new CodeMemberMethod ();
			CodeMemberMethod methodBegin = new CodeMemberMethod ();
			CodeMemberMethod methodEnd = new CodeMemberMethod ();
			method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			methodBegin.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			methodEnd.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			
			SoapBindingStyle style = soapOper.Style != SoapBindingStyle.Default ? soapOper.Style : soapBinding.Style;
			
			// Find unique names for temporary variables
			
			for (int n=0; n<inputMembers.Count; n++)
				pids.AddUnique (inputMembers[n].MemberName, inputMembers[n]);

			if (outputMembers != null)
				for (int n=0; n<outputMembers.Count; n++)
					pids.AddUnique (outputMembers[n].MemberName, outputMembers[n]);
				
			string varAsyncResult = pids.AddUnique ("asyncResult","asyncResult");
			string varResults = pids.AddUnique ("results","results");
			string varCallback = pids.AddUnique ("callback","callback");
			string varAsyncState = pids.AddUnique ("asyncState","asyncState");

			string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name),method);

			method.Name = CodeIdentifier.MakeValid(Operation.Name);
			if (method.Name == ClassName) method.Name += "1";
			methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + method.Name),method);
			methodEnd.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + method.Name),method);

			method.ReturnType = new CodeTypeReference (typeof(void));
			methodEnd.ReturnType = new CodeTypeReference (typeof(void));
			methodEnd.Parameters.Add (new CodeParameterDeclarationExpression (typeof (IAsyncResult),varAsyncResult));

			CodeExpression[] paramArray = new CodeExpression [inputMembers.Count];
			CodeParameterDeclarationExpression[] outParams = new CodeParameterDeclarationExpression [outputMembers != null ? outputMembers.Count : 0];

			for (int n=0; n<inputMembers.Count; n++)
			{
				CodeParameterDeclarationExpression param = GenerateParameter (inputMembers[n], FieldDirection.In);
				method.Parameters.Add (param);
				GenerateMemberAttributes (inputMembers, inputMembers[n], bodyBinding.Use, param);
				methodBegin.Parameters.Add (GenerateParameter (inputMembers[n], FieldDirection.In));
				paramArray [n] = new CodeVariableReferenceExpression (param.Name);
			}

			if (outputMembers != null)
			{
				bool hasReturn = false;
				for (int n=0; n<outputMembers.Count; n++)
				{
					CodeParameterDeclarationExpression cpd = GenerateParameter (outputMembers[n], FieldDirection.Out);
					outParams [n] = cpd;
					
					bool found = false;
					foreach (CodeParameterDeclarationExpression ip in method.Parameters)
					{
						if (ip.Name == cpd.Name && ip.Type.BaseType == cpd.Type.BaseType) {
							ip.Direction = FieldDirection.Ref;
							methodEnd.Parameters.Add (GenerateParameter (outputMembers[n], FieldDirection.Out));
							found = true;
							break;
						}
					}
					
					if (found) continue;
	
					if (!hasReturn) 
					{
						hasReturn = true;
						method.ReturnType = cpd.Type;
						methodEnd.ReturnType = cpd.Type;
						GenerateReturnAttributes (outputMembers, outputMembers[n], bodyBinding.Use, method);
						outParams [n] = null;
						continue;
					}
					
					method.Parameters.Add (cpd);
					GenerateMemberAttributes (outputMembers, outputMembers[n], bodyBinding.Use, cpd);
					methodEnd.Parameters.Add (GenerateParameter (outputMembers[n], FieldDirection.Out));
				}
			}
			
			methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (AsyncCallback),varCallback));
			methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object),varAsyncState));
			methodBegin.ReturnType = new CodeTypeReference (typeof(IAsyncResult));

			// Array of input parameters
			
			CodeArrayCreateExpression methodParams;
			if (paramArray.Length > 0)
				methodParams = new CodeArrayCreateExpression (typeof(object), paramArray);
			else
				methodParams = new CodeArrayCreateExpression (typeof(object), 0);

			// Assignment of output parameters
			
			CodeStatementCollection outAssign = new CodeStatementCollection ();
			CodeVariableReferenceExpression arrVar = new CodeVariableReferenceExpression (varResults);
			for (int n=0; n<outParams.Length; n++)
			{
				CodeExpression index = new CodePrimitiveExpression (n);
				if (outParams[n] == null)
				{
					CodeExpression res = new CodeCastExpression (method.ReturnType, new CodeArrayIndexerExpression (arrVar, index));
					outAssign.Add (new CodeMethodReturnStatement (res));
				}
				else
				{
					CodeExpression res = new CodeCastExpression (outParams[n].Type, new CodeArrayIndexerExpression (arrVar, index));
					CodeExpression var = new CodeVariableReferenceExpression (outParams[n].Name);
					outAssign.Insert (0, new CodeAssignStatement (var, res));
				}
			}
			
			if (Style == ServiceDescriptionImportStyle.Client) 
			{
				// Invoke call
				
				CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
				CodePrimitiveExpression varMsgName = new CodePrimitiveExpression (messageName);
				CodeMethodInvokeExpression inv;
				CodeVariableDeclarationStatement dec;
	
				inv = new CodeMethodInvokeExpression (ethis, "Invoke", varMsgName, methodParams);
				if (outputMembers != null && outputMembers.Count > 0)
				{
					dec = new CodeVariableDeclarationStatement (typeof(object[]), varResults, inv);
					method.Statements.Add (dec);
					method.Statements.AddRange (outAssign);
				}
				else
					method.Statements.Add (inv);
				
				// Begin Invoke Call
				
				CodeExpression expCallb = new CodeVariableReferenceExpression (varCallback);
				CodeExpression expAsyncs = new CodeVariableReferenceExpression (varAsyncState);
				inv = new CodeMethodInvokeExpression (ethis, "BeginInvoke", varMsgName, methodParams, expCallb, expAsyncs);
				methodBegin.Statements.Add (new CodeMethodReturnStatement (inv));
				
				// End Invoke call
				
				CodeExpression varAsyncr = new CodeVariableReferenceExpression (varAsyncResult);
				inv = new CodeMethodInvokeExpression (ethis, "EndInvoke", varAsyncr);
				if (outputMembers != null && outputMembers.Count > 0)
				{
					dec = new CodeVariableDeclarationStatement (typeof(object[]), varResults, inv);
					methodEnd.Statements.Add (dec);
					methodEnd.Statements.AddRange (outAssign);
				}
				else
					methodEnd.Statements.Add (inv);
			}
			else {
				method.Attributes = MemberAttributes.Public | MemberAttributes.Abstract;
			}
			
			// Attributes
			
			ImportHeaders (method);
			
			CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Web.Services.WebMethodAttribute");
			if (messageName != method.Name) att.Arguments.Add (GetArg ("MessageName",messageName));
			AddCustomAttribute (method, att, (Style == ServiceDescriptionImportStyle.Server));
			
			if (style == SoapBindingStyle.Rpc)
			{
				att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.SoapRpcMethodAttribute");
				att.Arguments.Add (GetArg (soapOper.SoapAction));
				if (inputMembers.ElementName != method.Name) att.Arguments.Add (GetArg ("RequestElementName", inputMembers.ElementName));
				if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response")) att.Arguments.Add (GetArg ("ResponseElementName", outputMembers.ElementName));
				att.Arguments.Add (GetArg ("RequestNamespace", inputMembers.Namespace));
				if (outputMembers != null) att.Arguments.Add (GetArg ("ResponseNamespace", outputMembers.Namespace));
				if (outputMembers == null) att.Arguments.Add (GetArg ("OneWay", true));
			}
			else
			{
				if (outputMembers != null && (inputMembers.ElementName == "" && outputMembers.ElementName != "" || 
					inputMembers.ElementName != "" && outputMembers.ElementName == ""))
					throw new InvalidOperationException ("Parameter style is not the same for the input message and output message");
	
				att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.SoapDocumentMethodAttribute");
				att.Arguments.Add (GetArg (soapOper.SoapAction));
				if (inputMembers.ElementName != "") {
					if (inputMembers.ElementName != method.Name) att.Arguments.Add (GetArg ("RequestElementName", inputMembers.ElementName));
					if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response")) att.Arguments.Add (GetArg ("ResponseElementName", outputMembers.ElementName));
					att.Arguments.Add (GetArg ("RequestNamespace", inputMembers.Namespace));
					if (outputMembers != null) att.Arguments.Add (GetArg ("ResponseNamespace", outputMembers.Namespace));
					att.Arguments.Add (GetEnumArg ("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Wrapped"));
				}
				else
					att.Arguments.Add (GetEnumArg ("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Bare"));
					
				if (outputMembers == null) att.Arguments.Add (GetArg ("OneWay", true));
					
				att.Arguments.Add (GetEnumArg ("Use", "System.Web.Services.Description.SoapBindingUse", bodyBinding.Use.ToString()));
			}
			
			AddCustomAttribute (method, att, true);
			
			CodeTypeDeclaration.Members.Add (method);
			
			if (Style == ServiceDescriptionImportStyle.Client) {
				CodeTypeDeclaration.Members.Add (methodBegin);
				CodeTypeDeclaration.Members.Add (methodEnd);
			}
			
			return method;
		}
        internal void ConnectStyleEvent(XamlClrEventNode xamlClrEventNode)
        {
            CodeConditionStatement ccsConnector = null;

            // validate the event handler name per C# grammar for identifiers
            ValidateEventHandlerName(xamlClrEventNode.EventName, xamlClrEventNode.Value);

            EnsureStyleConnector();

            if (!xamlClrEventNode.IsSameScope)
            {
                int connectionId = xamlClrEventNode.ConnectionId;
                if (SwitchStatementSupported())
                {
                    // break any previous case staements as we are starting a new connection scope.
                    if (_ccRoot.StyleConnectorFn.Statements.Count > 1)
                    {
                        CodeSnippetStatement cssBreak = new CodeSnippetStatement(BREAK_STATEMENT);
                        _ccRoot.StyleConnectorFn.Statements.Add(cssBreak);
                    }

                    // case 1:
                    //
                    CodeSnippetStatement cssCase = new CodeSnippetStatement(CASE_STATEMENT + connectionId + COLON);
                    _ccRoot.StyleConnectorFn.Statements.Add(cssCase);
                }
                else
                {
                    // if (connectionId == 1)
                    //
                    ccsConnector = new CodeConditionStatement();
                    ccsConnector.Condition = new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CONNECTIONID),
                                                                              CodeBinaryOperatorType.ValueEquality,
                                                                              new CodePrimitiveExpression(connectionId));
                }
            }
            else if (!SwitchStatementSupported())
            {
                // if in the same scope then use the if statement that was last generated
                // at the start of the scope
                Debug.Assert(_ccRoot.StyleConnectorFn.Statements.Count > 0);
                ccsConnector = _ccRoot.StyleConnectorFn.Statements[_ccRoot.StyleConnectorFn.Statements.Count - 1] as CodeConditionStatement;
                Debug.Assert(ccsConnector != null);
            }

            CodeArgumentReferenceExpression careTarget = new CodeArgumentReferenceExpression(TARGET);

            if (xamlClrEventNode.IsStyleSetterEvent)
            {
                // EventSetter declaration only once to avoid warning!
                if (!_hasEmittedEventSetterDeclaration)
                {
                    _hasEmittedEventSetterDeclaration = true;
                    
                    // EventSetter eventSetter;
                    //
                    CodeVariableDeclarationStatement cvdsES = new CodeVariableDeclarationStatement(KnownTypes.Types[(int)KnownElements.EventSetter], EVENTSETTER);
                    _ccRoot.StyleConnectorFn.Statements.Insert(0, cvdsES);
                }


                // eventSetter = new EventSetter();
                //
                CodeExpression[] esParams = {};
                CodeVariableReferenceExpression cvreES = new CodeVariableReferenceExpression(EVENTSETTER);
                CodeAssignStatement casES = new CodeAssignStatement(cvreES,
                                                                    new CodeObjectCreateExpression(KnownTypes.Types[(int)KnownElements.EventSetter],
                                                                                                   esParams));

                // eventSetter.Event = Button.ClickEvent;
                //
                CodePropertyReferenceExpression cpreEvent = new CodePropertyReferenceExpression(cvreES, EVENT);
                CodeAssignStatement casEvent = new CodeAssignStatement(cpreEvent,
                                                                       GetEvent(xamlClrEventNode.EventMember,
                                                                                xamlClrEventNode.EventName,
                                                                                xamlClrEventNode.Value));

                // eventSetter.Handler = new RoutedEventHandler(OnClick);
                //
                CodePropertyReferenceExpression cpreHandler = new CodePropertyReferenceExpression(cvreES, HANDLER);
                CodeAssignStatement casHandler = new CodeAssignStatement(cpreHandler,
                                                                         GetEventDelegate(null,
                                                                                          xamlClrEventNode.EventMember,
                                                                                          xamlClrEventNode.EventName,
                                                                                          xamlClrEventNode.Value));

                AddLinePragma(casHandler, xamlClrEventNode.LineNumber);

                // ((Style)target).Setters.Add(eventSetter);
                //
                CodeCastExpression cceTarget = new CodeCastExpression(KnownTypes.Types[(int)KnownElements.Style], careTarget);
                CodePropertyReferenceExpression cpreSetters = new CodePropertyReferenceExpression(cceTarget, SETTERS);
                CodeMethodInvokeExpression cmieAdd = new CodeMethodInvokeExpression(cpreSetters, ADD, cvreES);

                if (SwitchStatementSupported())
                {
                    _ccRoot.StyleConnectorFn.Statements.Add(casES);
                    _ccRoot.StyleConnectorFn.Statements.Add(casEvent);
                    _ccRoot.StyleConnectorFn.Statements.Add(casHandler);
                    _ccRoot.StyleConnectorFn.Statements.Add(new CodeExpressionStatement(cmieAdd));
                }
                else
                {
                    ccsConnector.TrueStatements.Add(casES);
                    ccsConnector.TrueStatements.Add(casEvent);
                    ccsConnector.TrueStatements.Add(casHandler);
                    ccsConnector.TrueStatements.Add(new CodeExpressionStatement(cmieAdd));
                    // Only add if statement at start of new scope
                    if (!xamlClrEventNode.IsSameScope)
                    {
                        _ccRoot.StyleConnectorFn.Statements.Add(ccsConnector);
                    }
                }
            }
            else
            {

                //
                // ((Foo)target).Bar += new BarEventHandler(OnBar);
                //
                // *or*
                //
                // ((Foo)target).AddHandler( Baz.BarEvent, new BarEventHandler(OnBar));
                //

                CodeCastExpression cceTarget;
                Type eventTarget;


                // Create the markup event information

                MarkupEventInfo mei = new MarkupEventInfo( xamlClrEventNode.Value,          // Event handler string
                                                           xamlClrEventNode.EventName,      // Event name string
                                                           xamlClrEventNode.EventMember,    // MemberInfo
                                                           xamlClrEventNode.LineNumber);    // LineNumber


                // Get the type that defines the event (e.g. typeof(Button) for Button.Clicked or typeof(Mouse) for Mouse.MouseMove)

                eventTarget = xamlClrEventNode.ListenerType;


                // Create the type cast expression "(Foo)target"

                cceTarget = new CodeCastExpression( eventTarget, careTarget);


                // Create the whole code statement (either in += form or in AddHandler form)

                CodeStatement csAddCLREvent = AddCLREvent( eventTarget, null, cceTarget, mei );

                if (SwitchStatementSupported())
                {
                    _ccRoot.StyleConnectorFn.Statements.Add( csAddCLREvent );
                }
                else
                {
                    ccsConnector.TrueStatements.Add( csAddCLREvent );

                    // Only add if statement at start of new scope
                    if (!xamlClrEventNode.IsSameScope)
                    {
                        _ccRoot.StyleConnectorFn.Statements.Add(ccsConnector);
                    }
                }
            }
        }
        internal void ConnectNameAndEvents(string elementName, ArrayList events, int connectionId)
        {
            CodeContext cc = (CodeContext)_codeContexts.Peek();
            bool isAllowedNameScope = cc.IsAllowedNameScope;

            if (_codeContexts.Count > 1 && KnownTypes.Types[(int)KnownElements.INameScope].IsAssignableFrom(cc.ElementType))
            {
                cc.IsAllowedNameScope = false;
            }

            if ((elementName == null || !isAllowedNameScope) && (events == null || events.Count == 0))
            {
                _typeArgsList = null;
                return;
            }

            EnsureHookupFn();

            CodeConditionStatement ccsConnector = null;

            if (SwitchStatementSupported())
            {
                // case 1:
                //
                CodeSnippetStatement cssCase = new CodeSnippetStatement(CASE_STATEMENT + connectionId + COLON);
                _ccRoot.HookupFn.Statements.Add(cssCase);
            }
            else
            {
                // if (connectionId == 1)
                //
                ccsConnector = new CodeConditionStatement();
                ccsConnector.Condition = new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CONNECTIONID),
                                                                          CodeBinaryOperatorType.ValueEquality,
                                                                          new CodePrimitiveExpression(connectionId));
            }


            // (System.Windows.Controls.Footype)target;
            CodeArgumentReferenceExpression careTarget = new CodeArgumentReferenceExpression(TARGET);
            CodeCastExpression cceTarget = new CodeCastExpression(cc.ElementTypeReference, careTarget);
            CodeExpression ceEvent = cceTarget;

            // Names in nested Name scopes not be hooked up via ICC.Connect() as no fields are generated in this case.
            if (elementName != null && isAllowedNameScope)
            {
                // this.fooId = (System.Windows.Controls.Footype)target;
                //
                ceEvent = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), elementName);
                CodeAssignStatement casName = new CodeAssignStatement(ceEvent, cceTarget);
                if (SwitchStatementSupported())
                {
                    _ccRoot.HookupFn.Statements.Add(casName);
                }
                else
                {
                    ccsConnector.TrueStatements.Add(casName);
                }
            }

            if (events != null)
            {
                foreach (MarkupEventInfo mei in events)
                {
                    CodeStatement csEvent = AddCLREvent(cc, ceEvent, mei);

                    if (SwitchStatementSupported())
                    {
                        _ccRoot.HookupFn.Statements.Add(csEvent);
                    }
                    else
                    {
                        ccsConnector.TrueStatements.Add(csEvent);
                    }
                }
            }

            // return;
            //
            if (SwitchStatementSupported())
            {
                _ccRoot.HookupFn.Statements.Add(new CodeMethodReturnStatement());
            }
            else
            {
                ccsConnector.TrueStatements.Add(new CodeMethodReturnStatement());
                _ccRoot.HookupFn.Statements.Add(ccsConnector);
            }

            _typeArgsList = null;
        }
        public override object VisitForeachStatement(ForeachStatement foreachStatement, object data)
        {
            // RG:
            //  foreach (T t in x)
            //  {
            //      stmts;
            //  }
            //
            // Emulate with
            //
            //  for (System.Collections.IEnumerator _it = x.GetEnumerator(); _it.MoveNext(); )
            //  {
            //      T t = ((T)_it.Current);
            //
            //      stmts;
            //  }

            foreachId++;
            string name = "_it" + foreachId.ToString();

            CodeIterationStatement _for1 = new CodeIterationStatement();
            breakableStack.Push(new Breakable());

            // init
            CodeVariableDeclarationStatement _decl2 = new CodeVariableDeclarationStatement();
            CodeMethodInvokeExpression _invoke1 = new CodeMethodInvokeExpression();
            CodeMethodReferenceExpression _GetEnumerator_method1 = new CodeMethodReferenceExpression();
            _GetEnumerator_method1.MethodName = "GetEnumerator";

            //CodeCastExpression _cast1 = new CodeCastExpression();
            //codeStack.Push(NullStmtCollection);
            //_cast1.Expression = (CodeExpression)foreachStatement.Expression.AcceptVisitor(this, data);
            //codeStack.Pop();
            //CodeTypeReference _IEnumerable_type1 = new CodeTypeReference("System.Collections.IEnumerable");
            //_cast1.TargetType = _IEnumerable_type1;

            //_GetEnumerator_method1.TargetObject = _cast1;

            codeStack.Push(NullStmtCollection);
            _GetEnumerator_method1.TargetObject = (CodeExpression)foreachStatement.Expression.AcceptVisitor(this, data);
            codeStack.Pop();

            _invoke1.Method = _GetEnumerator_method1;
            _decl2.InitExpression = _invoke1;
            _decl2.Name = name;
            CodeTypeReference _IEnumerator_type1 = new CodeTypeReference("System.Collections.IEnumerator");
            _decl2.Type = _IEnumerator_type1;
            _for1.InitStatement = _decl2;

            // Condition
            CodeMethodInvokeExpression _invoke2 = new CodeMethodInvokeExpression();
            CodeMethodReferenceExpression _MoveNext_method1 = new CodeMethodReferenceExpression();
            _MoveNext_method1.MethodName = "MoveNext";
            CodeVariableReferenceExpression _arg2 = new CodeVariableReferenceExpression();
            _arg2.VariableName = name;
            _MoveNext_method1.TargetObject = _arg2;
            _invoke2.Method = _MoveNext_method1;
            _for1.TestExpression = _invoke2;

            // Empty Increment
            _for1.IncrementStatement = new CodeExpressionStatement(new CodeSnippetExpression());

            // T t = ((T)_it.Current);
            CodeVariableDeclarationStatement _decl3 = new CodeVariableDeclarationStatement();
            CodeCastExpression _cast2 = new CodeCastExpression();
            CodePropertyReferenceExpression _prop1 = new CodePropertyReferenceExpression();
            _prop1.PropertyName = "Current";
            CodeVariableReferenceExpression _arg3 = new CodeVariableReferenceExpression();
            _arg3.VariableName = name;
            _prop1.TargetObject = _arg3;
            _cast2.Expression = _prop1;
            CodeTypeReference _System_String_type5 = ConvType(foreachStatement.TypeReference);
            _cast2.TargetType = _System_String_type5;
            _decl3.InitExpression = _cast2;
            _decl3.Name = foreachStatement.VariableName;
            CodeTypeReference _System_String_type6 = ConvType(foreachStatement.TypeReference);
            _decl3.Type = _System_String_type6;
            _for1.Statements.Add(_decl3);
            _for1.Statements.Add(new CodeSnippetStatement());

            codeStack.Push(_for1.Statements);
            foreachStatement.EmbeddedStatement.AcceptVisitor(this, data);
            codeStack.Pop();

            Breakable breakable = breakableStack.Pop();

            if (breakable.IsContinue)
            {
                _for1.Statements.Add(new CodeSnippetStatement());
                _for1.Statements.Add(new CodeLabeledStatement("continue" + breakable.Id, new CodeExpressionStatement(new CodeSnippetExpression())));
            }

            AddStmt(_for1);

            if (breakable.IsBreak)
            {
                AddStmt(new CodeLabeledStatement("break" + breakable.Id, new CodeExpressionStatement(new CodeSnippetExpression())));
            }

            return _for1;
        }
Beispiel #25
0
		public static void GenerateFile (string xaml_file, string out_file)
		{
			XmlDocument xmldoc = new XmlDocument ();
			xmldoc.Load (xaml_file);

			XmlNamespaceManager nsmgr = new XmlNamespaceManager (xmldoc.NameTable);
			nsmgr.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");

			XmlNode root = xmldoc.SelectSingleNode ("/*", nsmgr);
			if (root == null) {
				Console.Error.WriteLine ("{0}:  No root node found.", xaml_file);
				return;
			}

			XmlAttribute root_class = root.Attributes ["x:Class"];
			if (root_class == null) {
				File.WriteAllText (out_file, "");
				return;
			}

			bool is_application = root.LocalName == "Application";
			string root_ns;
			string root_type;
			string root_asm;

			ParseXmlns (root_class.Value, out root_type, out root_ns, out root_asm);

			Hashtable names_and_types = GetNamesAndTypes (root, nsmgr);
//			Hashtable keys_and_types = GetKeysAndTypes (root, nsmgr);

			CodeCompileUnit ccu = new CodeCompileUnit ();
			CodeNamespace decl_ns = new CodeNamespace (root_ns);
			ccu.Namespaces.Add (decl_ns);

			decl_ns.Imports.Add (new CodeNamespaceImport ("System"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Controls"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Controls.Primitives"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Documents"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Input"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Media"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Media.Animation"));
			decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Shapes"));

			CodeTypeDeclaration decl_type = new CodeTypeDeclaration (root_type);
			decl_type.IsPartial = true;

			decl_ns.Types.Add (decl_type);
			
			CodeMemberMethod initcomp = new CodeMemberMethod ();
			initcomp.Name = "InitializeComponent";
			decl_type.Members.Add (initcomp);

			if (sl2) {
				CodeMemberField field = new CodeMemberField ();
				field.Name = "_contentLoaded";
				field.Type = new CodeTypeReference (typeof (bool));

				decl_type.Members.Add (field);

				CodeConditionStatement is_content_loaded = new CodeConditionStatement (new CodeVariableReferenceExpression ("_contentLoaded"),
						new CodeStatement [] { new CodeMethodReturnStatement () });
				initcomp.Statements.Add (is_content_loaded);

				CodeAssignStatement set_content_loaded = new CodeAssignStatement (new CodeVariableReferenceExpression ("_contentLoaded"),
						new CodePrimitiveExpression (true));

				initcomp.Statements.Add (set_content_loaded);

				if (!Path.GetFullPath (xaml_file).StartsWith (root_folder))
					throw new ApplicationException ("the -root directory is not a parent of the xaml file");

				string component_path = String.Format ("/{0};component/{1}", app_name, Path.GetFullPath (xaml_file).Substring (root_folder.Length + (root_folder.EndsWith ("/") ? 0 : 1)));
				//string component_path = String.Format ("/{0};component/{1}", app_name, Path.GetFileName (xaml_file));

				CodeMethodInvokeExpression load_component = new CodeMethodInvokeExpression (
					new CodeTypeReferenceExpression ("System.Windows.Application"), "LoadComponent",
					new CodeExpression [] { new CodeThisReferenceExpression (),
								new CodeObjectCreateExpression (new CodeTypeReference ("System.Uri"), new CodeExpression [] {
									new CodePrimitiveExpression (component_path),
									new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.UriKind"), "Relative") })
					});
				initcomp.Statements.Add (load_component);
			}

			if (!is_application) {
				foreach (DictionaryEntry entry  in names_and_types) {
					string name = (string) entry.Key;
					CodeTypeReference type = (CodeTypeReference) entry.Value;

					CodeMemberField field = new CodeMemberField ();

					if (sl2)
						field.Attributes = MemberAttributes.Assembly;

					field.Name = name;
					field.Type = type;

					decl_type.Members.Add (field);

					CodeMethodInvokeExpression find_invoke = new CodeMethodInvokeExpression (
						new CodeThisReferenceExpression(), "FindName", 
						new CodeExpression[] { new CodePrimitiveExpression (name) } );

					CodeCastExpression cast = new CodeCastExpression (type, find_invoke);

					CodeAssignStatement assign = new CodeAssignStatement (
						new CodeVariableReferenceExpression (name), cast);

					initcomp.Statements.Add (assign);
				}
			}
			

			using (StreamWriter writer = new StreamWriter (out_file)) {
				provider.GenerateCodeFromCompileUnit (ccu, writer, new CodeGeneratorOptions ());
			}
		}
Beispiel #26
0
 protected override void GenerateCastExpression(CodeCastExpression e)
 {
     base.Output.Write("CType(");
     base.GenerateExpression(e.Expression);
     base.Output.Write(",");
     this.OutputType(e.TargetType);
     this.OutputArrayPostfix(e.TargetType);
     base.Output.Write(")");
 }
Beispiel #27
0
		void AddProfileClassGroupProperty (string groupName, string memberName, CodeTypeDeclaration profileClass)
		{			
			CodeMemberProperty property = new CodeMemberProperty ();
			property.Name = memberName;
			property.Type = new CodeTypeReference (groupName);
			property.Attributes = MemberAttributes.Public;

			CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
			CodeCastExpression cast = new CodeCastExpression ();
			ret.Expression = cast;

			CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
				new CodeThisReferenceExpression (),
				"GetProfileGroup");
			CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
				mref,
				new CodeExpression[] { new CodePrimitiveExpression (memberName) }
			);
			cast.TargetType = new CodeTypeReference (groupName);
			cast.Expression = minvoke;
			property.GetStatements.Add (ret);
			
			profileClass.Members.Add (property);
		}
Beispiel #28
0
		void AddProfileClassProperty (ProfileSection ps, CodeTypeDeclaration profileClass, ProfilePropertySettings pset)
		{
			string name = pset.Name;
			if (String.IsNullOrEmpty (name))
				throw new HttpException ("Profile property 'Name' attribute cannot be null.");
			CodeMemberProperty property = new CodeMemberProperty ();
			string typeName = pset.Type;
			if (typeName == "string")
				typeName = "System.String";
			property.Name = name;
			property.Type = GetProfilePropertyType (typeName);
			property.Attributes = MemberAttributes.Public;
			
			CodeAttributeDeclarationCollection collection = new CodeAttributeDeclarationCollection();
			GetProfileProviderAttribute (ps, collection, pset.Provider);
			GetProfileSettingsSerializeAsAttribute (ps, collection, pset.SerializeAs);

			property.CustomAttributes = collection;
			CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
			CodeCastExpression cast = new CodeCastExpression ();
			ret.Expression = cast;

			CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
				new CodeThisReferenceExpression (),
				"GetPropertyValue");
			CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
				mref,
				new CodeExpression[] { new CodePrimitiveExpression (name) }
			);
			cast.TargetType = new CodeTypeReference (typeName);
			cast.Expression = minvoke;
			property.GetStatements.Add (ret);

			if (!pset.ReadOnly) {
				mref = new CodeMethodReferenceExpression (
					new CodeThisReferenceExpression (),
					"SetPropertyValue");
				minvoke = new CodeMethodInvokeExpression (
					mref,
					new CodeExpression[] { new CodePrimitiveExpression (name), new CodeSnippetExpression ("value") }
				);
				property.SetStatements.Add (minvoke);
			}
			
			
			profileClass.Members.Add (property);
		}
Beispiel #29
0
        private void AddGetStatements(CodeStatementCollection getStatements)
        {
            if (IsSubstitutionHead)
            {
                AddSubstGetStatements(getStatements);
                return;
            }
            CodeExpression returnExp = null;

            if (FixedValue != null)
            {
                getStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeFieldReferenceExpression(
                            null,
                            NameGenerator.ChangeClrName(
                                this.propertyName,
                                NameOptions.MakeFixedValueField)))
                );
                return;
            }
            getStatements.Add(GetValueMethodCall());
            CheckOccurrence(getStatements);
            CodeVariableReferenceExpression returnValueExp =
                new CodeVariableReferenceExpression("x");
            if (!IsRef && typeRef.IsSimpleType)
            {
                //for referencing properties, directly create the object of referenced type
                CodeTypeReference parseType = ReturnType;
                if (typeRef.IsValueType && IsNullable)
                {
                    parseType = new CodeTypeReference(clrTypeName);
                }
                if (IsUnion)
                {
                    returnExp = CodeDomHelper.CreateMethodCall(
                        CodeDomHelper.CreateTypeReferenceExp(Constants.XTypedServices),
                        Constants.ParseUnionValue,
                        returnValueExp,
                        GetSimpleTypeClassExpression());
                }
                else
                {
                    string parseMethodName = null;
                    CodeExpression simpleTypeExpression = GetSchemaDatatypeExpression();
                    if (IsSchemaList)
                    {
                        parseMethodName = Constants.ParseListValue;
                        parseType = new CodeTypeReference(clrTypeName);
                    }
                    else
                    {
                        parseMethodName = Constants.ParseValue;
                    }
                    returnExp = CodeDomHelper.CreateGenericMethodCall(
                        CodeDomHelper.CreateTypeReferenceExp(
                            Constants.XTypedServices),
                        parseMethodName,
                        parseType,
                        returnValueExp,
                        simpleTypeExpression);

                    if(DefaultValue != null)
                    {
                         ((CodeMethodInvokeExpression)returnExp).Parameters.Add(
                            new CodeFieldReferenceExpression(
                                null,
                                NameGenerator.ChangeClrName(
                                    this.propertyName,
                                    NameOptions.MakeDefaultValueField)));
                    }
                }
            }
            else {
                returnExp = new CodeCastExpression(ReturnType, returnValueExp);
            }
            getStatements.Add(new CodeMethodReturnStatement(returnExp));
        }
		protected override void CreateMethods ()
		{
			base.CreateMethods ();

#if NET_2_0
			if (pageParser.MasterType != null) {
				CodeMemberProperty mprop = new CodeMemberProperty ();
				mprop.Name = "Master";
				mprop.Type = new CodeTypeReference (pageParser.MasterType);
				mprop.Attributes = MemberAttributes.Public | MemberAttributes.New;
				CodeExpression prop = new CodePropertyReferenceExpression (new CodeBaseReferenceExpression (), "Master");
				prop = new CodeCastExpression (pageParser.MasterType, prop);
				mprop.GetStatements.Add (new CodeMethodReturnStatement (prop));
				mainClass.Members.Add (mprop);
			}
#endif
			
			CreateGetTypeHashCode ();
		}
        private void GenerateInternalTypeHelperImplementation()
        {
            if (!IsInternalAccessSupported ||
                !(HasInternals || HasLocalReference) ||
                _hasGeneratedInternalTypeHelper)
            {
                return;
            }

            _hasGeneratedInternalTypeHelper = true;

            // namespace XamlGeneratedNamespace
            // {
            //
            CodeNamespace cns = new CodeNamespace();
            cns.Name = XamlTypeMapper.GeneratedNamespace;

            //     [EditorBrowsable(EditorBrowsableState.Never)]
            //     public sealed class GeneratedInternalTypeHelper : InternalTypeHelper
            //     {
            //
            CodeTypeDeclaration ctdClass = new CodeTypeDeclaration();
            ctdClass.Name = XamlTypeMapper.GeneratedInternalTypeHelperClassName;
            ctdClass.BaseTypes.Add(new CodeTypeReference("System.Windows.Markup.InternalTypeHelper"));
            ctdClass.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;
            AddDebuggerNonUserCodeAttribute(ctdClass);
            AddGeneratedCodeAttribute(ctdClass);
            AddEditorBrowsableAttribute(ctdClass);
            GenerateXmlComments(ctdClass, ctdClass.Name);

            //         protected override object CreateInstance(Type type, CultureInfo culture)
            //         {
            //             return Activator.CreateInstance(type,
            //                                             BindingFlags.Public |
            //                                             BindingFlags.NonPublic |
            //                                             BindingFlags.Instance |
            //                                             BindingFlags.CreateInstance,
            //                                             null,
            //                                             null,
            //                                             culture);
            //         }
            //
            CodeMemberMethod cmmCI = new CodeMemberMethod();
            cmmCI.Name = "CreateInstance";
            cmmCI.Attributes = MemberAttributes.Family | MemberAttributes.Override;
            cmmCI.ReturnType = new CodeTypeReference(typeof(Object));

            CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(Type), TYPE);
            CodeParameterDeclarationExpression param4 = new CodeParameterDeclarationExpression(typeof(CultureInfo), CULTURE);
            cmmCI.Parameters.Add(param1);
            cmmCI.Parameters.Add(param4);

            CodeMethodReferenceExpression cmreCI = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Activator)), "CreateInstance");
            CodeMethodInvokeExpression cmieCI = new CodeMethodInvokeExpression();
            cmieCI.Method = cmreCI;
            cmieCI.Parameters.Add(new CodeArgumentReferenceExpression(TYPE));
            CodeFieldReferenceExpression cfre1 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Public");
            CodeFieldReferenceExpression cfre2 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "NonPublic");
            CodeFieldReferenceExpression cfre3 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Instance");
            CodeFieldReferenceExpression cfre4 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "CreateInstance");
            CodeBinaryOperatorExpression cboe1 = new CodeBinaryOperatorExpression(cfre1, CodeBinaryOperatorType.BitwiseOr, cfre2);
            CodeBinaryOperatorExpression cboe2 = new CodeBinaryOperatorExpression(cfre3, CodeBinaryOperatorType.BitwiseOr, cfre4);
            CodeBinaryOperatorExpression cboeCI = new CodeBinaryOperatorExpression(cboe1, CodeBinaryOperatorType.BitwiseOr, cboe2);
            cmieCI.Parameters.Add(cboeCI);
            cmieCI.Parameters.Add(new CodePrimitiveExpression(null));
            cmieCI.Parameters.Add(new CodePrimitiveExpression(null));
            cmieCI.Parameters.Add(new CodeArgumentReferenceExpression(CULTURE));

            cmmCI.Statements.Add(new CodeMethodReturnStatement(cmieCI));
            GenerateXmlComments(cmmCI, cmmCI.Name);
            ctdClass.Members.Add(cmmCI);

            //         protected override object GetPropertyValue(PropertyInfo propertyInfo, object target, CultureInfo culture)
            //         {
            //             return propertyInfo.GetValue(target, BindingFlags.Default, null, null, culture);
            //         }
            //
            CodeMemberMethod cmmGPV = new CodeMemberMethod();
            cmmGPV.Name = "GetPropertyValue";
            cmmGPV.Attributes = MemberAttributes.Family | MemberAttributes.Override;
            cmmGPV.ReturnType = new CodeTypeReference(typeof(Object));

            param1 = new CodeParameterDeclarationExpression(typeof(PropertyInfo), PROPINFO);
            CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression(typeof(object), TARGET);
            cmmGPV.Parameters.Add(param1);
            cmmGPV.Parameters.Add(param2);
            cmmGPV.Parameters.Add(param4);

            CodeMethodReferenceExpression cmreGPV = new CodeMethodReferenceExpression(new CodeArgumentReferenceExpression(PROPINFO), "GetValue");
            CodeMethodInvokeExpression cmieGPV = new CodeMethodInvokeExpression();
            cmieGPV.Method = cmreGPV;
            cmieGPV.Parameters.Add(new CodeArgumentReferenceExpression(TARGET));
            cmieGPV.Parameters.Add(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), DEFAULT));
            cmieGPV.Parameters.Add(new CodePrimitiveExpression(null));
            cmieGPV.Parameters.Add(new CodePrimitiveExpression(null));
            cmieGPV.Parameters.Add(new CodeArgumentReferenceExpression(CULTURE));

            cmmGPV.Statements.Add(new CodeMethodReturnStatement(cmieGPV));
            GenerateXmlComments(cmmGPV, cmmGPV.Name);
            ctdClass.Members.Add(cmmGPV);

            //         protected override void SetPropertyValue(PropertyInfo propertyInfo, object target, object value, CultureInfo culture)
            //         {
            //             propertyInfo.SetValue(target, value, BindingFlags.Default, null, null, culture);
            //         }
            //
            CodeMemberMethod cmmSPV = new CodeMemberMethod();
            cmmSPV.Name = "SetPropertyValue";
            cmmSPV.Attributes = MemberAttributes.Family | MemberAttributes.Override;

            CodeParameterDeclarationExpression param3 = new CodeParameterDeclarationExpression(typeof(object), VALUE);
            cmmSPV.Parameters.Add(param1);
            cmmSPV.Parameters.Add(param2);
            cmmSPV.Parameters.Add(param3);
            cmmSPV.Parameters.Add(param4);

            CodeMethodReferenceExpression cmreSPV = new CodeMethodReferenceExpression(new CodeArgumentReferenceExpression(PROPINFO), "SetValue");
            CodeMethodInvokeExpression cmieSPV = new CodeMethodInvokeExpression();
            cmieSPV.Method = cmreSPV;
            cmieSPV.Parameters.Add(new CodeArgumentReferenceExpression(TARGET));
            cmieSPV.Parameters.Add(new CodeArgumentReferenceExpression(VALUE));
            cmieSPV.Parameters.Add(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), DEFAULT));
            cmieSPV.Parameters.Add(new CodePrimitiveExpression(null));
            cmieSPV.Parameters.Add(new CodePrimitiveExpression(null));
            cmieSPV.Parameters.Add(new CodeArgumentReferenceExpression(CULTURE));

            cmmSPV.Statements.Add(new CodeExpressionStatement(cmieSPV));
            GenerateXmlComments(cmmSPV, cmmSPV.Name);
            ctdClass.Members.Add(cmmSPV);

            //         protected override Delegate CreateDelegate(Type delegateType, object target, string handler)
            //         {
            //             return (Delegate)target.GetType().InvokeMember("_CreateDelegate",
            //                                                            BindingFlags.Instance |
            //                                                            BindingFlags.NonPublic |
            //                                                            BindingFlags.InvokeMethod,
            //                                                            null,
            //                                                            target,
            //                                                            new object[] { delegateType, handler });
            //         }
            //
            CodeMemberMethod cmmCD = new CodeMemberMethod();
            cmmCD.Name = "CreateDelegate";
            cmmCD.Attributes = MemberAttributes.Family | MemberAttributes.Override;
            cmmCD.ReturnType = new CodeTypeReference(typeof(Delegate));

            param1 = new CodeParameterDeclarationExpression(typeof(Type), DELEGATETYPE);
            param3 = new CodeParameterDeclarationExpression(typeof(string), HANDLERARG);
            cmmCD.Parameters.Add(param1);
            cmmCD.Parameters.Add(param2);
            cmmCD.Parameters.Add(param3);

            CodeArgumentReferenceExpression careTarget = new CodeArgumentReferenceExpression(TARGET);
            CodeMethodReferenceExpression cmreGetType = new CodeMethodReferenceExpression(careTarget, "GetType");
            CodeMethodInvokeExpression cmieGetType = new CodeMethodInvokeExpression();
            cmieGetType.Method = cmreGetType;

            CodeMethodReferenceExpression cmreCD = new CodeMethodReferenceExpression(cmieGetType, "InvokeMember");
            CodeMethodInvokeExpression cmieCD = new CodeMethodInvokeExpression();
            cmieCD.Method = cmreCD;
            cmieCD.Parameters.Add(new CodePrimitiveExpression(CREATEDELEGATEHELPER));

            CodeFieldReferenceExpression cfre5 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "InvokeMethod");
            CodeBinaryOperatorExpression cboe = new CodeBinaryOperatorExpression(cfre2, CodeBinaryOperatorType.BitwiseOr, cfre3);
            CodeBinaryOperatorExpression cboeCD = new CodeBinaryOperatorExpression(cfre5, CodeBinaryOperatorType.BitwiseOr, cboe);
            cmieCD.Parameters.Add(cboeCD);

            cmieCD.Parameters.Add(new CodePrimitiveExpression(null));
            cmieCD.Parameters.Add(careTarget);

            CodeArrayCreateExpression caceCD = new CodeArrayCreateExpression(typeof(object));
            CodeArgumentReferenceExpression careDelType = new CodeArgumentReferenceExpression(DELEGATETYPE);
            CodeArgumentReferenceExpression careHandler = new CodeArgumentReferenceExpression(HANDLERARG);
            caceCD.Initializers.Add(careDelType);
            caceCD.Initializers.Add(careHandler);
            cmieCD.Parameters.Add(caceCD);
            cmieCD.Parameters.Add(new CodePrimitiveExpression(null));

            CodeCastExpression cceCD = new CodeCastExpression(typeof(Delegate), cmieCD);
            cmmCD.Statements.Add(new CodeMethodReturnStatement(cceCD));
            GenerateXmlComments(cmmCD, cmmCD.Name);
            ctdClass.Members.Add(cmmCD);

            //         protected override void AddEventHandler(EventInfo eventInfo, object target, Delegate handler);
            //         {
            //             eventInfo.AddEventHandler(target, handler);
            //         }
            //
            CodeMemberMethod cmmAEH = new CodeMemberMethod();
            cmmAEH.Name = "AddEventHandler";
            cmmAEH.Attributes = MemberAttributes.Family | MemberAttributes.Override;

            param1 = new CodeParameterDeclarationExpression(typeof(EventInfo), EVENTINFO);
            param3 = new CodeParameterDeclarationExpression(typeof(Delegate), HANDLERARG);
            cmmAEH.Parameters.Add(param1);
            cmmAEH.Parameters.Add(param2);
            cmmAEH.Parameters.Add(param3);

            CodeMethodReferenceExpression cmreAEH = new CodeMethodReferenceExpression(new CodeArgumentReferenceExpression(EVENTINFO), "AddEventHandler");
            CodeMethodInvokeExpression cmieAEH = new CodeMethodInvokeExpression();
            cmieAEH.Method = cmreAEH;
            cmieAEH.Parameters.Add(new CodeArgumentReferenceExpression(TARGET));
            cmieAEH.Parameters.Add(new CodeArgumentReferenceExpression(HANDLERARG));

            cmmAEH.Statements.Add(new CodeExpressionStatement(cmieAEH));
            GenerateXmlComments(cmmAEH, cmmAEH.Name);
            ctdClass.Members.Add(cmmAEH);

            //     }
            //
            cns.Types.Add(ctdClass);

            // }
            //
            CodeCompileUnit ccu = new CodeCompileUnit();
            ccu.Namespaces.Add(cns);

            // For VB only we need to let the parser know about the RootNamespace value
            // in order to look for the XamlGeneratedNamespace.GeneratedInternalTypeHelper
            // type whose full type name would have been implicitly by the VB comopiler to
            // RootNS.XamlGeneratedNamespace.GeneratedInternalTypeHelper

            if (IsLanguageVB && !string.IsNullOrEmpty(DefaultNamespace))
            {
                // [assembly: RootNamespaceAttribute("RootNS")]
                CodeAttributeDeclaration cad = new CodeAttributeDeclaration(
                             "System.Windows.Markup.RootNamespaceAttribute",
                             new CodeAttributeArgument(new CodePrimitiveExpression(DefaultNamespace)));

                ccu.AssemblyCustomAttributes.Add(cad);
            }

            MemoryStream codeMemStream = new MemoryStream();

            // using Disposes the StreamWriter when it ends.  Disposing the StreamWriter
            // also closes the underlying MemoryStream.  Furthermore, don't add BOM here since
            // TaskFileService.WriteGeneratedCodeFile adds it.
            using (StreamWriter codeStreamWriter = new StreamWriter(codeMemStream, new UTF8Encoding(false)))
            {
                CodeGeneratorOptions o = new CodeGeneratorOptions();
                CodeDomProvider codeProvider = EnsureCodeProvider();
                codeProvider.GenerateCodeFromCompileUnit(ccu, codeStreamWriter, o);

                codeStreamWriter.Flush();
                TaskFileService.WriteGeneratedCodeFile(codeMemStream.ToArray(),
                    TargetPath + SharedStrings.GeneratedInternalTypeHelperFileName,
                    SharedStrings.GeneratedExtension, SharedStrings.IntellisenseGeneratedExtension,
                    LanguageSourceExtension);
            }
        }