Inheritance: System.CodeDom.CodeExpression
		public void CodeAssignStatementTest ()
		{
			CodeSnippetExpression cse1 = new CodeSnippetExpression("A");
			CodeSnippetExpression cse2 = new CodeSnippetExpression("B");

			CodeAssignStatement assignStatement = new CodeAssignStatement (cse1, cse2);
			statement = assignStatement;

			Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
				"A = B;{0}", NewLine), Generate (), "#1");

			assignStatement.Left = null;
			try {
				Generate ();
				Assert.Fail ("#2");
			} catch (ArgumentNullException) {
			}

			assignStatement.Left = cse1;
			Generate ();

			assignStatement.Right = null;
			try {
				Generate ();
				Assert.Fail ("#3");
			} catch (ArgumentNullException) {
			}

			assignStatement.Right = cse2;
			Generate ();
		}
Esempio n. 2
0
		public void Constructor1 ()
		{
			string value = "mono";

			CodeSnippetExpression cse = new CodeSnippetExpression (value);
			Assert.IsNotNull (cse.Value, "#1");
			Assert.AreSame (value, cse.Value, "#2");
		}
 public TypescriptSnippetExpression(
     CodeSnippetExpression codeExpression, 
     CodeGeneratorOptions options)
 {
     _codeExpression = codeExpression;
     _options = options;
     System.Diagnostics.Debug.WriteLine("TypescriptSnippetExpression Created");
 }
Esempio n. 4
0
		public void Constructor0 ()
		{
			CodeSnippetExpression cse = new CodeSnippetExpression ();
			Assert.IsNotNull (cse.Value, "#1");
			Assert.AreEqual (string.Empty, cse.Value, "#2");

			string value = "mono";
			cse.Value = value;
			Assert.IsNotNull (cse.Value, "#3");
			Assert.AreSame (value, cse.Value, "#4");

			cse.Value = null;
			Assert.IsNotNull (cse.Value, "#5");
			Assert.AreEqual (string.Empty, cse.Value, "#6");
		}
Esempio n. 5
0
 private static void LoadEnumElement(XmlElement element, CodeTypeDeclaration codeType,
     out CodeMemberProperty codeProperty)
 {
     codeProperty = new CodeMemberProperty();
     string name = element.GetAttribute("name");
     CodeTypeDeclaration codeEnum = new CodeTypeDeclaration(ToPublicName(name) + "Enum");
     codeEnum.IsEnum = true;
     codeEnum.Members.Add(new CodeSnippetTypeMember(element.InnerText));
     codeType.Members.Add(codeEnum);
     CodeExpression defaultValue = null;
     if(element.HasAttribute("default"))
         defaultValue = new CodeSnippetExpression(
         JoinNames(codeEnum.Name, element.GetAttribute("default")));
     GenerateProperty(codeType, codeEnum.Name, name, out codeProperty, defaultValue);
 }
Esempio n. 6
0
        /// <summary>
        /// Creates a reference to a collection based member field and initializes it with a new instance of the
        /// specified parameter type and adds a collection item to it.
        /// Sample values are used as the initializing expression.
        /// </summary>
        /// <param name="memberCollectionField">Name of the referenced collection field.</param>
        /// <param name="collectionInitializers">Defines the types of the new object list.</param>
        /// <returns>
        /// An assignment statement for the specified collection member field.
        /// </returns>
        /// <remarks>
        /// With a custom Type, this method produces a statement with a initializer like:
        /// <code>this.paths = new[] { pathsItem };</code>.
        /// where the item is defined like:
        /// <code>this.pathsItem = new PathItemType();</code>.
        /// myType of type System.Type:
        /// <code>this.pathsItem = "An Item";</code>.
        /// </remarks>
        public static CodeAssignStatement CreateAndInitializeCollectionField(
            //Type type,
            string memberCollectionField,
            params string[] collectionInitializers)
        {
            /*if (type == typeof(object))
            {

            }*/
            var fieldRef1 = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), memberCollectionField);
            //CodeExpression assignExpr = CreateExpressionByType(type, memberCollectionField);
            var para = collectionInitializers.Aggregate((x, y) => x += "," + y);
            CodeExpression assignExpr = new CodeSnippetExpression("new[] { " + para + " }");

            return new CodeAssignStatement(fieldRef1, assignExpr);
        }
        public static void AddArgument(this CodeAttributeDeclaration attribute, string name, string value)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            CodeExpression expression;
            // Use convention that if string starts with $ its a const
            if (value.StartsWith(SnippetIndicator.ToString()))
            {
                expression = new CodeSnippetExpression(value.TrimStart(SnippetIndicator));
            }
            else
            {
                expression = new CodePrimitiveExpression(value);
            }
            attribute.AddArgument(name, expression);
        }
        public static CodeStatement[] CreateMappingStatements(ClassMappingDescriptor descriptor, CodeGeneratorContext context)
        {
            Dictionary<string, List<MemberMappingDescriptor>> aggregateGroups = new Dictionary<string, List<MemberMappingDescriptor>>();
            List<CodeStatement> statements = new List<CodeStatement>(20);
            foreach (MemberMappingDescriptor member in descriptor.MemberDescriptors)
            {
                if (member.IsAggregateExpression)
                {
                    // group all agregates by expression to avoid multiple traversals over same path
                    //string path = GetPath(member.Expression);
                    string path = GetPath(descriptor, member);
                    if(!aggregateGroups.ContainsKey(path))
                        aggregateGroups[path] = new List<MemberMappingDescriptor>(1);
                    aggregateGroups[path].Add(member);
                }
                else
                {
                    CodeStatement[] st = CreateNonAggregateMappingStatements(descriptor, member, context);
                    if(member.HasNullValue)
                    {
                        CodeStatement[] falseStatements = st;
                        CodeStatement[] trueStatements = new CodeStatement[1];
                        trueStatements[0] = new CodeAssignStatement(
                            new CodeVariableReferenceExpression("target." + member.Member),
                            new CodeSnippetExpression(member.NullValue.ToString()));

                        string checkExpression = GetNullablePartsCheckExpression(member);
                        CodeExpression ifExpression = new CodeSnippetExpression(checkExpression);

                        st = new CodeStatement[1];
                        st[0] = new CodeConditionStatement(ifExpression, trueStatements, falseStatements);
                    }
                    statements.AddRange(st);
                }
            }

            foreach (List<MemberMappingDescriptor> group in aggregateGroups.Values)
            {
                    CodeStatement[] st = CreateAggregateMappingStatements(descriptor, group, context);
                    statements.AddRange(st);
            }

            return statements.ToArray();
        }
        //Create main method
        private void CreateEntryPoint(List<string> statements)
        {
            //Create an object and assign the name as "Main"
            CodeEntryPointMethod mymain = new CodeEntryPointMethod();
            mymain.Name = "Main";
            //Mark the access modifier for the main method as Public and //static
            mymain.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            //Change string to statements
            if(statements != null){

                foreach (string item in statements) {
                    if (item != null) {
                        CodeSnippetExpression exp1 = new CodeSnippetExpression(@item);
                        CodeExpressionStatement ces1 = new CodeExpressionStatement(exp1);
                        mymain.Statements.Add(ces1);
                    }
                }
            }
            myclass.Members.Add(mymain);
        }
        /// <summary>
        /// if (string.IsNullOrEmpty(APIKey) == false)
        ///    request = request.WithAPIKey(APIKey)
        /// </summary>
        /// <returns></returns>
        internal CodeConditionStatement CreateWithApiKey()
        {
            // !string.IsNullOrEmpty(Key)
            var condition =
                new CodeSnippetExpression("!string.IsNullOrEmpty(" + ApiKeyServiceDecorator.PropertyName + ")");

            // if (...) {
            var block = new CodeConditionStatement(condition);

            // request = request.WithKey(APIKey)
            var getProperty = new CodePropertyReferenceExpression(
                new CodeThisReferenceExpression(), ApiKeyServiceDecorator.PropertyName);
            var request = new CodeMethodInvokeExpression(
                new CodeVariableReferenceExpression("request"), "WithKey", getProperty);

            var trueCase = new CodeAssignStatement(new CodeVariableReferenceExpression("request"), request);

            // }
            block.TrueStatements.Add(trueCase);

            return block;
        }
		public void Constructor1 ()
		{
			CodeSnippetExpression expression = new CodeSnippetExpression("exp");

			CodeEventReferenceExpression cere = new CodeEventReferenceExpression (
				expression, "mono");
			Assert.AreEqual ("mono", cere.EventName, "#1");
			Assert.IsNotNull (cere.TargetObject, "#2");
			Assert.AreSame (expression, cere.TargetObject, "#3");

			cere.EventName = null;
			Assert.IsNotNull (cere.EventName, "#4");
			Assert.AreEqual (string.Empty, cere.EventName, "#5");

			cere.TargetObject = null;
			Assert.IsNull (cere.TargetObject, "#6");

			cere = new CodeEventReferenceExpression ((CodeExpression) null,
				(string) null);
			Assert.IsNotNull (cere.EventName, "#7");
			Assert.AreEqual (string.Empty, cere.EventName, "#8");
			Assert.IsNull (cere.TargetObject, "#9");
		}
Esempio n. 12
0
        public void CreateEntryPoint(ref CodeTypeDeclaration customClass)
        {
            //Create an object and assign the name as “Main”
            CodeEntryPointMethod main = new CodeEntryPointMethod();
            main.Name = "Main";

            //Mark the access modifier for the main method as Public and //static
            main.Attributes = MemberAttributes.Public | MemberAttributes.Static;

            //Provide defenition to the main method.
            //Create an object of the “Cmyclass” and invoke the method
            //by passing the required parameters.
            CodeSnippetExpression exp = new CodeSnippetExpression(CallingMethod(customClass));

            //Create expression statements for the snippets
            CodeExpressionStatement ces = new CodeExpressionStatement(exp);

            //Add the expression statements to the main method.
            main.Statements.Add(ces);

            //Add the main method to the class
            customClass.Members.Add(main);
        }
Esempio n. 13
0
 protected override void GenerateSnippetExpression(CodeSnippetExpression e)
 {
     base.Output.Write(e.Value);
 }
 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 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));
     }
 }
Esempio n. 16
0
		protected override void GenerateSnippetExpression (CodeSnippetExpression e)
		{
		}
Esempio n. 17
0
		protected override void GenerateSnippetExpression (CodeSnippetExpression expression)
		{
			Output.Write (expression.Value);
		}
Esempio n. 18
0
		protected abstract void GenerateSnippetExpression (CodeSnippetExpression e);
Esempio n. 19
0
			public void Visit (CodeSnippetExpression o)
			{
				g.GenerateSnippetExpression (o);
			}
Esempio n. 20
0
        private CodeStatement[] MakeWriteMethodBody(Type type)
        {
            List<CodeStatement> statements = new List<CodeStatement>();
            CodeExpression objExpr = new CodeArgumentReferenceExpression("obj");
            CodeExpression writerExpr = new CodeArgumentReferenceExpression("writer");

            if (type.IsArray)
            {
                if (type.GetElementType() == typeof(object))
                {
                    throw new DryadLinqException(DryadLinqErrorCode.CannotHandleObjectFields,
                                                 String.Format(SR.CannotHandleObjectFields, type.FullName));
                }

                int rank = type.GetArrayRank();
                for (int i = 0; i < rank; i++)
                {
                    CodeExpression lenExpr = new CodeMethodInvokeExpression(objExpr, "GetLength", new CodePrimitiveExpression(i));
                    CodeExpression lenCall = new CodeMethodInvokeExpression(writerExpr, "Write", lenExpr);
                    statements.Add(new CodeExpressionStatement(lenCall));
                }

                // Generate the writing code
                if (type.GetElementType().IsPrimitive)
                {
                    // Use a single WriteRawBytes for primitive array
                    string lenStr = "sizeof(" + type.GetElementType() + ")";
                    for (int i = 0; i < rank; i++)
                    {
                        lenStr += "*obj.GetLength(" + i + ")";
                    }
                    string writeBytes = "            unsafe { fixed (void *p = obj) writer.WriteRawBytes((byte*)p, " + lenStr + "); }";
                    statements.Add(new CodeSnippetStatement(writeBytes));
                }
                else
                {
                    CodeVariableReferenceExpression[] indexExprs = new CodeVariableReferenceExpression[rank];
                    for (int i = 0; i < rank; i++)
                    {
                        indexExprs[i] = new CodeVariableReferenceExpression("i" + i);
                    }
                    bool canBeNull = StaticConfig.AllowNullArrayElements && !type.GetElementType().IsValueType;
                    if (canBeNull)
                    {
                        string lenString = "obj.GetLength(0)";
                        for (int i = 1; i < rank; i++)
                        {
                            lenString += "*obj.GetLength(" + i + ")";
                        }
                        CodeExpression lenExpr = new CodeSnippetExpression(lenString);
                        CodeExpression bvExpr = new CodeObjectCreateExpression(typeof(BitVector), lenExpr);
                        CodeStatement bvStmt = new CodeVariableDeclarationStatement("BitVector", "bv", bvExpr);
                        statements.Add(bvStmt);
                    }
                    CodeStmtPair pair = this.MakeWriteFieldStatements(type.GetElementType(), objExpr, null, indexExprs);

                    CodeStatement[] writeStmts = pair.Key;
                    if (writeStmts != null)
                    {
                        for (int i = rank - 1; i >= 0; i--)
                        {
                            CodeVariableDeclarationStatement
                                initStmt = new CodeVariableDeclarationStatement(
                                                   typeof(int), indexExprs[i].VariableName, ZeroExpr);
                            CodeExpression lenExpr = new CodeMethodInvokeExpression(
                                                             objExpr, "GetLength", new CodePrimitiveExpression(i));
                            CodeExpression testExpr = new CodeBinaryOperatorExpression(
                                                              indexExprs[i],
                                                              CodeBinaryOperatorType.LessThan,
                                                              lenExpr);
                            CodeStatement incStmt = new CodeAssignStatement(
                                                            indexExprs[i],
                                                            new CodeBinaryOperatorExpression(
                                                                    indexExprs[i], CodeBinaryOperatorType.Add, OneExpr));
                            writeStmts = new CodeStatement[] { new CodeIterationStatement(initStmt, testExpr, incStmt, writeStmts) };
                        }
                        statements.AddRange(writeStmts);
                    }

                    if (canBeNull)
                    {
                        CodeExpression bvWriteExpr = new CodeSnippetExpression("BitVector.Write(writer, bv)");
                        statements.Add(new CodeExpressionStatement(bvWriteExpr));
                    }

                    writeStmts = pair.Value;
                    for (int i = rank - 1; i >= 0; i--)
                    {
                        CodeVariableDeclarationStatement
                            initStmt = new CodeVariableDeclarationStatement(
                                               typeof(int), indexExprs[i].VariableName, ZeroExpr);
                        CodeExpression lenExpr = new CodeMethodInvokeExpression(
                                                         objExpr, "GetLength", new CodePrimitiveExpression(i));
                        CodeExpression testExpr = new CodeBinaryOperatorExpression(
                                                          indexExprs[i], CodeBinaryOperatorType.LessThan, lenExpr);
                        CodeStatement incStmt = new CodeAssignStatement(
                                                        indexExprs[i],
                                                        new CodeBinaryOperatorExpression(
                                                                indexExprs[i], CodeBinaryOperatorType.Add, OneExpr));
                        writeStmts = new CodeStatement[] { new CodeIterationStatement(initStmt, testExpr, incStmt, writeStmts) };
                    }
                    statements.AddRange(writeStmts);
                }
            }
            else
            {
                FieldInfo[] fields = TypeSystem.GetAllFields(type);
                System.Array.Sort(fields, (x, y) => x.MetadataToken.CompareTo(y.MetadataToken));

                bool canBeNull = fields.Any(x => !x.FieldType.IsValueType && AttributeSystem.FieldCanBeNull(x));
                if (canBeNull)
                {
                    CodeExpression lenExpr = new CodePrimitiveExpression(fields.Length);
                    CodeExpression bvExpr = new CodeObjectCreateExpression(typeof(BitVector), lenExpr);
                    CodeStatement bvStmt = new CodeVariableDeclarationStatement("BitVector", "bv", bvExpr);
                    statements.Add(bvStmt);
                }
                    
                // For each field of type, generate its serialization code
                CodeStatement[][] stmtArray = new CodeStatement[fields.Length][];
                for (int i = 0; i < fields.Length; i++)
                {
                    FieldInfo finfo = fields[i];
                    if (TypeSystem.IsFieldSerialized(finfo))
                    {
                        if (finfo.FieldType == typeof(object))
                        {
                            throw new DryadLinqException(DryadLinqErrorCode.CannotHandleObjectFields,
                                                         String.Format(SR.CannotHandleObjectFields, type.FullName));
                        }

                        CodeVariableReferenceExpression[]
                            indexExprs = new CodeVariableReferenceExpression[] { new CodeVariableReferenceExpression(i.ToString()) };
                        CodeStmtPair pair = this.MakeWriteFieldStatements(finfo.FieldType, objExpr, finfo, indexExprs);
                        stmtArray[i] = pair.Value;
                        if (pair.Key != null)
                        {
                            statements.AddRange(pair.Key);
                        }
                    }
                }
                if (canBeNull)
                {
                    CodeExpression bvWriteExpr = new CodeSnippetExpression("BitVector.Write(writer, bv)");
                    statements.Add(new CodeExpressionStatement(bvWriteExpr));
                }
                for (int i = 0; i < stmtArray.Length; i++)
                {
                    if (stmtArray[i] != null)
                    {
                        statements.AddRange(stmtArray[i]);
                    }
                }
            }

            return statements.ToArray();
        }
Esempio n. 21
0
        private CodeStatement[] MakeReadMethodBody(Type type)
        {
            List<CodeStatement> statements = new List<CodeStatement>();
            CodeExpression objExpr = new CodeArgumentReferenceExpression("obj");
            if (type.IsArray)
            {
                if (type.GetElementType() == typeof(object))
                {
                    throw new DryadLinqException(DryadLinqErrorCode.CannotHandleObjectFields,
                                                 String.Format(SR.CannotHandleObjectFields, type.FullName));
                }

                // Generate obj = new MyType[reader.ReadInt32()]
                int rank = type.GetArrayRank();
                Type baseType = type.GetElementType();
                while (baseType.IsArray)
                {
                    baseType = baseType.GetElementType();
                }
                string[] lenNames = new string[rank];
                for (int i = 0; i < rank; i++)
                {
                    lenNames[i] = MakeUniqueName("len");
                    CodeExpression lenExpr = new CodeSnippetExpression("reader.ReadInt32()");
                    var lenStmt = new CodeVariableDeclarationStatement(typeof(int), lenNames[i], lenExpr);
                    statements.Add(lenStmt);
                }
                string newCallString = "new " + TypeSystem.TypeName(baseType, this.AnonymousTypeToName);
                newCallString += "[";
                for (int i = 0; i < rank; i++)
                {
                    if (i != 0)
                    {
                        newCallString += ",";
                    }
                    newCallString += lenNames[i];
                }
                newCallString += "]";

                Type elemType = type.GetElementType();
                while (elemType.IsArray)
                {
                    int elemRank = elemType.GetArrayRank();
                    newCallString += "[";
                    for (int i = 1; i < elemRank; i++)
                    {
                        newCallString += ',';
                    }
                    newCallString += "]";
                    elemType = elemType.GetElementType();
                }
                CodeExpression newCall = new CodeSnippetExpression(newCallString);
                statements.Add(new CodeVariableDeclarationStatement(type, "obj", newCall));

                // Generate reading code
                if (type.GetElementType().IsPrimitive)
                {
                    // Use a single ReadRawBytes for primitive array
                    string lenStr = "sizeof(" + type.GetElementType() + ")";
                    for (int i = 0; i < rank; i++)
                    {
                        lenStr += "*obj.GetLength(" + i + ")";
                    }
                    string readBytes = "            unsafe { fixed (void *p = obj) reader.ReadRawBytes((byte*)p, " + lenStr + "); }";
                    statements.Add(new CodeSnippetStatement(readBytes));
                }
                else
                {
                    if (StaticConfig.AllowNullArrayElements && !type.GetElementType().IsValueType)
                    {
                        CodeExpression bvReadExpr = new CodeSnippetExpression("BitVector.Read(reader)");
                        CodeStatement stmt = new CodeVariableDeclarationStatement(typeof(BitVector), "bv", bvReadExpr);
                        statements.Add(stmt);
                    }

                    CodeVariableReferenceExpression[] indexExprs = new CodeVariableReferenceExpression[lenNames.Length];
                    for (int i = 0; i < lenNames.Length; i++)
                    {
                        indexExprs[i] = new CodeVariableReferenceExpression("i" + i);
                    }
                    CodeStatement[] readStmts = this.MakeReadFieldStatements(type.GetElementType(), objExpr, null, indexExprs);
                    for (int i = lenNames.Length - 1; i >= 0; i--)
                    {
                        CodeVariableDeclarationStatement
                            initStmt = new CodeVariableDeclarationStatement(
                                               typeof(int), indexExprs[i].VariableName, ZeroExpr);
                        CodeExpression
                            testExpr = new CodeBinaryOperatorExpression(indexExprs[i],
                                                                        CodeBinaryOperatorType.LessThan,
                                                                        new CodeVariableReferenceExpression(lenNames[i]));
                        CodeStatement
                            incStmt = new CodeAssignStatement(
                                              indexExprs[i],
                                              new CodeBinaryOperatorExpression(indexExprs[i],
                                                                               CodeBinaryOperatorType.Add,
                                                                               OneExpr));
                        readStmts = new CodeStatement[] { new CodeIterationStatement(initStmt, testExpr, incStmt, readStmts) };
                    }
                    statements.AddRange(readStmts);
                }
            }
            else
            {
                CodeExpression newObjectCall;
                if (type.IsValueType)
                {
                    // default(type)
                    newObjectCall = new CodeObjectCreateExpression(type);
                }
                else
                {
                    // FormatterServices.GetUninitializedObject(type)
                    newObjectCall = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("FormatterServices"),
                                                                   "GetUninitializedObject",
                                                                   new CodeTypeOfExpression(type));
                    newObjectCall = new CodeCastExpression(type, newObjectCall);
                }
                statements.Add(new CodeVariableDeclarationStatement(type, "obj", newObjectCall));

                // For each field of type, generate its deserialization code.
                FieldInfo[] fields = TypeSystem.GetAllFields(type);
                System.Array.Sort(fields, (x, y) => x.MetadataToken.CompareTo(y.MetadataToken));

                bool canBeNull = fields.Any(x => !x.FieldType.IsValueType && AttributeSystem.FieldCanBeNull(x));
                if (canBeNull)
                {
                    CodeExpression bvReadExpr = new CodeSnippetExpression("BitVector.Read(reader)");
                    CodeStatement stmt = new CodeVariableDeclarationStatement(typeof(BitVector), "bv", bvReadExpr);
                    statements.Add(stmt);
                }
                for (int i = 0; i < fields.Length; i++)
                {
                    FieldInfo finfo = fields[i];
                    if (TypeSystem.IsFieldSerialized(finfo))
                    {
                        if (finfo.FieldType == typeof(object))
                        {
                            throw new DryadLinqException(DryadLinqErrorCode.CannotHandleObjectFields,
                                                         String.Format(SR.CannotHandleObjectFields, type.FullName));
                        }

                        CodeVariableReferenceExpression[]
                            indexExprs = new CodeVariableReferenceExpression[] { new CodeVariableReferenceExpression(i.ToString()) };
                        CodeStatement[] stmts = this.MakeReadFieldStatements(finfo.FieldType, objExpr, finfo, indexExprs);
                        statements.AddRange(stmts);
                    }
                }
            }
            statements.Add(new CodeMethodReturnStatement(objExpr));
            return statements.ToArray();
        }
Esempio n. 22
0
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeSnippetExpression cse = new CodeSnippetExpression ("mono");
			Assert.AreEqual ("mono", cse.Value, "Value");
			cse.Value = String.Empty;
		}
        private static void AddEntityOptionSetEnumDeclaration(CodeTypeDeclarationCollection types)
        {
            var enumClass = new CodeTypeDeclaration("EntityOptionSetEnum")
            {
                IsClass = true,
                TypeAttributes = TypeAttributes.Sealed | TypeAttributes.NotPublic,
            };

            // public static int? GetEnum(Microsoft.Xrm.Sdk.Entity entity, string attributeLogicalName)
            var get = new CodeMemberMethod
            {
                Name = "GetEnum",
                ReturnType = new CodeTypeReference(typeof(int?)),
                // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
                Attributes = System.CodeDom.MemberAttributes.Static | System.CodeDom.MemberAttributes.Public,
            };
            get.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Microsoft.Xrm.Sdk.Entity), "entity"));
            get.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "attributeLogicalName"));

            // entity.Attributes.ContainsKey(attributeLogicalName)
            var entityAttributesContainsKey =
                new CodeMethodReferenceExpression(
                    new CodePropertyReferenceExpression(
                        new CodeArgumentReferenceExpression("entity"),
                        "Attributes"),
                    "ContainsKey");
            var invokeContainsKey = new CodeMethodInvokeExpression(entityAttributesContainsKey, new CodeArgumentReferenceExpression("attributeLogicalName"));

            // Microsoft.Xrm.Sdk.OptionSetValue value = entity.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>(attributeLogicalName).Value;
            var declareAndSetValue =
                new CodeVariableDeclarationStatement
                {
                    Type = new CodeTypeReference(typeof(OptionSetValue)),
                    Name = "value",
                    InitExpression = new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(
                            new CodeArgumentReferenceExpression("entity"), "GetAttributeValue", new CodeTypeReference(typeof(OptionSetValue))),
                            new CodeArgumentReferenceExpression("attributeLogicalName"))
                };

            // value != null
            var valueNeNull = new CodeSnippetExpression("value != null");

            // value.Value
            var invokeValueGetValue = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("value"), "Value");

            // if(invokeContainsKey){return invokeGetAttributeValue;}else{return null}
            get.Statements.Add(new CodeConditionStatement(invokeContainsKey, declareAndSetValue, 
                new CodeConditionStatement(valueNeNull, new CodeMethodReturnStatement(invokeValueGetValue))));

            // return null;
            get.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));

            enumClass.Members.Add(get);

            types.Add(enumClass);
        }
		public override CodeExpression CreateMultidimensionalArray(string type, CodeExpression[] args)
		{
			var idxexp = new CodeSnippetExpression(string.Join(", ", args.Select(e => ExpressionToString(e)).ToArray()));

			return new CodeArrayCreateExpression(type, idxexp);
		}
Esempio n. 25
0
 protected override void GenerateSnippetExpression(System.CodeDom.CodeSnippetExpression e)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Esempio n. 26
0
        CodeMethodInvokeExpression GetRegisterMethod(string method, string member, CodeTypeReference type)
        {
            var helper = new CodeTypeReferenceExpression("RecordHelper");

            var name = new CodeSnippetExpression("\"" + member + "\"");
            var getter = new CodeSnippetExpression(
                string.Format("obj => obj.{0}", member)
                );
            var setter = new CodeSnippetExpression(
                string.Format("(obj, val) => obj.{0} = val", member)
                );

            var bl = new CodeMethodReferenceExpression(helper, method,
                new CodeTypeReference(this.Name.Substring(0, this.Name.Length - 1)),
                type);
            var g = new CodeMethodInvokeExpression(bl, name, getter, setter);

            return g;
        }
Esempio n. 27
0
        // Add a new vertex method to the DryadLinq vertex class
        internal CodeMemberMethod AddVertexMethod(DLinqQueryNode node)
        {
            CodeMemberMethod vertexMethod = new CodeMemberMethod();
            vertexMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            vertexMethod.ReturnType = new CodeTypeReference(typeof(int));
            vertexMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "args"));
            vertexMethod.Name = MakeUniqueName(node.NodeType.ToString());

            CodeTryCatchFinallyStatement tryBlock = new CodeTryCatchFinallyStatement();

            string startedMsg = "DryadLinqLog.AddInfo(\"Vertex " + vertexMethod.Name + 
                " started at {0}\", DateTime.Now.ToString(\"MM/dd/yyyy HH:mm:ss.fff\"))";
            vertexMethod.Statements.Add(new CodeSnippetExpression(startedMsg));

            // We need to add a call to CopyResources()
            vertexMethod.Statements.Add(new CodeSnippetExpression("CopyResources()"));
            
            if (StaticConfig.LaunchDebugger)
            {
                // If static config requests it, we do an unconditional Debugger.Launch() at vertex entry.
                // Currently this isn't used because StaticConfig.LaunchDebugger is hardcoded to false
                System.Console.WriteLine("Launch debugger: may block application");

                CodeExpression launchExpr = new CodeSnippetExpression("System.Diagnostics.Debugger.Launch()");
                vertexMethod.Statements.Add(new CodeExpressionStatement(launchExpr));
            }
            else
            {
                // Otherwise (the default behavior), we check an environment variable to decide whether
                // to launch the debugger, wait for a manual attach or simply skip straigt into vertex code.
                CodeMethodInvokeExpression debuggerCheckExpr = new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(HelperClassName), 
                                                          DebugHelperMethodName));

                vertexMethod.Statements.Add(new CodeExpressionStatement(debuggerCheckExpr));
            }
            
            vertexMethod.Statements.Add(MakeVertexParamsDecl(node));
            vertexMethod.Statements.Add(SetVertexParamField("VertexStageName", vertexMethod.Name));
            vertexMethod.Statements.Add(SetVertexParamField("UseLargeBuffer", node.UseLargeWriteBuffer));
            Int32[] portCountArray = node.InputPortCounts();
            bool[] keepPortOrderArray = node.KeepInputPortOrders();
            for (int i = 0; i < node.InputArity; i++)
            {
                CodeExpression setParamsExpr = new CodeMethodInvokeExpression(
                                                       new CodeVariableReferenceExpression(VertexParamName),
                                                       "SetInputParams",
                                                       new CodePrimitiveExpression(i),
                                                       new CodePrimitiveExpression(portCountArray[i]),
                                                       new CodePrimitiveExpression(keepPortOrderArray[i]));
                vertexMethod.Statements.Add(new CodeExpressionStatement(setParamsExpr));
            }
            // YY: We could probably do better here.
            for (int i = 0; i < node.GetReferencedQueries().Count; i++)
            {
                CodeExpression setParamsExpr = new CodeMethodInvokeExpression(
                                                       new CodeVariableReferenceExpression(VertexParamName),
                                                       "SetInputParams",
                                                       new CodePrimitiveExpression(i + node.InputArity),
                                                       new CodePrimitiveExpression(1),
                                                       new CodePrimitiveExpression(false));
                vertexMethod.Statements.Add(new CodeExpressionStatement(setParamsExpr));
            }
            
            // Push the parallel-code settings into DryadLinqVertex
            bool multiThreading = this.m_context.EnableMultiThreadingInVertex;
            vertexMethod.Statements.Add(SetVertexParamField("MultiThreading", multiThreading));
            vertexMethod.Statements.Add(
                  new CodeAssignStatement(
                     new CodeFieldReferenceExpression(DLVTypeExpr, "s_multiThreading"),
                     new CodePrimitiveExpression(multiThreading)));
                                                                 
            vertexMethod.Statements.Add(MakeVertexEnvDecl(node));

            Type[] outputTypes = node.OutputTypes;
            string[] writerNames = new string[outputTypes.Length];
            for (int i = 0; i < outputTypes.Length; i++)
            {
                CodeVariableDeclarationStatement
                    writerDecl = MakeVertexWriterDecl(outputTypes[i], this.GetStaticFactoryName(outputTypes[i]));
                vertexMethod.Statements.Add(writerDecl);
                writerNames[i] = writerDecl.Name;
            }

            // Add side readers:
            node.AddSideReaders(vertexMethod);

            // Generate code based on the node type:
            switch (node.NodeType)
            {
                case QueryNodeType.Where:
                case QueryNodeType.OrderBy:
                case QueryNodeType.Distinct:
                case QueryNodeType.Skip:
                case QueryNodeType.SkipWhile:
                case QueryNodeType.Take:
                case QueryNodeType.TakeWhile:
                case QueryNodeType.Merge:
                case QueryNodeType.Select:
                case QueryNodeType.SelectMany:
                case QueryNodeType.Zip:
                case QueryNodeType.GroupBy:
                case QueryNodeType.BasicAggregate:
                case QueryNodeType.Aggregate:                
                case QueryNodeType.Contains:
                case QueryNodeType.Join:
                case QueryNodeType.GroupJoin:
                case QueryNodeType.Union:
                case QueryNodeType.Intersect:
                case QueryNodeType.Except:
                case QueryNodeType.RangePartition:
                case QueryNodeType.HashPartition:
                case QueryNodeType.Apply:
                case QueryNodeType.Fork:
                case QueryNodeType.Dynamic:
                {
                    Type[] inputTypes = node.InputTypes;
                    string[] sourceNames = new string[inputTypes.Length];
                    for (int i = 0; i < inputTypes.Length; i++)
                    {
                        CodeVariableDeclarationStatement 
                            readerDecl = MakeVertexReaderDecl(inputTypes[i], this.GetStaticFactoryName(inputTypes[i]));
                        vertexMethod.Statements.Add(readerDecl);
                        sourceNames[i] = readerDecl.Name;
                    }
                    string sourceToSink = this.m_vertexCodeGen.AddVertexCode(node, vertexMethod, sourceNames, writerNames);
                    if (sourceToSink != null)
                    {
                        CodeExpression sinkExpr = new CodeMethodInvokeExpression(
                                                           new CodeVariableReferenceExpression(writerNames[0]),
                                                           "WriteItemSequence",
                                                           new CodeVariableReferenceExpression(sourceToSink));
                        vertexMethod.Statements.Add(sinkExpr);
                    }
                    break;
                }
                case QueryNodeType.Super:
                {
                    string sourceToSink = this.m_vertexCodeGen.AddVertexCode(node, vertexMethod, null, writerNames);
                    if (sourceToSink != null)
                    {
                        CodeExpression sinkExpr = new CodeMethodInvokeExpression(
                                                           new CodeVariableReferenceExpression(writerNames[0]),
                                                           "WriteItemSequence",
                                                           new CodeVariableReferenceExpression(sourceToSink));
                        vertexMethod.Statements.Add(sinkExpr);
                    }
                    break;
                }
                default:
                {
                    //@@TODO: this should not be reachable. could change to Assert/InvalidOpEx
                    throw new DryadLinqException(DryadLinqErrorCode.Internal,
                                                 String.Format(SR.AddVertexNotHandled, node.NodeType));
                }
            }

            string completedMsg = "DryadLinqLog.AddInfo(\"Vertex " + vertexMethod.Name + 
                " completed at {0}\", DateTime.Now.ToString(\"MM/dd/yyyy HH:mm:ss.fff\"))";
            vertexMethod.Statements.Add(new CodeSnippetExpression(completedMsg));
            
            // add a catch block
            CodeCatchClause catchBlock = new CodeCatchClause("e");
            CodeTypeReferenceExpression errorReportClass = new CodeTypeReferenceExpression("VertexEnv");
            CodeMethodReferenceExpression
                errorReportMethod = new CodeMethodReferenceExpression(errorReportClass, "ReportVertexError");
            CodeVariableReferenceExpression exRef = new CodeVariableReferenceExpression(catchBlock.LocalName);
            catchBlock.Statements.Add(new CodeMethodInvokeExpression(errorReportMethod, exRef));
            tryBlock.CatchClauses.Add(catchBlock);
            
            // wrap the entire vertex method in a try/catch block
            tryBlock.TryStatements.AddRange(vertexMethod.Statements);
            vertexMethod.Statements.Clear();
            vertexMethod.Statements.Add(tryBlock);
            
            // Always add "return 0", to make CLR hosting happy...
            vertexMethod.Statements.Add(new CodeMethodReturnStatement(ZeroExpr));

            this.m_dryadVertexClass.Members.Add(vertexMethod);
            return vertexMethod;
        }
		protected override void GenerateSnippetExpression(CodeSnippetExpression e)
		{
			Output.Write("[CodeSnippetExpression: {0}]", e.ToString());
		}
Esempio n. 29
0
        // Copy user resources to the vertex working directory
        private void AddCopyResourcesMethod()
        {
            CodeMemberMethod copyResourcesMethod = new CodeMemberMethod();
            copyResourcesMethod.Name = CopyResourcesMethodName;
            copyResourcesMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;

            IEnumerable<string> resourcesToExclude = this.m_context.ResourcesToRemove;
            foreach (string res in this.m_context.ResourcesToAdd)
            {
                if (!resourcesToExclude.Contains(res))
                {
                    string fname = Path.GetFileName(res);
                    string stmt = @"System.IO.File.Copy(@""" + Path.Combine("..", fname) + "\", @\"" + fname + "\")";
                    CodeExpression stmtExpr = new CodeSnippetExpression(stmt);
                    copyResourcesMethod.Statements.Add(new CodeExpressionStatement(stmtExpr));
                }
            }
            this.m_dryadVertexClass.Members.Add(copyResourcesMethod);
        }
Esempio n. 30
0
        /// <summary>
        /// Creates a class declaration
        /// </summary>
        /// <param name="schema">record schema</param>
        /// <param name="ns">namespace</param>
        /// <returns></returns>
        protected virtual CodeTypeDeclaration processRecord(Schema schema)
        {
            RecordSchema recordSchema = schema as RecordSchema;
            if (null == recordSchema) throw new CodeGenException("Unable to cast schema into a record");

            // declare the class
            var ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(recordSchema.Name));
            ctd.BaseTypes.Add("ISpecificRecord");
            ctd.Attributes = MemberAttributes.Public;
            ctd.IsClass = true;
            ctd.IsPartial = true;

            createSchemaField(schema, ctd, false);

            // declare Get() to be used by the Writer classes
            var cmmGet = new CodeMemberMethod();
            cmmGet.Name = "Get";
            cmmGet.Attributes = MemberAttributes.Public;
            cmmGet.ReturnType = new CodeTypeReference("System.Object");
            cmmGet.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
            StringBuilder getFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");

            // declare Put() to be used by the Reader classes
            var cmmPut = new CodeMemberMethod();
            cmmPut.Name = "Put";
            cmmPut.Attributes = MemberAttributes.Public;
            cmmPut.ReturnType = new CodeTypeReference(typeof(void));
            cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
            cmmPut.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "fieldValue"));
            var putFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");

            foreach (Field field in recordSchema.Fields)
            {
                // Determine type of field
                bool nullibleEnum = false;
                string baseType = getType(field.Schema, false, ref nullibleEnum);
                var ctrfield = new CodeTypeReference(baseType);

                // Create field
                string privFieldName = string.Concat("_", field.Name);
                var codeField = new CodeMemberField(ctrfield, privFieldName);
                codeField.Attributes = MemberAttributes.Private;

                // Process field documentation if it exist and add to the field
                CodeCommentStatement propertyComment = null;
                if (!string.IsNullOrEmpty(field.Documentation))
                {
                    propertyComment = createDocComment(field.Documentation);
                    if (null != propertyComment)
                        codeField.Comments.Add(propertyComment);
                }

                // Add field to class
                ctd.Members.Add(codeField);

                // Create reference to the field - this.fieldname
                var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), privFieldName);
                var mangledName = CodeGenUtil.Instance.Mangle(field.Name);

                // Create field property with get and set methods
                var property = new CodeMemberProperty();
                property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                property.Name = mangledName;
                property.Type = ctrfield;
                property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef));
                property.SetStatements.Add(new CodeAssignStatement(fieldRef, new CodePropertySetValueReferenceExpression()));
                if (null != propertyComment)
                    property.Comments.Add(propertyComment);

                // Add field property to class
                ctd.Members.Add(property);

                // add to Get()
                getFieldStmt.Append("\t\t\tcase ");
                getFieldStmt.Append(field.Pos);
                getFieldStmt.Append(": return this.");
                getFieldStmt.Append(mangledName);
                getFieldStmt.Append(";\n");

                // add to Put()
                putFieldStmt.Append("\t\t\tcase ");
                putFieldStmt.Append(field.Pos);
                putFieldStmt.Append(": this.");
                putFieldStmt.Append(mangledName);

                if (nullibleEnum)
                {
                    putFieldStmt.Append(" = fieldValue == null ? (");
                    putFieldStmt.Append(baseType);
                    putFieldStmt.Append(")null : (");

                    string type = baseType.Remove(0, 16);  // remove System.Nullable<
                    type = type.Remove(type.Length - 1);   // remove >

                    putFieldStmt.Append(type);
                    putFieldStmt.Append(")fieldValue; break;\n");
                }
                else
                {
                    putFieldStmt.Append(" = (");
                    putFieldStmt.Append(baseType);
                    putFieldStmt.Append(")fieldValue; break;\n");
                }
            }

            // end switch block for Get()
            getFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Get()\");\n\t\t\t}");
            var cseGet = new CodeSnippetExpression(getFieldStmt.ToString());
            cmmGet.Statements.Add(cseGet);
            ctd.Members.Add(cmmGet);

            // end switch block for Put()
            putFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Put()\");\n\t\t\t}");
            var csePut = new CodeSnippetExpression(putFieldStmt.ToString());
            cmmPut.Statements.Add(csePut);
            ctd.Members.Add(cmmPut);

            string nspace = recordSchema.Namespace;
            if (string.IsNullOrEmpty(nspace))
                throw new CodeGenException("Namespace required for record schema " + recordSchema.Name);
            CodeNamespace codens = addNamespace(nspace);

            codens.Types.Add(ctd);

            return ctd;
        }
Esempio n. 31
0
        // Add an anonymous class
        internal bool AddAnonymousClass(Type type)
        {
            if (!TypeSystem.IsAnonymousType(type)) return false;
            if (this.m_anonymousTypeToName.ContainsKey(type)) return true;

            string className = AnonymousClassName(type);
            this.m_anonymousTypeToName.Add(type, className);

            CodeTypeDeclaration anonymousClass = new CodeTypeDeclaration(className);
            anonymousClass.IsClass = true;
            anonymousClass.TypeAttributes = TypeAttributes.Public;

            // Add the fields, the constructor, and properties:
            CodeConstructor con = new CodeConstructor();
            con.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            PropertyInfo[] props = type.GetProperties();
            System.Array.Sort(props, (x, y) => x.MetadataToken.CompareTo(y.MetadataToken));
            string[] fieldNames = new string[props.Length];
            for (int i = 0; i < props.Length; i++)
            {
                fieldNames[i] = "_" + props[i].Name;
                CodeParameterDeclarationExpression paramExpr;
                CodeMemberField memberField;
                if (this.AddAnonymousClass(props[i].PropertyType))
                {
                    string typeName = this.AnonymousTypeToName[props[i].PropertyType];
                    memberField = new CodeMemberField(typeName, fieldNames[i]);
                    paramExpr = new CodeParameterDeclarationExpression(typeName, props[i].Name);
                }
                else
                {
                    memberField = new CodeMemberField(props[i].PropertyType, fieldNames[i]);
                    paramExpr = new CodeParameterDeclarationExpression(props[i].PropertyType, props[i].Name);
                }
                memberField.Attributes = MemberAttributes.Public;
                anonymousClass.Members.Add(memberField);
                con.Parameters.Add(paramExpr);
                CodeExpression fieldExpr = new CodeFieldReferenceExpression(
                                                   new CodeThisReferenceExpression(), fieldNames[i]);
                con.Statements.Add(new CodeAssignStatement(
                                           fieldExpr, new CodeVariableReferenceExpression(paramExpr.Name)));

                CodeMemberProperty p = new CodeMemberProperty();
                p.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                p.Name = props[i].Name;
                p.Type = paramExpr.Type;
                p.GetStatements.Add(new CodeMethodReturnStatement(fieldExpr));
                anonymousClass.Members.Add(p);
            }
            anonymousClass.Members.Add(con);

            // Add Equals method:
            CodeMemberMethod equalsMethod = new CodeMemberMethod();
            equalsMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            equalsMethod.Name = "Equals";
            equalsMethod.Parameters.Add(new CodeParameterDeclarationExpression("Object", "obj"));
            equalsMethod.ReturnType = new CodeTypeReference(typeof(bool));

            CodeExpression initExpr = new CodeSnippetExpression("obj as " + className);
            equalsMethod.Statements.Add(
                  new CodeVariableDeclarationStatement(className, "myObj", initExpr));
            CodeStatement ifStmt = new CodeConditionStatement(
                                           new CodeSnippetExpression("myObj == null"),
                                           new CodeMethodReturnStatement(new CodePrimitiveExpression(false)));
            equalsMethod.Statements.Add(ifStmt);
            string equalsCode = "";
            for (int i = 0; i < props.Length; i++)
            {
                string fieldTypeName;
                // we must use the proxy-type for anonymous-types.
                if (m_anonymousTypeToName.ContainsKey(props[i].PropertyType))
                {
                    fieldTypeName = m_anonymousTypeToName[props[i].PropertyType];
                }
                else
                {
                    fieldTypeName = TypeSystem.TypeName(props[i].PropertyType);
                }

                if (i > 0) equalsCode += " && ";
                equalsCode += String.Format("EqualityComparer<{0}>.Default.Equals(this.{1}, myObj.{1})",
                                            fieldTypeName, props[i].Name);
            }
            CodeExpression returnExpr = new CodeSnippetExpression(equalsCode);
            equalsMethod.Statements.Add(new CodeMethodReturnStatement(returnExpr));
            anonymousClass.Members.Add(equalsMethod);

            // Add GetHashCode method:
            CodeMemberMethod getHashCodeMethod = new CodeMemberMethod();
            getHashCodeMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            getHashCodeMethod.Name = "GetHashCode";
            getHashCodeMethod.ReturnType = new CodeTypeReference(typeof(int));

            CodeVariableDeclarationStatement
                hashDecl = new CodeVariableDeclarationStatement(typeof(int), "num", ZeroExpr);
            getHashCodeMethod.Statements.Add(hashDecl);

            CodeExpression numExpr = new CodeArgumentReferenceExpression(hashDecl.Name);
            for (int i = 0; i < props.Length; i++)
            {
                if (props[i].PropertyType.IsValueType)
                {
                    CodeExpression hashExpr = new CodeSnippetExpression(
                                                      "(-1521134295 * num) + this." + props[i].Name + ".GetHashCode()");
                    getHashCodeMethod.Statements.Add(new CodeAssignStatement(numExpr, hashExpr));
                }
                else
                {
                    CodeExpression hashExpr = new CodeSnippetExpression(
                                                      String.Format("(-1521134295 * num) + (this.{0} != null ? this.{0}.GetHashCode() : 0)",
                                                                    props[i].Name));
                    getHashCodeMethod.Statements.Add(new CodeAssignStatement(numExpr, hashExpr));
                }
            }
            getHashCodeMethod.Statements.Add(new CodeMethodReturnStatement(numExpr));
            anonymousClass.Members.Add(getHashCodeMethod);

            // Add ToString method:
            CodeMemberMethod toStringMethod = new CodeMemberMethod();
            toStringMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            toStringMethod.Name = "ToString";
            toStringMethod.ReturnType = new CodeTypeReference(typeof(string));
            StringBuilder toStringCode = new StringBuilder();
            toStringCode.Append("\"{ \"");
            for (int i = 0; i < props.Length; i++)
            {
                if (i > 0) toStringCode.Append(" + \", \"");
                toStringCode.Append(" + \"");
                toStringCode.Append(props[i].Name);
                toStringCode.Append(" = \" + this.");
                toStringCode.Append(props[i].Name);
                toStringCode.Append(".ToString()");
            }
            toStringCode.Append(" + \" }\"");
            returnExpr = new CodeSnippetExpression(toStringCode.ToString());
            toStringMethod.Statements.Add(new CodeMethodReturnStatement(returnExpr));
            anonymousClass.Members.Add(toStringMethod);

            this.m_dryadCodeSpace.Types.Add(anonymousClass);
            return true;
        }