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);
        }
Example #2
0
        private void BuildPropertySetter(CodeMemberProperty memberProperty, PropertyInfo property)
        {
            CodeExpression valueExpression = new CodePropertySetValueReferenceExpression();

            if (IsRegistered(property.PropertyType))
            {
                valueExpression = new CodePropertyReferenceExpression(valueExpression, WrappedPropertyName);
            }

            if (property.IsIndexer())
            {
                memberProperty.SetStatements.Add(
                    new CodeAssignStatement(
                        new CodeIndexerExpression(
                            WrappedField,
                            memberProperty.Parameters.Cast <CodeParameterDeclarationExpression>()
                            .Select(p => new CodeVariableReferenceExpression(p.Name))
                            .ToArray <CodeExpression>()),
                        valueExpression
                        )
                    );

                return;
            }

            memberProperty.SetStatements.Add(
                new CodeAssignStatement(
                    new CodePropertyReferenceExpression(
                        WrappedField, memberProperty.Name),
                    valueExpression)
                );
        }
    static CodeTypeMember [] GenerateInstrumentedProperty(SupportedType typeProperty, string namePrefix)
    {
        string name            = namePrefix /*+typeProperty.type.Name*/;
        string hiddenFieldName = "_" + name;

        CodePropertySetValueReferenceExpression valueExp = new CodePropertySetValueReferenceExpression();

        CodeMemberField hiddenField = new CodeMemberField(typeProperty.type, hiddenFieldName);

        hiddenField.Attributes = MemberAttributes.Private;

        CodeFieldReferenceExpression hiddenFieldExp = new CodeFieldReferenceExpression(null, hiddenField.Name);

        CodeMemberProperty property = new CodeMemberProperty();

        property.Name       = name;
        property.Type       = new CodeTypeReference(typeProperty.type);
        property.Attributes = MemberAttributes.Public;
        property.UserData.Add("wmimember", typeProperty);
        property.HasGet = true;
        property.HasSet = true;
        property.GetStatements.Add(new CodeMethodReturnStatement(hiddenFieldExp));
        property.SetStatements.Add(new CodeAssignStatement(hiddenFieldExp, valueExp));

        CodeTypeMember [] members = new CodeTypeMember[2];
        members[0] = hiddenField;
        members[1] = property;

        return(members);
    }
Example #4
0
        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);
        }
        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);
        }
Example #6
0
        /// <summary>
        /// Emit the property set statments to properly set a ComplexType.
        /// </summary>
        /// <param name="statements">The collection of statements that the set statements should be added to.</param>
        private void EmitComplexTypePropertySetStatements(CodeStatementCollection statements, CollectionKind collectionKind)
        {
            CodePropertySetValueReferenceExpression valueRef = new CodePropertySetValueReferenceExpression();

            //Since collections are not supported by
            //the stack, we don't need to do anything special
            //like doing an Attach or Detatch like the way we do for complex types.
            if (collectionKind == CollectionKind.None)
            {
                // this.fieldName = SetValidValue( this.fieldName, value, _pifieldName);
                statements.Add(
                    new CodeAssignStatement(
                        FieldRef,
                        new CodeMethodInvokeExpression(
                            ThisRef,
                            Utils.SetValidValueMethodName,
                            FieldRef,
                            valueRef,
                            new CodePrimitiveExpression(PropertyName))));

                // this._complexPropertyInitialized = true;
                statements.Add(
                    new CodeAssignStatement(
                        ComplexPropertyInitializedFieldRef,
                        new CodePrimitiveExpression(true)));
            }
            else
            {
                // this.fieldName = value;
                statements.Add(
                    new CodeAssignStatement(
                        FieldRef, valueRef));
            }
        }
        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);
        }
Example #8
0
 public TypescriptPropertySetValueReferenceExpression(
     CodePropertySetValueReferenceExpression codeExpression,
     CodeGeneratorOptions options)
 {
     _codeExpression = codeExpression;
     _options        = options;
     System.Diagnostics.Debug.WriteLine("TypescriptPropertySetValueReferenceExpression Created");
 }
 private bool HandleDynamic(CodePropertySetValueReferenceExpression obj, Context ctx)
 {
     if (string.IsNullOrEmpty(PropertySetValueReferenceKeyword))
     {
         return(false);
     }
     ctx.Writer.Write(PropertySetValueReferenceKeyword);
     return(true);
 }
Example #10
0
        /// <summary>
        /// Emit the set statements for a property that is a scalar type
        /// </summary>
        /// <param name="statements">The statement collection to add the set statements to.</param>
        private void EmitScalarTypePropertySetStatements(CodeStatementCollection statements,
                                                         CollectionKind collectionKind)
        {
            Debug.Assert(statements != null, "statments can't be null");
            Debug.Assert(((MetadataUtil.IsPrimitiveType(Item.TypeUsage.EdmType)) || (MetadataUtil.IsCollectionType(Item.TypeUsage.EdmType)))
                         , "Must be a primitive type or collection type property");

            CodePropertySetValueReferenceExpression valueRef = new CodePropertySetValueReferenceExpression();

            //Since collections are not supported by
            //the stack, we don't need to do anything special
            //like doing an Attach or Detatch like the way we do for complex types.
            if (collectionKind == CollectionKind.None)
            {
                PrimitiveType primitiveType = (PrimitiveType)Item.TypeUsage.EdmType;

                // basic pattern
                // this.fieldName = SetValidValue( value );
                //
                List <CodeExpression> parameters = new List <CodeExpression>();
                parameters.Add(valueRef);


                // pattern for non Nullable<T> types (string, byte[])
                //
                // this.fieldName = SetValidVaue( value, nullability );

                if (primitiveType.ClrEquivalentType.IsClass)
                {
                    // ref types have an extra boolean parameter to tell if the property is allowed to
                    // be null or not
                    parameters.Add(new CodePrimitiveExpression(Item.Nullable));
                }

                // now create and add the built statement
                statements.Add(
                    new CodeAssignStatement(
                        FieldRef,
                        new CodeMethodInvokeExpression(
                            CreateEdmStructuralObjectRef(TypeReference),
                            Utils.SetValidValueMethodName,
                            parameters.ToArray())));
            }
            else
            {
                // this.fieldName = value;
                statements.Add(
                    new CodeAssignStatement(
                        FieldRef, valueRef));
            }
        }
 protected void AddFixedValueChecking(CodeStatementCollection setStatements)
 {
     if (this.FixedValue != null)
     {
         CodeExpression fixedValueExpr = new CodeFieldReferenceExpression(null, NameGenerator.ChangeClrName(this.propertyName, NameOptions.MakeFixedValueField));
         CodePropertySetValueReferenceExpression codePropertySetValueReferenceExpression = new CodePropertySetValueReferenceExpression();
         CodeExpression[]           codeExpressionArray         = new CodeExpression[] { fixedValueExpr };
         CodeMethodInvokeExpression codeMethodInvokeExpression  = CodeDomHelper.CreateMethodCall(codePropertySetValueReferenceExpression, "Equals", codeExpressionArray);
         CodeStatement[]            codeStatementArray          = new CodeStatement[0];
         CodeStatement[]            codeThrowExceptionStatement = new CodeStatement[1];
         Type type = typeof(LinqToXsdFixedValueException);
         codeExpressionArray            = new CodeExpression[] { new CodePropertySetValueReferenceExpression(), fixedValueExpr };
         codeThrowExceptionStatement[0] = new CodeThrowExceptionStatement(new CodeObjectCreateExpression(type, codeExpressionArray));
         setStatements.Add(new CodeConditionStatement(codeMethodInvokeExpression, codeStatementArray, codeThrowExceptionStatement));
     }
 }
Example #12
0
        private void GenerateBitVectorPropertySet(CodeMemberProperty prop, string fieldName, uint mask, int offset, NativeBitVector bitVector)
        {
            prop.HasSet = true;

            // Shift it
            CodeExpression exprShift = default(CodeExpression);

            if (offset != 0)
            {
                exprShift = new CodeBinaryOperatorExpression(new CodePropertySetValueReferenceExpression(), CodeBinaryOperatorType.Multiply, new CodePrimitiveExpression(Math.Pow(2, offset)));
            }
            else
            {
                exprShift = new CodePropertySetValueReferenceExpression();
            }

            // Or it with the current
            CodeBinaryOperatorExpression exprOr = new CodeBinaryOperatorExpression(exprShift, CodeBinaryOperatorType.BitwiseOr, new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName));

            // Assign it to the field
            CodeAssignStatement asg = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodeCastExpression(new CodeTypeReference(typeof(uint)), exprOr));

            prop.SetStatements.Add(asg);
        }
Example #13
0
        private static CodeMemberProperty CreateProperty(ColumnInfo column)
        {
            var prop = new CodeMemberProperty
            {
                Name       = column.Name,
                Type       = GetType(column),
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            };

            var backupFieldName = FormatPrivateFieldName(column);
            var _this           = new CodeThisReferenceExpression();

            prop.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(_this, backupFieldName)));

            var propValue = new CodePropertySetValueReferenceExpression();

            prop.SetStatements.Add(
                new CodeAssignStatement(
                    new CodeFieldReferenceExpression(_this, backupFieldName), propValue));

            return(prop);
        }
Example #14
0
 protected virtual void Visit(CodePropertySetValueReferenceExpression expr)
 {
 }
Example #15
0
 protected override void Visit(CodePropertySetValueReferenceExpression expr)
 {
     base.Visit(expr);
 }
Example #16
0
 protected override void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
 {
     Output.Write("propertySetValueReference");
 }
Example #17
0
 private void ValidatePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
 { // Do nothing
 }
Example #18
0
 private void ValidatePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
 {
 }
	protected override void GeneratePropertySetValueReferenceExpression
				(CodePropertySetValueReferenceExpression e)
			{
				Output.Write("value");
			}
Example #20
0
        private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String nameSpace, String baseName, String resourcesNamespace, bool internalClass, bool useStatic)
        {
            const String tmpVarName = "temp";
            String       resMgrCtorParam;

            if (resourcesNamespace != null)
            {
                if (resourcesNamespace.Length > 0)
                {
                    resMgrCtorParam = resourcesNamespace + '.' + baseName;
                }
                else
                {
                    resMgrCtorParam = baseName;
                }
            }
            else if (!string.IsNullOrEmpty(nameSpace))
            {
                resMgrCtorParam = nameSpace + '.' + baseName;
            }
            else
            {
                resMgrCtorParam = baseName;
            }

            var suppressMessageAttrib = new CodeAttributeDeclaration(new CodeTypeReference(typeof(SuppressMessageAttribute)));

            suppressMessageAttrib.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference;
            suppressMessageAttrib.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("Microsoft.Performance")));
            suppressMessageAttrib.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("CA1811:AvoidUncalledPrivateCode")));

            // Emit a constructor - make it protected even if it is a "static" class to allow subclassing
            CodeConstructor ctor = new CodeConstructor();

            ctor.CustomAttributes.Add(suppressMessageAttrib);
            if (useStatic || internalClass)
            {
                ctor.Attributes = MemberAttributes.FamilyAndAssembly;
            }
            else
            {
                ctor.Attributes = MemberAttributes.Public;
            }
            srClass.Members.Add(ctor);

            // Emit _resMgr field.
            var ResMgrCodeTypeReference = new CodeTypeReference(typeof(ResourceManager), CodeTypeReferenceOptions.GlobalReference);
            var field = new CodeMemberField(ResMgrCodeTypeReference, ResMgrFieldName)
            {
                Attributes = MemberAttributes.Private
            };

            if (useStatic)
            {
                field.Attributes |= MemberAttributes.Static;
            }
            srClass.Members.Add(field);

            // Emit _resCulture field, and leave it set to null.
            var CultureTypeReference = new CodeTypeReference(typeof(CultureInfo), CodeTypeReferenceOptions.GlobalReference);

            field            = new CodeMemberField(CultureTypeReference, CultureInfoFieldName);
            field.Attributes = MemberAttributes.Private;
            if (useStatic)
            {
                field.Attributes |= MemberAttributes.Static;
            }
            srClass.Members.Add(field);

            // Emit ResMgr property
            CodeMemberProperty resMgr = new CodeMemberProperty();

            srClass.Members.Add(resMgr);
            resMgr.Name   = ResMgrPropertyName;
            resMgr.HasGet = true;
            resMgr.HasSet = false;
            resMgr.Type   = ResMgrCodeTypeReference;
            if (internalClass)
            {
                resMgr.Attributes = MemberAttributes.Assembly;
            }
            else
            {
                resMgr.Attributes = MemberAttributes.Public;
            }
            if (useStatic)
            {
                resMgr.Attributes |= MemberAttributes.Static;
            }

            // Mark the ResMgr property as advanced
            var editorBrowsableStateTypeRef =
                new CodeTypeReference(typeof(System.ComponentModel.EditorBrowsableState))
            {
                Options = CodeTypeReferenceOptions.GlobalReference
            };

            var editorBrowsableStateAdvanced     = new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(editorBrowsableStateTypeRef), "Advanced"));
            var editorBrowsableAdvancedAttribute = new CodeAttributeDeclaration("System.ComponentModel.EditorBrowsableAttribute", editorBrowsableStateAdvanced);

            editorBrowsableAdvancedAttribute.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference;
            resMgr.CustomAttributes.Add(editorBrowsableAdvancedAttribute);

            // Emit the Culture property (read/write)
            var culture = new CodeMemberProperty();

            srClass.Members.Add(culture);
            culture.Name   = CultureInfoPropertyName;
            culture.HasGet = true;
            culture.HasSet = true;
            culture.Type   = CultureTypeReference;
            if (internalClass)
            {
                culture.Attributes = MemberAttributes.Assembly;
            }
            else
            {
                culture.Attributes = MemberAttributes.Public;
            }

            if (useStatic)
            {
                culture.Attributes |= MemberAttributes.Static;
            }

            // Mark the Culture property as advanced
            culture.CustomAttributes.Add(editorBrowsableAdvancedAttribute);

            /*
             * // Here's what I'm trying to emit.  Since not all languages support
             * // try/finally, we'll avoid our double lock pattern here.
             * // This will only hurt perf when we get two threads racing through
             * // this method the first time.  Unfortunate, but not a big deal.
             * // Also, the .NET Compact Framework doesn't support
             * // Thread.MemoryBarrier (they only run on processors w/ a strong
             * // memory model, and who knows about IA64...)
             * // Once we have Interlocked.CompareExchange<T>, we should use it here.
             * if (_resMgr == null) {
             *    ResourceManager tmp = new ResourceManager("<resources-name-with-namespace>", typeof("<class-name>").Assembly);
             *    _resMgr = tmp;
             * }
             * return _resMgr;
             */
            var field_resMgr        = new CodeFieldReferenceExpression(null, ResMgrFieldName);
            var object_equalsMethod = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Object)), "ReferenceEquals");

            var isResMgrNull = new CodeMethodInvokeExpression(object_equalsMethod, field_resMgr, new CodePrimitiveExpression(null));

            // typeof(<class-name>).Assembly
            var getAssembly = new CodePropertyReferenceExpression(new CodeTypeOfExpression(new CodeTypeReference(srClass.Name)), "Assembly");

            // new ResourceManager(resMgrCtorParam, typeof(<class-name>).Assembly);
            var newResMgr = new CodeObjectCreateExpression(ResMgrCodeTypeReference, new CodePrimitiveExpression(resMgrCtorParam), getAssembly);

            var init = new CodeStatement[2];

            init[0] = new CodeVariableDeclarationStatement(ResMgrCodeTypeReference, tmpVarName, newResMgr);
            init[1] = new CodeAssignStatement(field_resMgr, new CodeVariableReferenceExpression(tmpVarName));

            resMgr.GetStatements.Add(new CodeConditionStatement(isResMgrNull, init));
            resMgr.GetStatements.Add(new CodeMethodReturnStatement(field_resMgr));

            // Add a doc comment to the ResourceManager property
            resMgr.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true));
            resMgr.Comments.Add(new CodeCommentStatement(SR.GetString(SR.ResMgrPropertyComment), true));
            resMgr.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true));

            // Emit code for Culture property
            var field_resCulture = new CodeFieldReferenceExpression(null, CultureInfoFieldName);

            culture.GetStatements.Add(new CodeMethodReturnStatement(field_resCulture));

            var newCulture = new CodePropertySetValueReferenceExpression();

            culture.SetStatements.Add(new CodeAssignStatement(field_resCulture, newCulture));

            // Add a doc comment to Culture property
            culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true));
            culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment1), true));
            culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment2), true));
            culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true));
        }
Example #21
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);
            }
        }
Example #22
0
 private void ValidatePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)   // Do nothing
 {
 }
        /// <summary>
        /// Generates a property getter/setter pair into the given proxy class to match the given property info.
        /// </summary>
        /// <param name="propertyDescriptor">PropertyDescriptor for the property to generate for.</param>
        protected virtual void GenerateProperty(PropertyDescriptor propertyDescriptor)
        {
            string propertyName = propertyDescriptor.Name;
            Type   propertyType = CodeGenUtilities.TranslateType(propertyDescriptor.PropertyType);

            // ----------------------------------------------------------------
            // Property type ref
            // ----------------------------------------------------------------
            var propTypeReference = CodeGenUtilities.GetTypeReference(propertyType, this.ClientProxyGenerator, this.ProxyClass);

            // ----------------------------------------------------------------
            // Property decl
            // ----------------------------------------------------------------
            var property = new CodeMemberProperty();

            property.Name       = propertyName;
            property.Type       = propTypeReference;
            property.Attributes = MemberAttributes.Public | MemberAttributes.Final; // final needed, else becomes virtual
            List <Attribute> propertyAttributes = propertyDescriptor.ExplicitAttributes().Cast <Attribute>().ToList();

            // Generate <summary> for property
            string comment = string.Format(CultureInfo.CurrentCulture, Resource.CodeGen_Entity_Property_Summary_Comment, propertyName);

            property.Comments.AddRange(CodeGenUtilities.GenerateSummaryCodeComment(comment, this.ClientProxyGenerator.IsCSharp));

            // ----------------------------------------------------------------
            // [DataMember] -> Add if not already present.
            // ----------------------------------------------------------------
            // Add if not already present.

            if (!propertyAttributes.OfType <DataMemberAttribute>().Any())
            {
                CodeAttributeDeclaration dataMemberAtt = CodeGenUtilities.CreateAttributeDeclaration(typeof(DataMemberAttribute), this.ClientProxyGenerator, this.ProxyClass);
                property.CustomAttributes.Add(dataMemberAtt);
            }

            // Here, we check for the existence of [ReadOnly(true)] attributes generated when
            // the property does not not have a setter.  We want to inject an [Editable(false)]
            // attribute into the pipeline.
            ReadOnlyAttribute readOnlyAttr = propertyAttributes.OfType <ReadOnlyAttribute>().SingleOrDefault();

            if (readOnlyAttr != null && !propertyAttributes.OfType <EditableAttribute>().Any())
            {
                propertyAttributes.Add(new EditableAttribute(!readOnlyAttr.IsReadOnly));

                // REVIEW:  should we strip out [ReadOnly] attributes here?
            }

            // Here we check if the type has a RoundtripOriginalAttribute. In that case we strip it out from the property
            if (this._isRoundtripType)
            {
                propertyAttributes.RemoveAll(attr => attr.GetType() == typeof(RoundtripOriginalAttribute));
            }

            // Here we check for database generated fields. In that case we strip any RequiredAttribute from the property.
            if (propertyAttributes.Any(a => a.GetType().Name == "DatabaseGeneratedAttribute"))
            {
                propertyAttributes.RemoveAll(attr => attr.GetType() == typeof(RequiredAttribute));
            }

            // Here, we check for the presence of a complex type. If it exists we need to add a DisplayAttribute
            // if not already there. DataSources windows do not handle complex types
            if (TypeUtility.IsSupportedComplexType(propertyType) && !propertyAttributes.OfType <DisplayAttribute>().Any())
            {
                CodeAttributeDeclaration displayAttribute = CodeGenUtilities.CreateDisplayAttributeDeclaration(this.ClientProxyGenerator, this.ProxyClass);
                property.CustomAttributes.Add(displayAttribute);
            }

            // ----------------------------------------------------------------
            // Propagate the custom attributes
            // ----------------------------------------------------------------

            CustomAttributeGenerator.GenerateCustomAttributes(
                this.ClientProxyGenerator,
                this.ProxyClass,
                ex => string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeTypeMember, ex.Message, property.Name, this.ProxyClass.Name, ex.InnerException.Message),
                propertyAttributes.Cast <Attribute>(),
                property.CustomAttributes,
                property.Comments);

            // ----------------------------------------------------------------
            // backing private field (CodeDom doesn't yet know about auto properties)
            // ----------------------------------------------------------------
            string fieldName = CodeGenUtilities.MakeCompliantFieldName(propertyName);
            var    field     = new CodeMemberField(propTypeReference, fieldName);

            this.ProxyClass.Members.Add(field);
            var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName);
            var valueRef = new CodePropertySetValueReferenceExpression();

            // ----------------------------------------------------------------
            // getter body
            // ----------------------------------------------------------------
            property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef));

            // ----------------------------------------------------------------
            // setter body
            // ----------------------------------------------------------------
            List <CodeStatement> bodyStatements = new List <CodeStatement>();

            // this.OnPropertyXxxChanging(PropType value);
            bodyStatements.Add(this.NotificationMethodGen.GetMethodInvokeExpressionStatementFor(propertyName + "Changing"));

            bool propertyIsReadOnly = this.IsPropertyReadOnly(propertyDescriptor);

            if (!propertyIsReadOnly)
            {
                bodyStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "RaiseDataMemberChanging", new CodePrimitiveExpression(propertyDescriptor.Name))));
            }

            // Generate the validation tests.
            CodeStatement validationCode = GeneratePropertySetterValidation(propertyDescriptor.Name);

            bodyStatements.Add(validationCode);

            // this._field = value
            bodyStatements.Add(new CodeAssignStatement(fieldRef, valueRef));

            if (!propertyIsReadOnly)
            {
                bodyStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "RaiseDataMemberChanged", new CodePrimitiveExpression(propertyDescriptor.Name))));
            }
            else
            {
                // even read-only members need to raise PropertyChanged
                bodyStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "RaisePropertyChanged", new CodePrimitiveExpression(propertyDescriptor.Name))));
            }

            // this.OnPropertyXxxChanged();
            bodyStatements.Add(this.NotificationMethodGen.GetMethodInvokeExpressionStatementFor(propertyName + "Changed"));

            // if (this._field != value)...
            CodeExpression valueTest = CodeGenUtilities.MakeNotEqual(propertyType, fieldRef, valueRef, this.ClientProxyGenerator.IsCSharp);

            CodeConditionStatement body = new CodeConditionStatement(valueTest, bodyStatements.ToArray <CodeStatement>());

            property.SetStatements.Add(body);

            // add property
            this.ProxyClass.Members.Add(property);
        }
Example #24
0
 protected override void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
 {
 }
Example #25
0
			public void Visit(CodePropertySetValueReferenceExpression o)
			{
				g.GeneratePropertySetValueReferenceExpression(o);
			}
Example #26
0
    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
        };

        CodeMemberField wabeCountFld =
            new CodeMemberField(typeof(int), "_wabeCount")
        {
            Attributes = MemberAttributes.Private
        };

        jubjubClass.Members.Add(wabeCountFld);

        var typrefArrayList =
            new CodeTypeReference("ArrayList");

        CodeMemberField updatesFld =
            new CodeMemberField(typrefArrayList, "_updates");

        jubjubClass.Members.Add(updatesFld);

        mimsyNamespace.Types.Add(jubjubClass);

        CodeConstructor jubjubCtor =
            new CodeConstructor()
        {
            Attributes = MemberAttributes.Public
        };

        var jubjubCtorParam =
            new CodeParameterDeclarationExpression(
                typeof(int), "wabeCount");

        jubjubCtor.Parameters.Add(jubjubCtorParam);

        var refUpdatesFld =
            new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(),
                "_updates");
        var newArrayList =
            new CodeObjectCreateExpression(typrefArrayList);
        var assignUpdates =
            new CodeAssignStatement(
                refUpdatesFld, newArrayList);

        jubjubCtor.Statements.Add(assignUpdates);

        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,
            Type = new CodeTypeReference(typeof(int)),
            Name = "WabeCount"
        };

        wabeCountProp.GetStatements.Add(
            new CodeMethodReturnStatement(refWabeCountFld));

        var suppliedPropertyValue =
            new CodePropertySetValueReferenceExpression();
        var zero = new CodePrimitiveExpression(0);

        var suppliedPropValIsLessThanZero =
            new CodeBinaryOperatorExpression(
                suppliedPropertyValue,
                CodeBinaryOperatorType.LessThan,
                zero);

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

        methGetWabeCountHistory.Statements.Add(
            new CodeVariableDeclarationStatement(
                typeof(int), "ndx"));
        var refNdxVar =
            new CodeVariableReferenceExpression("ndx");

        methGetWabeCountHistory.Statements.Add(
            new CodeIterationStatement(
                new CodeAssignStatement(
                    refNdxVar,
                    new CodePrimitiveExpression(0)),
                new CodeBinaryOperatorExpression(
                    refNdxVar,
                    CodeBinaryOperatorType.LessThan,
                    new CodePropertyReferenceExpression(
                        refUpdatesFld,
                        "Count")),
                new CodeAssignStatement(
                    refNdxVar,
                    new CodeBinaryOperatorExpression(
                        refNdxVar,
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))),
                new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(
                        refNdxVar,
                        CodeBinaryOperatorType.ValueEquality,
                        new CodePrimitiveExpression(0)),
                    new CodeStatement[]
        {
            new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        refResultVar,
                        "AppendFormat"),
                    new CodePrimitiveExpression("{0}"),
                    new CodeArrayIndexerExpression(
                        refUpdatesFld,
                        refNdxVar)))
        },
                    new CodeStatement[]
        {
            new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        refResultVar,
                        "AppendFormat"),
                    new CodePrimitiveExpression(", {0}"),
                    new CodeArrayIndexerExpression(
                        refUpdatesFld,
                        refNdxVar)))
        })));

        methGetWabeCountHistory.Statements.Add(
            new CodeMethodReturnStatement(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        refResultVar, "ToString"))));

        return(mimsyNamespace);
    }
 private void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
 {
     Output.Write("value");
 }
Example #28
0
            /// <summary>
            /// Generates the set statements of a normal reference
            /// </summary>
            /// <param name="property">The NMeta reference</param>
            /// <param name="codeProperty">The generated code property</param>
            /// <param name="fieldReference">A reference to the backening field</param>
            /// <remarks>Normal means in this case that the reference is not an overridden container reference</remarks>
            protected virtual void GenerateSetStatement(IReference property, CodeMemberProperty codeProperty, CodeExpression fieldReference, ITransformationContext context)
            {
                var ifStmt = new CodeConditionStatement();
                var val    = new CodePropertySetValueReferenceExpression();

                ifStmt.Condition = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityInequality, val);

                var assignment = new CodeAssignStatement(fieldReference, val);

                var oldDef = new CodeVariableDeclarationStatement(codeProperty.Type, "old", fieldReference);
                var oldRef = new CodeVariableReferenceExpression("old");

                ifStmt.TrueStatements.Add(oldDef);

                var valueChangeTypeRef = typeof(ValueChangedEventArgs).ToTypeReference();
                var valueChangeDef     = new CodeVariableDeclarationStatement(valueChangeTypeRef, "e",
                                                                              new CodeObjectCreateExpression(typeof(ValueChangedEventArgs).ToTypeReference(), oldRef, val));
                var valueChangeRef = new CodeVariableReferenceExpression(valueChangeDef.Name);

                ifStmt.TrueStatements.Add(valueChangeDef);

                var referenceRef = new CodeFieldReferenceExpression(null, "_" + property.Name.ToCamelCase() + "Reference");

                ifStmt.TrueStatements.Add(codeProperty.CreateOnChangingEventPattern(typeof(ValueChangedEventArgs).ToTypeReference(), valueChangeRef));
                ifStmt.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "OnPropertyChanging",
                                                                         new CodePrimitiveExpression(codeProperty.Name), valueChangeRef, referenceRef));

                var targetClass  = property.Type;
                var nullRef      = new CodePrimitiveExpression(null);
                var thisRef      = new CodeThisReferenceExpression();
                var oldNotNull   = new CodeBinaryOperatorExpression(oldRef, CodeBinaryOperatorType.IdentityInequality, nullRef);
                var valueNotNull = new CodeBinaryOperatorExpression(val, CodeBinaryOperatorType.IdentityInequality, nullRef);

                ifStmt.TrueStatements.Add(assignment);

                var oldCheck = new CodeConditionStatement(oldNotNull);
                var newCheck = new CodeConditionStatement(valueNotNull);

                if (property.Opposite != null)
                {
                    var oppositeName = context.Trace.ResolveIn(this, property.Opposite).Name;
                    var oldOpposite  = new CodePropertyReferenceExpression(oldRef, oppositeName);
                    var valOpposite  = new CodePropertyReferenceExpression(val, oppositeName);

                    if (property.Opposite.UpperBound == 1)
                    {
                        oldCheck.TrueStatements.Add(new CodeAssignStatement(oldOpposite, nullRef));

                        newCheck.TrueStatements.Add(new CodeAssignStatement(valOpposite, thisRef));
                    }
                    else
                    {
                        oldCheck.TrueStatements.Add(new CodeMethodInvokeExpression(oldOpposite, "Remove", thisRef));

                        var addThis = new CodeMethodInvokeExpression(valOpposite, "Add", thisRef);
                        if (property.Opposite.IsUnique)
                        {
                            newCheck.TrueStatements.Add(addThis);
                        }
                        else
                        {
                            var ifNotContains = new CodeConditionStatement(new CodeBinaryOperatorExpression(
                                                                               new CodeMethodInvokeExpression(valOpposite, "Contains", thisRef), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(true)));

                            ifNotContains.TrueStatements.Add(addThis);
                            newCheck.TrueStatements.Add(ifNotContains);
                        }
                    }

                    if (property.Opposite.IsContainment)
                    {
                        ifStmt.TrueStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(thisRef, "Parent"), val));
                    }
                }

                if (property.IsContainment)
                {
                    oldCheck.TrueStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(oldRef, "Parent"), nullRef));
                    newCheck.TrueStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(val, "Parent"), thisRef));
                }

                var resetEvent = property.IsContainment || (property.Opposite?.IsContainment).GetValueOrDefault() ? "ParentChanged" : "Deleted";

                oldCheck.TrueStatements.Add(new CodeRemoveEventStatement(
                                                new CodeEventReferenceExpression(oldRef, resetEvent),
                                                new CodeMethodReferenceExpression(thisRef, "OnReset" + codeProperty.Name)));

                newCheck.TrueStatements.Add(new CodeAttachEventStatement(
                                                new CodeEventReferenceExpression(val, resetEvent),
                                                new CodeMethodReferenceExpression(thisRef, "OnReset" + codeProperty.Name)));

                ifStmt.TrueStatements.Add(oldCheck);
                ifStmt.TrueStatements.Add(newCheck);


                ifStmt.TrueStatements.Add(codeProperty.CreateOnChangedEventPattern(typeof(ValueChangedEventArgs).ToTypeReference(),
                                                                                   valueChangeRef));

                ifStmt.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "OnPropertyChanged",
                                                                         new CodePrimitiveExpression(codeProperty.Name), valueChangeRef, referenceRef));

                codeProperty.SetStatements.Add(ifStmt);
                codeProperty.HasSet = true;
            }
Example #29
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)
                {
                    // Special handling for dict
                    Type   argType = property.PropertyType.GetGenericArguments()[0];
                    bool   magicalDictConversion = propertyType == "IDictionary";
                    string wrapperArgType        = argType.FullName.StartsWith("System") || argType.FullName.StartsWith("Microsoft.Azure.Batch.Common") ? argType.FullName : OMtoPSClassMappings[argType.FullName];
                    string wrapperType           = magicalDictConversion ? string.Format("Dictionary<string, string>") : string.Format("List<{0}>", wrapperArgType);
                    string variableName          = magicalDictConversion ? "dict" : "list";
                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        // Collections are not kept in sync with the wrapped OM object. Cmdlets will need to sync them before sending
                        // a request to the server.
                        CodeVariableDeclarationStatement declaration = new CodeVariableDeclarationStatement(wrapperType, variableName);
                        CodeVariableReferenceExpression  reference   = new CodeVariableReferenceExpression(variableName);
                        CodeAssignStatement initialize = new CodeAssignStatement(reference, new CodeObjectCreateExpression(wrapperType));

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

                        // Fill the list by individually wrapping each item in the loop
                        if (magicalDictConversion)
                        {
                            var keyReference   = new CodePropertyReferenceExpression(enumeratorCurrent, OMToPSDictionaryConversionMappings[argType.FullName].Item1);
                            var valueReference = new CodePropertyReferenceExpression(enumeratorCurrent, OMToPSDictionaryConversionMappings[argType.FullName].Item2);
                            CodeMethodInvokeExpression addToList = new CodeMethodInvokeExpression(reference, "Add", keyReference, valueReference);
                            loopStatement.Statements.Add(addToList);
                        }
                        else
                        {
                            // Fill the list by individually wrapping each item in the loop
                            if (wrapperArgType.Contains("System") || wrapperArgType.StartsWith("Microsoft.Azure.Batch.Common"))
                            {
                                CodeMethodInvokeExpression addToList = new CodeMethodInvokeExpression(reference, "Add", enumeratorCurrent);
                                loopStatement.Statements.Add(addToList);
                            }
                            else
                            {
                                CodeObjectCreateExpression createListItem = new CodeObjectCreateExpression(wrapperArgType, enumeratorCurrent);
                                CodeMethodInvokeExpression addToList      = new CodeMethodInvokeExpression(reference, "Add", createListItem);
                                loopStatement.Statements.Add(addToList);
                            }
                        }
                        // Initialize the backing field with the built list on first access of the property
                        CodeAssignStatement assignStatement = new CodeAssignStatement(fieldReference, reference);

                        CodePrimitiveExpression      nullExpression           = new CodePrimitiveExpression(null);
                        CodeBinaryOperatorExpression fieldNullCheck           = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityEquality, nullExpression);
                        CodeBinaryOperatorExpression wrappedPropertyNullCheck = new CodeBinaryOperatorExpression(wrappedObjectProperty, CodeBinaryOperatorType.IdentityInequality, nullExpression);
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(fieldNullCheck, CodeBinaryOperatorType.BooleanAnd, wrappedPropertyNullCheck);
                        CodeConditionStatement       ifBlock   = new CodeConditionStatement(condition, declaration, initialize, enumeratorDeclaration, initializeEnumerator, loopStatement, assignStatement);
                        codeProperty.GetStatements.Add(ifBlock);
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(fieldReference));
                    }

                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        // Call the "set" on the OM object to ensure that constraints are enforced.
                        codeProperty.HasSet = true;
                        CodePropertySetValueReferenceExpression valueReference = new CodePropertySetValueReferenceExpression();
                        CodeBinaryOperatorExpression            nullCheck      = new CodeBinaryOperatorExpression(valueReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
                        CodeAssignStatement    nullAssignment    = new CodeAssignStatement(wrappedObjectProperty, new CodePrimitiveExpression(null));
                        CodeAssignStatement    nonNullAssignment = new CodeAssignStatement(wrappedObjectProperty, new CodeObjectCreateExpression(string.Format("List<{0}>", argType.FullName)));
                        CodeConditionStatement ifBlock           = new CodeConditionStatement(nullCheck, new CodeStatement[] { nullAssignment }, new CodeStatement[] { nonNullAssignment });
                        codeProperty.SetStatements.Add(ifBlock);
                        codeProperty.SetStatements.Add(new CodeAssignStatement(fieldReference, valueReference));
                    }
                }
                else if (OMtoPSClassMappings.ContainsKey(property.PropertyType.FullName))
                {
                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        codeProperty.HasGet = true;
                        CodeObjectCreateExpression   createFieldObject        = new CodeObjectCreateExpression(OMtoPSClassMappings[property.PropertyType.FullName], wrappedObjectProperty);
                        CodeAssignStatement          assignStatement          = new CodeAssignStatement(fieldReference, createFieldObject);
                        CodePrimitiveExpression      nullExpression           = new CodePrimitiveExpression(null);
                        CodeBinaryOperatorExpression fieldNullCheck           = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityEquality, nullExpression);
                        CodeBinaryOperatorExpression wrappedPropertyNullCheck = new CodeBinaryOperatorExpression(wrappedObjectProperty, CodeBinaryOperatorType.IdentityInequality, nullExpression);
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(fieldNullCheck, CodeBinaryOperatorType.BooleanAnd, wrappedPropertyNullCheck);
                        CodeConditionStatement       ifBlock   = new CodeConditionStatement(condition, assignStatement);
                        codeProperty.GetStatements.Add(ifBlock);
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(fieldReference));
                    }
                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        codeProperty.HasSet = true;
                        CodePropertySetValueReferenceExpression valueReference = new CodePropertySetValueReferenceExpression();
                        CodeBinaryOperatorExpression            nullCheck      = new CodeBinaryOperatorExpression(valueReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
                        CodeAssignStatement             nullAssignment         = new CodeAssignStatement(wrappedObjectProperty, new CodePrimitiveExpression(null));
                        CodePropertyReferenceExpression valueProperty          = new CodePropertyReferenceExpression(valueReference, OmObject);
                        CodeAssignStatement             nonNullAssignment      = new CodeAssignStatement(wrappedObjectProperty, valueProperty);
                        CodeConditionStatement          ifBlock = new CodeConditionStatement(nullCheck, new CodeStatement[] { nullAssignment }, new CodeStatement[] { nonNullAssignment });
                        codeProperty.SetStatements.Add(ifBlock);
                        codeProperty.SetStatements.Add(new CodeAssignStatement(fieldReference, valueReference));
                    }
                }
                else
                {
                    // By default, just pass through to the wrapped OM object's property.
                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        codeProperty.HasGet = true;
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(wrappedObjectProperty));
                    }
                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        codeProperty.HasSet = true;
                        codeProperty.SetStatements.Add(new CodeAssignStatement(wrappedObjectProperty, new CodePropertySetValueReferenceExpression()));
                    }
                }
                codeType.Members.Add(codeProperty);
            }
        }
Example #30
0
            /// <summary>
            /// Initializes the generated property
            /// </summary>
            /// <param name="input">The input NMeta attribute</param>
            /// <param name="generatedProperty">The generated property</param>
            /// <param name="context">The transformation context</param>
            public override void Transform(IAttribute input, CodeMemberProperty generatedProperty, ITransformationContext context)
            {
                generatedProperty.Attributes = MemberAttributes.Public;
                var summary = input.Summary;

                if (string.IsNullOrEmpty(summary))
                {
                    summary = string.Format("The {0} property", input.Name);
                }
                generatedProperty.WriteDocumentation(summary, input.Remarks);

                var fieldType = CreateTypeReference(input, att => generatedProperty.CustomAttributes.Add(att),
                                                    CreateCollectionImplementationType, context);
                var t = Transformation as Meta2ClassesTransformation;

                if ((t == null || t.IsValueType(input.Type)) && input.LowerBound == 0 && input.UpperBound == 1)
                {
                    fieldType = new CodeTypeReference(typeof(System.Nullable <>).Name, fieldType);
                }

                var fieldRef = generatedProperty.CreateBackingField(fieldType, CreateDefaultValue(input, fieldType, generatedProperty));

                generatedProperty.ImplementGetter(fieldRef);

                if (input.UpperBound == 1)
                {
                    generatedProperty.Type = fieldType;

                    var oldDef = new CodeVariableDeclarationStatement(fieldType, "old", fieldRef);
                    var oldRef = new CodeVariableReferenceExpression("old");
                    var value  = new CodePropertySetValueReferenceExpression();

                    var valueChangeTypeRef = typeof(ValueChangedEventArgs).ToTypeReference();
                    var valueChangeDef     = new CodeVariableDeclarationStatement(valueChangeTypeRef, "e",
                                                                                  new CodeObjectCreateExpression(typeof(ValueChangedEventArgs).ToTypeReference(), oldRef, value));
                    var valueChangeRef = new CodeVariableReferenceExpression(valueChangeDef.Name);

                    var callOnPropertyChanging = new CodeMethodInvokeExpression(
                        new CodeThisReferenceExpression(), "OnPropertyChanging",
                        new CodePrimitiveExpression(generatedProperty.Name), valueChangeRef);

                    var callOnPropertyChanged = new CodeMethodInvokeExpression(
                        new CodeThisReferenceExpression(), "OnPropertyChanged",
                        new CodePrimitiveExpression(generatedProperty.Name), valueChangeRef);

                    generatedProperty.SetStatements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(fieldRef, CodeBinaryOperatorType.IdentityInequality, value),
                                                                                   oldDef,
                                                                                   valueChangeDef,
                                                                                   generatedProperty.CreateOnChangingEventPattern(valueChangeTypeRef, valueChangeRef),
                                                                                   new CodeExpressionStatement(callOnPropertyChanging),
                                                                                   new CodeAssignStatement(fieldRef, value),
                                                                                   generatedProperty.CreateOnChangedEventPattern(valueChangeTypeRef, valueChangeRef),
                                                                                   new CodeExpressionStatement(callOnPropertyChanged)));
                }
                else
                {
                    generatedProperty.Type = CreateTypeReference(input, null, CreateCollectionInterfaceType, context);
                    generatedProperty.MarkCollectionProperty();

                    var createEmptyCollection = new CodeAssignStatement(fieldRef, new CodeObjectCreateExpression(fieldType));
                    var constructorStmts      = generatedProperty.ImpliedConstructorStatements(true);
                    constructorStmts.Add(createEmptyCollection);
                    constructorStmts.Add(new CodeAttachEventStatement(fieldRef, "CollectionChanging",
                                                                      GenerateCollectionBubbleHandler(generatedProperty, "CollectionChanging", typeof(NotifyCollectionChangingEventArgs))));
                    constructorStmts.Add(new CodeAttachEventStatement(fieldRef, "CollectionChanged",
                                                                      GenerateCollectionBubbleHandler(generatedProperty, "CollectionChanged", typeof(NotifyCollectionChangedEventArgs))));
                }

                GenerateSerializationAttributes(input, generatedProperty, context);
            }
Example #31
0
            public override void Transform(IClass scope, IReference reference, CodeMemberProperty property, Transformations.Core.ITransformationContext context)
            {
                var baseTypes = Layering <IClass> .CreateLayers(scope, c => c.BaseTypes).Select(c => c.Single()).ToList();

                if (!baseTypes.Contains((IClass)reference.DeclaringType))
                {
                    throw new InvalidOperationException(string.Format("The reference {0} cannot be refined in the scope of class {1} because {1} does not inherit from its declaring class.", reference.Name, scope.Name));
                }

                var classDeclaration  = context.Trace.ResolveIn(Rule <Type2Type>(), scope);
                var originalReference = context.Trace.ResolveIn(Rule <Reference2Property>(), reference);

                property.Attributes = MemberAttributes.Private;
                property.Name       = originalReference.Name;
                property.PrivateImplementationType = CreateReference(reference.DeclaringType, false, context);
                property.Type = originalReference.Type;

                lock (classDeclaration)
                {
                    classDeclaration.Shadows(true).Add(originalReference);
                    classDeclaration.DependentMembers(true).Add(property);
                }

                var implementations = baseTypes.SelectMany(s => s.References).Where(r => r.Refines == reference).ToList();
                var constraints     = baseTypes.SelectMany(s => s.ReferenceConstraints).Where(rc => rc.Constrains == reference);

                foreach (var declClass in implementations.Select(a => a.DeclaringType).OfType <IClass>().Concat(constraints.Select(c => c.DeclaringType)).Distinct())
                {
                    if (declClass != scope)
                    {
                        var refinedReference = context.Trace.ResolveIn(this, declClass, reference);
                        if (refinedReference != null)
                        {
                            property.Shadows(true).Add(refinedReference);
                        }
                    }
                }

                if (implementations.Count == 0 && !constraints.Any())
                {
                    throw new InvalidOperationException(
                              string.Format("The reference {0} can not be refined in the scope of class {1} because no reference refines it. ", reference, scope)
                              );
                }

                var referenceType = CreateReference(reference.Type, true, context);

                if (reference.UpperBound == 1)
                {
                    var nullRef = new CodePrimitiveExpression(null);
                    if (!constraints.Any())
                    {
                        var castedThisVariable    = new CodeVariableDeclarationStatement(classDeclaration.GetReferenceForType(), "_this", new CodeThisReferenceExpression());
                        var castedThisVariableRef = new CodeVariableReferenceExpression("_this");
                        property.GetStatements.Add(castedThisVariable);
                        property.SetStatements.Add(castedThisVariable);
                        var setRef = new CodePropertySetValueReferenceExpression();
                        var ifNull = new CodeConditionStatement();
                        ifNull.Condition = new CodeBinaryOperatorExpression(setRef, CodeBinaryOperatorType.IdentityInequality, nullRef);
                        var foundMatch = false;

                        foreach (var implementation in implementations)
                        {
                            var implementationRef = new CodePropertyReferenceExpression(castedThisVariableRef, context.Trace.ResolveIn(Rule <Reference2Property>(), implementation).Name);

                            if (implementation.Type == reference.Type)
                            {
                                property.GetStatements.Add(new CodeMethodReturnStatement(implementationRef));
                                property.SetStatements.Add(new CodeAssignStatement(implementationRef, setRef));
                                foundMatch = true;
                                break;
                            }
                            else
                            {
                                var getIfStmt = new CodeConditionStatement();
                                getIfStmt.Condition = new CodeBinaryOperatorExpression(implementationRef, CodeBinaryOperatorType.IdentityInequality, nullRef);
                                getIfStmt.TrueStatements.Add(new CodeMethodReturnStatement(implementationRef));
                                property.GetStatements.Add(getIfStmt);

                                var implementationType = CreateReference(implementation.Type, true, context);
                                var asRef       = new CodeMethodReferenceExpression(setRef, "As", implementationType);
                                var localVar    = new CodeVariableDeclarationStatement(implementationType, "__" + implementation.Name, new CodeMethodInvokeExpression(asRef));
                                var localVarRef = new CodeVariableReferenceExpression(localVar.Name);
                                var setIfStmt   = new CodeConditionStatement();
                                setIfStmt.Condition = new CodeBinaryOperatorExpression(localVarRef, CodeBinaryOperatorType.IdentityInequality, nullRef);
                                setIfStmt.TrueStatements.Add(new CodeAssignStatement(implementationRef, localVarRef));
                                setIfStmt.TrueStatements.Add(new CodeMethodReturnStatement());
                                ifNull.TrueStatements.Add(localVar);
                                ifNull.TrueStatements.Add(setIfStmt);
                                ifNull.FalseStatements.Add(new CodeAssignStatement(implementationRef, nullRef));
                            }
                        }
                        ifNull.FalseStatements.Add(new CodeMethodReturnStatement());

                        if (ifNull.TrueStatements.Count > 0)
                        {
                            property.SetStatements.Add(ifNull);
                        }

                        if (!foundMatch)
                        {
                            property.GetStatements.Add(new CodeMethodReturnStatement(nullRef));
                            property.SetStatements.Add(new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(System.ArgumentException), new CodePrimitiveExpression("There was no suitable refining reference found for this object"))));
                        }
                    }
                    else
                    {
                        var constraint   = constraints.Last();
                        var ifNotDefault = new CodeConditionStatement();
                        ifNotDefault.TrueStatements.Add(new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(System.NotSupportedException))));
                        CodeExpression value;
                        if (constraint.References.Count == 0)
                        {
                            value = nullRef;
                        }
                        else
                        {
                            var refEl = constraint.References[0];
                            var uri   = refEl.AbsoluteUri;
                            if (uri == null)
                            {
                                throw new System.InvalidOperationException();
                            }
                            var metaRepositoryInstance = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(MetaRepository)), "Instance");
                            var refElExpression        = new CodeMethodInvokeExpression(metaRepositoryInstance, "Resolve", new CodePrimitiveExpression(uri.AbsoluteUri));
                            refElExpression = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(refElExpression, "As", property.Type));

                            var retrieveValueMethod = new CodeMemberMethod
                            {
                                Name       = "Retrieve" + reference.Name.ToPascalCase(),
                                Attributes = MemberAttributes.Private | MemberAttributes.Static,
                                ReturnType = property.Type
                            };
                            retrieveValueMethod.Statements.Add(new CodeMethodReturnStatement(refElExpression));
                            property.DependentMembers(true).Add(retrieveValueMethod);

                            var staticField = new CodeMemberField(new CodeTypeReference("Lazy", property.Type), "_" + reference.Name.ToPascalCase());
                            staticField.Attributes     = MemberAttributes.Private | MemberAttributes.Static;
                            staticField.InitExpression = new CodeObjectCreateExpression(staticField.Type, new CodeMethodReferenceExpression(null, retrieveValueMethod.Name));
                            property.DependentMembers(true).Add(staticField);
                            value = new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(null, staticField.Name), "Value");
                        }
                        property.GetStatements.Add(new CodeMethodReturnStatement(value));
                        ifNotDefault.Condition = new CodeBinaryOperatorExpression(new CodePropertySetValueReferenceExpression(), CodeBinaryOperatorType.IdentityInequality, value);
                        property.SetStatements.Add(ifNotDefault);
                    }

                    CreateChangeEvent(property, implementations, context, "Changed");
                    CreateChangeEvent(property, implementations, context, "Changing");
                }
                else
                {
                    if (reference.IsUnique)
                    {
                        throw new System.InvalidOperationException("Unique references must not be refined!");
                    }

                    if (implementations.Count > 0 || constraints.Any(c => c.References.Any()))
                    {
                        var collectionType = context.Trace.ResolveIn(Rule <RefinedReferenceCollectionClassGenerator>(), scope, reference);
                        property.GetStatements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression(collectionType.GetReferenceForType(), new CodeThisReferenceExpression())));
                        property.DependentTypes(true).Add(collectionType);
                    }
                    else
                    {
                        property.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(EmptyList <>).Name, referenceType)), "Instance")));
                    }
                }
            }
Example #32
0
    static void Main()
    {
        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.NotPublic
        };

        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 jubjubCtorParam =
            new CodeParameterDeclarationExpression(
                typeof(int), "wabeCount");

        jubjubCtor.Parameters.Add(jubjubCtorParam);

        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,
            Type = new CodeTypeReference(typeof(int)),
            Name = "WabeCount"
        };

        wabeCountProp.GetStatements.Add(
            new CodeMethodReturnStatement(refWabeCountFld));

        var suppliedPropertyValue =
            new CodePropertySetValueReferenceExpression();
        var zero = new CodePrimitiveExpression(0);

        var suppliedPropValIsLessThanZero =
            new CodeBinaryOperatorExpression(
                suppliedPropertyValue,
                CodeBinaryOperatorType.LessThan,
                zero);

        var testSuppliedPropValAndAssign =
            new CodeConditionStatement(
                suppliedPropValIsLessThanZero,
                new CodeStatement[]
        {
            new CodeAssignStatement(
                refWabeCountFld,
                zero)
        },
                new CodeStatement[]
        {
            new CodeAssignStatement(
                refWabeCountFld,
                suppliedPropertyValue)
        });

        wabeCountProp.SetStatements.Add(
            testSuppliedPropValAndAssign);

        jubjubClass.Members.Add(wabeCountProp);

        Console.WriteLine(GenerateCSharpCodeFromNamespace(mimsyNamespace));
        Console.ReadLine();
    }
Example #33
0
        private static void GenerateFilterPropertyMembers(CodeTypeDeclaration genClass, Type entityType)
        {
            foreach (
                PropertyInfo pi in
                entityType.GetInstanceProperties().Where(pi => FilterPropertyTypes.Contains(pi.PropertyType)))
            {
                string fieldName    = string.Format("_Filter{0}", pi.Name);
                string propertyName = string.Format("Filter{0}", pi.Name);
                bool   isValueType  = pi.PropertyType.IsValueType;

                bool isNullable = (pi.PropertyType.IsGenericType &&
                                   pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>));

                string fieldType = isValueType && !isNullable
                                       ? string.Format("System.Nullable<{0}>", pi.PropertyType)
                                       : pi.PropertyType.FullName;

                #region field

                //generate field
                var clsMember = new CodeMemberField
                {
                    Name       = string.Format(fieldName),
                    Attributes = MemberAttributes.Private,
                    Type       = new CodeTypeReference(fieldType)
                };

                genClass.Members.Add(clsMember);

                #endregion

                #region Property

                //generate property getter and setter
                var property = new CodeMemberProperty
                {
                    Name       = string.Format(propertyName),
                    Type       = new CodeTypeReference(fieldType),
                    Attributes = MemberAttributes.Public
                };

                //Add [Display] Attribute
                property.DefineDisplayAttribute(null, true);

                var codeFieldReferenceExpression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                                                                                    fieldName);
                var codePropertySetValueReferenceExpression = new CodePropertySetValueReferenceExpression();

                #region getter

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

                #endregion

                #region setter

                //if (_PropValue == value) return;
                property.SetStatements.Add(
                    new CodeConditionStatement(new CodeBinaryOperatorExpression(codeFieldReferenceExpression,
                                                                                CodeBinaryOperatorType.ValueEquality,
                                                                                codePropertySetValueReferenceExpression),
                                               new CodeMethodReturnStatement()));


                var beforeVariableDeclaration = new CodeVariableDeclarationStatement(typeof(object), "before");
                var beforeVariableReference   = new CodeVariableReferenceExpression("before");

                //object before;
                property.SetStatements.Add(beforeVariableDeclaration);

                //before = _PropValue;
                property.SetStatements.Add(new CodeAssignStatement(beforeVariableReference,
                                                                   codeFieldReferenceExpression));

                //_PropValue = value;
                property.SetStatements.Add(new CodeAssignStatement(codeFieldReferenceExpression,
                                                                   codePropertySetValueReferenceExpression));


                var onPropertyChangedMethodReference =
                    new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "OnPropertyChanged");

                //OnPropertyChanged("PropertyName",before,value)
                property.SetStatements.Add(new CodeMethodInvokeExpression(onPropertyChangedMethodReference,
                                                                          new CodePrimitiveExpression(propertyName),
                                                                          beforeVariableReference,
                                                                          codePropertySetValueReferenceExpression));

                #endregion

                genClass.Members.Add(property);

                #endregion
            }
        }
Example #34
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)));
         }
     }
 }
Example #35
0
 protected abstract void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e);