Inheritance: System.CodeDom.CodeExpression
Esempio n. 1
0
        // Generates a codedom instantiation expression: new foo() or new foo[x].
        public static CodeExpression Emit(Instantiation instantiation)
        {
            // Array instantiation needs a different treatment.
            if (instantiation.IsArray)
            {
                var c = new CodeArrayCreateExpression();

                c.CreateType = new CodeTypeReference(instantiation.Name);
                c.SizeExpression = CodeDomEmitter.EmitCodeExpression(instantiation.Parameters.ChildExpressions[0]);
                return c;
            }
            else // Non-array instantiation
            {
                var c = new CodeObjectCreateExpression();

                // The type that is being created
                var createType = new CodeTypeReference(instantiation.Name);

                // Apply the generic type names, if any.
                foreach (var g in instantiation.GenericTypes)
                {
                    createType.TypeArguments.Add(new CodeTypeReference(g));
                }
                c.CreateType = createType;

                // Translate the instantiation parameters.
                foreach (var a in instantiation.Parameters.ChildExpressions)
                    c.Parameters.Add(CodeDomEmitter.EmitCodeExpression(a));

                return c;
            }
        }
Esempio n. 2
0
	public void EmitGetFingerprint (CodeTypeDeclaration ctd)
	{
	    byte[] hash = Hash;
	    
	    CodeArrayCreateExpression mkdata = new CodeArrayCreateExpression (CDH.Byte, hash.Length);
	    
	    for (int i = 0; i < hash.Length; i++)
		// well, this for loop sucks
		mkdata.Initializers.Add (new CodePrimitiveExpression (hash[i]));
	    
	    CodeMemberMethod m = new CodeMemberMethod ();
	    m.Name = "GetFingerprint";
	    m.Attributes = MemberAttributes.Public | MemberAttributes.Override;
	    m.ReturnType = CDH.Fingerprint;
	    m.Parameters.Add (CDH.Param (CDH.IContext, "unused1"));
	    m.Parameters.Add (CDH.Param (CDH.Fingerprint, "unused2"));
			
	    CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
	    invoke.Method = new CodeMethodReferenceExpression (Generic, "Constant");
	    invoke.Parameters.Add (mkdata);
	    
	    m.Statements.Add (new CodeMethodReturnStatement (invoke));
	    
	    ctd.Members.Add (m);
	}
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeArrayCreateExpression cace = new CodeArrayCreateExpression (ctr, ce);
			Assert.AreEqual ("System.Void", cace.CreateType.BaseType, "CreateType.BaseType");
			Assert.AreEqual (0, cace.Initializers.Count, "Initializers");
			Assert.AreEqual (0, cace.Size, "Size");
			Assert.AreSame (ce, cace.SizeExpression, "SizeExpression");
		}
Esempio n. 4
0
        public static CodeMethodInvokeExpression GetConcatExpression(IList<ExpressionStringToken> values)
        {
            var stringType = new CodeTypeReference(typeof(string));
            var arrayExpression = new CodeArrayCreateExpression
            {
                CreateType = new CodeTypeReference("System.String", 1)
                {
                    ArrayElementType = stringType
                },
                Size = 0
            };

            foreach (var expressionStringToken in values)
            {
                if (expressionStringToken.IsExpression)
                {
                    var toStringExpression = new CodeMethodInvokeExpression
                    {
                        Method = new CodeMethodReferenceExpression
                        {
                            MethodName = "ToString",
                            TargetObject =
                                new CodeVariableReferenceExpression
                                {
                                    VariableName = "Convert"
                                }
                        }
                    };

                    toStringExpression.Parameters.Add(new CodeSnippetExpression
                    {
                        Value = expressionStringToken.Value
                    });
                    arrayExpression.Initializers.Add(toStringExpression);
                }
                else
                {
                    var _value3 = new CodePrimitiveExpression
                    {
                        Value = expressionStringToken.Value
                    };
                    arrayExpression.Initializers.Add(_value3);
                }
            }
            var concatExpression = new CodeMethodInvokeExpression
            {
                Method = new CodeMethodReferenceExpression
                {
                    MethodName = "Concat",
                    TargetObject = new CodeTypeReferenceExpression
                    {
                        Type = stringType
                    }
                }
            };
            concatExpression.Parameters.Add(arrayExpression);
            return concatExpression;
        }
Esempio n. 5
0
		//
		// Methods
		//

		protected override void GenerateArrayCreateExpression (CodeArrayCreateExpression expression)
		{
			//
			// This tries to replicate MS behavior as good as
			// possible.
			//
			// The Code-Array stuff in ms.net seems to be broken
			// anyways, or I'm too stupid to understand it.
			//
			// I'm sick of it. If you try to develop array
			// creations, test them on windows. If it works there
			// but not in mono, drop me a note.  I'd be especially
			// interested in jagged-multidimensional combinations
			// with proper initialization :}
			//

			TextWriter output = Output;

			output.Write ("new ");

			CodeExpressionCollection initializers = expression.Initializers;
			CodeTypeReference createType = expression.CreateType;

			if (initializers.Count > 0) {

				OutputType (createType);

				if (expression.CreateType.ArrayRank == 0) {
					output.Write ("[]");
				}

				OutputStartBrace ();
				++Indent;
				OutputExpressionList (initializers, true);
				--Indent;
				output.Write ("}");
			} else {
				CodeTypeReference arrayType = createType.ArrayElementType;
				while (arrayType != null) {
					createType = arrayType;
					arrayType = arrayType.ArrayElementType;
				}

				OutputType (createType);

				output.Write ('[');

				CodeExpression size = expression.SizeExpression;
				if (size != null)
					GenerateExpression (size);
				else
					output.Write (expression.Size);

				output.Write(']');
			}
		}
		public void NullCreateType ()
		{
			CodeArrayCreateExpression cace = new CodeArrayCreateExpression ((CodeTypeReference) null, 0);
			Assert.IsNotNull (cace.CreateType, "#1");
			Assert.AreEqual (typeof (void).FullName, cace.CreateType.BaseType, "#2");

			cace.CreateType = null;
			Assert.IsNotNull (cace.CreateType, "#3");
			Assert.AreEqual (typeof (void).FullName, cace.CreateType.BaseType, "#4");
		}
        /// <summary>
        /// Visits a <see cref="CodeArrayCreateExpression"/>.
        /// </summary>
        /// <param name="codeArrayCreateExpression">The <see cref="CodeArrayCreateExpression"/> to visit.</param>
        protected virtual void VisitCodeArrayCreateExpression(CodeArrayCreateExpression codeArrayCreateExpression)
        {
            if (codeArrayCreateExpression == null)
            {
                return;
            }

            this.VisitCodeTypeReference(codeArrayCreateExpression.CreateType);
            this.VisitCodeExpressionCollection(codeArrayCreateExpression.Initializers);
            this.VisitCodeExpression(codeArrayCreateExpression.SizeExpression);
        }
 public static CodeArrayCreateExpression Clone(this CodeArrayCreateExpression expression)
 {
     if (expression == null) return null;
     CodeArrayCreateExpression e = new CodeArrayCreateExpression();
     e.CreateType = expression.CreateType.Clone();
     e.Initializers.AddRange(expression.Initializers.Clone());
     e.Size = expression.Size;
     e.SizeExpression = expression.SizeExpression.Clone();
     e.UserData.AddRange(expression.UserData);
     return e;
 }
 public TypescriptArrayCreateExpression(
     IExpressionFactory expressionFactory,
     CodeArrayCreateExpression codeExpression, 
     CodeGeneratorOptions options,
     ITypescriptTypeMapper typescriptTypeMapper)
 {
     _expressionFactory = expressionFactory;
     _codeExpression = codeExpression;
     _options = options;
     _typescriptTypeMapper = typescriptTypeMapper;
     System.Diagnostics.Debug.WriteLine("TypescriptArrayCreateExpression Created");
 }
        internal static CodeExpression MaterializeSimpleTypeDef(
            ClrSimpleTypeInfo typeInfo, 
            Dictionary<XmlSchemaObject, string> nameMappings,
            LinqToXsdSettings settings)  
        {
            CodeObjectCreateExpression simpleTypeCreate = null;
            CodeExpressionCollection expressions = null;
            switch(typeInfo.Variety) {
                case XmlSchemaDatatypeVariety.Atomic:
                    simpleTypeCreate = new CodeObjectCreateExpression(
                        Constants.AtomicSimpleTypeValidator);
                    expressions = simpleTypeCreate.Parameters;
                    expressions.Add(CreateGetBuiltInSimpleType(typeInfo.TypeCode));
                    expressions.Add(CreateFacets(typeInfo));
                break;
                
                case XmlSchemaDatatypeVariety.List:
                    simpleTypeCreate = new CodeObjectCreateExpression(
                        Constants.ListSimpleTypeValidator);
                    expressions = simpleTypeCreate.Parameters;
                    expressions.Add(CreateGetBuiltInSimpleType(typeInfo.TypeCode));
                    expressions.Add(CreateFacets(typeInfo));
                    
                    ListSimpleTypeInfo listType = typeInfo as ListSimpleTypeInfo;
                    ClrSimpleTypeInfo itemType = listType.ItemType;
                    expressions.Add(CreateSimpleTypeDef(
                        itemType, nameMappings, settings, true));
                break;
                
                case XmlSchemaDatatypeVariety.Union:
                    simpleTypeCreate = new CodeObjectCreateExpression(
                        Constants.UnionSimpleTypeValidator);
                    expressions = simpleTypeCreate.Parameters;
                    expressions.Add(CreateGetBuiltInSimpleType(typeInfo.TypeCode));
                    expressions.Add(CreateFacets(typeInfo));

                    UnionSimpleTypeInfo unionType = typeInfo as UnionSimpleTypeInfo;
                    CodeArrayCreateExpression memberTypeCreate = 
                        new CodeArrayCreateExpression();
                    memberTypeCreate.CreateType = new CodeTypeReference(
                        Constants.SimpleTypeValidator);
                    foreach (ClrSimpleTypeInfo st in unionType.MemberTypes) 
                    {
                        memberTypeCreate.Initializers.Add(CreateSimpleTypeDef(
                            st, nameMappings, settings, true));
                    }
                    expressions.Add(memberTypeCreate);
                break;
            }
            return simpleTypeCreate;
        }
 internal override CodeExpression Clone(CodeExpression expression)
 {
     CodeArrayCreateExpression expression2 = (CodeArrayCreateExpression) expression;
     CodeArrayCreateExpression expression3 = new CodeArrayCreateExpression {
         CreateType = TypeReferenceExpression.CloneType(expression2.CreateType),
         Size = expression2.Size
     };
     if (expression2.SizeExpression != null)
     {
         expression3.SizeExpression = RuleExpressionWalker.Clone(expression2.SizeExpression);
     }
     foreach (CodeExpression expression4 in expression2.Initializers)
     {
         expression3.Initializers.Add(RuleExpressionWalker.Clone(expression4));
     }
     return expression3;
 }
        public override void Generate(object codeObject, Entity entity)
        {
            base.Generate(codeObject, entity);

            var attribute = (CodeAttributeDeclaration)codeObject;
            var docType = (DocumentType)entity;
            var info = (DocumentTypeInfo)docType.Info;

            AddAttributeArgumentIfValue(attribute, "DefaultTemplate", info.DefaultTemplate);

            var allowedTemplates = 
                info.AllowedTemplates
                    .NonNullOrWhiteSpace()
                    .AsPrimitiveExpressions();
            var arrayCreateExpression = new CodeArrayCreateExpression("String", allowedTemplates);
            if (allowedTemplates.Any())
                AddAttributeArgument(attribute, "AllowedTemplates", arrayCreateExpression);
        }
		public CodeExpression[] Generate(Table table, HardwireCodeGenerationContext generator,
			CodeTypeMemberCollection members)
		{
			List<CodeExpression> initializers = new List<CodeExpression>();

			generator.DispatchTablePairs(table.Get("overloads").Table, members, exp =>
			{
				initializers.Add(exp);
			});

			var name = new CodePrimitiveExpression((table["name"] as string));
			var type = new CodeTypeOfExpression(table["decltype"] as string);

			var array = new CodeArrayCreateExpression(typeof(IOverloadableMemberDescriptor), initializers.ToArray());

			return new CodeExpression[] {
					new CodeObjectCreateExpression(typeof(OverloadedMethodMemberDescriptor), name, type, array)
			};
		}
Esempio n. 14
0
 protected override void GenerateArrayCreateExpression(System.CodeDom.CodeArrayCreateExpression e)
 {
     //throw new Exception("The method or operation is not implemented.");
     Output.Write("new ");
     OutputType(e.CreateType);
     Output.Write("[");
     Output.Write(e.Initializers.Count);
     Output.Write("]");
     if (e.Initializers.Count > 0)
     {
         Output.Write("(");
         GenerateExpression(e.Initializers[0]);
         for (int i = 1; i < e.Initializers.Count; i++)
         {
             Output.Write(", ");
             GenerateExpression(e.Initializers[i]);
         }
         Output.Write(")");
     }
 }
Esempio n. 15
0
        void EmitArray(CodeArrayCreateExpression array)
        {
            writer.Write(Parser.ArrayOpen);

            bool first = true;
            depth++;
            foreach (CodeExpression expr in array.Initializers)
            {
                if (first)
                    first = false;
                else
                {
                    writer.Write(Parser.DefaultMulticast);
                    writer.Write(Parser.SingleSpace);
                }
                EmitExpression(expr);
            }
            depth--;

            writer.Write(Parser.ArrayClose);
        }
        public override void Generate(object codeObject, Entity entity)
        {
            var contentType = (ContentType) entity;
            var attribute = (CodeAttributeDeclaration) codeObject;

            var structure = contentType.Structure;
            if (structure.All(String.IsNullOrWhiteSpace))
                return;

            var typeofExpressions = 
                structure
                    .Where(allowedType => !String.IsNullOrWhiteSpace(allowedType))
                    .Select(allowedType => new CodeTypeOfExpression(allowedType.PascalCase()))
                    .Cast<CodeExpression>()
                    .ToArray();
            var expression = new CodeArrayCreateExpression(
                typeof(Type[]),
                typeofExpressions
                );

            AddAttributeArgument(attribute, "Structure", expression);
        }
Esempio n. 17
0
		protected override void GenerateArrayCreateExpression (CodeArrayCreateExpression expression) 
		{
			TextWriter output = Output;
			output.Write ("new ");
			CodeExpressionCollection initializers = expression.Initializers;
			CodeTypeReference createType = expression.CreateType;

			if (initializers.Count > 0) {
				OutputType (createType);

				if (expression.CreateType.ArrayRank == 0)
					output.Write ("[]");

				output.Write ('[');
				++Indent;
				OutputExpressionList (initializers, true);
				--Indent;
				output.Write (']');
			} else {
				CodeTypeReference arrayType = createType.ArrayElementType;

				while (arrayType != null) {
					createType = arrayType;
					arrayType = arrayType.ArrayElementType;
				}

				OutputType (createType);
				output.Write ('[');

				CodeExpression size = expression.SizeExpression;

				if (size != null)
					GenerateExpression (size);
				else
					output.Write (expression.Size);

				output.Write (']');
			}
		}
Esempio n. 18
0
 protected override void GenerateArrayCreateExpression(CodeArrayCreateExpression e)
 {
     CodeExpressionCollection initializers = e.Initializers;
     // Literal array
     if (initializers.Count > 0)
     {
         // the syntax is something like <int>{ 10,12,14 }
         this.Output.Write("<");
         // Is a specific type indicated ?
         if (e.CreateType.ArrayElementType != null)
         {
             this.OutputType(e.CreateType.ArrayElementType);
         }
         else
         {
             this.OutputType(e.CreateType);
         }
         //
         this.Output.Write(">{ ");
         this.OutputExpressionList(initializers, false);
         this.Output.Write(" }");
     }
     else
     {
         // Standard Array declaration
         base.Output.Write(this.GetBaseTypeOutput(e.CreateType));
         base.Output.Write("[");
         if (e.SizeExpression != null)
         {
             base.GenerateExpression(e.SizeExpression);
         }
         else
         {
             base.Output.Write(e.Size);
         }
         base.Output.Write("]");
     }
 }
Esempio n. 19
0
        CodeExpression StringConcat(params CodeExpression[] parts)
        {
            var list = new List<CodeExpression>(parts.Length);

            foreach (var part in parts)
            {
                if (part is CodePrimitiveExpression)
                {
                    var value = ((CodePrimitiveExpression)part).Value;
                    if (value is string && string.IsNullOrEmpty((string)value))
                        continue;
                }

                list.Add(part);
            }

            if (list.Count == 1)
                return list[0];

            Type str = typeof(string);
            var method = (CodeMethodReferenceExpression)InternalMethods.Concat;
            var all = new CodeArrayCreateExpression(str, list.ToArray());
            return new CodeMethodInvokeExpression(method, all);
        }
 private void AddFindByMethods(CodeTypeDeclaration dataTableClass)
 {
     DataTable dataTable = this.designTable.DataTable;
     for (int i = 0; i < dataTable.Constraints.Count; i++)
     {
         if ((dataTable.Constraints[i] is UniqueConstraint) && ((UniqueConstraint) dataTable.Constraints[i]).IsPrimaryKey)
         {
             DataColumn[] columns = ((UniqueConstraint) dataTable.Constraints[i]).Columns;
             string inVarName = "FindBy";
             bool flag = true;
             for (int j = 0; j < columns.Length; j++)
             {
                 inVarName = inVarName + this.codeGenerator.TableHandler.Tables[columns[j].Table.TableName].DesignColumns[columns[j].ColumnName].GeneratorColumnPropNameInRow;
                 if (columns[j].ColumnMapping != MappingType.Hidden)
                 {
                     flag = false;
                 }
             }
             if (!flag)
             {
                 CodeMemberMethod method = CodeGenHelper.MethodDecl(CodeGenHelper.Type(this.rowClassName), NameHandler.FixIdName(inVarName), MemberAttributes.Public | MemberAttributes.Final);
                 for (int k = 0; k < columns.Length; k++)
                 {
                     method.Parameters.Add(CodeGenHelper.ParameterDecl(CodeGenHelper.Type(columns[k].DataType), this.codeGenerator.TableHandler.Tables[columns[k].Table.TableName].DesignColumns[columns[k].ColumnName].GeneratorColumnPropNameInRow));
                 }
                 CodeArrayCreateExpression par = new CodeArrayCreateExpression(typeof(object), columns.Length);
                 for (int m = 0; m < columns.Length; m++)
                 {
                     par.Initializers.Add(CodeGenHelper.Argument(this.codeGenerator.TableHandler.Tables[columns[m].Table.TableName].DesignColumns[columns[m].ColumnName].GeneratorColumnPropNameInRow));
                 }
                 method.Statements.Add(CodeGenHelper.Return(CodeGenHelper.Cast(CodeGenHelper.Type(this.rowClassName), CodeGenHelper.MethodCall(CodeGenHelper.Property(CodeGenHelper.This(), "Rows"), "Find", par))));
                 dataTableClass.Members.Add(method);
             }
         }
     }
 }
		protected override void GenerateArrayCreateExpression(CodeArrayCreateExpression e)
		{
			Output.Write("[CodeArrayCreateExpression: {0}]", e.ToString());
		}
Esempio n. 22
0
        public void GenerateModelCode(ViewModel model, DirectoryInfo saveDir)
        {
            //TODO: Make code more modular, add more comments

            CodeCompileUnit compileUnit = new CodeCompileUnit();
            CodeNamespace globalNamespace = new CodeNamespace();
            globalNamespace.Imports.AddRange(
                configuration.Namespaces.Select(x => new CodeNamespaceImport(x)).ToArray());
            //Add global using statements
            compileUnit.Namespaces.Add(globalNamespace);

            CodeTypeDeclaration modelClass = new CodeTypeDeclaration(model.Name);
            // Sets the member attributes for the type to public
            modelClass.Attributes = MemberAttributes.Public;
            // Set the base class which the model inherits from
            modelClass.BaseTypes.Add(model.BaseClass.Name);
            //Add the View Model Attribute
            modelClass.CustomAttributes.Add(new CodeAttributeDeclaration("ViewModel",
                new CodeAttributeArgument(new CodePrimitiveExpression(model.SchemaName)), //Schema Name
                new CodeAttributeArgument(new CodePrimitiveExpression(true)) //Is Default
                ));
            foreach (var field in model.FieldProperties)
            {
                if (configuration.FieldAttributeTypes.ContainsKey(field.FieldType))
                {
                    CodeAttributeDeclaration fieldAttribute = new CodeAttributeDeclaration(
                        configuration.FieldAttributeTypes[field.FieldType].Name, //Field Attribute Name
                        new CodeAttributeArgument(new CodePrimitiveExpression(field.FieldName))); //Schema Field Name

                    if (field.FieldType == FieldType.Linked)
                    {
                        //Field is a Linked Component, we need to assemble the list of possible Types
                        var modelTypes = new List<CodeExpression>();
                        //Populate list of Types
                        foreach (var modelName in field.LinkedComponentTypeNames)
                        {
                            modelTypes.Add(new CodeTypeOfExpression(modelName));
                        }
                        if (modelTypes.Count > 0)
                        {
                            //Create Array of Types and pass in the list of Types
                            CodeArrayCreateExpression codeArrayCreate = new CodeArrayCreateExpression("Type",
                            modelTypes.ToArray());
                            //Add the array of Types to the Attribute arguments
                            fieldAttribute.Arguments.Add(
                                new CodeAttributeArgument(configuration.LinkedComponentTypesAttributeParameterName,
                                    codeArrayCreate));
                        }
                    }
                    else if (field.FieldType == FieldType.Embedded
                        && !string.IsNullOrEmpty(field.EmbeddedTypeName))
                    {
                        //Add the required Type argument for embedded fields
                        fieldAttribute.Arguments.Add(
                            new CodeAttributeArgument(new CodeTypeOfExpression(field.EmbeddedTypeName)));
                    }
                    if (field.IsMultiValue)
                    {
                        //Add boolean value for multiple values
                        fieldAttribute.Arguments.Add(new CodeAttributeArgument("AllowMultipleValues",
                            new CodePrimitiveExpression(true)));
                    }
                    if (field.IsMetadata)
                    {
                        //Add boolean for metadata fields
                        fieldAttribute.Arguments.Add(new CodeAttributeArgument("IsMetadata",
                            new CodePrimitiveExpression(true)));
                    }
                    //Create and populate the model Property
                    CodeMemberField property = new CodeMemberField { Name = field.PropertyName }; //Use CodeMemberField as a hack to add a blank getter/setter
                    property.Attributes = MemberAttributes.Public;
                    property.Type = GetPropertyType(model.BaseClass, field);
                    property.CustomAttributes.Add(fieldAttribute); //Add the Field Attribute
                    property.Name += " { get; set; }"; //Hack to add empty get/set
                    modelClass.Members.Add(property);
                }
            }
            if (configuration.ModelAttributeTypes.ContainsKey(model.ModelType))
            {
                var attrs = configuration.ModelAttributeTypes[model.ModelType];
                //loop through all the "extra" model properties in the config that don't necessarily have a direct link to the Schema i.e. multimedia
                foreach (var attr in attrs)
                {
                    CodeAttributeDeclaration modelAttribute = new CodeAttributeDeclaration(attr.Name); //Field Attribute Name
                    CodeMemberField property = new CodeMemberField { Name = attr.DefaultPropertyName }; //Use CodeMemberField as a hack to add a blank getter/setter
                    property.Attributes = MemberAttributes.Public;
                    property.Type = new CodeTypeReference(attr.ReturnTypeName);
                    property.CustomAttributes.Add(modelAttribute); //Add the Field Attribute
                    property.Name += " { get; set; }"; //Hack to add empty get/set
                    modelClass.Members.Add(property);
                }
            }
            var ns = new CodeNamespace(namespaceName);
            ns.Types.Add(modelClass);
            compileUnit.Namespaces.Add(ns);

            if (!saveDir.Exists) saveDir.Create();
            DirectoryInfo dir = new DirectoryInfo(Path.Combine(saveDir.FullName, model.ContainingFolder));
            if (!dir.Exists) dir.Create();
            string filePath = Path.Combine(dir.FullName, model.Name + ".cs");
            CreateFile(filePath, compileUnit);
        }
		internal override CodeExpression BuildInvokeAsync (string messageName, CodeArrayCreateExpression paramsArray, CodeExpression delegateField, CodeExpression userStateVar)
		{
			HttpOperationBinding httpOper = OperationBinding.Extensions.Find (typeof (HttpOperationBinding)) as HttpOperationBinding;
			
			CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
			
			CodeExpression thisURlExp = new CodeFieldReferenceExpression (ethis, "Url");
			CodePrimitiveExpression metUrl = new CodePrimitiveExpression (httpOper.Location);
			CodeBinaryOperatorExpression expMethodLocation = new CodeBinaryOperatorExpression (thisURlExp, CodeBinaryOperatorType.Add, metUrl);
			
			CodeMethodInvokeExpression inv2 = new CodeMethodInvokeExpression (ethis, "InvokeAsync");
			inv2.Parameters.Add (new CodePrimitiveExpression (messageName));
			inv2.Parameters.Add (expMethodLocation);
			inv2.Parameters.Add (paramsArray);
			inv2.Parameters.Add (delegateField);
			inv2.Parameters.Add (userStateVar);
			return inv2;
		}
		CodeMemberMethod GenerateMethod (CodeIdentifiers memberIds, HttpOperationBinding httpOper, XmlMembersMapping inputMembers, XmlTypeMapping outputMember)
		{
			CodeIdentifiers pids = new CodeIdentifiers ();
			CodeMemberMethod method = new CodeMemberMethod ();
			CodeMemberMethod methodBegin = new CodeMemberMethod ();
			CodeMemberMethod methodEnd = new CodeMemberMethod ();
			method.Attributes = MemberAttributes.Public;
			methodBegin.Attributes = MemberAttributes.Public;
			methodEnd.Attributes = MemberAttributes.Public;
			
			// Find unique names for temporary variables
			
			for (int n=0; n<inputMembers.Count; n++)
				pids.AddUnique (inputMembers[n].MemberName, inputMembers[n]);

			string varAsyncResult = pids.AddUnique ("asyncResult","asyncResult");
			string varCallback = pids.AddUnique ("callback","callback");
			string varAsyncState = pids.AddUnique ("asyncState","asyncState");

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

			method.Name = Operation.Name;
			methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + Operation.Name),method);
			methodEnd.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + Operation.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];

			for (int n=0; n<inputMembers.Count; n++)
			{
				string ptype = GetSimpleType (inputMembers[n]);
				CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (ptype, inputMembers[n].MemberName);
				
				param.Direction = FieldDirection.In;
				method.Parameters.Add (param);
				methodBegin.Parameters.Add (param);
				paramArray [n] = new CodeVariableReferenceExpression (param.Name);
			}

			bool isVoid = true;
			if (outputMember != null)
			{
				method.ReturnType = new CodeTypeReference (outputMember.TypeFullName);
				methodEnd.ReturnType = new CodeTypeReference (outputMember.TypeFullName);
				xmlExporter.AddMappingMetadata (method.ReturnTypeCustomAttributes, outputMember, "");
				isVoid = false;
			}

			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);

			// Generate method url
			
			CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
			
			CodeExpression thisURlExp = new CodeFieldReferenceExpression (ethis, "Url");
			CodePrimitiveExpression metUrl = new CodePrimitiveExpression (httpOper.Location);
			CodeBinaryOperatorExpression expMethodLocation = new CodeBinaryOperatorExpression (thisURlExp, CodeBinaryOperatorType.Add, metUrl);
			
			// Invoke call
			
			CodePrimitiveExpression varMsgName = new CodePrimitiveExpression (messageName);
			CodeMethodInvokeExpression inv;

			inv = new CodeMethodInvokeExpression (ethis, "Invoke", varMsgName, expMethodLocation, methodParams);
			if (!isVoid)
				method.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (method.ReturnType, inv)));
			else
				method.Statements.Add (inv);
			
			// Begin Invoke Call
			
			CodeExpression expCallb = new CodeVariableReferenceExpression (varCallback);
			CodeExpression expAsyncs = new CodeVariableReferenceExpression (varAsyncState);
			inv = new CodeMethodInvokeExpression (ethis, "BeginInvoke", varMsgName, expMethodLocation, methodParams, expCallb, expAsyncs);
			methodBegin.Statements.Add (new CodeMethodReturnStatement (inv));
			
			// End Invoke call
			
			CodeExpression varAsyncr = new CodeVariableReferenceExpression (varAsyncResult);
			inv = new CodeMethodInvokeExpression (ethis, "EndInvoke", varAsyncr);
			if (!isVoid)
				methodEnd.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (methodEnd.ReturnType, inv)));
			else
				methodEnd.Statements.Add (inv);
			
			// Attributes

			CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.HttpMethodAttribute");
			att.Arguments.Add (new CodeAttributeArgument (new CodeTypeOfExpression(GetOutMimeFormatter ())));
			att.Arguments.Add (new CodeAttributeArgument (new CodeTypeOfExpression(GetInMimeFormatter ())));
			AddCustomAttribute (method, att, true);
		
			CodeTypeDeclaration.Members.Add (method);
			CodeTypeDeclaration.Members.Add (methodBegin);
			CodeTypeDeclaration.Members.Add (methodEnd);
			
			return method;
		}		
		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;
		}
        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);
            }
        }
Esempio n. 27
0
 protected override void GenerateArrayCreateExpression(CodeArrayCreateExpression e)
 {
     base.Output.Write("New ");
     CodeExpressionCollection initializers = e.Initializers;
     if (initializers.Count > 0)
     {
         string typeOutput = this.GetTypeOutput(e.CreateType);
         base.Output.Write(typeOutput);
         if (typeOutput.IndexOf('(') == -1)
         {
             base.Output.Write("()");
         }
         base.Output.Write(" {");
         base.Indent++;
         this.OutputExpressionList(initializers);
         base.Indent--;
         base.Output.Write("}");
     }
     else
     {
         string str2 = this.GetTypeOutput(e.CreateType);
         int index = str2.IndexOf('(');
         if (index == -1)
         {
             base.Output.Write(str2);
             base.Output.Write('(');
         }
         else
         {
             base.Output.Write(str2.Substring(0, index + 1));
         }
         if (e.SizeExpression != null)
         {
             base.Output.Write("(");
             base.GenerateExpression(e.SizeExpression);
             base.Output.Write(") - 1");
         }
         else
         {
             base.Output.Write((int)(e.Size - 1));
         }
         if (index == -1)
         {
             base.Output.Write(')');
         }
         else
         {
             base.Output.Write(str2.Substring(index + 1));
         }
         base.Output.Write(" {}");
     }
 }
 private void GenerateStrings(Property property, CodeMemberProperty propertyName)
 {
     this.GenerateCommon(property, propertyName, "String", typeof(string), "Value");
     string referencedProperty = null;
     if (property.Values.Count > 0)
     {
         CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement("System.String[][]", "switchMap");
         List<CodeExpression> list = new List<CodeExpression>();
         int num = 0;
         CodeTypeReference createType = new CodeTypeReference(typeof(string));
         foreach (Value value2 in property.Values)
         {
             if (this.ContainsCurrentPlatform(value2.SwitchName))
             {
                 CodeSnippetExpression[] initializers = new CodeSnippetExpression[2];
                 initializers[0] = new CodeSnippetExpression(this.SurroundWithQuotes(value2.Name));
                 if (value2.SwitchName != string.Empty)
                 {
                     initializers[1] = new CodeSnippetExpression(this.SurroundWithQuotes(value2.Prefix + value2.SwitchName));
                 }
                 else
                 {
                     initializers[1] = new CodeSnippetExpression(this.SurroundWithQuotes(""));
                 }
                 CodeArrayCreateExpression item = new CodeArrayCreateExpression(createType, initializers);
                 list.Add(item);
                 num++;
             }
         }
         CodeArrayCreateExpression expression2 = new CodeArrayCreateExpression("System.String[][]", list.ToArray());
         statement.InitExpression = expression2;
         propertyName.SetStatements.Add(statement);
         CodeAssignStatement statement2 = new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("switchToAdd"), "SwitchValue"), new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "ReadSwitchMap", new CodeExpression[] { new CodeSnippetExpression(this.SurroundWithQuotes(property.Name)), new CodeVariableReferenceExpression("switchMap"), new CodeVariableReferenceExpression("value") }));
         propertyName.SetStatements.Add(statement2);
         CodeAssignStatement statement3 = new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("switchToAdd"), "Name"), new CodeSnippetExpression(this.SurroundWithQuotes(property.Name)));
         propertyName.SetStatements.Add(statement3);
         referencedProperty = "Value";
         this.GenerateAssignPropertyToValue(propertyName, "AllowMultipleValues", new CodeSnippetExpression("true"));
     }
     else
     {
         CodeAssignStatement statement4 = new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("switchToAdd"), "Name"), new CodeSnippetExpression(this.SurroundWithQuotes(property.Name)));
         propertyName.SetStatements.Add(statement4);
         referencedProperty = "Value";
         CodeAssignStatement statement5 = new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("switchToAdd"), "SwitchValue"), (property.SwitchName != string.Empty) ? new CodeSnippetExpression(this.SurroundWithQuotes(property.Prefix + property.SwitchName)) : new CodeSnippetExpression(this.SurroundWithQuotes("")));
         propertyName.SetStatements.Add(statement5);
         this.GenerateAssignToolSwitch(propertyName, "ReverseSwitchValue", property.Prefix, property.ReverseSwitchName);
     }
     this.GenerateCommonSetStatements(property, propertyName, referencedProperty);
 }
 private void BuildLinkedStyleSheetMember()
 {
     CodeMemberField field = new CodeMemberField(typeof(string[]), "__linkedStyleSheets");
     if ((this._themeParser.CssFileList != null) && (this._themeParser.CssFileList.Count > 0))
     {
         CodeExpression[] initializers = new CodeExpression[this._themeParser.CssFileList.Count];
         int num = 0;
         foreach (string str in this._themeParser.CssFileList)
         {
             initializers[num++] = new CodePrimitiveExpression(str);
         }
         CodeArrayCreateExpression expression = new CodeArrayCreateExpression(typeof(string), initializers);
         field.InitExpression = expression;
     }
     else
     {
         field.InitExpression = new CodePrimitiveExpression(null);
     }
     base._sourceDataClass.Members.Add(field);
 }
        private void GenerateCodeFromCodeArrayCreateExpression(CodeArrayCreateExpression e, TextWriter w)
        {
            w.Write("@(");

            for (var i = 0; i < e.Initializers.Count; i++)
            {
                GenerateCodeFromExpression(e.Initializers[i], w, null);
                if (i < e.Initializers.Count - 1)
                    w.Write(",");
            }

            w.Write(")");
        }
 private void GenerateConstructor(CodeTypeDeclaration taskClass)
 {
     CodeConstructor constructor = new CodeConstructor {
         Attributes = MemberAttributes.Public
     };
     CodeTypeReference createType = new CodeTypeReference("System.Resources.ResourceManager");
     CodeSnippetExpression expression = new CodeSnippetExpression(this.SurroundWithQuotes(this.taskParser.ResourceNamespace));
     CodeTypeReferenceExpression targetObject = new CodeTypeReferenceExpression("System.Reflection.Assembly");
     CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(targetObject, "GetExecutingAssembly");
     CodeMethodInvokeExpression expression4 = new CodeMethodInvokeExpression(method, new CodeExpression[0]);
     CodeObjectCreateExpression expression5 = new CodeObjectCreateExpression(createType, new CodeExpression[] { expression, expression4 });
     CodeTypeReference reference2 = new CodeTypeReference(new CodeTypeReference("System.String"), 1);
     List<CodeExpression> list = new List<CodeExpression>();
     foreach (string str in this.taskParser.SwitchOrderList)
     {
         list.Add(new CodeSnippetExpression(this.SurroundWithQuotes(str)));
     }
     CodeArrayCreateExpression expression6 = new CodeArrayCreateExpression(reference2, list.ToArray());
     constructor.BaseConstructorArgs.Add(expression6);
     constructor.BaseConstructorArgs.Add(expression5);
     taskClass.Members.Add(constructor);
     if (this.GenerateComments)
     {
         constructor.Comments.Add(new CodeCommentStatement(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("StartSummary", new object[0]), true));
         string text = Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("ConstructorDescription", new object[0]);
         constructor.Comments.Add(new CodeCommentStatement(text, true));
         constructor.Comments.Add(new CodeCommentStatement(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("EndSummary", new object[0]), true));
     }
 }