public TypescriptPropertySetValueReferenceExpression(
     CodePropertySetValueReferenceExpression codeExpression, 
     CodeGeneratorOptions options)
 {
     _codeExpression = codeExpression;
     _options = options;
     System.Diagnostics.Debug.WriteLine("TypescriptPropertySetValueReferenceExpression Created");
 }
		protected override void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
		{
			Output.Write("[CodePropertySetValueReferenceExpression: {0}]", e.ToString());
		}
        public void GenerateProperties(CodeTypeDeclaration ctd, ClassInfo ci)
        {
            CodeMemberProperty prop;

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

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

            int primaryKeyComponentNumber = 0;

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

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

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

                CodeTypeReference returnType;

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

                    ctd.Members.Add(prop);

#if DOTNET35
                    CodeExpression whereExpression = new CodeMethodInvokeExpression(
                        new CodeTypeReferenceExpression(typeof(Sooda.QL.Soql)),
                        "CollectionFor",
                        new CodeMethodInvokeExpression(
                                new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(classInfo.Name + "_Factory"), "TheClassInfo"),
                                "FindCollectionManyToMany",
                                new CodePrimitiveExpression(coli.Name)),
                        This);
                    prop = GetCollectionLinqQuery(coli, whereExpression);
                    ctd.Members.Add(prop);
#endif
                }
            }
        }
 protected override void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
 {
     base.Output.Write("value");
 }
        /// <summary>
        /// Generate a navigation property
        /// </summary>
        /// <param name="target">the other end</param>
        /// <param name="referenceProperty">True to emit Reference navigation property</param>
        /// <returns>the generated property</returns>
        private CodeMemberProperty EmitNavigationProperty(RelationshipEndMember target)
        {
            CodeTypeReference typeRef = GetReturnType(target);

            // raise the PropertyGenerated event
            PropertyGeneratedEventArgs eventArgs = new PropertyGeneratedEventArgs(Item,
                                                                                  null, // no backing field
                                                                                  typeRef);
            this.Generator.RaisePropertyGeneratedEvent(eventArgs);

            // [System.ComponentModel.Browsable(false)]
            // public TargetType TargetName
            // public EntityReference<TargetType> TargetName
            // or
            // public EntityCollection<targetType> TargetNames
            CodeMemberProperty property = new CodeMemberProperty();

            // Only reference navigation properties are currently currently supported with XML serialization
            // and thus we should use the XmlIgnore and SoapIgnore attributes on other property types.
            AttributeEmitter.AddIgnoreAttributes(property);

            AttributeEmitter.AddBrowsableAttribute(property);

            AttributeEmitter.AddGeneratedCodeAttribute(property);

            CommentEmitter.EmitSummaryComments(Item, property.Comments);

            property.Name = Item.Name;

            if (eventArgs.ReturnType != null && !eventArgs.ReturnType.Equals(typeRef))
            {
                property.Type = eventArgs.ReturnType;
            }
            else
            {
                property.Type = typeRef;
            }

            property.Attributes = MemberAttributes.Final;

            CodeExpression getMethod = EmitGetMethod(target);
            CodeExpression getReturnExpression;

            if (target.RelationshipMultiplicity != RelationshipMultiplicity.Many)
            {
                property.Attributes |= AccessibilityFromGettersAndSetters(Item);

                // insert user-supplied Set code here, before the assignment
                //
                List<CodeStatement> additionalSetStatements = eventArgs.AdditionalSetStatements;
                if (additionalSetStatements != null && additionalSetStatements.Count > 0)
                {
                    try
                    {
                        property.SetStatements.AddRange(additionalSetStatements.ToArray());
                    }
                    catch (ArgumentNullException e)
                    {
                        Generator.AddError(Strings.InvalidSetStatementSuppliedForProperty(Item.Name),
                                           ModelBuilderErrorCode.InvalidSetStatementSuppliedForProperty,
                                           EdmSchemaErrorSeverity.Error,
                                           e);
                    }
                }

                CodeExpression valueRef = new CodePropertySetValueReferenceExpression();
                if (typeRef != eventArgs.ReturnType)
                {
                    // we need to cast to the actual type
                    valueRef = new CodeCastExpression(typeRef, valueRef);
                }


                CodeExpression valueProperty = getMethod;

                // get                
                //     return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName").Value;
                getReturnExpression = valueProperty;

                // set
                //     ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName").Value = value;
                property.SetStatements.Add(
                    new CodeAssignStatement(valueProperty, valueRef));

                // setup the accessibility of the navigation property setter and getter
                MemberAttributes propertyAccessibility = property.Attributes & MemberAttributes.AccessMask;
                PropertyEmitter.AddGetterSetterFixUp(Generator.FixUps, GetFullyQualifiedPropertyName(property.Name),
                    PropertyEmitter.GetGetterAccessibility(Item), propertyAccessibility, true);
                PropertyEmitter.AddGetterSetterFixUp(Generator.FixUps, GetFullyQualifiedPropertyName(property.Name),
                    PropertyEmitter.GetSetterAccessibility(Item), propertyAccessibility, false);

                List<CodeStatement> additionalAfterSetStatements = eventArgs.AdditionalAfterSetStatements;
                if (additionalAfterSetStatements != null && additionalAfterSetStatements.Count > 0)
                {
                    try
                    {
                        property.SetStatements.AddRange(additionalAfterSetStatements.ToArray());
                    }
                    catch (ArgumentNullException e)
                    {
                        Generator.AddError(Strings.InvalidSetStatementSuppliedForProperty(Item.Name),
                                           ModelBuilderErrorCode.InvalidSetStatementSuppliedForProperty,
                                           EdmSchemaErrorSeverity.Error,
                                           e);
                    }
                }
            }
            else
            {
                property.Attributes |= PropertyEmitter.GetGetterAccessibility(Item);
                // get
                //     return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName");
                getReturnExpression = getMethod;

                // set
                // if (value != null) ==> Only for non-binding scenario
                // {
                //    this = 
                //    this.OnPropertyChanged("")
                // }  
                
                CodeExpression valueRef = new CodePropertySetValueReferenceExpression();

                CodeStatementCollection csc = null;

                if (this.Generator.UseDataServiceCollection == true)
                {
                    csc = property.SetStatements;
                }
                else
                {
                    CodeConditionStatement ccs = new CodeConditionStatement(EmitExpressionDoesNotEqualNull(valueRef));
                    property.SetStatements.Add(ccs);

                    csc = ccs.TrueStatements;
                }

                csc.Add(new CodeAssignStatement(getMethod, valueRef));

                if (eventArgs.AdditionalAfterSetStatements != null)
                {
                    try
                    {
                        foreach (CodeStatement s in eventArgs.AdditionalAfterSetStatements)
                        {
                            csc.Add(s);
                        }
                    }
                    catch (ArgumentNullException e)
                    {
                        Generator.AddError(Strings.InvalidSetStatementSuppliedForProperty(Item.Name),
                                           ModelBuilderErrorCode.InvalidSetStatementSuppliedForProperty,
                                           EdmSchemaErrorSeverity.Error,
                                           e);
                    }
                }
            }

            // if additional Get statements were specified by the event subscriber, insert them now
            //
            List<CodeStatement> additionalGetStatements = eventArgs.AdditionalGetStatements;
            if (additionalGetStatements != null && additionalGetStatements.Count > 0)
            {
                try
                {
                    property.GetStatements.AddRange(additionalGetStatements.ToArray());
                }
                catch (ArgumentNullException ex)
                {
                    Generator.AddError(Strings.InvalidGetStatementSuppliedForProperty(Item.Name),
                                       ModelBuilderErrorCode.InvalidGetStatementSuppliedForProperty,
                                       EdmSchemaErrorSeverity.Error,
                                       ex);
                }
            }

            property.GetStatements.Add(new CodeMethodReturnStatement(getReturnExpression));

            return property;
        }
Beispiel #6
0
			public void Visit (CodePropertySetValueReferenceExpression o)
			{
				g.GeneratePropertySetValueReferenceExpression (o);
			}
 private  void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e) {
     Output.Write("value");
 }
		static void AddOutletProperty (CodeTypeReference outletAtt, CodeTypeDeclaration type, string name,
			CodeTypeReference typeRef)
		{
			var fieldName = "__impl_" + name;
			var field = new CodeMemberField (typeRef, fieldName);
			
			var prop = new CodeMemberProperty () {
				Name = name,
				Type = typeRef
			};
			AddAttribute (prop.CustomAttributes, outletAtt, name);
			
			var setValue = new CodePropertySetValueReferenceExpression ();
			var thisRef = new CodeThisReferenceExpression ();
			var fieldRef = new CodeFieldReferenceExpression (thisRef, fieldName);
			
			prop.SetStatements.Add (new CodeAssignStatement (fieldRef, setValue));
			prop.GetStatements.Add (new CodeMethodReturnStatement (fieldRef));
			
			prop.Attributes = field.Attributes = (prop.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
			
			type.Members.Add (prop);
			type.Members.Add (field);
		}
        private static void EmitBasicClassMembers(Type callerType, CodeTypeDeclaration resourceClass, string nameSpace, string baseName,
            string resourcesNamespace, bool internalClass, bool useStatic, bool supportsTryCatch, string logicalName, bool generateCTor)
        {
            //logicalName added by Ðonny
            // Full class name generation
            string fullClassName;
            if (resourcesNamespace != null)
            {
                if (resourcesNamespace.Length > 0)
                    fullClassName = resourcesNamespace + '.' + baseName;
                else
                    fullClassName = baseName;
            }
            else if ((nameSpace != null) && (nameSpace.Length > 0))
                fullClassName = nameSpace + '.' + baseName;
            else
                fullClassName = baseName;

            // Generation of class comments
            string callerTypeName = callerType != null ? callerType.Name : "NULL";
            CodeCommentStatement classCommentStatement = new CodeCommentStatement(string.Format(ClassComments1Format, callerTypeName));
            resourceClass.Comments.Add(classCommentStatement);

            classCommentStatement = new CodeCommentStatement(string.Format(ClassComments2Format, callerTypeName));
            resourceClass.Comments.Add(classCommentStatement);

            classCommentStatement = new CodeCommentStatement(string.Format(ClassCommentsCopyright, DateTime.Today.Year));
            resourceClass.Comments.Add(classCommentStatement);

            // Generation of the SuppressMessage attribute
            CodeAttributeDeclaration suppressAttributeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(SuppressMessageAttribute)));
            suppressAttributeDeclaration.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference;
            suppressAttributeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("Microsoft.Performance")));
            suppressAttributeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("CA1811:AvoidUncalledPrivateCode")));

            // Generation of the constructor
            if (generateCTor) {
                CodeConstructor codeConstructor = new CodeConstructor();
                codeConstructor.CustomAttributes.Add(suppressAttributeDeclaration);
                codeConstructor.Attributes = MemberAttributes.Private;
                resourceClass.Members.Add(codeConstructor);
            }

            // Generation of the _resourceManager field
            CodeTypeReference resourceManagerTypeReference = new CodeTypeReference(typeof(ResourceManager), CodeTypeReferenceOptions.GlobalReference);
            CodeMemberField resourceManagerMemberField = new CodeMemberField(resourceManagerTypeReference, ResMgrFieldName);
            resourceManagerMemberField.Attributes = MemberAttributes.Private;
            if (useStatic)
                resourceManagerMemberField.Attributes |= MemberAttributes.Static;
            resourceClass.Members.Add(resourceManagerMemberField);

            // Generation of the _internalSyncObject field
            CodeTypeReference objectTypeReference = new CodeTypeReference(typeof(object), CodeTypeReferenceOptions.GlobalReference);
            CodeMemberField internalSyncObjectMemberField = new CodeMemberField(objectTypeReference, InternalSyncObjectFieldName);
            internalSyncObjectMemberField.Attributes = MemberAttributes.Private;
            if (useStatic)
                internalSyncObjectMemberField.Attributes |= MemberAttributes.Static;
            resourceClass.Members.Add(internalSyncObjectMemberField);

            // Generation of the _resourceCulture field
            CodeTypeReference cultureInfoTypeReference = new CodeTypeReference(typeof(CultureInfo), CodeTypeReferenceOptions.GlobalReference);
            CodeMemberField cultureInfoMemberField = new CodeMemberField(cultureInfoTypeReference, CultureInfoFieldName);
            cultureInfoMemberField.Attributes = MemberAttributes.Private;
            if (useStatic)
                cultureInfoMemberField.Attributes |= MemberAttributes.Static;
            resourceClass.Members.Add(cultureInfoMemberField);

            // Generation of the InternalSyncObject property
            CodeMemberProperty internalSyncObjectProperty = new CodeMemberProperty();
            resourceClass.Members.Add(internalSyncObjectProperty);
            internalSyncObjectProperty.Name = InternalSyncObjectPropertyName;
            internalSyncObjectProperty.HasGet = true;
            internalSyncObjectProperty.HasSet = false;
            internalSyncObjectProperty.Type = objectTypeReference;
            /*if (internalClass)
                internalSyncObjectProperty.Attributes = MemberAttributes.Assembly;
            else*///Ð
                internalSyncObjectProperty.Attributes = MemberAttributes.Public;

            if (useStatic)
                internalSyncObjectProperty.Attributes |= MemberAttributes.Static;

            CodeTypeReference interlockedCodeTypeReference = new CodeTypeReference(typeof(Interlocked), CodeTypeReferenceOptions.GlobalReference);

            CodeMethodReferenceExpression referenceEqualsMethodReference = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(object)),
                "ReferenceEquals");
            CodeFieldReferenceExpression internalSyncObjectFieldReference = new CodeFieldReferenceExpression(null, InternalSyncObjectFieldName);
            CodeMethodInvokeExpression referenceEqualInvokeExpression = new CodeMethodInvokeExpression(referenceEqualsMethodReference,
                new CodeExpression[] { internalSyncObjectFieldReference, new CodePrimitiveExpression(null) });
            CodeObjectCreateExpression objectCreateExpression = new CodeObjectCreateExpression(objectTypeReference, new CodeExpression[] {});
            CodeMethodReferenceExpression compareExchangeMethodReference = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(interlockedCodeTypeReference),
                "CompareExchange");
            CodeMethodInvokeExpression compareExchangeMethodInvokeExpression = new CodeMethodInvokeExpression(compareExchangeMethodReference,
                new CodeDirectionExpression(FieldDirection.Ref, internalSyncObjectFieldReference), objectCreateExpression,
                new CodePrimitiveExpression(null));
            internalSyncObjectProperty.GetStatements.Add(new CodeConditionStatement(referenceEqualInvokeExpression,
                new CodeExpressionStatement(compareExchangeMethodInvokeExpression)));
            internalSyncObjectProperty.GetStatements.Add(new CodeMethodReturnStatement(internalSyncObjectFieldReference));

            AddComments(internalSyncObjectProperty, InternalSyncObjectPropertyComment);

            // Generation of the ResourceManager property
            CodeMemberProperty resourceManagerProperty = new CodeMemberProperty();
            resourceClass.Members.Add(resourceManagerProperty);
            resourceManagerProperty.Name = ResMgrPropertyName;
            resourceManagerProperty.HasGet = true;
            resourceManagerProperty.HasSet = false;
            resourceManagerProperty.Type = resourceManagerTypeReference;
            /*if (internalClass)
                resourceManagerProperty.Attributes = MemberAttributes.Assembly;
            else*///Ð
                resourceManagerProperty.Attributes = MemberAttributes.Public;

            if (useStatic)
                resourceManagerProperty.Attributes |= MemberAttributes.Static;

            CodeTypeReference eitorBrowsableTypeReference = new CodeTypeReference(typeof(EditorBrowsableState));
            eitorBrowsableTypeReference.Options = CodeTypeReferenceOptions.GlobalReference;
            CodeAttributeArgument codeAttributeArgument = new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(eitorBrowsableTypeReference), "Advanced"));
            CodeAttributeDeclaration codeAttributeDeclaration = new CodeAttributeDeclaration("System.ComponentModel.EditorBrowsableAttribute", new CodeAttributeArgument[] { codeAttributeArgument });
            codeAttributeDeclaration.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference;
            resourceManagerProperty.CustomAttributes.Add(codeAttributeDeclaration);

            CodeFieldReferenceExpression resourceManagerFieldReference = new CodeFieldReferenceExpression(null, ResMgrFieldName);
            CodeMethodInvokeExpression referenceEqualsMethodInvokeExpression = new CodeMethodInvokeExpression(referenceEqualsMethodReference,
                resourceManagerFieldReference, new CodePrimitiveExpression(null));

            CodeTypeReference monitorCodeTypeReference = new CodeTypeReference(typeof(Monitor), CodeTypeReferenceOptions.GlobalReference);

            CodeMethodReferenceExpression monitorEnterMethodReference = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(monitorCodeTypeReference),
                "Enter");
            CodePropertyReferenceExpression internalSyncObjectPropertyReference = new CodePropertyReferenceExpression(null, InternalSyncObjectPropertyName);
            CodeMethodInvokeExpression monitorEnterMethodInvokeExpression = new CodeMethodInvokeExpression(monitorEnterMethodReference,
                internalSyncObjectPropertyReference);

            CodePropertyReferenceExpression assemblyPropertyReference = new CodePropertyReferenceExpression(new CodeTypeOfExpression(new CodeTypeReference(resourceClass.Name)),
                "Assembly");
            CodeObjectCreateExpression resourceManagerCreateExpression = new CodeObjectCreateExpression(resourceManagerTypeReference,
                new CodePrimitiveExpression(logicalName), assemblyPropertyReference); //logicalName changed by Ðonny

            CodeMethodReferenceExpression interlockedExchangeMethodReference = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(interlockedCodeTypeReference),
                "Exchange");
            CodeMethodInvokeExpression interlockedExchangeMethodInvokeExpression = new CodeMethodInvokeExpression(interlockedExchangeMethodReference,
                new CodeDirectionExpression(FieldDirection.Ref, resourceManagerFieldReference), resourceManagerCreateExpression);

            CodeMethodReferenceExpression monitorExitMethodReference = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(monitorCodeTypeReference),
                "Exit");
            CodeMethodInvokeExpression monitorExitMethodInvokeExpression = new CodeMethodInvokeExpression(monitorExitMethodReference,
                internalSyncObjectPropertyReference);

            CodeTryCatchFinallyStatement tryFinallyStatement = new CodeTryCatchFinallyStatement();
            tryFinallyStatement.TryStatements.Add(new CodeConditionStatement(referenceEqualsMethodInvokeExpression,
                new CodeExpressionStatement(interlockedExchangeMethodInvokeExpression)));
            tryFinallyStatement.FinallyStatements.Add(monitorExitMethodInvokeExpression);

            resourceManagerProperty.GetStatements.Add(new CodeConditionStatement(referenceEqualsMethodInvokeExpression,
                new CodeExpressionStatement(monitorEnterMethodInvokeExpression), tryFinallyStatement));
            resourceManagerProperty.GetStatements.Add(new CodeMethodReturnStatement(resourceManagerFieldReference));

            AddComments(resourceManagerProperty, ResMgrPropertyComment);

            // Generation of the Culture property
            CodeMemberProperty cultureProperty = new CodeMemberProperty();
            resourceClass.Members.Add(cultureProperty);
            cultureProperty.Name = CultureInfoPropertyName;
            cultureProperty.HasGet = true;
            cultureProperty.HasSet = true;
            cultureProperty.Type = cultureInfoTypeReference;
            /*if (internalClass)
                cultureProperty.Attributes = MemberAttributes.Assembly;
            else*///Ð
                cultureProperty.Attributes = MemberAttributes.Public;

            if (useStatic)
                cultureProperty.Attributes |= MemberAttributes.Static;
            cultureProperty.CustomAttributes.Add(codeAttributeDeclaration);

            CodeFieldReferenceExpression resourceCultureFieldReference = new CodeFieldReferenceExpression(null, CultureInfoFieldName);
            cultureProperty.GetStatements.Add(new CodeMethodReturnStatement(resourceCultureFieldReference));

            CodePropertySetValueReferenceExpression codePropertySetValueReferenceExpression = new CodePropertySetValueReferenceExpression();
            cultureProperty.SetStatements.Add(new CodeAssignStatement(resourceCultureFieldReference, codePropertySetValueReferenceExpression));

            AddComments(cultureProperty, CulturePropertyComment1, CulturePropertyComment2);
        }
 public void Generate(CodePropertySetValueReferenceExpression expression)
 {
     Write("value");
 }
Beispiel #11
0
 protected override void GeneratePropertySetValueReferenceExpression(System.CodeDom.CodePropertySetValueReferenceExpression e)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Beispiel #12
0
 private void Write(CodePropertySetValueReferenceExpression e){
   this.writer.Write("value");
 }
Beispiel #13
0
        private void CreateDocTypes(IEnumerable<DocType> docTypes, CodeNamespace ns)
        {
            foreach (var docType in docTypes)
            {
                string genName = docType.TypeName;

                CodeCompileUnit currUnit = new CodeCompileUnit();

                currUnit.Namespaces.Add(ns);

                //create class
                CodeTypeDeclaration currClass = new CodeTypeDeclaration(genName);
                //create the custom attribute
                CodeAttributeDeclarationCollection classAttributes = new CodeAttributeDeclarationCollection(
                    new CodeAttributeDeclaration[] {
                        new CodeAttributeDeclaration("UmbracoInfo",
                            new CodeAttributeArgument(new CodePrimitiveExpression(docType.Alias))
                            ),
                        new CodeAttributeDeclaration("DocType")
                    });

                if (!Args.IsInterface)
                {
                    classAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(DataContractAttribute))));
                }

                //add the address to the class
                currClass.CustomAttributes.AddRange(classAttributes);

                currClass.IsClass = true;
                //add the summary decoration
                currClass.Comments.AddRange(GenerateSummary(docType.Description));
                //set up the type
                currClass.TypeAttributes = TypeAttributes.Public;
                if (docType.ParentId > 0)
                {
                    string typeName = docTypes.Single(d => d.Id == docType.ParentId).TypeName;

                    if (!Args.IsInterface)
                    {
                        currClass.BaseTypes.Add(new CodeTypeReference(typeName)); //docType inheritance
                    }
                    else
                    {
                        currClass.BaseTypes.Add(new CodeTypeReference("I" + typeName)); //docType inheritance of interface type
                    }
                }
                else
                {
                    if (!Args.IsInterface)
                    {
                        currClass.BaseTypes.Add(new CodeTypeReference("DocTypeBase")); //base class
                    }
                    else
                    {
                        currClass.BaseTypes.Add(new CodeTypeReference("IDocTypeBase")); //base interface
                    }
                }
                if (!Args.IsInterface)
                {
                    currClass.IsPartial = true;
                }
                else
                {
                    currClass.IsInterface = true;
                    currClass.Name = "I" + currClass.Name;
                }

                currClass.Members.AddRange(GenerateConstructors());

                #region Doc Type Properties
                foreach (var docTypeProperty in docType.Properties)
                {
                    CodeMemberField valueField = new CodeMemberField();
                    valueField.Attributes = MemberAttributes.Private;
                    valueField.Name = "_" + docTypeProperty.TypeName;
                    valueField.Type = new CodeTypeReference(docTypeProperty.DatabaseType);
                    currClass.Members.Add(valueField);

                    //store the umbraco data in an attribute.
                    CodeMemberProperty p = new CodeMemberProperty();
                    p.CustomAttributes.AddRange(GenerateDocTypePropertyAttributes(docTypeProperty));

                    p.Name = docTypeProperty.TypeName;
                    p.Type = new CodeTypeReference(docTypeProperty.DatabaseType);
                    p.Attributes = MemberAttributes.Public;
                    p.HasGet = true;
                    p.HasSet = false;
                    p.GetStatements.Add(new CodeMethodReturnStatement(
                        new CodeFieldReferenceExpression(
                            new CodeThisReferenceExpression(), valueField.Name))
                        );

                    #region Set statement
                    //have a conditional statment so we can use the INotifyChanging and INotifyChanged events
                    CodeExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), valueField.Name);
                    CodeExpression right = new CodePropertySetValueReferenceExpression();

                    CodeExpression cond = GenerateInequalityConditionalStatement(left, right);

                    //Build the statements to execute when we are changing the property value
                    //The order is:
                    // - RaisePropertyChanging event
                    // - Assign the property
                    // - RaisePropertyChanged event
                    var trues = new CodeStatement[] {
                        new CodeExpressionStatement(new CodeMethodInvokeExpression(
                            new CodeThisReferenceExpression(),
                            "RaisePropertyChanging"
                            )
                        ),
                        new CodeAssignStatement(
                            new CodeFieldReferenceExpression(
                                new CodeThisReferenceExpression(), valueField.Name),
                            new CodePropertySetValueReferenceExpression()
                        ),
                        new CodeExpressionStatement(
                            new CodeMethodInvokeExpression(
                                new CodeThisReferenceExpression(),
                                "RaisePropertyChanged",
                                new CodePrimitiveExpression(docTypeProperty.TypeName)
                            )
                        )
                    };

                    CodeConditionStatement condition = new CodeConditionStatement(cond, trues);
                    //enforce the validation from umbraco. It's there for a reason ;)
                    if (!string.IsNullOrEmpty(docTypeProperty.RegularExpression))
                    {
                        p.SetStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(
                                        null,
                                        "ValidateProperty",
                                        new CodePrimitiveExpression(docTypeProperty.RegularExpression),
                                        new CodePropertySetValueReferenceExpression())
                                        )
                                    );
                    }
                    p.SetStatements.Add(condition);
                    #endregion

                    //comment the property with the description from umbraco
                    p.Comments.AddRange(GenerateSummary(docTypeProperty.Description));
                    currClass.Members.Add(p);

                    CodeMemberProperty retypedProperty = CreateCustomProperty(docTypeProperty, valueField.Name);
                    if (retypedProperty != null)
                    {
                        currClass.Members.Add(retypedProperty);
                    }
                }
                #endregion

                #region Child Associations
                foreach (var child in docType.Associations)
                {
                    var realDocType = docTypes.SingleOrDefault(dt => dt.Id == child.AllowedId);

                    //put a check that a docType is actually returned
                    //This will cater for the bug of when you don't select to generate a
                    //docType but it is a child of the current
                    if (realDocType != null)
                    {
                        string name = realDocType.TypeName;
                        if (this.PluralizeCollections)
                        {
                            name = PluraliseName(realDocType.TypeName);
                        }
                        var t = new CodeTypeReference("AssociationTree");
                        t.TypeArguments.Add(realDocType.TypeName);

                        CodeMemberProperty p = new CodeMemberProperty();
                        p.Name = name;
                        p.Type = t;
                        p.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                        p.HasGet = true;
                        p.HasSet = true;

                        if (!Args.IsInterface)
                        {
                            CodeMemberField childMember = new CodeMemberField();
                            childMember.Attributes = MemberAttributes.Private;
                            childMember.Name = "_" + name;
                            childMember.Type = t;
                            currClass.Members.Add(childMember);

                            CodeExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), childMember.Name);
                            CodeExpression right = new CodePrimitiveExpression(null);

                            CodeExpression cond = GenerateEqualityConditionalStatement(left, right);

                            var trues = new CodeConditionStatement(cond, new CodeAssignStatement(
                                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), childMember.Name),
                                new CodeMethodInvokeExpression(
                                    new CodeMethodReferenceExpression(
                                        new CodeThisReferenceExpression(),
                                        "ChildrenOfType",
                                        new CodeTypeReference[] {
                                        new CodeTypeReference(realDocType.TypeName)
                                    })
                                    )
                                )
                            );

                            p.GetStatements.Add(trues);
                            p.GetStatements.Add(new CodeMethodReturnStatement(
                                new CodeFieldReferenceExpression(
                                    new CodeThisReferenceExpression(), childMember.Name))
                                );

                            p.SetStatements.Add(
                                new CodeAssignStatement(
                                new CodeFieldReferenceExpression(
                                    new CodeThisReferenceExpression(), childMember.Name),
                                new CodePropertySetValueReferenceExpression()
                                )
                            );
                        }

                        currClass.Members.Add(p);
                    }
                }
                #endregion

                ns.Types.Add(currClass);
            }
        }
 private CodeMemberProperty CreateProperty(CodeTypeReference type, string propertyName, string fieldName, bool isValueType)
 {
     CodeMemberProperty property = new CodeMemberProperty {
         Type = type,
         Name = propertyName,
         Attributes = MemberAttributes.Final
     };
     if (this.GenerateInternalTypes)
     {
         property.Attributes |= MemberAttributes.Assembly;
     }
     else
     {
         property.Attributes |= MemberAttributes.Public;
     }
     CodeMethodReturnStatement statement = new CodeMethodReturnStatement {
         Expression = new CodeFieldReferenceExpression(this.ThisReference, fieldName)
     };
     property.GetStatements.Add(statement);
     CodeAssignStatement statement2 = new CodeAssignStatement {
         Left = new CodeFieldReferenceExpression(this.ThisReference, fieldName),
         Right = new CodePropertySetValueReferenceExpression()
     };
     if (this.EnableDataBinding && this.SupportsDeclareEvents)
     {
         CodeConditionStatement statement3 = new CodeConditionStatement();
         CodeExpression targetObject = new CodeFieldReferenceExpression(this.ThisReference, fieldName);
         CodeExpression right = new CodePropertySetValueReferenceExpression();
         if (!isValueType)
         {
             targetObject = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(Globals.TypeOfObject), "ReferenceEquals", new CodeExpression[] { targetObject, right });
         }
         else
         {
             targetObject = new CodeMethodInvokeExpression(targetObject, "Equals", new CodeExpression[] { right });
         }
         right = new CodePrimitiveExpression(true);
         statement3.Condition = new CodeBinaryOperatorExpression(targetObject, CodeBinaryOperatorType.IdentityInequality, right);
         statement3.TrueStatements.Add(statement2);
         statement3.TrueStatements.Add(new CodeMethodInvokeExpression(this.ThisReference, this.RaisePropertyChangedEventMethod.Name, new CodeExpression[] { new CodePrimitiveExpression(propertyName) }));
         property.SetStatements.Add(statement3);
         return property;
     }
     property.SetStatements.Add(statement2);
     return property;
 }
        CodeMemberProperty CreateProperty(CodeTypeReference type, string propertyName, string fieldName, bool isValueType, bool raisePropertyChanged)
        {
            CodeMemberProperty property = new CodeMemberProperty();
            property.Type = type;
            property.Name = propertyName;
            property.Attributes = MemberAttributes.Final;
            if (GenerateInternalTypes)
                property.Attributes |= MemberAttributes.Assembly;
            else
                property.Attributes |= MemberAttributes.Public;

            CodeMethodReturnStatement propertyGet = new CodeMethodReturnStatement();
            propertyGet.Expression = new CodeFieldReferenceExpression(ThisReference, fieldName);
            property.GetStatements.Add(propertyGet);

            CodeAssignStatement propertySet = new CodeAssignStatement();
            propertySet.Left = new CodeFieldReferenceExpression(ThisReference, fieldName);
            propertySet.Right = new CodePropertySetValueReferenceExpression();
            if (raisePropertyChanged)
            {
                CodeConditionStatement ifStatement = new CodeConditionStatement();
                CodeExpression left = new CodeFieldReferenceExpression(ThisReference, fieldName);
                CodeExpression right = new CodePropertySetValueReferenceExpression();
                if (!isValueType)
                {
                    left = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(Globals.TypeOfObject),
                        "ReferenceEquals", new CodeExpression[] { left, right });
                }
                else
                {
                    left = new CodeMethodInvokeExpression(left, "Equals", new CodeExpression[] { right });
                }
                right = new CodePrimitiveExpression(true);
                ifStatement.Condition = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.IdentityInequality, right);
                ifStatement.TrueStatements.Add(propertySet);
                ifStatement.TrueStatements.Add(new CodeMethodInvokeExpression(ThisReference, RaisePropertyChangedEventMethod.Name, new CodePrimitiveExpression(propertyName)));
                property.SetStatements.Add(ifStatement);
            }
            else
                property.SetStatements.Add(propertySet);
            return property;
        }
Beispiel #16
0
 private void ValidatePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e) { // Do nothing
 }
		private void CreateConstantSetters(IShaderDom shader, Action<CodeTypeMember, string> add, string name, CodeExpression assignmentField, CodeExpression assignmentArrayField)
		{
			/*
			 * Something like:

			public void SetInvTargetSize(ref Microsoft.Xna.Framework.Vector2 value)
			{
				this.vreg.SetVector2(130, ref value);
			}

			public Microsoft.Xna.Framework.Vector2 InvTargetSize
			{
				set
				{
					this.SetInvTargetSize(ref value);
				}
			}*/

			Register reg;
			Type dataType;
			bool hasSetMethod;
			int stride;

			if (!ExtractRegType(name, out reg, out dataType, out hasSetMethod, out stride))
				return;

			Type arrayOrSingleType = dataType;

			//right...

			//create the method of the given type.


			//public void SetInvTargetSize(ref Microsoft.Xna.Framework.Vector2 value)
			CodeStatementCollection methodStatements = new CodeStatementCollection();

			CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(dataType, "value");
			List<CodeParameterDeclarationExpression> additionalParams = new List<CodeParameterDeclarationExpression>();

			if (reg.ArraySize == -1)
				param.Direction = FieldDirection.Ref;
			else
			{
				arrayOrSingleType = dataType.MakeArrayType();
				param.Type = new CodeTypeReference(arrayOrSingleType);

				//add array params, readIndex, writeIndex, count
				additionalParams.Add(new CodeParameterDeclarationExpression(typeof(uint), "readIndex"));
				additionalParams.Add(new CodeParameterDeclarationExpression(typeof(uint), "writeIndex"));
				additionalParams.Add(new CodeParameterDeclarationExpression(typeof(uint), "count"));
			}

			CodeExpression valueRef = new CodeArgumentReferenceExpression(param.Name);

			//when there isn't a set method, there is just a set property
			if (!hasSetMethod)
				valueRef = new CodePropertySetValueReferenceExpression();

			//create the guts
			//depends on what constants use it...

			//eg:
			//this.vreg.SetVector2(130, ref value);

			Register sreg;

			if (dataType == typeof(bool))
			{
				//special case for booleans, assign the array directly.
				//looks like:
				// 
				// if (preg_bool[index] != value)
				// {
				//  preg_bool[index] = value;
				//  preg_bool_changed = true;
				// }

				foreach (KeyValuePair<AsmListing, CodeExpression> listing in listingRegisters)
				{
					RegisterSet registers = listing.Key.RegisterSet;
					CodeExpression registersRef = listing.Value;

					if (registers.TryGetRegister(name, out sreg))
					{
						if (listing.Key == asm.PixelShader)
						{
							CodeExpression arrayIndex = new CodeArrayIndexerExpression(shader.PixelShaderBooleanRegistersRef, new CodePrimitiveExpression(sreg.Index));

							CodeStatement assign = new CodeAssignStatement(arrayIndex, new CodePropertySetValueReferenceExpression());
							CodeStatement change = new CodeAssignStatement(shader.PixelShaderBooleanRegistersChangedRef, new CodePrimitiveExpression(true));

							CodeStatement condition = new CodeConditionStatement(
								new CodeBinaryOperatorExpression(arrayIndex, CodeBinaryOperatorType.IdentityInequality, new CodePropertySetValueReferenceExpression()),
								new CodeStatement[]{assign, change});

							methodStatements.Add(condition);
						}
						if (listing.Key == asm.VertexShader)
						{
							CodeExpression arrayIndex = new CodeArrayIndexerExpression(shader.VertexShaderBooleanRegistersRef, new CodePrimitiveExpression(sreg.Index));

							CodeStatement assign = new CodeAssignStatement(arrayIndex, new CodePropertySetValueReferenceExpression());
							CodeStatement change = new CodeAssignStatement(shader.VertexShaderBooleanRegistersChangedRef, new CodePrimitiveExpression(true));

							CodeStatement condition = new CodeConditionStatement(
								new CodeBinaryOperatorExpression(arrayIndex, CodeBinaryOperatorType.IdentityInequality, new CodePropertySetValueReferenceExpression()),
								new CodeStatement[] { assign, change });

							methodStatements.Add(condition);
						}
					}
				}
			}
			else
			{
				//some array set methods require temporary values, but should only be created once.
				bool tempValuesCreated = false;

				foreach (KeyValuePair<AsmListing, CodeExpression> listing in listingRegisters)
				{
					RegisterSet registers = listing.Key.RegisterSet;
					CodeExpression registersRef = listing.Value;

					if (registers.TryGetRegister(name, out sreg))
					{
						//Assign the register array data
						AssignRegister(dataType, sreg, reg, listing.Value, valueRef, methodStatements, ref tempValuesCreated);

						//set changed
						CodeExpression changeValue = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), (registersRef as CodeFieldReferenceExpression).FieldName + "_change");

						methodStatements.Add(new CodeAssignStatement(changeValue, new CodePrimitiveExpression(true)));
					}
				}
			}

			string upperName = Common.ToUpper(name);

			//there is always a setable property
			CodeMemberProperty property = new CodeMemberProperty();
			property.Name = upperName;
			property.Type = param.Type;
			property.Attributes = MemberAttributes.Final | MemberAttributes.Public;
			property.HasSet = true;
			property.HasGet = false;

			//there isn't always a set method
			CodeMemberMethod method = null;

			CodeStatement assignAttribute = null;

			if (hasSetMethod || reg.ArraySize != -1)
			{
				//create the method to set the value
				string methodName = "Set" + upperName;

				method = new CodeMemberMethod();
				method.Name = methodName;
				method.Attributes = MemberAttributes.Final | MemberAttributes.Public;

				method.Parameters.Add(param);
				method.Parameters.AddRange(additionalParams.ToArray());
				method.Statements.AddRange(methodStatements);


				//create a property that calls the Set method

				//is not an array
				CodeMethodInvokeExpression invokeSetter =
					new CodeMethodInvokeExpression(
						shader.Instance, method.Name,
						new CodeDirectionExpression(reg.ArraySize == -1 ? FieldDirection.Ref : FieldDirection.In, new CodePropertySetValueReferenceExpression()));

				if (reg.ArraySize != -1)
				{
					//add method ops (readIndex, writeIndex, count)
					invokeSetter.Parameters.Add(new CodePrimitiveExpression(0));
					invokeSetter.Parameters.Add(new CodePrimitiveExpression(0));
					invokeSetter.Parameters.Add(new CodeCastExpression(typeof(uint), new CodePropertyReferenceExpression(valueRef, "Length")));
				}

				property.SetStatements.Add(invokeSetter);



				//call the method as well for attribute assign
				CodeMethodInvokeExpression assignSetter = 
					new CodeMethodInvokeExpression(
						shader.Instance, method.Name,
						new CodeDirectionExpression(param.Direction, shader.AttributeAssignValue));

				if (reg.ArraySize != -1)
				{
					//add method ops (readIndex, writeIndex, count)
					assignSetter.Parameters.Add(new CodePrimitiveExpression(0));
					assignSetter.Parameters.Add(new CodePrimitiveExpression(0));
					assignSetter.Parameters.Add(new CodeCastExpression(typeof(uint), new CodePropertyReferenceExpression(valueRef, "Length")));
				}

				assignAttribute = shader.ETS(assignSetter);
			}
			else
			{
				//create a property to directly set the value

				property.SetStatements.AddRange(methodStatements);

				//attribute assign sets the property
				assignAttribute = new CodeAssignStatement(
					new CodePropertyReferenceExpression(shader.Instance, property.Name),
						shader.AttributeAssignValue);
			}
			

			if (reg.ArraySize > 0)
			{
				if (method != null)
					add(method, string.Format("Set the shader array value '{0} {1}[{2}]'", reg.Type, reg.Name, reg.ArraySize));
				add(property, string.Format("Set and copy the array data for the shader value '{0} {1}[{2}]'", reg.Type, reg.Name, reg.ArraySize));
			}
			else
			{
				if (method != null)
					add(method, string.Format("Set the shader value '{0} {1}'", reg.Type, reg.Name));
				add(property, string.Format("Assign the shader value '{0} {1}'", reg.Type, reg.Name));
			}

			//create the attribute assignment value statement.

			List<CodeStatement> assignList;
			if (!attributeAssignment.TryGetValue(arrayOrSingleType, out assignList))
			{
				assignList = new List<CodeStatement>();
				attributeAssignment.Add(arrayOrSingleType, assignList);
			}

			//create the statement...
			
			CodeExpression assignIdsMatch =
				new CodeBinaryOperatorExpression(shader.AttributeAssignId,  CodeBinaryOperatorType.IdentityEquality, assignmentField);

			CodeConditionStatement performAssign =
				new CodeConditionStatement(assignIdsMatch,
					assignAttribute, //call the assignment code
					new CodeMethodReturnStatement(new CodePrimitiveExpression(true))); //return true, set correctly.

			assignList.Add(performAssign);
		}
        private void ReplaceSetValue(ref CodeObject target, CodeObject parent, int indent)
        {
            CodeVariableReferenceExpression variableRefExpr = target as CodeVariableReferenceExpression;

            if (variableRefExpr != null && StringUtils.CaseInsensitiveEquals(variableRefExpr.VariableName, _name))
            {
                target = new CodePropertySetValueReferenceExpression();
            }
        }
 /// <summary>
 /// Generates the "SetInstanceVariable" statement.
 /// </summary>
 /// <returns>The "SetInstanceVariable" statement.</returns>
 /// <param name="thisRef">This reference.</param>
 /// <param name="typeRef">Type reference.</param>
 /// <param name="nameRef">Name reference.</param>
 /// <param name="valueRef">Value reference</param>
 protected override CodeExpression GenerateSetInstanceVariableStatement(CodeThisReferenceExpression thisRef, CodeTypeReference typeRef, CodePrimitiveExpression nameRef, CodePropertySetValueReferenceExpression valueRef)
 {
     throw new NotImplementedException();
 }
Beispiel #20
0
		static void ProcessType(Type type, CodeTypeDeclaration ctd)
		{
			foreach (FieldInfo field in type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic)) {
				ctd.AddField(ConvertType(field.FieldType), field.Name).Attributes = 0;
			}
			foreach (FieldInfo field in type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic)) {
				EasyProperty p = ctd.AddProperty(ConvertType(field.FieldType), GetPropertyName(field.Name));
				p.Getter.Return(Easy.Var(field.Name));
				CodeExpression ex;
				if (field.FieldType.IsValueType)
					ex = new CodePropertySetValueReferenceExpression();
				else
					ex = GetDefaultValue("value", field);
				p.Setter.Assign(Easy.Var(field.Name), ex);
				if (typeof(INode).IsAssignableFrom(field.FieldType)) {
					if (typeof(INullable).IsAssignableFrom(field.FieldType)) {
						p.SetStatements.Add(new CodeSnippetStatement("\t\t\t\tif (!" +field.Name+".IsNull) "+field.Name+".Parent = this;"));
					} else {
						p.SetStatements.Add(new CodeSnippetStatement("\t\t\t\t"+field.Name+".Parent = this;"));
					}
				}
			}
			foreach (ConstructorInfo ctor in type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
				CodeConstructor c = new CodeConstructor();
				if (type.IsAbstract)
					c.Attributes = MemberAttributes.Family;
				else
					c.Attributes = MemberAttributes.Public;
				ctd.Members.Add(c);
				ConstructorInfo baseCtor = GetBaseCtor(type);
				foreach(ParameterInfo param in ctor.GetParameters()) {
					c.Parameters.Add(new CodeParameterDeclarationExpression(ConvertType(param.ParameterType),
					                                                        param.Name));
					if (baseCtor != null && Array.Exists(baseCtor.GetParameters(), delegate(ParameterInfo p) { return param.Name == p.Name; }))
						continue;
					c.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(GetPropertyName(param.Name)),
					                                         new CodeVariableReferenceExpression(param.Name)));
				}
				if (baseCtor != null) {
					foreach(ParameterInfo param in baseCtor.GetParameters()) {
						c.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(param.Name));
					}
				}
				// initialize fields that were not initialized by parameter
				foreach (FieldInfo field in type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic)) {
					if (field.FieldType.IsValueType && field.FieldType != typeof(Location))
						continue;
					if (Array.Exists(ctor.GetParameters(), delegate(ParameterInfo p) { return field.Name == p.Name; }))
						continue;
					c.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(field.Name),
					                                         GetDefaultValue(null, field)));
				}
			}
		}
Beispiel #21
0
 /// <summary>
 /// Generates code for the specified property set value reference expression.
 /// </summary>
 /// <remarks>Not supported.</remarks>
 protected override void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Beispiel #22
0
		protected abstract void GeneratePropertySetValueReferenceExpression (CodePropertySetValueReferenceExpression e);
 internal CodeMemberProperty CreatePropertyDeclaration(CodeMemberField field, string name, string typeName)
 {
     CodeMemberProperty property;
     property = new CodeMemberProperty {
         Type = new CodeTypeReference(typeName),
         Name = name,
         Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public
     };
     CodeMethodReturnStatement statement = new CodeMethodReturnStatement {
         Expression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name)
     };
     property.GetStatements.Add(statement);
     CodeAssignStatement statement2 = new CodeAssignStatement();
     CodeExpression expression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);
     CodeExpression expression2 = new CodePropertySetValueReferenceExpression();
     statement2.Left = expression;
     statement2.Right = expression2;
     if (this.EnableDataBinding)
     {
         property.SetStatements.Add(statement2);
         property.SetStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), RaisePropertyChangedEventMethod.Name, new CodeExpression[] { new CodePrimitiveExpression(name) }));
         return property;
     }
     property.SetStatements.Add(statement2);
     return property;
 }
Beispiel #24
0
		protected override void GeneratePropertySetValueReferenceExpression (CodePropertySetValueReferenceExpression e)
		{
		}
 private CodeExpression GetPropertySetRValue(ComAliasEnum alias, System.Type propertyType)
 {
     CodeExpression expression = new CodePropertySetValueReferenceExpression();
     if (alias == ComAliasEnum.None)
     {
         return expression;
     }
     string wFToComConverter = ComAliasConverter.GetWFToComConverter(alias);
     string wFToComParamConverter = ComAliasConverter.GetWFToComParamConverter(alias, propertyType);
     CodeExpression[] parameters = new CodeExpression[] { expression };
     CodeMethodInvokeExpression expression2 = new CodeMethodInvokeExpression(null, wFToComConverter, parameters);
     if (wFToComParamConverter.Length == 0)
     {
         return expression2;
     }
     return new CodeCastExpression(wFToComParamConverter, expression2);
 }
        /// <summary>
        /// 构造一个命名空间
        /// </summary>
        /// <returns>code</returns>
        static CodeNamespace CreateMimsyNamespace()
        {
            // 定义命名空间
            CodeNamespace mimsyNamespace = new CodeNamespace("Mimsy");
            // 添加引用
            mimsyNamespace.Imports.AddRange(new[]
            {
               new CodeNamespaceImport("System"),
               new CodeNamespaceImport("System.Text"),
               new CodeNamespaceImport("System.Collections")
            });

            // 定义类
            CodeTypeDeclaration jubjubClass = new CodeTypeDeclaration("Jubjub")
            {
                TypeAttributes = TypeAttributes.Public  // NotPublic = internal, the internal type isn't visible to the dynamic binder
            };

            // 定义成员字段
            CodeMemberField wabeCountFld = new CodeMemberField(typeof(int), "_wabeCount")
            {
                Attributes = MemberAttributes.Private
            };

            jubjubClass.Members.Add(wabeCountFld);  // 附加字段到类
            mimsyNamespace.Types.Add(jubjubClass);  // 附加类到命名空间

            // 定义实例构造函数
            CodeConstructor jubjubCtor = new CodeConstructor
            {
                Attributes = MemberAttributes.Public
            };

            // 定义参数
            var para = new CodeParameterDeclarationExpression(typeof(int), "wabeCount");
            jubjubCtor.Parameters.Add(para);  // 附加参数到构造函数

            // 添加 ArrayList 字段
            var typerefArrayList = new CodeTypeReference("ArrayList");
            CodeMemberField updatesFld = new CodeMemberField(typerefArrayList, "_updates");
            jubjubClass.Members.Add(updatesFld);

            // 引用 _updates 字段
            var refUpdatesFld = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_updates");
            // 实例化 ArrayList
            var newArrayList = new CodeObjectCreateExpression(typerefArrayList);
            // 赋值
            var assignUpdates = new CodeAssignStatement(refUpdatesFld, newArrayList);
            jubjubCtor.Statements.Add(assignUpdates); // 附加赋值语句到构造函数

            // 引用 _wabeCount 字段
            var refWabeCountFld = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_wabeCount");
            // 定义引用属性(用于赋值时进行判断)
            var refWabeCountProp = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "WabeCount");
            // 定义引用参数
            var refWabeCountArg = new CodeArgumentReferenceExpression("wabeCount");
            // 定义赋值语句
            var assignWabeCount = new CodeAssignStatement(refWabeCountProp, refWabeCountArg);

            jubjubCtor.Statements.Add(assignWabeCount);  // 附加赋值语句到构造函数

            jubjubClass.Members.Add(jubjubCtor);    // 附加构造函数到类

            // 定义成员属性
            CodeMemberProperty wabeCountProp = new CodeMemberProperty()
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final, // Final == Nonvirtual
                Type = new CodeTypeReference(typeof(int)),
                Name = "WabeCount"
            };
            // 为属性添加 get 语句
            wabeCountProp.GetStatements.Add(new CodeMethodReturnStatement(refWabeCountFld));

            // 为属性添加 set 语句
            var suppliedPropertyValue = new CodePropertySetValueReferenceExpression();  // value
            var zero = new CodePrimitiveExpression(0);
            var suppliedPropValIsLessThanZero = new CodeBinaryOperatorExpression(suppliedPropertyValue, CodeBinaryOperatorType.LessThan, zero);

            // if/else 语句进行赋值判断, CodeDOM 不支持三元运算表达式 (value < 0) ? 0 : value;
            var testSuppliedPropValAndAssign = new CodeConditionStatement(suppliedPropValIsLessThanZero,
                new CodeStatement[]
                {
                    new CodeAssignStatement(refWabeCountFld,zero)
                },
                new CodeStatement[]
                {
                    new CodeAssignStatement(refWabeCountFld,suppliedPropertyValue)
                });
            wabeCountProp.SetStatements.Add(testSuppliedPropValAndAssign);
            wabeCountProp.SetStatements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(refUpdatesFld, "Add"), refWabeCountFld));

            jubjubClass.Members.Add(wabeCountProp);  // 附加属性到类

            // 定义一个方法
            CodeMemberMethod methGetWabeCountHistory = new CodeMemberMethod
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                Name = "GetWabeCountHistory",
                ReturnType = new CodeTypeReference(typeof(string))
            };

            jubjubClass.Members.Add(methGetWabeCountHistory);  // 附加方法到类

            // 定义本地变量并实例化
            methGetWabeCountHistory.Statements.Add(new CodeVariableDeclarationStatement("StringBuilder", "result"));
            var refResultVar = new CodeVariableReferenceExpression("result");
            methGetWabeCountHistory.Statements.Add(new CodeAssignStatement(refResultVar, new CodeObjectCreateExpression("StringBuilder")));

            // 定义本地变量 ndx
            methGetWabeCountHistory.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "ndx"));
            // 引用本地变量 ndx
            var refNdxVar = new CodeVariableReferenceExpression("ndx");

            #region  创建 for 语句

            // 赋值语句 ndx = 0
            var initNdxVar = new CodeAssignStatement(refNdxVar, new CodePrimitiveExpression(0));
            // 条件语句  ndx < this._updates.Count
            var testNdxWithUpdatesCount = new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.LessThan,
                new CodePropertyReferenceExpression(refUpdatesFld, "Count"));
            // 自增语句
            var incrementNdxVar = new CodeAssignStatement(refNdxVar,
                new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(1)));
            // 比较 if(ndx == 0)
            var compareNdxWithZero = new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression(0));
            // 方法调用 result.AppendFormat("{0}", this._updates[ndx])
            var methAppendFormatInvoke = new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(refResultVar, "AppendFormat"),
                    new CodePrimitiveExpression("{0}"),
                    new CodeArrayIndexerExpression(refUpdatesFld, refNdxVar)
                    )
                  );
            // 方法调用 result.AppendFormat(", {0}", this._updates[ndx])
            var methAppendFormtInvokeWithCommas = new CodeExpressionStatement(
            new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(refResultVar, "AppendFormat"),
                new CodePrimitiveExpression(", {0}"),
                new CodeArrayIndexerExpression(refUpdatesFld, refNdxVar)
                )
              );

            methGetWabeCountHistory.Statements.Add(
                new CodeIterationStatement(initNdxVar, testNdxWithUpdatesCount, incrementNdxVar,
                    new CodeConditionStatement(compareNdxWithZero,
                        new CodeStatement[] { methAppendFormatInvoke },
                        new CodeStatement[] { methAppendFormtInvokeWithCommas })));

            #endregion

            // 定义返回值
            methGetWabeCountHistory.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(refResultVar, "ToString"))));

            return mimsyNamespace;
        }
 public bool ValidateCodePropertySetValueReferenceExpression (CodePropertySetValueReferenceExpression exp) {
     return true;
 }
Beispiel #28
0
        private static void GenerateProperties(Type t, CodeTypeDeclaration codeType)
        {
            foreach (PropertyInfo property in t.GetProperties())
            {
                if (OmittedProperties.ContainsKey(t.FullName) && OmittedProperties[t.FullName].Contains(property.Name))
                {
                    continue;
                }

                if (property.CustomAttributes.Any(x => x.AttributeType.FullName.Contains("Obsolete")))
                {
                    continue;
                }

                string propertyType = GetPropertyType(property.PropertyType);
                bool isGenericCollection = property.PropertyType.IsGenericType &&
                    (property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>) || property.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(IReadOnlyList<>));

                CodeFieldReferenceExpression wrappedObject = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), OmObject);
                CodePropertyReferenceExpression wrappedObjectProperty = new CodePropertyReferenceExpression(wrappedObject, property.Name);
                CodeFieldReferenceExpression fieldReference = null;
                if (isGenericCollection || OMtoPSClassMappings.ContainsKey(property.PropertyType.FullName))
                {
                    // Add a backing field for the property with the same name but using camel case.
                    string fieldName = string.Format("{0}{1}", property.Name.ToLower()[0], property.Name.Substring(1, property.Name.Length - 1));
                    CodeMemberField backingField = new CodeMemberField();
                    backingField.Attributes = MemberAttributes.Private;
                    backingField.Name = fieldName;
                    backingField.Type = new CodeTypeReference(propertyType);
                    codeType.Members.Add(backingField);

                    fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName);
                }

                CodeMemberProperty codeProperty = new CodeMemberProperty();
                codeProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                codeProperty.Name = property.Name;
                codeProperty.Type = new CodeTypeReference(propertyType);

                // For properties with a backing field, the field will not be initialized in the constructor in order to avoid
                // hitting a run time access constraint from the OM. Instead, the field is initialized on the first access of
                // the property.

                if (isGenericCollection)
                {
                    // Collections are not kept in sync with the wrapped OM object. Cmdlets will need to sync them before sending
                    // a request to the server.
                    Type argType = property.PropertyType.GetGenericArguments()[0];
                    string wrapperArgType = argType.FullName.StartsWith("System") ? argType.FullName : OMtoPSClassMappings[argType.FullName];
                    string wrapperListType = string.Format("List<{0}>", wrapperArgType);

                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        codeProperty.HasGet = true;
                        // Build a list of wrapper objects
                        const string listVariableName = "list";
                        CodeVariableDeclarationStatement listDeclaration = new CodeVariableDeclarationStatement(wrapperListType, listVariableName);
                        CodeVariableReferenceExpression listReference = new CodeVariableReferenceExpression(listVariableName);
                        CodeAssignStatement initializeList = new CodeAssignStatement(listReference, new CodeObjectCreateExpression(wrapperListType));

                        // CodeDom doesn't support foreach loops very well, so instead explicitly get the enumerator and loop on MoveNext() calls
                        const string enumeratorVariableName = "enumerator";
                        CodeVariableDeclarationStatement enumeratorDeclaration = new CodeVariableDeclarationStatement(string.Format("IEnumerator<{0}>", argType.FullName), enumeratorVariableName);
                        CodeVariableReferenceExpression enumeratorReference = new CodeVariableReferenceExpression(enumeratorVariableName);
                        CodeAssignStatement initializeEnumerator = new CodeAssignStatement(enumeratorReference, new CodeMethodInvokeExpression(wrappedObjectProperty, "GetEnumerator"));
                        CodeIterationStatement loopStatement = new CodeIterationStatement();
                        loopStatement.TestExpression = new CodeMethodInvokeExpression(enumeratorReference, "MoveNext");
                        loopStatement.IncrementStatement = new CodeSnippetStatement(string.Empty);
                        loopStatement.InitStatement = new CodeSnippetStatement(string.Empty);
                        CodePropertyReferenceExpression enumeratorCurrent = new CodePropertyReferenceExpression(enumeratorReference, "Current");

                        // Fill the list by individually wrapping each item in the loop
                        if (wrapperArgType.Contains("System"))
                        {
                            CodeMethodInvokeExpression addToList = new CodeMethodInvokeExpression(listReference, "Add", enumeratorCurrent);
                            loopStatement.Statements.Add(addToList);
                        }
                        else
                        {
                            CodeObjectCreateExpression createListItem = new CodeObjectCreateExpression(wrapperArgType, enumeratorCurrent);
                            CodeMethodInvokeExpression addToList = new CodeMethodInvokeExpression(listReference, "Add", createListItem);
                            loopStatement.Statements.Add(addToList);
                        }

                        // Initialize the backing field with the built list on first access of the property
                        CodeAssignStatement assignStatement;
                        if (property.PropertyType.GetGenericTypeDefinition() == typeof(IReadOnlyList<>))
                        {
                            CodeMethodInvokeExpression asReadOnlyList = new CodeMethodInvokeExpression(listReference, "AsReadOnly");
                            assignStatement = new CodeAssignStatement(fieldReference, asReadOnlyList);
                        }
                        else
                        {
                            assignStatement = new CodeAssignStatement(fieldReference, listReference);
                        }
                        CodePrimitiveExpression nullExpression = new CodePrimitiveExpression(null);
                        CodeBinaryOperatorExpression fieldNullCheck = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityEquality, nullExpression);
                        CodeBinaryOperatorExpression wrappedPropertyNullCheck = new CodeBinaryOperatorExpression(wrappedObjectProperty, CodeBinaryOperatorType.IdentityInequality, nullExpression);
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(fieldNullCheck, CodeBinaryOperatorType.BooleanAnd, wrappedPropertyNullCheck);
                        CodeConditionStatement ifBlock = new CodeConditionStatement(condition, listDeclaration, initializeList, enumeratorDeclaration, initializeEnumerator, loopStatement, assignStatement);
                        codeProperty.GetStatements.Add(ifBlock);
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(fieldReference));
                    }
                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        // Call the "set" on the OM object to ensure that constraints are enforced.
                        codeProperty.HasSet = true;
                        CodePropertySetValueReferenceExpression valueReference = new CodePropertySetValueReferenceExpression();
                        CodeBinaryOperatorExpression nullCheck = new CodeBinaryOperatorExpression(valueReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
                        CodeAssignStatement nullAssignment = new CodeAssignStatement(wrappedObjectProperty, new CodePrimitiveExpression(null));
                        CodeAssignStatement nonNullAssignment = new CodeAssignStatement(wrappedObjectProperty, new CodeObjectCreateExpression(string.Format("List<{0}>", argType.FullName)));
                        CodeConditionStatement ifBlock = new CodeConditionStatement(nullCheck, new CodeStatement[] { nullAssignment }, new CodeStatement[] { nonNullAssignment });
                        codeProperty.SetStatements.Add(ifBlock);
                        codeProperty.SetStatements.Add(new CodeAssignStatement(fieldReference, valueReference));
                    }
                }
                else if (OMtoPSClassMappings.ContainsKey(property.PropertyType.FullName))
                {
                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        codeProperty.HasGet = true;
                        CodeObjectCreateExpression createFieldObject = new CodeObjectCreateExpression(OMtoPSClassMappings[property.PropertyType.FullName], wrappedObjectProperty);
                        CodeAssignStatement assignStatement = new CodeAssignStatement(fieldReference, createFieldObject);
                        CodePrimitiveExpression nullExpression = new CodePrimitiveExpression(null);
                        CodeBinaryOperatorExpression fieldNullCheck = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityEquality, nullExpression);
                        CodeBinaryOperatorExpression wrappedPropertyNullCheck = new CodeBinaryOperatorExpression(wrappedObjectProperty, CodeBinaryOperatorType.IdentityInequality, nullExpression);
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(fieldNullCheck, CodeBinaryOperatorType.BooleanAnd, wrappedPropertyNullCheck);
                        CodeConditionStatement ifBlock = new CodeConditionStatement(condition, assignStatement);
                        codeProperty.GetStatements.Add(ifBlock);
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(fieldReference));
                    }
                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        codeProperty.HasSet = true;
                        CodePropertySetValueReferenceExpression valueReference = new CodePropertySetValueReferenceExpression();
                        CodeBinaryOperatorExpression nullCheck = new CodeBinaryOperatorExpression(valueReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
                        CodeAssignStatement nullAssignment = new CodeAssignStatement(wrappedObjectProperty, new CodePrimitiveExpression(null));
                        CodePropertyReferenceExpression valueProperty = new CodePropertyReferenceExpression(valueReference, OmObject);
                        CodeAssignStatement nonNullAssignment = new CodeAssignStatement(wrappedObjectProperty, valueProperty);
                        CodeConditionStatement ifBlock = new CodeConditionStatement(nullCheck, new CodeStatement[] { nullAssignment }, new CodeStatement[] { nonNullAssignment });
                        codeProperty.SetStatements.Add(ifBlock);
                        codeProperty.SetStatements.Add(new CodeAssignStatement(fieldReference, valueReference));
                    }
                }
                else
                {
                    // By default, just pass through to the wrapped OM object's property.
                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        codeProperty.HasGet = true;
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(wrappedObjectProperty));
                    }
                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        codeProperty.HasSet = true;
                        codeProperty.SetStatements.Add(new CodeAssignStatement(wrappedObjectProperty, new CodePropertySetValueReferenceExpression()));
                    }
                }
                codeType.Members.Add(codeProperty);
            }
        }
		public static void AddOutletProperty (CodeTypeDeclaration type, string name, CodeTypeReference typeRef)
		{
			var fieldName = "__mt_" + name;
			var field = new CodeMemberField (typeRef, fieldName);
			
			var prop = new CodeMemberProperty () {
				Name = name,
				Type = typeRef
			};
			prop.CustomAttributes.Add (
				new CodeAttributeDeclaration ("MonoTouch.Foundation.Connect",
			    		new CodeAttributeArgument (new CodePrimitiveExpression (name))));
			
			var setValue = new CodePropertySetValueReferenceExpression ();
			var thisRef = new CodeThisReferenceExpression ();
			var fieldRef = new CodeFieldReferenceExpression (thisRef, fieldName);
			var setNativeRef = new CodeMethodReferenceExpression (thisRef, "SetNativeField");
			var getNativeRef = new CodeMethodReferenceExpression (thisRef, "GetNativeField");
			var namePrimitive = new CodePrimitiveExpression (name);
			var invokeGetNative = new CodeMethodInvokeExpression (getNativeRef, namePrimitive);
			
			prop.SetStatements.Add (new CodeAssignStatement (fieldRef, setValue));
			prop.SetStatements.Add (new CodeMethodInvokeExpression (setNativeRef, namePrimitive, setValue));
			
			prop.GetStatements.Add (new CodeAssignStatement (fieldRef, new CodeCastExpression (typeRef, invokeGetNative)));
			prop.GetStatements.Add (new CodeMethodReturnStatement (fieldRef));
			
			prop.Attributes = field.Attributes = (prop.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
			
			type.Members.Add (prop);
			type.Members.Add (field);
		}
        internal CodeMemberProperty CreatePropertyDeclaration(CodeMemberField field, string name, string typeName) {
            CodeMemberProperty prop = new CodeMemberProperty();
            prop.Type = new CodeTypeReference(typeName);
            prop.Name = name;
            prop.Attributes = (prop.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            //add get
            CodeMethodReturnStatement ret = new CodeMethodReturnStatement();
            ret.Expression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);
            prop.GetStatements.Add(ret);
   
            CodeAssignStatement propertySet = new CodeAssignStatement();
            CodeExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);
            CodeExpression right = new CodePropertySetValueReferenceExpression();
            propertySet.Left = left;
            propertySet.Right = right;

            if (EnableDataBinding)
            {
                prop.SetStatements.Add(propertySet);
                prop.SetStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), RaisePropertyChangedEventMethod.Name, new CodePrimitiveExpression(name)));
            }
            else
                prop.SetStatements.Add(propertySet);

            return prop;
        }
 private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, string nameSpace, string baseName, string resourcesNamespace, bool internalClass, bool useStatic, bool supportsTryCatch)
 {
     string str;
     if (resourcesNamespace != null)
     {
         if (resourcesNamespace.Length > 0)
         {
             str = resourcesNamespace + '.' + baseName;
         }
         else
         {
             str = baseName;
         }
     }
     else if ((nameSpace != null) && (nameSpace.Length > 0))
     {
         str = nameSpace + '.' + baseName;
     }
     else
     {
         str = baseName;
     }
     CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(SuppressMessageAttribute))) {
         AttributeType = { Options = CodeTypeReferenceOptions.GlobalReference }
     };
     declaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("Microsoft.Performance")));
     declaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("CA1811:AvoidUncalledPrivateCode")));
     CodeConstructor constructor = new CodeConstructor();
     constructor.CustomAttributes.Add(declaration);
     if (useStatic || internalClass)
     {
         constructor.Attributes = MemberAttributes.FamilyAndAssembly;
     }
     else
     {
         constructor.Attributes = MemberAttributes.Public;
     }
     srClass.Members.Add(constructor);
     CodeTypeReference type = new CodeTypeReference(typeof(ResourceManager), CodeTypeReferenceOptions.GlobalReference);
     CodeMemberField field = new CodeMemberField(type, "resourceMan") {
         Attributes = MemberAttributes.Private
     };
     if (useStatic)
     {
         field.Attributes |= MemberAttributes.Static;
     }
     srClass.Members.Add(field);
     CodeTypeReference reference2 = new CodeTypeReference(typeof(CultureInfo), CodeTypeReferenceOptions.GlobalReference);
     field = new CodeMemberField(reference2, "resourceCulture") {
         Attributes = MemberAttributes.Private
     };
     if (useStatic)
     {
         field.Attributes |= MemberAttributes.Static;
     }
     srClass.Members.Add(field);
     CodeMemberProperty property = new CodeMemberProperty();
     srClass.Members.Add(property);
     property.Name = "ResourceManager";
     property.HasGet = true;
     property.HasSet = false;
     property.Type = type;
     if (internalClass)
     {
         property.Attributes = MemberAttributes.Assembly;
     }
     else
     {
         property.Attributes = MemberAttributes.Public;
     }
     if (useStatic)
     {
         property.Attributes |= MemberAttributes.Static;
     }
     CodeTypeReference reference3 = new CodeTypeReference(typeof(EditorBrowsableState)) {
         Options = CodeTypeReferenceOptions.GlobalReference
     };
     CodeAttributeArgument argument = new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(reference3), "Advanced"));
     CodeAttributeDeclaration declaration2 = new CodeAttributeDeclaration("System.ComponentModel.EditorBrowsableAttribute", new CodeAttributeArgument[] { argument }) {
         AttributeType = { Options = CodeTypeReferenceOptions.GlobalReference }
     };
     property.CustomAttributes.Add(declaration2);
     CodeMemberProperty property2 = new CodeMemberProperty();
     srClass.Members.Add(property2);
     property2.Name = "Culture";
     property2.HasGet = true;
     property2.HasSet = true;
     property2.Type = reference2;
     if (internalClass)
     {
         property2.Attributes = MemberAttributes.Assembly;
     }
     else
     {
         property2.Attributes = MemberAttributes.Public;
     }
     if (useStatic)
     {
         property2.Attributes |= MemberAttributes.Static;
     }
     property2.CustomAttributes.Add(declaration2);
     CodeFieldReferenceExpression left = new CodeFieldReferenceExpression(null, "resourceMan");
     CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(object)), "ReferenceEquals");
     CodeMethodInvokeExpression condition = new CodeMethodInvokeExpression(method, new CodeExpression[] { left, new CodePrimitiveExpression(null) });
     CodePropertyReferenceExpression expression4 = new CodePropertyReferenceExpression(new CodeTypeOfExpression(new CodeTypeReference(srClass.Name)), "Assembly");
     CodeObjectCreateExpression initExpression = new CodeObjectCreateExpression(type, new CodeExpression[] { new CodePrimitiveExpression(str), expression4 });
     CodeStatement[] trueStatements = new CodeStatement[] { new CodeVariableDeclarationStatement(type, "temp", initExpression), new CodeAssignStatement(left, new CodeVariableReferenceExpression("temp")) };
     property.GetStatements.Add(new CodeConditionStatement(condition, trueStatements));
     property.GetStatements.Add(new CodeMethodReturnStatement(left));
     property.Comments.Add(new CodeCommentStatement("<summary>", true));
     property.Comments.Add(new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ResMgrPropertyComment"), true));
     property.Comments.Add(new CodeCommentStatement("</summary>", true));
     CodeFieldReferenceExpression expression = new CodeFieldReferenceExpression(null, "resourceCulture");
     property2.GetStatements.Add(new CodeMethodReturnStatement(expression));
     CodePropertySetValueReferenceExpression right = new CodePropertySetValueReferenceExpression();
     property2.SetStatements.Add(new CodeAssignStatement(expression, right));
     property2.Comments.Add(new CodeCommentStatement("<summary>", true));
     property2.Comments.Add(new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("CulturePropertyComment1"), true));
     property2.Comments.Add(new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("CulturePropertyComment2"), true));
     property2.Comments.Add(new CodeCommentStatement("</summary>", true));
 }