Ejemplo n.º 1
0
        /// <summary>
        ///    Returns the property descriptors for the described ModelClass domain class, adding tracking property
        ///    descriptor(s).
        /// </summary>
        private PropertyDescriptorCollection GetCustomProperties(Attribute[] attributes)
        {
            // Get the default property descriptors from the base class
            PropertyDescriptorCollection propertyDescriptors = base.GetProperties(attributes);

            //Add the descriptor for the tracking property.
            if (ModelElement is Association association)
            {
                storeDomainDataDirectory = association.Store.DomainDataDirectory;

                // only display roles for 1..1 and 0-1..0-1 associations
                if (((association.SourceMultiplicity != Multiplicity.One || association.TargetMultiplicity != Multiplicity.One) &&
                     (association.SourceMultiplicity != Multiplicity.ZeroOne || association.TargetMultiplicity != Multiplicity.ZeroOne)))
                {
                    PropertyDescriptor sourceRoleTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "SourceRole");
                    propertyDescriptors.Remove(sourceRoleTypeDescriptor);

                    PropertyDescriptor targetRoleTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "TargetRole");
                    propertyDescriptors.Remove(targetRoleTypeDescriptor);
                }

                // only display delete behavior on the principal end
                if (association.SourceRole != EndpointRole.Principal)
                {
                    PropertyDescriptor sourceDeleteActionTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "SourceDeleteAction");
                    propertyDescriptors.Remove(sourceDeleteActionTypeDescriptor);
                }

                if (association.TargetRole != EndpointRole.Principal)
                {
                    PropertyDescriptor targetDeleteActionTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "TargetDeleteAction");
                    propertyDescriptors.Remove(targetDeleteActionTypeDescriptor);
                }

                /********************************************************************************/

                DomainPropertyInfo collectionClassPropertyInfo           = storeDomainDataDirectory.GetDomainProperty(Association.CollectionClassDomainPropertyId);
                DomainPropertyInfo isCollectionClassTrackingPropertyInfo = storeDomainDataDirectory.GetDomainProperty(Association.IsCollectionClassTrackingDomainPropertyId);

                // Define attributes for the tracking property/properties so that the Properties window displays them correctly.
                Attribute[] collectionClassAttributes =
                {
                    new DisplayNameAttribute("Collection Class"),
                    new DescriptionAttribute("Type of collections generated. Overrides the default collection class for the model"),
                    new CategoryAttribute("Code Generation")
                };

                propertyDescriptors.Add(new TrackingPropertyDescriptor(association, collectionClassPropertyInfo, isCollectionClassTrackingPropertyInfo, collectionClassAttributes));
            }

            // Return the property descriptors for this element
            return(propertyDescriptors);
        }
Ejemplo n.º 2
0
        public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
        {
            var Props    = DynamicProperties_.OfType <PropertyDescriptor>();
            var Filtered = Props.Where(x => x.Attributes.Contains(attributes)).ToArray();

            return(new PropertyDescriptorCollection(Filtered));
        }
Ejemplo n.º 3
0
 private void CheckDataPointName(string dataPointName)
 {
     if (!properties.OfType <DPPropertyDescriptor>().Select(p => p.Name).Contains(dataPointName))
     {
         throw new InvalidOperationException(string.Format("ChartDataPoint is not initialized correctly! Unknown data point name: {0}", dataPointName));
     }
 }
Ejemplo n.º 4
0
        public override PropertyDescriptorCollection GetProperties()
        {
            PropertyDescriptorCollection props =
                parentTypeDescriptionProvider.GetTypeDescriptor(instance).GetProperties();

            var assoc            = instance as Association;
            var propsToBeRemoved = new List <string>();

            if (!(assoc.End1Multiplicity == Multiplicity.ZeroMany && assoc.End2Multiplicity == Multiplicity.ZeroMany))
            {
                propsToBeRemoved.AddRange(new[] { "ManyToManyMappingTable", "End1ManyToManyMappingColumn",
                                                  "End1ManyToManyNavigationProperty", "End1ManyToManyFieldName", "End2ManyToManyMappingColumn",
                                                  "End2ManyToManyNavigationProperty", "End2ManyToManyFieldName" });
            }

            foreach (PropertyDescriptor p in props.OfType <PropertyDescriptor>())
            {
                if (propsToBeRemoved.Contains(p.Name))
                {
                    props.Remove(p);
                }
            }

            return(props);
        }
Ejemplo n.º 5
0
        public override PropertyDescriptorCollection GetProperties()
        {
            PropertyDescriptorCollection props =
                parentTypeDescriptionProvider.GetTypeDescriptor(instance).GetProperties();

            try
            {
                var navProp = instance as NavigationProperty;
                var assoc   = navProp.Store.ElementDirectory.FindElements <Association>().First(a => a.Name == navProp.Association);
                var primaryMultiplicities = new[] { Multiplicity.One, Multiplicity.ZeroOne };
                var propsToBeRemoved      = new List <string>();

                if (!(primaryMultiplicities.Any(m => m == assoc.End1Multiplicity) && primaryMultiplicities.Any(m => m == assoc.End2Multiplicity)))
                {
                    propsToBeRemoved.AddRange(new[] { "IsForeignkey", "ForeignkeyColumn" });
                }
                else if (!navProp.IsForeignkey)
                {
                    propsToBeRemoved.Add("ForeignkeyColumn");
                }

                foreach (PropertyDescriptor p in props.OfType <PropertyDescriptor>())
                {
                    if (propsToBeRemoved.Contains(p.Name))
                    {
                        props.Remove(p);
                    }
                }
            }
            catch { }

            return(props);
        }
        public static DataTable ConvertToDataTable <T>(this IEnumerable <T> data, IDictionary <string, string> columnMappings = null)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

            columnMappings = columnMappings ?? properties.OfType <PropertyDescriptor>().ToDictionary(k => k.Name, v => v.Name);

            DataTable table = new DataTable();

            foreach (PropertyDescriptor prop in properties)
            {
                if (columnMappings.ContainsKey(prop.Name))
                {
                    table.Columns.Add(columnMappings[prop.Name], Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
                }
            }

            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                {
                    if (columnMappings.ContainsKey(prop.Name))
                    {
                        string columnName = columnMappings[prop.Name];
                        row[columnName] = prop.GetValue(item) ?? DBNull.Value;
                    }
                }
                table.Rows.Add(row);
            }
            return(table);
        }
Ejemplo n.º 7
0
        private static IEnumerable <PropertyValueVM> FromComponent(PropertyDescriptorCollection collection, object component)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }

            return(FromComponent(collection.OfType <PropertyDescriptor>(), component));
        }
        public static void Remove(this PropertyDescriptorCollection propertyDescriptors, string name)
        {
            PropertyDescriptor propertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == name);

            if (propertyDescriptor != null)
            {
                propertyDescriptors.Remove(propertyDescriptor);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates a collection of property descriptors that contain both this object's property
        /// descriptors as well as exchanged property descriptors for the contained data object.
        /// </summary>
        /// <param name="nativePds">The collection of property descriptors that belong to this
        /// object.</param>
        /// <param name="dataObjectPds">The collection of original property descriptors obtained
        /// from the contained data object.</param>
        /// <returns>A collection of property descriptor objects that represent both the
        /// properties of this object as well as the contained data object.</returns>
        private PropertyDescriptorCollection CreateMergedPropertyDescriptorCollection(PropertyDescriptorCollection nativePds, PropertyDescriptorCollection dataObjectPds)
        {
            PropertyDescriptorCollection pds = new PropertyDescriptorCollection(nativePds.OfType <PropertyDescriptor>().ToArray());

            foreach (PropertyDescriptor pd in dataObjectPds)
            {
                pds.Add(new ContainedDataPropertyDescriptor <TData>(pd));
            }
            return(pds);
        }
Ejemplo n.º 10
0
 private static bool IsSpecialEnumerable(Type t, PropertyDescriptorCollection properties)
 {
     return(properties.OfType <PropertyDescriptor>().Any(p => !_irrelevantEnumerableProperties.Contains(p.Name)) &&
            !typeof(IEnumerator).IsAssignableFrom(t) &&
            !t.IsArray &&
            t.Namespace?.StartsWith("System.Collections", StringComparison.Ordinal) != true &&
            t.Namespace?.StartsWith("System.Linq", StringComparison.Ordinal) != true &&
            t.Name.IndexOf("Collection", StringComparison.Ordinal) < 0 &&
            !t.Name.Equals("JArray", StringComparison.Ordinal));
 }
Ejemplo n.º 11
0
            public AttributeBuilderImplementation(ElementTypeDescriptor descriptor, Attribute[] attributes,
                                                  PropertyDescriptorCollection propertyDescriptors, ModelElement appliedTo)
            {
                this.Element         = appliedTo;
                this.descriptor      = descriptor;
                this.outerAttributes = attributes;

                this.propertyDescriptors = propertyDescriptors;// descriptor.GetProperties(attributes);
                //this.modelElement = descriptor.ModelElement;

                if (this.Element != null)
                {
                    List <PropertyDescriptor> elementPropertyDescriptors =
                        propertyDescriptors.OfType <ElementPropertyDescriptor>().Cast <PropertyDescriptor>().ToList();
                    processingPropertyDescriptors.Add(ProcessPropertyType.Element, elementPropertyDescriptors);

                    List <PropertyDescriptor> rolePlayerPropertyDescriptors =
                        propertyDescriptors.OfType <RolePlayerPropertyDescriptor>().Cast <PropertyDescriptor>().ToList();
                    processingPropertyDescriptors.Add(ProcessPropertyType.RolePlayer, rolePlayerPropertyDescriptors);
                }
            }
Ejemplo n.º 12
0
        /// <summary>
        /// Generates DataTable columns from PropertyDescriptorCollection.
        /// </summary>
        /// <param name="result">DataTable</param>
        /// <param name="properties">PropertyDescriptorCollection</param>
        public static void GenerateDataColumns(this DataTable result, PropertyDescriptorCollection properties)
        {
            Contract.Requires(result != null);
            Contract.Requires(properties != null);

            var columns = properties.OfType <PropertyDescriptor>()
                          .Select(p => new DataColumn(p.Name, p.PropertyType)
            {
                Caption = p.DisplayName
            });

            result.Columns.AddRange(columns.ToArray());
        }
Ejemplo n.º 13
0
        private void lookUpEditSubLinea_Properties_PopupFilter(object sender, DevExpress.XtraEditors.Controls.PopupFilterEventArgs e)
        {
            if (string.IsNullOrEmpty(e.SearchText))
            {
                return;
            }
            LookUpEdit edit = sender as LookUpEdit;
            PropertyDescriptorCollection   propertyDescriptors = ListBindingHelper.GetListItemProperties(edit.Properties.DataSource);
            IEnumerable <FunctionOperator> operators           = propertyDescriptors.OfType <PropertyDescriptor>().Select(
                t => new FunctionOperator(FunctionOperatorType.Contains, new OperandProperty(t.Name), new OperandValue(e.SearchText)));

            e.Criteria = new GroupOperator(GroupOperatorType.Or, operators);
            e.SuppressSearchCriteria = true;
        }
Ejemplo n.º 14
0
        private static void GenerateGridColumns(SPGridView grid, PropertyDescriptorCollection properties)
        {
            Contract.Requires(grid != null);

            grid.Columns.Clear();
            if (properties != null)
            {
                var fields = properties.OfType <PropertyDescriptor>()
                             .Select(p => new SPBoundField
                {
                    DataField      = p.Name,
                    HeaderText     = p.DisplayName,
                    SortExpression = p.Name
                })
                             .ToList();
                fields.ForEach(grid.Columns.Add);
                grid.FilterDataFields = string.Join(",", fields.Select(f => f.DataField).ToArray());
            }
        }
Ejemplo n.º 15
0
 /// <summary>Установка значений словаря в поля объекта (строки, словаря)</summary>
 /// <param name="targetObject">целевой объект (строка, словарь, контейнер контролов)</param>
 /// <param name="pars">словарь значений (ключи соответствуют именам полей объекта)</param>
 public static void SetValues(object targetObject, Dictionary <string, object> pars)
 {
     if (targetObject is DataRow)
     {
         var row = (DataRow)targetObject;
         foreach (var key in pars.Keys)
         {
             if (row.Table.Columns.Contains(key))
             {
                 row[key] = pars[key] ?? DBNull.Value;
             }
         }
     }
     else if (targetObject is IEnumerable <Control> )
     {
         var cpars = (targetObject as IEnumerable <Control>);
         foreach (var key in pars.Keys)
         {
             var par = cpars.FirstOrDefault(x => x.Name.TrimStart('_') == key);
             if (par != null)
             {
                 SetControlValue(par, pars[key]?.ToString());
             }
         }
     }
     else if (targetObject is Dictionary <string, object> )
     {
         ((Dictionary <string, object>)targetObject).AddFromDictionary(pars, false);
     }
     else if (targetObject != null)
     {
         PropertyDescriptorCollection props = TypeDescriptor.GetProperties(targetObject);
         foreach (var key in pars.Keys)
         {
             if (props.OfType <PropertyDescriptor>().Any(x => x.Name == key))
             {
                 props[key].SetValue(targetObject, pars[key]);
             }
         }
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        ///    Returns the property descriptors for the described ModelAttribute domain class, adding tracking property
        ///    descriptor(s).
        /// </summary>
        private PropertyDescriptorCollection GetCustomProperties(Attribute[] attributes)
        {
            ModelAttribute modelAttribute = ModelElement as ModelAttribute;

            // Get the default property descriptors from the base class
            PropertyDescriptorCollection propertyDescriptors = base.GetProperties(attributes);

            if (modelAttribute != null)
            {
                storeDomainDataDirectory = modelAttribute.Store.DomainDataDirectory;

                EFCoreValidator.RemoveHiddenProperties(propertyDescriptors, modelAttribute);

                // dono't display IdentityType unless the IsIdentity is true
                if (!modelAttribute.IsIdentity)
                {
                    PropertyDescriptor identityTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "IdentityType");
                    propertyDescriptors.Remove(identityTypeDescriptor);
                }

                /********************************************************************************/

                DomainPropertyInfo columnNamePropertyInfo           = storeDomainDataDirectory.GetDomainProperty(ModelAttribute.ColumnNameDomainPropertyId);
                DomainPropertyInfo isColumnNameTrackingPropertyInfo = storeDomainDataDirectory.GetDomainProperty(ModelAttribute.IsColumnNameTrackingDomainPropertyId);

                // Define attributes for the tracking property/properties so that the Properties window displays them correctly.
                Attribute[] columnNameAttributes =
                {
                    new DisplayNameAttribute("Column Name"),
                    new DescriptionAttribute("Overrides default column name"),
                    new CategoryAttribute("Database")
                };

                propertyDescriptors.Add(new TrackingPropertyDescriptor(modelAttribute, columnNamePropertyInfo, isColumnNameTrackingPropertyInfo, columnNameAttributes));
            }

            // Return the property descriptors for this element
            return(propertyDescriptors);
        }
Ejemplo n.º 17
0
        public override PropertyDescriptorCollection GetProperties()
        {
            PropertyDescriptorCollection props =
                parentTypeDescriptionProvider.GetTypeDescriptor(instance).GetProperties();

            foreach (PropertyDescriptor p in props.OfType <PropertyDescriptor>())
            {
                switch (p.Name)
                {
                case "IsFixedLength":
                case "IsUnicode":
                case "MaxLength":
                    if ((instance as ModelField).Type != BuiltInTypes.String)
                    {
                        props.Remove(p);
                    }
                    break;
                }
            }

            return(props);
        }
Ejemplo n.º 18
0
        public override PropertyDescriptorCollection GetProperties()
        {
            if (_properties == null)
            {
                // Get properties from our parent
                var originalCollection = base.GetProperties();

                // Set _properties to avoid a stack overflow when CreateProjectionProperties
                // ends up recursively calling TypeDescriptor.GetProperties on a type.
                _properties = originalCollection;

                var customDescriptorsCreated = false;
                var tempPropertyDescriptors  = new List <PropertyDescriptor>();

                // for every property exposed by our parent, see if we have additional metadata to add,
                // and if we do we need to add a wrapper PropertyDescriptor to add the new attributes
                foreach (var propDescriptor in _properties.OfType <PropertyDescriptor>())
                {
                    var newMetadata = GetAdditionalAttributes(propDescriptor);
                    if (newMetadata.Length > 0)
                    {
                        tempPropertyDescriptors.Add(new DataControllerPropertyDescriptor(propDescriptor, newMetadata));
                        customDescriptorsCreated = true;
                    }
                    else
                    {
                        tempPropertyDescriptors.Add(propDescriptor);
                    }
                }

                if (customDescriptorsCreated)
                {
                    _properties = new PropertyDescriptorCollection(tempPropertyDescriptors.ToArray(), true);
                }
            }

            return(_properties);
        }
Ejemplo n.º 19
0
        public void NoExtraPropertiesAdded()
        {
            //Arrange.
            TestClass             data          = new TestClass();
            Container <TestClass> containedData = new Container <TestClass>(data);

            //Act.
            Attribute[] atts = new Attribute[] { new BrowsableAttribute(true) };
            PropertyDescriptorCollection dataProps      = TypeDescriptor.GetProperties(data, atts);
            PropertyDescriptorCollection containedProps = TypeDescriptor.GetProperties(containedData, atts);

            //Assert.
            string reason = null;

            Assert.That(() =>
            {
                bool equal = dataProps.Count == containedProps.Count;
                if (equal)
                {
                    IEqualityComparer <PropertyDescriptor> eqComparer = new PropertyDescriptorEqComparer();
                    foreach (PropertyDescriptor pd in dataProps)
                    {
                        if (!containedProps.OfType <PropertyDescriptor>().Contains(pd, eqComparer))
                        {
                            equal  = false;
                            reason = $"The data object provides a property descriptor for a property named '{pd.Name}' but a corresponding one was not found in the data container.";
                            break;
                        }
                    }
                }
                else
                {
                    reason = $"The data property count is {dataProps.Count} and differs from the container property count, {containedProps.Count}.";
                }
                return(equal);
            }, reason);
        }
Ejemplo n.º 20
0
        public StructureWatcher(Type t)
        {
            if (!(typeof(SerializedEntityBase).IsAssignableFrom(t)))
            {
                throw new InvalidEnumArgumentException("StructureWatcher need SerializableEntityBase!");
            }
            //read structure of type
            PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(t);

            foreach (ChainingPropertyDescriptor pd in pdc.OfType <ChainingPropertyDescriptor>())
            {
                if (pd.Attributes.OfType <model.attributes.MutableAttribute>().ToList().Count > 0)
                {
                    //we have one mutable filed
                    lock (_descriptorsCache) {
                        if (!_descriptorsCache.ContainsKey(pd.Name))
                        {
                            _descriptorsCache[pd.Name] = pd;
                        }
                    }
                }
            }
            _targetType = t;
        }
        /// <summary>
        ///    Returns the property descriptors for the described ModelAttribute domain class, adding tracking property
        ///    descriptor(s).
        /// </summary>
        private PropertyDescriptorCollection GetCustomProperties(Attribute[] attributes)
        {
            // Get the default property descriptors from the base class
            PropertyDescriptorCollection propertyDescriptors = base.GetProperties(attributes);

            if (ModelElement is ModelAttribute modelAttribute)
            {
                storeDomainDataDirectory = modelAttribute.Store.DomainDataDirectory;

                EFCoreValidator.AdjustEFCoreProperties(propertyDescriptors, modelAttribute);

                // No sense asking for initial values if we won't use them
                if (!modelAttribute.SupportsInitialValue)
                {
                    PropertyDescriptor initialValuePropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "InitialValue");

                    if (initialValuePropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(initialValuePropertyDescriptor);
                    }
                }

                // don't display IdentityType unless the IsIdentity is true
                if (!modelAttribute.IsIdentity)
                {
                    PropertyDescriptor identityPropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "IdentityType");

                    if (identityPropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(identityPropertyDescriptor);
                    }
                }

                // ImplementNotify implicitly defines autoproperty as false, so we don't display it
                if (modelAttribute.ModelClass.ImplementNotify)
                {
                    PropertyDescriptor autoPropertyPropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "AutoProperty");

                    if (autoPropertyPropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(autoPropertyPropertyDescriptor);
                    }
                }

                // don't need a persistence point type if it's not persistent
                if (!modelAttribute.Persistent)
                {
                    PropertyDescriptor persistencePointPropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "PersistencePoint");

                    if (persistencePointPropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(persistencePointPropertyDescriptor);
                    }
                }

                /********************************************************************************/

                // don't display String property modifiers unless the type is "String"
                if (modelAttribute.Type != "String")
                {
                    PropertyDescriptor minLengthPropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "MinLength");

                    if (minLengthPropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(minLengthPropertyDescriptor);
                    }

                    PropertyDescriptor maxLengthPropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "MaxLength");

                    if (maxLengthPropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(maxLengthPropertyDescriptor);
                    }

                    PropertyDescriptor stringTypePropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "StringType");

                    if (stringTypePropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(stringTypePropertyDescriptor);
                    }
                }

                /********************************************************************************/

                // don't display IndexedUnique unless the Indexed is true
                if (!modelAttribute.Indexed)
                {
                    PropertyDescriptor indexedUniquePropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "IndexedUnique");

                    if (indexedUniquePropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(indexedUniquePropertyDescriptor);
                    }
                }

                /********************************************************************************/

                //Add the descriptors for the tracking properties

                propertyDescriptors.Add(new TrackingPropertyDescriptor(modelAttribute
                                                                       , storeDomainDataDirectory.GetDomainProperty(ModelAttribute.ColumnNameDomainPropertyId)
                                                                       , storeDomainDataDirectory.GetDomainProperty(ModelAttribute.IsColumnNameTrackingDomainPropertyId)
                                                                       , new Attribute[]
                {
                    new DisplayNameAttribute("Column Name")
                    , new DescriptionAttribute("Overrides default column name")
                    , new CategoryAttribute("Database")
                }));

                propertyDescriptors.Add(new TrackingPropertyDescriptor(modelAttribute
                                                                       , storeDomainDataDirectory.GetDomainProperty(ModelAttribute.ColumnTypeDomainPropertyId)
                                                                       , storeDomainDataDirectory.GetDomainProperty(ModelAttribute.IsColumnTypeTrackingDomainPropertyId)
                                                                       , new Attribute[]
                {
                    new DisplayNameAttribute("Column Type")
                    , new DescriptionAttribute("Overrides default column type")
                    , new CategoryAttribute("Database")
                }));

                propertyDescriptors.Add(new TrackingPropertyDescriptor(modelAttribute
                                                                       , storeDomainDataDirectory.GetDomainProperty(ModelAttribute.AutoPropertyDomainPropertyId)
                                                                       , storeDomainDataDirectory.GetDomainProperty(ModelAttribute.IsAutoPropertyTrackingDomainPropertyId)
                                                                       , new Attribute[]
                {
                    new DisplayNameAttribute("AutoProperty")
                    , new DescriptionAttribute("Overrides default autoproperty setting")
                    , new CategoryAttribute("Code Generation")
                }));

                propertyDescriptors.Add(new TrackingPropertyDescriptor(modelAttribute
                                                                       , storeDomainDataDirectory.GetDomainProperty(ModelAttribute.ImplementNotifyDomainPropertyId)
                                                                       , storeDomainDataDirectory.GetDomainProperty(ModelAttribute.IsImplementNotifyTrackingDomainPropertyId)
                                                                       , new Attribute[]
                {
                    new DisplayNameAttribute("Implement INotifyPropertyChanged")
                    , new DescriptionAttribute("Should this attribute implement INotifyPropertyChanged?")
                    , new CategoryAttribute("Code Generation")
                }));
            }

            // Return the property descriptors for this element
            return(propertyDescriptors);
        }
        /// <summary>
        ///    Returns the property descriptors for the described ModelAttribute domain class, adding tracking property
        ///    descriptor(s).
        /// </summary>
        private PropertyDescriptorCollection GetCustomProperties(Attribute[] attributes)
        {
            // Get the default property descriptors from the base class
            PropertyDescriptorCollection propertyDescriptors = base.GetProperties(attributes);

            if (ModelElement is ModelAttribute modelAttribute)
            {
                storeDomainDataDirectory = modelAttribute.Store.DomainDataDirectory;

                EFCoreValidator.RemoveHiddenProperties(propertyDescriptors, modelAttribute);

                // No sense asking for initial values if we won't use them
                if (!modelAttribute.SupportsInitialValue)
                {
                    PropertyDescriptor initialValueTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "InitialValue");
                    propertyDescriptors.Remove(initialValueTypeDescriptor);
                }

                // don't display IdentityType unless the IsIdentity is true
                if (!modelAttribute.IsIdentity)
                {
                    PropertyDescriptor identityTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "IdentityType");
                    propertyDescriptors.Remove(identityTypeDescriptor);
                }

                // ImplementNotify implicitly defines autoproperty as false, so we don't display it
                if (modelAttribute.ModelClass.ImplementNotify)
                {
                    PropertyDescriptor autoPropertyTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "AutoProperty");
                    propertyDescriptors.Remove(autoPropertyTypeDescriptor);
                }

                /********************************************************************************/

                // don't display String property modifiers unless the type is "String"
                if (modelAttribute.Type != "String")
                {
                    PropertyDescriptor minLengthTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "MinLength");
                    propertyDescriptors.Remove(minLengthTypeDescriptor);

                    PropertyDescriptor maxLengthTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "MaxLength");
                    propertyDescriptors.Remove(maxLengthTypeDescriptor);

                    PropertyDescriptor stringTypeTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "StringType");
                    propertyDescriptors.Remove(stringTypeTypeDescriptor);
                }

                /********************************************************************************/

                // don't display IndexedUnique unless the Indexed is true
                if (!modelAttribute.Indexed)
                {
                    PropertyDescriptor indexedUniqueTypeDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().Single(x => x.Name == "IndexedUnique");
                    propertyDescriptors.Remove(indexedUniqueTypeDescriptor);
                }

                /********************************************************************************/

                DomainPropertyInfo columnNamePropertyInfo           = storeDomainDataDirectory.GetDomainProperty(ModelAttribute.ColumnNameDomainPropertyId);
                DomainPropertyInfo isColumnNameTrackingPropertyInfo = storeDomainDataDirectory.GetDomainProperty(ModelAttribute.IsColumnNameTrackingDomainPropertyId);

                // Define attributes for the tracking property/properties so that the Properties window displays them correctly.
                Attribute[] columnNameAttributes =
                {
                    new DisplayNameAttribute("Column Name"),
                    new DescriptionAttribute("Overrides default column name"),
                    new CategoryAttribute("Database")
                };

                propertyDescriptors.Add(new TrackingPropertyDescriptor(modelAttribute, columnNamePropertyInfo, isColumnNameTrackingPropertyInfo, columnNameAttributes));
            }

            // Return the property descriptors for this element
            return(propertyDescriptors);
        }
Ejemplo n.º 23
0
 private void InitializeColumns(PropertyDescriptorCollection columnDescriptors)
 {
     _columns = columnDescriptors.OfType <PropertyDescriptor>().Select(p => new SimpleColumnProvider(this, p)).OfType <ColumnProvider>().ToList();
 }
        public void InitializeTest()
        {
            _test = new TTestClass();

            // Get dependency properties.
            _propertyAttributes = (from p in typeof(TTestClass).GetProperties()
                                   let attributes = p.GetAttributes <DependencyPropertyAttribute>()
                                                    where attributes.Count() > 0
                                                    select new
            {
                Property = p,
                Attribute = attributes.First()
            }).ToDictionary(p => p.Property, p => p.Attribute);

            // Get all dependency property descriptors, linked to the property enum.
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(_test);

            _propertyDescriptors = (from property in _propertyAttributes
                                    from descriptor in properties.OfType <PropertyDescriptor>()
                                    where property.Key.Name == descriptor.Name
                                    select new
            {
                EnumValue = (Property)property.Value.GetId(),
                Descriptor = descriptor
            }).ToDictionary(p => p.EnumValue, p => p.Descriptor);

            // Verify whether all dependency properties where created.
            Assert.IsTrue(_propertyAttributes.Count == _propertyDescriptors.Count);

            // Verify whether all set values are specified in the dictionary.
            Assert.IsTrue(SetValues.Count == EnumHelper <Property> .GetValues().Count());

            // Get default values from the attributes applied to the properties.
            _initializeValues = _propertyAttributes.ToDictionary(
                p => (Property)p.Value.GetId(),
                p =>
            {
                if (p.Value.DefaultValueProvider == null)
                {
                    return(p.Value.DefaultValue);
                }
                else
                {
                    var provider = (IDefaultValueProvider <Property>)Activator.CreateInstance(p.Value.DefaultValueProvider);
                    return(provider.GetDefaultValue((Property)p.Value.GetId(), p.Key.PropertyType));
                }
            });

            // Create getters and setters for the CLR properties.
            _propertyGetters = _propertyAttributes.ToDictionary(
                p => (Property)p.Value.GetId(),
                p => p.Key.GetGetMethod().CreateDelegate <Func <object> >(_test, DelegateHelper.CreateOptions.Downcasting));
            _propertySetters = _propertyAttributes
                               .Where(p => p.Key.GetSetMethod() != null)
                               .ToDictionary(
                p => (Property)p.Value.GetId(),
                p => p.Key.GetSetMethod().CreateDelegate <Action <object> >(_test, DelegateHelper.CreateOptions.Downcasting));

            // Verify whether correct amount of read only properties where created.
            Assert.IsTrue(_propertySetters.Count == _propertyDescriptors.Where(d => !d.Value.IsReadOnly).Count());
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Creates a property source for the specified CLR object using reflection.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="name">The name for the property source.</param>
        /// <param name="typeName">The type name of the property source.</param>
        /// <returns>The property source.</returns>
        /// <remarks>
        /// <para>
        /// This method can be used for static types and dynamic types that implement
        /// <see cref="ICustomTypeDescriptor"/>. The property source lists instance properties.
        /// Properties where the <see cref="BrowsableAttribute"/> is set to <see langword="false"/>
        /// are ignored.
        /// </para>
        /// <para>
        /// To find the name of the property source the method uses (in this order):
        /// </para>
        /// <list type="number">
        /// <item>The <paramref name="name"/> parameter.</item>
        /// <item>The <see cref="INamedObject"/> interface.</item>
        /// <item>A string property called "Name".</item>
        /// </list>
        /// <para>
        /// To find the type name of the property source the method uses (in this order):
        /// </para>
        /// <list type="number">
        /// <item>The <paramref name="typeName"/> parameter.</item>
        /// <item>The CLR type name.</item>
        /// </list>
        /// <para>
        /// The <paramref name="instance"/> is stored in the <see cref="PropertySource.UserData"/>
        /// of the <see cref="PropertySource"/>.
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instance"/> is <see langword="null"/>.
        /// </exception>
        public static PropertySource CreatePropertySource(object instance, string name = null, string typeName = null)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            var propertySource = new PropertySource {
                UserData = instance
            };

            // Get property descriptors.
            var typeConverter = TypeDescriptor.GetConverter(instance);
            PropertyDescriptorCollection propertyDescriptors = null;

            if (typeConverter != null && typeConverter.GetPropertiesSupported())
            {
                // Try to get properties from type converter.
                propertyDescriptors = typeConverter.GetProperties(instance);
            }

            if (propertyDescriptors == null && instance is ICustomTypeDescriptor)
            {
                // Instance is a dynamic object.
                propertyDescriptors = ((ICustomTypeDescriptor)instance).GetProperties();
            }

            bool isBasicObject = false;

            if (propertyDescriptors == null)
            {
                // Instance is a regular CLR object.
                isBasicObject       = true;
                propertyDescriptors = TypeDescriptor.GetProperties(instance.GetType());
            }

            // Create a list of all properties.
            propertySource.Properties.AddRange(
                propertyDescriptors.OfType <PropertyDescriptor>()
                .Where(descriptor => descriptor.IsBrowsable)
                .Select(descriptor => new ReflectedProperty(instance, descriptor))
                .OrderBy(p => p, PropertyComparer.Instance));

            // Add public fields of regular CLR objects (very important for structs like Vector3).
            if (isBasicObject)
            {
                foreach (var field in instance.GetType().GetFields())
                {
                    if (!field.IsLiteral && !field.IsStatic)
                    {
                        propertySource.Properties.Add(new ReflectedField(instance, field));
                    }
                }
            }

            // Add items of an IEnumerable.
            var enumerable = instance as IEnumerable;

            if (enumerable != null)
            {
                int index = 0;
                foreach (var item in enumerable)
                {
                    string itemName  = "Item[" + index + "]";
                    var    namedItem = item as INamedObject;
                    if (namedItem != null)
                    {
                        itemName = Invariant($"{itemName}: {namedItem.Name}");
                    }

                    propertySource.Properties.Add(new CustomProperty(itemName, item)
                    {
                        Category   = "Items",
                        IsReadOnly = true
                    });
                    index++;
                }
            }

            // ----- Set name:
            // 1. Try name parameter.
            propertySource.Name = name;

            // 2. Try INamedObject interface.
            if (propertySource.Name == null)
            {
                var namedObject = instance as INamedObject;
                if (namedObject != null)
                {
                    propertySource.Name = namedObject.Name;
                }
            }

            // 3. Try "Name" property.
            if (propertySource.Name == null)
            {
                var namePropertyDescriptor =
                    propertyDescriptors.OfType <PropertyDescriptor>()
                    .FirstOrDefault(d => d.Name == "Name" && d.PropertyType == typeof(string));

                if (namePropertyDescriptor != null)
                {
                    propertySource.Name = (string)namePropertyDescriptor.GetValue(instance);
                }
            }

            // Fallback: Empty string.
            if (propertySource.Name == null)
            {
                propertySource.Name = string.Empty;
            }

            // Set type name.
            propertySource.TypeName = typeName;
            if (propertySource.TypeName == null)
            {
                propertySource.TypeName = instance.GetType().Name;
            }

            return(propertySource);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Returns an <see cref="IEnumerable{T}"/> of <see cref="IDataValue"/> for
        /// the specified <see cref="ReflectedDataDefinition"/>
        /// </summary>
        /// <param name="dataDefinition"></param>
        /// <returns></returns>
        public virtual IEnumerable <IDataValue> Evaluate(ReflectedDataDefinition dataDefinition)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(dataDefinition.Data);

            return(properties.OfType <PropertyDescriptor>().Select(property => GetDataValue(property, dataDefinition.Data)));
        }
        /// <summary>
        ///    Returns the property descriptors for the described ModelClass domain class, adding tracking property
        ///    descriptor(s).
        /// </summary>
        private PropertyDescriptorCollection GetCustomProperties(Attribute[] attributes)
        {
            // Get the default property descriptors from the base class
            PropertyDescriptorCollection propertyDescriptors = base.GetProperties(attributes);

            //Add the descriptor for the tracking property.
            if (ModelElement is Association association)
            {
                storeDomainDataDirectory = association.Store.DomainDataDirectory;

                EFCoreValidator.AdjustEFCoreProperties(propertyDescriptors, association);

                // ImplementNotify implicitly defines autoproperty as false, so we don't display it
                // Similarly, collections are autoproperty == true, so no need to display it then either
                if ((association.Target.ImplementNotify || association.SourceMultiplicity == Multiplicity.ZeroMany) && association is BidirectionalAssociation)
                {
                    PropertyDescriptor sourceAutoPropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "SourceAutoProperty");
                    if (sourceAutoPropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(sourceAutoPropertyDescriptor);
                    }
                }

                if (association.Source.ImplementNotify || association.TargetMultiplicity == Multiplicity.ZeroMany)
                {
                    PropertyDescriptor targetAutoPropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "TargetAutoProperty");
                    if (targetAutoPropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(targetAutoPropertyDescriptor);
                    }
                }

                // only display roles for 1..1 and 0-1..0-1 associations
                if (((association.SourceMultiplicity != Multiplicity.One || association.TargetMultiplicity != Multiplicity.One) &&
                     (association.SourceMultiplicity != Multiplicity.ZeroOne || association.TargetMultiplicity != Multiplicity.ZeroOne)))
                {
                    PropertyDescriptor sourceRolePropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "SourceRole");
                    if (sourceRolePropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(sourceRolePropertyDescriptor);
                    }

                    PropertyDescriptor targetRolePropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "TargetRole");
                    if (targetRolePropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(targetRolePropertyDescriptor);
                    }
                }

                // only display delete behavior on the principal end
                if (association.SourceRole != EndpointRole.Principal)
                {
                    PropertyDescriptor sourceDeleteActionPropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "SourceDeleteAction");
                    if (sourceDeleteActionPropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(sourceDeleteActionPropertyDescriptor);
                    }
                }

                if (association.TargetRole != EndpointRole.Principal)
                {
                    PropertyDescriptor targetDeleteActionPropertyDescriptor = propertyDescriptors.OfType <PropertyDescriptor>().SingleOrDefault(x => x.Name == "TargetDeleteAction");
                    if (targetDeleteActionPropertyDescriptor != null)
                    {
                        propertyDescriptors.Remove(targetDeleteActionPropertyDescriptor);
                    }
                }

                /********************************************************************************/

                DomainPropertyInfo collectionClassPropertyInfo           = storeDomainDataDirectory.GetDomainProperty(Association.CollectionClassDomainPropertyId);
                DomainPropertyInfo isCollectionClassTrackingPropertyInfo = storeDomainDataDirectory.GetDomainProperty(Association.IsCollectionClassTrackingDomainPropertyId);

                // Define attributes for the tracking property/properties so that the Properties window displays them correctly.
                Attribute[] collectionClassAttributes =
                {
                    new DisplayNameAttribute("Collection Class"),
                    new DescriptionAttribute("Type of collections generated. Overrides the default collection class for the model"),
                    new CategoryAttribute("Code Generation")
                };

                propertyDescriptors.Add(new TrackingPropertyDescriptor(association, collectionClassPropertyInfo, isCollectionClassTrackingPropertyInfo, collectionClassAttributes));
            }

            // Return the property descriptors for this element
            return(propertyDescriptors);
        }