private static void AddBooleanProperty(string propertyName, bool value, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { PropertyDescriptor<bool> propertyDescriptor = propertyDescriptors[propertyName] as PropertyDescriptor<bool>; if (propertyDescriptor != null) { properties.Add(new BooleanProperty(propertyDescriptor, value)); } }
public void can_get_a_property_by_its_id() { var property0 = PropertyDescriptor.For(typeof(DecoratedType).GetProperty("Property0")); var property1 = PropertyDescriptor.For(typeof(DecoratedType).GetProperty("Property1")); var collection = new PropertyDescriptorCollection(new[] { property0, property1 }); Assert.Equal(property0, collection.GetById(0)); Assert.Equal(property1, collection.GetById(1)); }
public void AddTests() { var collection = new PropertyDescriptorCollection(null); for (var i = 0; i < 100; i++) { Assert.Equal(i, collection.Add(new MockPropertyDescriptor($"name{i}"))); Assert.Equal(i + 1, collection.Count); } }
public void ReadOnlyThrows() { var collection = new PropertyDescriptorCollection(null, true); // The readonly check occurs before anything else, so we don't need to pass in actual valid values Assert.Throws<NotSupportedException>(() => collection.Add(null)); Assert.Throws<NotSupportedException>(() => collection.Insert(1, null)); Assert.Throws<NotSupportedException>(() => collection.RemoveAt(1)); Assert.Throws<NotSupportedException>(() => collection.Remove(null)); Assert.Throws<NotSupportedException>(() => collection.Clear()); }
public void can_create() { var property0 = PropertyDescriptor.For(typeof(DecoratedType).GetProperty("Property0")); var property1 = PropertyDescriptor.For(typeof(DecoratedType).GetProperty("Property1")); var collection = new PropertyDescriptorCollection(new[] { property0, property1 }); Assert.True(collection.Contains(property0)); Assert.True(collection.Contains(property1)); Assert.Equal(2, collection.Count); Assert.Equal(0, collection.IndexOf(property0)); Assert.Equal(1, collection.IndexOf(property1)); }
public void collection_cannot_be_mutated() { var property0 = PropertyDescriptor.For(typeof(DecoratedType).GetProperty("Property0")); var property1 = PropertyDescriptor.For(typeof(DecoratedType).GetProperty("Property1")); IList<PropertyDescriptor> collection = new PropertyDescriptorCollection(new[] { property0, property1 }); Assert.Throws<NotSupportedException>(() => collection.Add(property1)); Assert.Throws<NotSupportedException>(() => collection.Clear()); Assert.Throws<NotSupportedException>(() => collection.Insert(0, property1)); Assert.Throws<NotSupportedException>(() => collection.Remove(property0)); Assert.Throws<NotSupportedException>(() => collection.RemoveAt(0)); }
private static void LoadBooleanProperty(string propertyName, XmlNode propertyNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { bool flag; if (bool.TryParse(propertyNode.InnerText, out flag)) { PropertyDescriptor<bool> propertyDescriptor = propertyDescriptors[propertyName] as PropertyDescriptor<bool>; if (propertyDescriptor != null) { properties.Add(new BooleanProperty(propertyDescriptor, flag)); } } }
private static void AddOrUpdateLegacyBooleanProperty(string ruleName, bool value, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { string propertyName = ruleName + "#Enabled"; BooleanProperty property = properties[propertyName] as BooleanProperty; if (property == null) { AddBooleanProperty(propertyName, value, properties, propertyDescriptors); } else if (!value) { property.Value = false; } }
public void ConstructorReadOnlyTests() { var descriptors = new PropertyDescriptor[] { new MockPropertyDescriptor("descriptor1") }; var collection = new PropertyDescriptorCollection(descriptors, true); Assert.Equal(descriptors.Cast<PropertyDescriptor>(), collection.Cast<PropertyDescriptor>()); // These methods are implemented as explicit properties so we need to ensure they are what we expect Assert.True(((IDictionary)collection).IsReadOnly); Assert.True(((IDictionary)collection).IsFixedSize); Assert.True(((IList)collection).IsReadOnly); Assert.True(((IList)collection).IsFixedSize); }
private static void LoadCollectionProperty(string propertyName, XmlNode propertyNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { List<string> innerCollection = new List<string>(); XmlNodeList list2 = propertyNode.SelectNodes("Value"); if ((list2 != null) && (list2.Count > 0)) { foreach (XmlNode node in list2) { if (!string.IsNullOrEmpty(node.InnerText)) { innerCollection.Add(node.InnerText); } } } if (innerCollection.Count > 0) { CollectionPropertyDescriptor propertyDescriptor = propertyDescriptors[propertyName] as CollectionPropertyDescriptor; if (propertyDescriptor != null) { CollectionProperty property = new CollectionProperty(propertyDescriptor, innerCollection); properties.Add(property); } } }
private PropertyDescriptorCollection GetPropertiesWithMetadata(PropertyDescriptorCollection originalCollection) { if (AssociatedMetadataType == null) { return originalCollection; } bool customDescriptorsCreated = false; List<PropertyDescriptor> tempPropertyDescriptors = new List<PropertyDescriptor>(); foreach (PropertyDescriptor propDescriptor in originalCollection) { Attribute[] newMetadata = TypeDescriptorCache.GetAssociatedMetadata(AssociatedMetadataType, propDescriptor.Name); PropertyDescriptor descriptor = propDescriptor; if (newMetadata.Length > 0) { // Create a metadata descriptor that wraps the property descriptor descriptor = new MetadataPropertyDescriptorWrapper(propDescriptor, newMetadata); customDescriptorsCreated = true; } tempPropertyDescriptors.Add(descriptor); } if (customDescriptorsCreated) { return new PropertyDescriptorCollection(tempPropertyDescriptors.ToArray(), true); } return originalCollection; }
private void AddCustomDataTableStyle() { DataGridTableStyle ts1 = new DataGridTableStyle(); ts1.MappingName = "Customers"; // Set other properties. ts1.AlternatingBackColor = Color.LightGray; /* Add a GridColumnStyle and set its MappingName * to the name of a DataColumn in the DataTable. * Set the HeaderText and Width properties. */ DataGridColumnStyle boolCol = new DataGridBoolColumn(); boolCol.MappingName = "Current"; boolCol.HeaderText = "IsCurrent Customer"; boolCol.Width = 150; ts1.GridColumnStyles.Add(boolCol); // Add a second column style. DataGridColumnStyle TextCol = new DataGridTextBoxColumn(); TextCol.MappingName = "custName"; TextCol.HeaderText = "Customer Name"; TextCol.Width = 250; ts1.GridColumnStyles.Add(TextCol); // Create the second table style with columns. DataGridTableStyle ts2 = new DataGridTableStyle(); ts2.MappingName = "Orders"; // Set other properties. ts2.AlternatingBackColor = Color.LightBlue; // Create new ColumnStyle objects DataGridColumnStyle cOrderDate = new DataGridTextBoxColumn(); cOrderDate.MappingName = "OrderDate"; cOrderDate.HeaderText = "Order Date"; cOrderDate.Width = 100; ts2.GridColumnStyles.Add(cOrderDate); /* Use a PropertyDescriptor to create a formatted * column. First get the PropertyDescriptorCollection * for the data source and data member. */ PropertyDescriptorCollection pcol = this.BindingContext [myDataSet, "Customers.custToOrders"].GetItemProperties(); /* Create a formatted column using a PropertyDescriptor. * The formatting character "c" specifies a currency format. */ DataGridColumnStyle csOrderAmount = new DataGridTextBoxColumn(pcol["OrderAmount"], "c", true); csOrderAmount.MappingName = "OrderAmount"; csOrderAmount.HeaderText = "Total"; csOrderAmount.Width = 100; ts2.GridColumnStyles.Add(csOrderAmount); /* Add the DataGridTableStyle instances to * the GridTableStylesCollection. */ myDataGrid.TableStyles.Add(ts1); myDataGrid.TableStyles.Add(ts2); // Sets the TablesAlreadyAdded to true so this doesn't happen again. TablesAlreadyAdded = true; }
/// <summary> /// Loads a property collection from the settings file. /// </summary> /// <param name="propertyCollectionNode"> /// The node containing the property collection. /// </param> /// <param name="properties"> /// The property collection storage object. /// </param> /// <param name="propertyDescriptors"> /// The collection of property descriptors. /// </param> /// <param name="ruleName"> /// An optional rule name to prepend the each property name. /// </param> private static void LoadPropertyCollection( XmlNode propertyCollectionNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors, string ruleName) { Param.AssertNotNull(propertyCollectionNode, "settingsNode"); Param.AssertNotNull(properties, "properties"); Param.AssertNotNull(propertyDescriptors, "propertyDescriptors"); Param.Ignore(ruleName); foreach (XmlNode propertyNode in propertyCollectionNode.ChildNodes) { PropertyType type = DeterminePropertyNodeType(propertyNode.Name); if (type != PropertyType.None) { // Get the property name. XmlAttribute propertyName = propertyNode.Attributes["Name"]; if (propertyName != null && !string.IsNullOrEmpty(propertyName.Value)) { // Prepend the rule name to the property name if necessary. string adjustedPropertyName = propertyName.InnerText; if (!string.IsNullOrEmpty(ruleName)) { adjustedPropertyName = ruleName + "#" + propertyName.InnerText; } // Load the property. switch (type) { case PropertyType.Boolean: LoadBooleanProperty(adjustedPropertyName, propertyNode, properties, propertyDescriptors); break; case PropertyType.Integer: LoadIntProperty(adjustedPropertyName, propertyNode, properties, propertyDescriptors); break; case PropertyType.String: LoadStringProperty(adjustedPropertyName, propertyNode, properties, propertyDescriptors); break; case PropertyType.Collection: LoadCollectionProperty(adjustedPropertyName, propertyNode, properties, propertyDescriptors); break; default: // Ignore any unexpected settings. break; } } } } }
/// <summary> /// Fills the specified table by reading data from the configuration database. /// </summary> public void Fill(IBaseTable baseTable) { if (baseTable == null) { throw new ArgumentNullException(nameof(baseTable)); } Stream stream; BinaryReader reader = null; try { stream = Stream ?? new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); reader = new BinaryReader(stream, Encoding.UTF8, Stream != null); // prepare table baseTable.ClearItems(); baseTable.IndexesEnabled = false; // read header byte[] buffer = new byte[Math.Max(HeaderSize, FieldDefSize)]; if (!ReadHeader(reader, buffer, out int fieldCount)) { return; } // read field definitions FieldDef[] fieldDefs = ReadFieldDefs(reader, buffer, fieldCount); // map the field definitions and entity properties PropertyDescriptorCollection allProps = TypeDescriptor.GetProperties(baseTable.ItemType); PropertyDescriptor[] props = new PropertyDescriptor[fieldCount]; for (int i = 0; i < fieldCount; i++) { props[i] = allProps[fieldDefs[i].Name]; } // read rows while (true) { // read row data ReadRowToBuffer(reader, ref buffer); // read fields object item = baseTable.NewItem(); int index = 6; for (int i = 0; i < fieldCount; i++) { FieldDef fieldDef = fieldDefs[i]; PropertyDescriptor prop = props[i]; object value = GetFieldValueIfExists(fieldDef, buffer, ref index); if (prop != null) { prop.SetValue(item, value ?? (fieldDef.AllowNull ? null : fieldDef.DefaultValue)); } } baseTable.AddObject(item); } } catch (EndOfStreamException) { // normal file ending case } finally { reader?.Close(); baseTable.IndexesEnabled = true; } }
public void Find(string name, bool ignoreCase, bool exists) { const int LoopCount = 100; var propertyDescriptors = new PropertyDescriptor[] { new MockPropertyDescriptor("propertyDescriptor1"), new MockPropertyDescriptor("propertyDescriptor2"), new MockPropertyDescriptor("propertyDescriptor3"), new MockPropertyDescriptor("propertyDescriptor4"), new MockPropertyDescriptor("propertyDescriptor5"), new MockPropertyDescriptor("propertyDescriptor6"), new MockPropertyDescriptor("propertyDescriptor7"), new MockPropertyDescriptor("propertyDescriptor8"), new MockPropertyDescriptor("propertyDescriptor9") }; // Loop through as there is caching that occurs for (int count = 0; count < LoopCount; count++) { var collection = new PropertyDescriptorCollection(propertyDescriptors); var result = collection.Find(name, ignoreCase); if (exists) { Assert.NotNull(result); PropertyDescriptor expected = propertyDescriptors .First(p => string.Equals(p.Name, name, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)); Assert.Equal(expected, result); } else { Assert.Null(result); } } }
private static void LoadRulesSettings(XmlNode addInNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { XmlNode node = addInNode["Rules"]; if (node != null) { foreach (XmlNode node2 in node.ChildNodes) { if (string.Equals(node2.Name, "Rule", StringComparison.Ordinal)) { XmlAttribute attribute = node2.Attributes["Name"]; if ((attribute != null) && !string.IsNullOrEmpty(attribute.Value)) { string legacyAnalyzerId = attribute.Value; XmlNode propertyCollectionNode = node2["RuleSettings"]; if (propertyCollectionNode != null) { LoadPropertyCollection(propertyCollectionNode, properties, propertyDescriptors, legacyAnalyzerId); } } } } } }
protected virtual void FilterProperties(PropertyDescriptorCollection globalizedProps) { }
// This method may be called concurrently, by both the ReduceTask (for removal) // and by the ReducingExecuter (for add/modify). This is okay with us, since the // Write() call is already handling locking properly public void ReduceDocuments(AbstractViewGenerator viewGenerator, IEnumerable <object> mappedResults, WorkContext context, IStorageActionsAccessor actions, string[] reduceKeys) { var count = 0; Write(context, (indexWriter, analyzer) => { actions.Indexing.SetCurrentIndexStatsTo(name); var batchers = context.IndexUpdateTriggers.Select(x => x.CreateBatcher(name)) .Where(x => x != null) .ToList(); foreach (var reduceKey in reduceKeys) { var entryKey = reduceKey; indexWriter.DeleteDocuments(new Term(Raven.Abstractions.Data.Constants.ReduceKeyFieldName, entryKey.ToLowerInvariant())); batchers.ApplyAndIgnoreAllErrors( exception => { logIndexing.WarnFormat(exception, "Error when executed OnIndexEntryDeleted trigger for index '{0}', key: '{1}'", name, entryKey); context.AddError(name, entryKey, exception.Message ); }, trigger => trigger.OnIndexEntryDeleted(name, entryKey)); } PropertyDescriptorCollection properties = null; foreach (var doc in RobustEnumerationReduce(mappedResults, viewGenerator.ReduceDefinition, actions, context)) { count++; var fields = GetFields(doc, ref properties).ToList(); string reduceKeyAsString = ExtractReduceKey(viewGenerator, doc); var luceneDoc = new Document(); luceneDoc.Add(new Field(Raven.Abstractions.Data.Constants.ReduceKeyFieldName, reduceKeyAsString.ToLowerInvariant(), Field.Store.NO, Field.Index.NOT_ANALYZED)); foreach (var field in fields) { luceneDoc.Add(field); } batchers.ApplyAndIgnoreAllErrors( exception => { logIndexing.WarnFormat(exception, "Error when executed OnIndexEntryCreated trigger for index '{0}', key: '{1}'", name, reduceKeyAsString); context.AddError(name, reduceKeyAsString, exception.Message ); }, trigger => trigger.OnIndexEntryCreated(name, reduceKeyAsString, luceneDoc)); logIndexing.DebugFormat("Reduce key {0} result in index {1} gave document: {2}", reduceKeyAsString, name, luceneDoc); AddDocumentToIndex(indexWriter, luceneDoc, analyzer); actions.Indexing.IncrementReduceSuccessIndexing(); } batchers.ApplyAndIgnoreAllErrors( e => { logIndexing.Warn("Failed to dispose on index update trigger", e); context.AddError(name, null, e.Message); }, x => x.Dispose()); return(true); }); if (logIndexing.IsDebugEnabled) { logIndexing.DebugFormat("Reduce resulted in {0} entries for {1} for reduce keys: {2}", count, name, string.Join(", ", reduceKeys)); } }
public void Constructor_Always_PropertiesHaveExpectedAttributeValues() { // Call var properties = new ClosingStructuresFailureMechanismProperties(new ClosingStructuresFailureMechanism()); // Assert const string generalCategory = "Algemeen"; const string modelSettingsCategory = "Modelinstellingen"; PropertyDescriptorCollection dynamicProperties = PropertiesTestHelper.GetAllVisiblePropertyDescriptors(properties); Assert.AreEqual(7, dynamicProperties.Count); PropertyDescriptor nameProperty = dynamicProperties[namePropertyIndex]; PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties(nameProperty, generalCategory, "Naam", "De naam van het faalmechanisme.", true); PropertyDescriptor codeProperty = dynamicProperties[codePropertyIndex]; PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties(codeProperty, generalCategory, "Label", "Het label van het faalmechanisme.", true); PropertyDescriptor gravitationalAccelerationProperty = dynamicProperties[gravitationalAccelerationPropertyIndex]; PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties(gravitationalAccelerationProperty, generalCategory, "Valversnelling [m/s²]", "Valversnelling.", true); PropertyDescriptor modelFactorOvertoppingFlowProperty = dynamicProperties[modelFactorOvertoppingFlowPropertyIndex]; Assert.IsInstanceOf <ExpandableObjectConverter>(modelFactorOvertoppingFlowProperty.Converter); PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties(modelFactorOvertoppingFlowProperty, modelSettingsCategory, "Modelfactor overslagdebiet [-]", "Modelfactor voor het overslagdebiet.", true); PropertyDescriptor modelFactorStorageVolumeProperty = dynamicProperties[modelFactorStorageVolumePropertyIndex]; Assert.IsInstanceOf <ExpandableObjectConverter>(modelFactorStorageVolumeProperty.Converter); PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties(modelFactorStorageVolumeProperty, modelSettingsCategory, "Modelfactor kombergend vermogen [-]", "Modelfactor kombergend vermogen.", true); PropertyDescriptor modelFactorLongThresholdProperty = dynamicProperties[modelFactorLongThresholdPropertyIndex]; Assert.IsInstanceOf <ExpandableObjectConverter>(modelFactorLongThresholdProperty.Converter); PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties(modelFactorLongThresholdProperty, modelSettingsCategory, "Modelfactor lange overlaat [-]", "Modelfactor voor een lange overlaat.", true); PropertyDescriptor modelFactorInflowVolumeProperty = dynamicProperties[modelFactorInflowVolumePropertyIndex]; PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties(modelFactorInflowVolumeProperty, modelSettingsCategory, "Modelfactor instromend volume [-]", "Modelfactor instromend volume.", true); }
private DataTable ObtainDataTableFromIEnumerable(IEnumerable ien) { try { //Referencing "column" variable DataColumn column = null; //Creating a list of "DataColumn" to hold the primary key columns of the table List <DataColumn> keys = new List <DataColumn>(); IEnumerable tempien = (IEnumerable)HttpContext.Current.Session[SessionVarName]; Type actualType = tempien.GetType(); if (actualType == typeof(Object)) { throw new System.ArgumentException("Object is not a CustomList<T> or List<T> instance.", "Obj"); } Type itemType = actualType.GetGenericArguments()[0]; //PropertyInfo[] properties = itemType.GetProperties(); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(itemType); DataTable table = new DataTable(); foreach (PropertyDescriptor info in properties) { if (info.IsBrowsable.IsFalse() && info.Name.NotEquals("VID")) { continue; } Type propertyType = info.PropertyType; CustomAttributes.FormatString attribs = (CustomAttributes.FormatString)info.Attributes[typeof(CustomAttributes.FormatString)]; //Getting "IsPrimary" custom attribute of the property //Object[] attribs = info.GetCustomAttributes(typeof(CustomAttributes.IsPrimaryAttribute), false); //Getting "FormatString" custom attribute of the property //Object[] attribs = info.GetCustomAttributes(typeof(CustomAttributes.FormatString), false); if (propertyType.IsGenericType && (propertyType.GetGenericTypeDefinition() == typeof(Nullable <>))) { propertyType = Nullable.GetUnderlyingType(propertyType); } //Line commented //table.Columns.Add(info.Name, propertyType); //Creating a new column and adding it to the table column = new DataColumn(info.Name, propertyType); table.Columns.Add(column); //If "IsPrimary" custom attribute of the property is true, then adding the column to the "keys" list //if ((attribs.Length > 0) && ((CustomAttributes.IsPrimaryAttribute)attribs[0]).IsPrimary) //{ // keys.Add(column); //} //If "FormatString" custom attribute of the property is true, then adding the column to the "Expression" if ((attribs.IsNotNull()) && attribs.Format.IsNotNullOrEmpty()) { column.ExtendedProperties.Add("DateFormat", attribs.Format); } } foreach (Object obj2 in ien) { if (((BaseItem)obj2).IsDeleted) { continue; } DataRow row = table.NewRow(); foreach (PropertyDescriptor info2 in properties) { if (info2.IsBrowsable.IsFalse() && info2.Name.NotEquals("VID")) { continue; } Object obj3 = info2.GetValue(obj2); if (obj3.IsNotNull()) { if (info2.PropertyType == typeof(DateTime)) { row[info2.Name] = obj3.Equals(DateTime.MinValue) ? DBNull.Value : obj3; } else { row[info2.Name] = obj3; } } else { row[info2.Name] = DBNull.Value; } } table.Rows.Add(row); } try { //Setting Primary Key of the table table.PrimaryKey = keys.ToArray(); } catch (Exception ex) { throw ex; } return(table); } catch (Exception ex) { throw ex; } }
public void SetCurrentObject(IEnumerable <object> obj, bool isEnable = true, bool isRootNode = false, string rootType = "") { this.isRootNode = isRootNode; this.currentObject = (object)obj; if (this._property != null) { foreach (PropertyItem propertyItem in this._property) { if (propertyItem != null && propertyItem.TypeEditor != null) { propertyItem.TypeEditor.EditorDispose(); } } } foreach (Widget child in this.container.Children) { this.container.Remove(child); } foreach (Widget child in this._propertyTable.Children) { this._propertyTable.Remove(child); } if (this._property == null) { this._property = new List <PropertyItem>(); } this._property.Clear(); if (obj == null) { return; } List <object> source = new List <object>(); foreach (object obj1 in obj) { object item = obj1; if (source.FirstOrDefault <object>((Func <object, bool>)(w => w.GetType().Name == item.GetType().Name)) == null) { source.Add(item); } } if (source.Count <object>() == 0) { return; } PropertyDescriptorCollection propertyDescriptors1 = PropertyGridUtilities.GetPropertyDescriptors(this.currentObject = source[0]); List <PropertyDescriptor> propertyDescriptorList = new List <PropertyDescriptor>(); foreach (PropertyDescriptor propertyDescriptor in propertyDescriptors1) { propertyDescriptorList.Add(propertyDescriptor); } for (int index1 = 1; index1 <= source.Count - 1; ++index1) { PropertyDescriptorCollection propertyDescriptors2 = PropertyGridUtilities.GetPropertyDescriptors(source[index1]); for (int index2 = propertyDescriptorList.Count - 1; index2 >= 0; --index2) { PropertyDescriptor propertyDescriptor1 = propertyDescriptorList[index2]; if (!propertyDescriptors2.Contains(propertyDescriptor1)) { propertyDescriptorList.RemoveAt(index2); } else { PropertyDescriptor propertyDescriptor2 = propertyDescriptors2.Find(propertyDescriptor1.Name, true); if (propertyDescriptor2 != null && (propertyDescriptor2.Attributes.OfType <BrowsableAttribute>().FirstOrDefault <BrowsableAttribute>() == null || !propertyDescriptor2.Attributes.OfType <BrowsableAttribute>().FirstOrDefault <BrowsableAttribute>().Browsable)) { propertyDescriptorList.RemoveAt(index2); } } } } ITransform currentObject = this.currentObject as ITransform; foreach (PropertyDescriptor property in propertyDescriptorList) { if (property.Attributes.Contains((Attribute) new UndoPropertyAttribute()) || !string.IsNullOrEmpty(property.Category)) { PropertyItem propertyItem = PropertyGridUtilities.CreatePropertyItem(property, obj.LastOrDefault <object>()); if (propertyItem != null) { propertyItem.IsEnable = isEnable; propertyItem.InstanceList = obj.ToList <object>(); propertyItem.InstanceCount = obj.Count <object>(); if (obj.Count <object>() <= 1 || !(propertyItem.Calegory != "Group_Routine")) { this._property.Add(propertyItem); } } } } int type = this._selectTab; if (this.currentObject is IPropertyTitle) { this._generalGrid = new GeneralGrid(new List <string>() { LanguageInfo.BasicProperty, LanguageInfo.AdvancedProperty }, 0, this._selectTab); this._generalGrid.TabChanged += new EventHandler <TabEventArgs>(this._generalGrid_TabChanged); this._propertyTable.Attach((Widget)this._generalGrid, 0U, 1U, 0U, 1U, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Fill, 1U, 0U); this._generalGrid.Show(); this._titleTable = new GeneralTitle(this._editorManager); this._propertyTable.Attach((Widget)this._titleTable.hBox, 0U, 1U, 1U, 2U, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Fill, 1U, 0U); this._titleTable.hBox.Show(); if (this.currentObject is IPropertyTitle) { this._titleTable.SetImage(obj.Count <object>() == 1 ? this.currentObject : (object)null, obj.Count <object>(), rootType); } List <PropertyItem> list = this._property.Where <PropertyItem>((Func <PropertyItem, bool>)(w => w.DiaplayName == "Display_Name" || w.DiaplayName == "Display_Target")).ToList <PropertyItem>(); if (list != null) { this._titleTable.SetControl(list); } if (list != null) { list.ForEach((System.Action <PropertyItem>)(w => this._property.Remove(w))); } PropertyItem propertyItem = this._property.FirstOrDefault <PropertyItem>((Func <PropertyItem, bool>)(w => w.DiaplayName == "CallBack_ClassName")); if (propertyItem != null) { if (isRootNode) { this._property.Clear(); this._property.Add(propertyItem); } else { this._property.Remove(propertyItem); } } } else { type = 0; } this.AddTable(type); }
/// <include file='doc\UserControlDesigner.uex' path='docs/doc[@for="ControlDesigner.PersistAttribute"]/*' /> /// <devdoc> /// <para> /// Persists individual attributes into HTML. /// </para> /// </devdoc> private void PersistAttribute(PropertyDescriptor pd, object component, string strPropertyName) { // if this is a parent property with sub property, don't bother to persist it PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(pd.PropertyType, new Attribute[] { PersistenceModeAttribute.Attribute, NotifyParentPropertyAttribute.Yes }); if (properties != null && properties.Count > 0) { return; } object objNewValue = pd.GetValue(component); string strNewValue = null; if (objNewValue != null) { if (pd.PropertyType.IsEnum) { strNewValue = Enum.Format(pd.PropertyType, objNewValue, "G"); } else { TypeConverter converter = pd.Converter; if (converter != null) { strNewValue = converter.ConvertToInvariantString(null, objNewValue); } else { strNewValue = objNewValue.ToString(); } } } // if this is the same as default value, don't persist it DefaultValueAttribute defAttr = (DefaultValueAttribute)pd.Attributes[typeof(DefaultValueAttribute)]; // BUG: if user delete the property value from properties window and the default value is not empty, // we want to persist this empty string. However, since trident does not allow setting empty string value for // SetAttribute, we pass in a white space for now.... if ((objNewValue == null || strNewValue.Equals("")) && (defAttr != null && defAttr.Value != null && ShouldPersistBlankValue(defAttr.Value, pd.PropertyType))) { Behavior.SetAttribute(strPropertyName, " ", true); } else { if (objNewValue == null || (defAttr != null && objNewValue.Equals(defAttr.Value)) || strNewValue == null || strNewValue.Length == 0 || strNewValue.Equals("NotSet") || (pd.PropertyType.IsArray && strNewValue.Length == 0)) { Behavior.RemoveAttribute(strPropertyName, true); } else { Behavior.SetAttribute(strPropertyName, strNewValue, true); } } }
/// <include file='doc\UserControlDesigner.uex' path='docs/doc[@for="ControlDesigner.PersistProperties"]/*' /> /// <devdoc> /// <para> /// Enumerates and persists all properties of a control /// including sub properties. /// </para> /// </devdoc> private string PersistProperties(string strPrefix, object parent, PropertyDescriptor propDesc) { try { // Obtain the HTML element to which the associated behavior is attached to. Debug.Assert(parent != null, "parent is null"); StringBuilder sb = new StringBuilder(strPrefix); // property name of the parent property object objValue = null; PropertyDescriptorCollection properties; // get all sub properties for parent property if (propDesc == null) { objValue = parent; properties = TypeDescriptor.GetProperties(parent, new Attribute[] { PersistenceModeAttribute.Attribute }); } else { objValue = propDesc.GetValue(parent); // value object for parent property if (propDesc.SerializationVisibility != DesignerSerializationVisibility.Content) { return(sb.ToString()); } properties = TypeDescriptor.GetProperties(propDesc.PropertyType, new Attribute[] { PersistenceModeAttribute.Attribute }); } for (int i = 0; i < properties.Count; i++) { // Only deal with attributes that need to be persisted if (properties[i].SerializationVisibility == DesignerSerializationVisibility.Hidden) { continue; } // Skip design-time only properties such as DefaultModifiers DesignOnlyAttribute doAttr = (DesignOnlyAttribute)properties[i].Attributes[typeof(DesignOnlyAttribute)]; if ((doAttr != null) && doAttr.IsDesignOnly) { continue; } // We don't want to persist these designer properties on a control if (parent is WebUIControl) { if (properties[i].Name.Equals("ID")) { continue; } } // The "objNewValue" is being moved to PersistAttributes(), but we leave // this variable here in order to test if this is a System.Strings[] and // break out of the for loop (which cannot be done from inside // PersistAttributes() object objNewValue = properties[i].GetValue(objValue); if (sb.Length != 0) { sb.Append("-"); } sb.Append(properties[i].Name); sb = new StringBuilder(PersistProperties(sb.ToString(), objValue, properties[i])); // check if this property has subproperties, if not, persist it as an attribute. Need to check // for NotifyParentPropertyAttribute to ensure it's really a bottom property PropertyDescriptorCollection array = TypeDescriptor.GetProperties(properties[i].PropertyType, new Attribute[] { PersistenceModeAttribute.Attribute, NotifyParentPropertyAttribute.Yes }); if (array == null || array.Count == 0) { try { PersistAttribute(properties[i], objValue, sb.ToString()); } catch (Exception) { // Debug.Fail(e.ToString()); } } sb = new StringBuilder(strPrefix); } return(sb.ToString()); } catch (Exception e) { Debug.Fail(e.ToString()); return(string.Empty); } }
/// <summary> /// Updates the configuration database by writing data of the specified table. /// </summary> public void Update(IBaseTable baseTable) { if (baseTable == null) { throw new ArgumentNullException(nameof(baseTable)); } Stream stream; BinaryWriter writer = null; try { stream = Stream ?? new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); writer = new BinaryWriter(stream, Encoding.UTF8, Stream != null); // write header writer.Write(TableType.BaseTable); writer.Write(MajorVersion); writer.Write(MinorVersion); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(baseTable.ItemType); int fieldCount = Math.Min(props.Count, ushort.MaxValue); writer.Write((ushort)fieldCount); writer.Write(ReserveBuffer, 0, 12); if (fieldCount > 0) { // create and write field definitions FieldDef[] fieldDefs = new FieldDef[fieldCount]; byte[] buffer = new byte[FieldDefSize]; for (int i = 0; i < fieldCount; i++) { PropertyDescriptor prop = props[i]; bool isNullable = prop.PropertyType.IsNullable(); FieldDef fieldDef = new FieldDef( prop.Name, isNullable ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType, isNullable || prop.PropertyType.IsClass); fieldDefs[i] = fieldDef; WriteFieldDef(writer, fieldDef, buffer); } // write rows byte[][] rowData = new byte[fieldCount][]; bool[] isNullArr = new bool[fieldCount]; foreach (object item in baseTable.EnumerateItems()) { // get row data and size int rowDataSize = 2; // CRC for (int i = 0; i < fieldCount; i++) { object value = props[i].GetValue(item); if (value == null) { isNullArr[i] = true; } else { FieldDef fieldDef = fieldDefs[i]; byte[] fieldData = GetFieldData(fieldDef, value, rowData[i]); rowData[i] = fieldData; isNullArr[i] = false; rowDataSize += (fieldDef.DataSize <= 0 ? 2 : 0) + fieldData.Length; } rowDataSize++; // null flag } // copy row data to the buffer int fullRowSize = rowDataSize + 6; int copyIndex = 0; ResizeBuffer(ref buffer, fullRowSize, 2); CopyUInt16(BlockMarker, buffer, ref copyIndex); CopyInt32(rowDataSize, buffer, ref copyIndex); for (int i = 0; i < fieldCount; i++) { if (isNullArr[i]) { buffer[copyIndex++] = 1; } else { buffer[copyIndex++] = 0; FieldDef fieldDef = fieldDefs[i]; byte[] fieldData = rowData[i]; if (fieldDef.DataSize <= 0) { CopyUInt16((ushort)fieldData.Length, buffer, ref copyIndex); } fieldData.CopyTo(buffer, copyIndex); copyIndex += fieldData.Length; } } ushort crc = ScadaUtils.CRC16(buffer, 0, fullRowSize - 2); CopyUInt16(crc, buffer, fullRowSize - 2); // write row data writer.Write(buffer, 0, fullRowSize); } } } finally { writer?.Close(); } }
public void get_by_id_returns_null_if_no_property_exists_with_specified_id() { var collection = new PropertyDescriptorCollection(new PropertyDescriptor[0]); Assert.Null(collection.GetById(5)); }
public ITUWidget CreateITUWidget() { ITUListBox listbox = new ITUListBox(); listbox.type = ITUWidgetType.ITU_LISTBOX; listbox.name = this.Name; listbox.flags |= this.TabStop ? ITU.ITU_TAPSTOP : 0; PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(this); listbox.visible = (bool)properties["Visible"].GetValue(this); listbox.active = false; listbox.dirty = false; listbox.alpha = 255; listbox.tabIndex = this.TabIndex; listbox.rect.x = this.Location.X; listbox.rect.y = this.Location.Y; listbox.rect.width = this.Size.Width; listbox.rect.height = this.Size.Height; listbox.color.alpha = this.BackAlpha; listbox.color.red = this.BackColor.R; listbox.color.green = this.BackColor.G; listbox.color.blue = this.BackColor.B; listbox.bound.x = 0; listbox.bound.y = 0; listbox.bound.width = 0; listbox.bound.height = 0; foreach (object item in this.Items) { ITUScrollText text = new ITUScrollText(); text.name = ""; text.visible = true; text.active = false; text.dirty = false; text.alpha = 255; text.rect.x = 0; text.rect.y = 0; text.rect.width = this.Size.Width; text.rect.height = this.ItemHeight; text.color.alpha = this.ForeColor.A; text.color.red = this.ForeColor.R; text.color.green = this.ForeColor.G; text.color.blue = this.ForeColor.B; text.bound.x = 0; text.bound.y = 0; text.bound.width = 0; text.bound.height = 0; text.bgColor.alpha = 0; text.bgColor.red = 0; text.bgColor.green = 0; text.bgColor.blue = 0; text.fontWidth = (int)Math.Round(this.Font.Size * (this.Font.FontFamily.GetCellAscent(FontStyle.Regular) + this.Font.FontFamily.GetCellDescent(FontStyle.Regular)) / this.Font.FontFamily.GetEmHeight(FontStyle.Regular)); text.fontHeight = text.fontWidth; text.fontIndex = this.FontIndex; if (base.Font.Bold) { text.textFlags |= ITUText.ITU_TEXT_BOLD; } text.boldSize = this.BoldSize; string[] texts = new string[] { item.ToString() }; text.stringSet = ITU.CreateStringSetNode(texts); text.width = this.Size.Width; switch (this.TextAlign) { case ContentAlignment.BottomLeft: text.layout = ITULayout.ITU_LAYOUT_BOTTOM_LEFT; break; case ContentAlignment.MiddleLeft: text.layout = ITULayout.ITU_LAYOUT_MIDDLE_LEFT; break; case ContentAlignment.TopLeft: text.layout = ITULayout.ITU_LAYOUT_TOP_LEFT; break; case ContentAlignment.BottomCenter: text.layout = ITULayout.ITU_LAYOUT_BOTTOM_CENTER; break; case ContentAlignment.MiddleCenter: text.layout = ITULayout.ITU_LAYOUT_MIDDLE_CENTER; break; case ContentAlignment.TopCenter: text.layout = ITULayout.ITU_LAYOUT_TOP_CENTER; break; case ContentAlignment.BottomRight: text.layout = ITULayout.ITU_LAYOUT_BOTTOM_RIGHT; break; case ContentAlignment.MiddleRight: text.layout = ITULayout.ITU_LAYOUT_MIDDLE_RIGHT; break; case ContentAlignment.TopRight: text.layout = ITULayout.ITU_LAYOUT_TOP_RIGHT; break; default: text.layout = ITULayout.ITU_LAYOUT_DEFAULT; break; } text.scrollDelay = this.ScrollDelay; text.stopDelay = this.StopDelay; text.scrollTextState = 1; WidgetNode node = new WidgetNode(); node.widget = text; listbox.items.Add(node); } listbox.pageIndexName = this.PageIndexTarget; listbox.pageCountName = this.PageCountTarget; listbox.focusColor.alpha = this.FocusColor.A; listbox.focusColor.red = this.FocusColor.R; listbox.focusColor.green = this.FocusColor.G; listbox.focusColor.blue = this.FocusColor.B; listbox.focusFontColor.alpha = this.FocusFontColor.A; listbox.focusFontColor.red = this.FocusFontColor.R; listbox.focusFontColor.green = this.FocusFontColor.G; listbox.focusFontColor.blue = this.FocusFontColor.B; listbox.orgFontColor.alpha = this.ForeColor.A; listbox.orgFontColor.red = this.ForeColor.R; listbox.orgFontColor.green = this.ForeColor.G; listbox.orgFontColor.blue = this.ForeColor.B; listbox.readFontColor.alpha = this.ReadFontColor.A; listbox.readFontColor.red = this.ReadFontColor.R; listbox.readFontColor.green = this.ReadFontColor.G; listbox.readFontColor.blue = this.ReadFontColor.B; listbox.scrollDelay = this.ScrollDelay; listbox.stopDelay = this.StopDelay; listbox.actions[0].action = (ITUActionType)this.Action01.Action; listbox.actions[0].ev = (ITUEvent)this.Action01.Event; listbox.actions[0].target = this.Action01.Target; listbox.actions[0].param = this.Action01.Parameter; listbox.actions[1].action = (ITUActionType)this.Action02.Action; listbox.actions[1].ev = (ITUEvent)this.Action02.Event; listbox.actions[1].target = this.Action02.Target; listbox.actions[1].param = this.Action02.Parameter; listbox.actions[2].action = (ITUActionType)this.Action03.Action; listbox.actions[2].ev = (ITUEvent)this.Action03.Event; listbox.actions[2].target = this.Action03.Target; listbox.actions[2].param = this.Action03.Parameter; listbox.actions[3].action = (ITUActionType)this.Action04.Action; listbox.actions[3].ev = (ITUEvent)this.Action04.Event; listbox.actions[3].target = this.Action04.Target; listbox.actions[3].param = this.Action04.Parameter; listbox.actions[4].action = (ITUActionType)this.Action05.Action; listbox.actions[4].ev = (ITUEvent)this.Action05.Event; listbox.actions[4].target = this.Action05.Target; listbox.actions[4].param = this.Action05.Parameter; listbox.actions[5].action = (ITUActionType)this.Action06.Action; listbox.actions[5].ev = (ITUEvent)this.Action06.Event; listbox.actions[5].target = this.Action06.Target; listbox.actions[5].param = this.Action06.Parameter; listbox.actions[6].action = (ITUActionType)this.Action07.Action; listbox.actions[6].ev = (ITUEvent)this.Action07.Event; listbox.actions[6].target = this.Action07.Target; listbox.actions[6].param = this.Action07.Parameter; listbox.actions[7].action = (ITUActionType)this.Action08.Action; listbox.actions[7].ev = (ITUEvent)this.Action08.Event; listbox.actions[7].target = this.Action08.Target; listbox.actions[7].param = this.Action08.Parameter; listbox.actions[8].action = (ITUActionType)this.Action09.Action; listbox.actions[8].ev = (ITUEvent)this.Action09.Event; listbox.actions[8].target = this.Action09.Target; listbox.actions[8].param = this.Action09.Parameter; listbox.actions[9].action = (ITUActionType)this.Action10.Action; listbox.actions[9].ev = (ITUEvent)this.Action10.Event; listbox.actions[9].target = this.Action10.Target; listbox.actions[9].param = this.Action10.Parameter; listbox.actions[10].action = (ITUActionType)this.Action11.Action; listbox.actions[10].ev = (ITUEvent)this.Action11.Event; listbox.actions[10].target = this.Action11.Target; listbox.actions[10].param = this.Action11.Parameter; listbox.actions[11].action = (ITUActionType)this.Action12.Action; listbox.actions[11].ev = (ITUEvent)this.Action12.Event; listbox.actions[11].target = this.Action12.Target; listbox.actions[11].param = this.Action12.Parameter; listbox.actions[12].action = (ITUActionType)this.Action13.Action; listbox.actions[12].ev = (ITUEvent)this.Action13.Event; listbox.actions[12].target = this.Action13.Target; listbox.actions[12].param = this.Action13.Parameter; listbox.actions[13].action = (ITUActionType)this.Action14.Action; listbox.actions[13].ev = (ITUEvent)this.Action14.Event; listbox.actions[13].target = this.Action14.Target; listbox.actions[13].param = this.Action14.Parameter; listbox.actions[14].action = (ITUActionType)this.Action15.Action; listbox.actions[14].ev = (ITUEvent)this.Action15.Event; listbox.actions[14].target = this.Action15.Target; listbox.actions[14].param = this.Action15.Parameter; return(listbox); }
private static void LoadIntProperty(string propertyName, XmlNode propertyNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { int num; if (int.TryParse(propertyNode.InnerText, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { PropertyDescriptor<int> propertyDescriptor = propertyDescriptors[propertyName] as PropertyDescriptor<int>; properties.Add(new IntProperty(propertyDescriptor, num)); } }
public System.ComponentModel.PropertyDescriptorCollection GetProperties(System.Attribute[] attributes) { PropertyDescriptorCollection Properties = new PropertyDescriptorCollection(null); CustomProperty CustomProp; foreach (CustomProperty tempLoopVar_CustomProp in base.List) { CustomProp = tempLoopVar_CustomProp; if (CustomProp.Visible) { ArrayList attrs = new ArrayList(); // Expandable Object Converter if (CustomProp.IsBrowsable) { attrs.Add(new TypeConverterAttribute(typeof(BrowsableTypeConverter))); } // The Filename Editor if (CustomProp.UseFileNameEditor == true) { attrs.Add(new EditorAttribute(typeof(UIFilenameEditor), typeof(UITypeEditor))); } // Custom Choices Type Converter if (CustomProp.Choices != null) { attrs.Add(new TypeConverterAttribute(typeof(CustomChoices.CustomChoicesTypeConverter))); } // Password Property if (CustomProp.IsPassword) { attrs.Add(new PasswordPropertyTextAttribute(true)); } // Parenthesize Property if (CustomProp.Parenthesize) { attrs.Add(new ParenthesizePropertyNameAttribute(true)); } // Datasource if (CustomProp.Datasource != null) { attrs.Add(new EditorAttribute(typeof(UIListboxEditor), typeof(UITypeEditor))); } // Custom Editor if (CustomProp.CustomEditor != null) { attrs.Add(new EditorAttribute(CustomProp.CustomEditor.GetType(), typeof(UITypeEditor))); } // Custom Type Converter if (CustomProp.CustomTypeConverter != null) { attrs.Add(new TypeConverterAttribute(CustomProp.CustomTypeConverter.GetType())); } // Is Percentage if (CustomProp.IsPercentage) { attrs.Add(new TypeConverterAttribute(typeof(OpacityConverter))); } // 3-dots button event delegate if (CustomProp.OnClick != null) { attrs.Add(new EditorAttribute(typeof(UICustomEventEditor), typeof(UITypeEditor))); } // Default value attribute if (CustomProp.DefaultValue != null) { attrs.Add(new DefaultValueAttribute(CustomProp.Type, CustomProp.Value.ToString())); } else { // Default type attribute if (CustomProp.DefaultType != null) { attrs.Add(new DefaultValueAttribute(CustomProp.DefaultType, null)); } } // Extra Attributes if (CustomProp.Attributes != null) { attrs.AddRange(CustomProp.Attributes); } // Add my own attributes Attribute[] attrArray = (System.Attribute[])attrs.ToArray(typeof(Attribute)); Properties.Add(new CustomProperty.CustomPropertyDescriptor(CustomProp, attrArray)); } } return(Properties); }
public override PropertyDescriptorCollection GetProperties() { PropertyDescriptorCollection cols = base.GetProperties(); return(cols); }
internal HyperTypeDescriptor(ICustomTypeDescriptor parent) : base(parent) { propertyCollections = WrapProperties(parent.GetProperties()); }
public PropertyDescriptorCollection GetProperties() { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(this, true); return(properties); }
public void Constructor_ValidData_PropertiesHaveExpectedAttributesValues(bool useDefaultOffsets) { // Setup var mocks = new MockRepository(); var changeHandler = mocks.Stub <IObservablePropertyChangeHandler>(); mocks.ReplayAll(); var input = new TestMacroStabilityInwardsLocationInput { UseDefaultOffsets = useDefaultOffsets }; // Call var properties = new MacroStabilityInwardsLocationInputOffsetProperties(input, changeHandler); // Assert PropertyDescriptorCollection dynamicProperties = PropertiesTestHelper.GetAllVisiblePropertyDescriptors(properties); Assert.AreEqual(5, dynamicProperties.Count); const string offsetCategory = "Offsets PL 1"; PropertyDescriptor useDefaultOffsetsProperty = dynamicProperties[expectedUseDefaultOffsetsPropertyIndex]; PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties( useDefaultOffsetsProperty, offsetCategory, "Gebruik default waarden voor offsets van PL 1", "Gebruik standaard waterstandsverschillen voor het bepalen van de freatische lijn?"); PropertyDescriptor phreaticLineOffsetBelowDikeTopAtRiverProperty = dynamicProperties[expectedPhreaticLineOffsetBelowDikeTopAtRiverPropertyIndex]; PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties( phreaticLineOffsetBelowDikeTopAtRiverProperty, offsetCategory, "PL 1 offset onder buitenkruin [m]", "Verschil tussen de waterstand en de freatische lijn onder kruin buitentalud.", useDefaultOffsets); PropertyDescriptor phreaticLineOffsetBelowDikeTopAtPolderProperty = dynamicProperties[expectedPhreaticLineOffsetBelowDikeTopAtPolderPropertyIndex]; PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties( phreaticLineOffsetBelowDikeTopAtPolderProperty, offsetCategory, "PL 1 offset onder binnenkruin [m]", "Verschil tussen de waterstand en de freatische lijn onder kruin binnentalud.", useDefaultOffsets); PropertyDescriptor phreaticLineOffsetBelowShoulderBaseInsideProperty = dynamicProperties[expectedPhreaticLineOffsetBelowShoulderBaseInsidePropertyIndex]; PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties( phreaticLineOffsetBelowShoulderBaseInsideProperty, offsetCategory, "PL 1 offset onder insteek binnenberm [m]", "Waterstandsverschil tussen het maaiveld en de freatische lijn onder insteek binnenberm.", useDefaultOffsets); PropertyDescriptor phreaticLineOffsetBelowDikeToeAtPolderProperty = dynamicProperties[expectedPhreaticLineOffsetBelowDikeToeAtPolderPropertyIndex]; PropertiesTestHelper.AssertRequiredPropertyDescriptorProperties( phreaticLineOffsetBelowDikeToeAtPolderProperty, offsetCategory, "PL 1 offset onder teen dijk binnenwaarts [m]", "Waterstandsverschil tussen het maaiveld en de freatische lijn onder teen dijk binnenwaarts.", useDefaultOffsets); mocks.VerifyAll(); }
public void ConstructorNullTests() { var collection = new PropertyDescriptorCollection(null); Assert.Equal(0, collection.Count); }
public void RemoveExistingTests(int index) { var propertyDescriptors = new PropertyDescriptor[] { new MockPropertyDescriptor("propertyDescriptor1"), new MockPropertyDescriptor("propertyDescriptor2"), new MockPropertyDescriptor("propertyDescriptor3"), new MockPropertyDescriptor("propertyDescriptor4"), new MockPropertyDescriptor("propertyDescriptor5"), new MockPropertyDescriptor("propertyDescriptor6"), new MockPropertyDescriptor("propertyDescriptor7"), new MockPropertyDescriptor("propertyDescriptor8"), new MockPropertyDescriptor("propertyDescriptor9") }; // Must send in a copy to the constructor as the array itself is manipulated var collection = new PropertyDescriptorCollection(propertyDescriptors.ToArray()); Assert.True(index >= 0 && index < propertyDescriptors.Length, $"Index '{index}' is out of bounds"); collection.Remove(propertyDescriptors[index]); for (int i = 0; i < propertyDescriptors.Length; i++) { if (i == index) { Assert.False(collection.Contains(propertyDescriptors[index]), "Should have removed descriptor"); } else { Assert.True(collection.Contains(propertyDescriptors[i]), $"Descriptor should be in collection: {i}"); } } }
/// <summary> /// Updates each entry in the ChangeSet with its corresponding conflict info. /// </summary> /// <param name="operationConflictMap">Map of conflicts to their corresponding operations entries.</param> private void SetChangeSetConflicts(Dictionary <DbEntityEntry, ChangeSetEntry> operationConflictMap) { object storeValue; EntityKey refreshEntityKey; ObjectContext objectContext = ((IObjectContextAdapter)DbContext).ObjectContext; ObjectStateManager objectStateManager = objectContext.ObjectStateManager; if (objectStateManager == null) { throw Error.InvalidOperation(Resource.ObjectStateManagerNotFoundException, DbContext.GetType().Name); } foreach (var conflictEntry in operationConflictMap) { DbEntityEntry entityEntry = conflictEntry.Key; ObjectStateEntry stateEntry = objectStateManager.GetObjectStateEntry(entityEntry.Entity); if (stateEntry.State == EntityState.Unchanged) { continue; } // Note: we cannot call Refresh StoreWins since this will overwrite Current entity and remove the optimistic concurrency ex. ChangeSetEntry operationInConflict = conflictEntry.Value; refreshEntityKey = RefreshContext.CreateEntityKey(stateEntry.EntitySet.Name, stateEntry.Entity); RefreshContext.TryGetObjectByKey(refreshEntityKey, out storeValue); operationInConflict.StoreEntity = storeValue; // StoreEntity will be null if the entity has been deleted in the store (i.e. Delete/Delete conflict) bool isDeleted = (operationInConflict.StoreEntity == null); if (isDeleted) { operationInConflict.IsDeleteConflict = true; } else { // Determine which members are in conflict by comparing original values to the current DB values PropertyDescriptorCollection propDescriptors = TypeDescriptor.GetProperties(operationInConflict.Entity.GetType()); List <string> membersInConflict = new List <string>(); object originalValue; PropertyDescriptor pd; for (int i = 0; i < stateEntry.OriginalValues.FieldCount; i++) { originalValue = stateEntry.OriginalValues.GetValue(i); if (originalValue is DBNull) { originalValue = null; } string propertyName = stateEntry.OriginalValues.GetName(i); pd = propDescriptors[propertyName]; if (pd == null) { // This might happen in the case of a private model // member that isn't mapped continue; } if (!Object.Equals(originalValue, pd.GetValue(operationInConflict.StoreEntity))) { membersInConflict.Add(pd.Name); } } operationInConflict.ConflictMembers = membersInConflict; } } }
private ComponentExporter(Type inputType, PropertyDescriptorCollection properties) : base(inputType) { Debug.Assert(properties != null); _properties = properties; }
/// <include file='doc\RectangleConverter.uex' path='docs/doc[@for="RectangleConverter.GetProperties"]/*' /> /// <devdoc> /// Retrieves the set of properties for this type. By default, a type has /// does not return any properties. An easy implementation of this method /// can just call TypeDescriptor.GetProperties for the correct data type. /// </devdoc> public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(Rectangle), attributes); return(props.Sort(new string[] { "X", "Y", "Width", "Height" })); }
public RoleTypeDecorator(RoleType role) { this.roleType = role; this.allPropertyDescriptors = TypeDescriptor.GetProperties(this, true); }
/// <summary> /// Loads and stores a boolean property. /// </summary> /// <param name="propertyName"> /// The name of the property to load. /// </param> /// <param name="propertyNode"> /// The node containing the property. /// </param> /// <param name="properties"> /// The collection in which to store the property. /// </param> /// <param name="propertyDescriptors"> /// The collection of property descriptors. /// </param> private static void LoadBooleanProperty( string propertyName, XmlNode propertyNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { Param.AssertValidString(propertyName, "propertyName"); Param.AssertNotNull(propertyNode, "propertyNode"); Param.AssertNotNull(properties, "properties"); Param.AssertNotNull(propertyDescriptors, "propertyDescriptors"); // Skip corrupted properties. bool value; if (bool.TryParse(propertyNode.InnerText, out value)) { // Get the property descriptor. PropertyDescriptor<bool> descriptor = propertyDescriptors[propertyName] as PropertyDescriptor<bool>; if (descriptor != null) { // Create and add the property. properties.Add(new BooleanProperty(descriptor, value)); } } }
public ActionResult ExportFocusVsAch(string Month, string Year) { try { System.Data.DataTable table = new System.Data.DataTable(); System.Data.DataTable tableToExport = new System.Data.DataTable(); tableToExport.Columns.Add("Name"); tableToExport.Columns.Add("Type"); tableToExport.Columns.Add("VolumeFocus"); tableToExport.Columns.Add("VolumeAch"); tableToExport.Columns.Add("VolumeAch%"); tableToExport.Columns.Add("VolumePoints"); tableToExport.Columns.Add("ValueFocus"); tableToExport.Columns.Add("ValueAch"); tableToExport.Columns.Add("ValueAch%"); tableToExport.Columns.Add("ValuePoints"); CustomerDetail UserSession = new CustomerDetail(); UserSession = (CustomerDetail)Session["ChitaleUser"]; TgtVsAchViewModel objData = new TgtVsAchViewModel(); objData.objOverAll = PLR.GetOverallData(UserSession.CustomerId, Month, Year); objData.objCategory = PLR.GetCategoryData(UserSession.CustomerId, Month, Year); objData.objSubCategory = PLR.GetSubCategoryData(UserSession.CustomerId, Month, Year); objData.objProducts = PLR.GetProductData(UserSession.CustomerId, Month, Year); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(TgtvsAchMaster)); foreach (PropertyDescriptor prop in properties) { table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); } DataRow row = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row[prop.Name] = prop.GetValue(objData.objOverAll) ?? DBNull.Value; } table.Rows.Add(row); foreach (TgtvsAchMaster item1 in objData.objCategory) { DataRow row1 = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row1[prop.Name] = prop.GetValue(item1) ?? DBNull.Value; } table.Rows.Add(row1); foreach (TgtvsAchMaster item2 in objData.objSubCategory) { if (item1.CategoryCode == item2.CategoryCode) { DataRow row2 = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row2[prop.Name] = prop.GetValue(item2) ?? DBNull.Value; } table.Rows.Add(row2); foreach (TgtvsAchMaster item3 in objData.objProducts) { if (item2.SubCategoryCode == item3.SubCategoryCode) { DataRow row3 = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row3[prop.Name] = prop.GetValue(item3) ?? DBNull.Value; } table.Rows.Add(row3); } } } } } foreach (DataRow item in table.Rows) { DataRow newDr = tableToExport.NewRow(); newDr["Name"] = item["Name"]; newDr["Type"] = item["ProductType"]; newDr["VolumeFocus"] = item["VolumeTgt"]; newDr["VolumeAch"] = item["VolumeAch"]; newDr["VolumeAch%"] = item["VolumeAchPercentage"]; newDr["VolumePoints"] = item["VolumePoints"]; newDr["ValueFocus"] = item["ValueTgt"]; newDr["ValueAch"] = item["ValueAch"]; newDr["ValueAch%"] = item["ValueAchPercentage"]; newDr["ValuePoints"] = item["ValuePoints"]; tableToExport.Rows.Add(newDr); } string ReportName = "Focus Vs Ach"; string fileName = ReportName + ".xlsx"; using (XLWorkbook wb = new XLWorkbook()) { tableToExport.TableName = ReportName; wb.Worksheets.Add(tableToExport); using (MemoryStream stream = new MemoryStream()) { wb.SaveAs(stream); return(File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName)); } } } catch (Exception ex) { newexception.AddException(ex); return(null); } }
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { PropertyDescriptorCollection collection = TypeDescriptor.GetProperties(value, true); List <PropertyDescriptor> list = new List <PropertyDescriptor>(); STControlPropertyDescriptor propText = new STControlPropertyDescriptor(collection["Text"]); propText.SetCategory(ResourceMng.GetString("CategoryAppearance")); propText.SetDisplayName(ResourceMng.GetString("PropText")); propText.SetDescription(ResourceMng.GetString("DescriptionForPropText")); list.Add(propText); STControlPropertyDescriptor PropX = new STControlPropertyDescriptor(collection["X"]); PropX.SetCategory(ResourceMng.GetString("CategoryLayout")); PropX.SetDisplayName(ResourceMng.GetString("PropX")); PropX.SetDescription(ResourceMng.GetString("")); list.Add(PropX); STControlPropertyDescriptor PropY = new STControlPropertyDescriptor(collection["Y"]); PropY.SetCategory(ResourceMng.GetString("CategoryLayout")); PropY.SetDisplayName(ResourceMng.GetString("PropY")); PropY.SetDescription(ResourceMng.GetString("")); list.Add(PropY); STControlPropertyDescriptor PropWidth = new STControlPropertyDescriptor(collection["Width"]); PropWidth.SetCategory(ResourceMng.GetString("CategoryLayout")); PropWidth.SetDisplayName(ResourceMng.GetString("PropWidth")); PropWidth.SetDescription(ResourceMng.GetString("")); list.Add(PropWidth); STControlPropertyDescriptor PropHeight = new STControlPropertyDescriptor(collection["Height"]); PropHeight.SetCategory(ResourceMng.GetString("CategoryLayout")); PropHeight.SetDisplayName(ResourceMng.GetString("PropHeight")); PropHeight.SetDescription(ResourceMng.GetString("")); list.Add(PropHeight); //STControlPropertyDescriptor PropLocation = new STControlPropertyDescriptor(collection["Location"]); //PropLocation.SetCategory(ResourceMng.GetString("CategoryLayout")); //PropLocation.SetDisplayName(ResourceMng.GetString("PropLocation")); //PropLocation.SetDescription(ResourceMng.GetString("")); //list.Add(PropLocation); //STControlPropertyDescriptor PropSize = new STControlPropertyDescriptor(collection["Size"]); //PropSize.SetCategory(ResourceMng.GetString("CategoryLayout")); //PropSize.SetDisplayName(ResourceMng.GetString("PropSize")); //PropSize.SetDescription(ResourceMng.GetString("")); //list.Add(PropSize); STControlPropertyDescriptor PropBorderWidth = new STControlPropertyDescriptor(collection["DisplayBorder"]); PropBorderWidth.SetCategory(ResourceMng.GetString("CategoryBorder")); PropBorderWidth.SetDisplayName(ResourceMng.GetString("PropDisplayBorder")); PropBorderWidth.SetDescription(ResourceMng.GetString("")); list.Add(PropBorderWidth); STControlPropertyDescriptor PropBorderColor = new STControlPropertyDescriptor(collection["BorderColor"]); PropBorderColor.SetCategory(ResourceMng.GetString("CategoryBorder")); PropBorderColor.SetDisplayName(ResourceMng.GetString("PropBorderColor")); PropBorderColor.SetDescription(ResourceMng.GetString("")); list.Add(PropBorderColor); STControlPropertyDescriptor PropAlpha = new STControlPropertyDescriptor(collection["Alpha"]); PropAlpha.SetCategory(ResourceMng.GetString("CategoryStyle")); PropAlpha.SetDisplayName(ResourceMng.GetString("PropAlpha")); PropAlpha.SetDescription(ResourceMng.GetString("DescriptionForPropAlpha")); list.Add(PropAlpha); STControlPropertyDescriptor PropRadius = new STControlPropertyDescriptor(collection["Radius"]); PropRadius.SetCategory(ResourceMng.GetString("CategoryStyle")); PropRadius.SetDisplayName(ResourceMng.GetString("PropRadius")); PropRadius.SetDescription(ResourceMng.GetString("DescriptionForPropRadius")); list.Add(PropRadius); STControlPropertyDescriptor PropBackColor = new STControlPropertyDescriptor(collection["BackgroundColor"]); PropBackColor.SetCategory(ResourceMng.GetString("CategoryAppearance")); PropBackColor.SetDisplayName(ResourceMng.GetString("PropBackColor")); PropBackColor.SetDescription(ResourceMng.GetString("DescriptionForPropBackgroundColor")); list.Add(PropBackColor); STControlPropertyDescriptor PropFlatStyle = new STControlPropertyDescriptor(collection["FlatStyle"]); PropFlatStyle.SetCategory(ResourceMng.GetString("CategoryStyle")); PropFlatStyle.SetDisplayName(ResourceMng.GetString("PropFlatStyle")); PropFlatStyle.SetDescription(ResourceMng.GetString("DescriptionForPropFlatStyle")); list.Add(PropFlatStyle); STControlPropertyDescriptor PropFontColor = new STControlPropertyDescriptor(collection["FontColor"]); PropFontColor.SetCategory(ResourceMng.GetString("CategoryAppearance")); PropFontColor.SetDisplayName(ResourceMng.GetString("PropFontColor")); PropFontColor.SetDescription(ResourceMng.GetString("DescriptionForPropFontColor")); list.Add(PropFontColor); STControlPropertyDescriptor PropFontSize = new STControlPropertyDescriptor(collection["FontSize"]); PropFontSize.SetCategory(ResourceMng.GetString("CategoryAppearance")); PropFontSize.SetDisplayName(ResourceMng.GetString("PropFontSize")); PropFontSize.SetDescription(ResourceMng.GetString("DescriptionForPropFontSize")); list.Add(PropFontSize); STControlPropertyDescriptor PropEtsWriteAddressIds = new STControlPropertyDescriptor(collection["WriteAddressIds"]); PropEtsWriteAddressIds.SetCategory("KNX"); PropEtsWriteAddressIds.SetDisplayName(ResourceMng.GetString("PropEtsWriteAddressIds")); PropEtsWriteAddressIds.SetDescription(ResourceMng.GetString("")); list.Add(PropEtsWriteAddressIds); STControlPropertyDescriptor PropEtsReadAddressId = new STControlPropertyDescriptor(collection["ReadAddressId"]); PropEtsReadAddressId.SetCategory("KNX"); PropEtsReadAddressId.SetDisplayName(ResourceMng.GetString("PropEtsReadAddressId")); PropEtsReadAddressId.SetDescription(ResourceMng.GetString("")); list.Add(PropEtsReadAddressId); //STControlPropertyDescriptor PropHasTip = new STControlPropertyDescriptor(collection["HasTip"]); //PropHasTip.SetCategory(ResourceMng.GetString("CategoryOperation")); //PropHasTip.SetDisplayName(ResourceMng.GetString("PropHasTip")); //PropHasTip.SetDescription(ResourceMng.GetString("")); //list.Add(PropHasTip); //STControlPropertyDescriptor PropTip = new STControlPropertyDescriptor(collection["Tip"]); //PropTip.SetCategory(ResourceMng.GetString("CategoryOperation")); //PropTip.SetDisplayName(ResourceMng.GetString("PropTip")); //PropTip.SetDescription(ResourceMng.GetString("")); //list.Add(PropTip); //STControlPropertyDescriptor PropClickable = new STControlPropertyDescriptor(collection["Clickable"]); //PropClickable.SetCategory(ResourceMng.GetString("CategoryOperation")); //PropClickable.SetDisplayName(ResourceMng.GetString("PropClickable")); //PropClickable.SetDescription(ResourceMng.GetString("")); //list.Add(PropClickable); STControlPropertyDescriptor PropIcon = new STControlPropertyDescriptor(collection["Icon"]); PropIcon.SetCategory(ResourceMng.GetString("")); PropIcon.SetDisplayName(ResourceMng.GetString("PropIcon")); PropIcon.SetDescription(ResourceMng.GetString("")); list.Add(PropIcon); return(new PropertyDescriptorCollection(list.ToArray())); }
//Export Functions for Participant Category public ActionResult ExportParticipantList() { try { System.Data.DataTable table = new System.Data.DataTable(); var UserSession = (CustomerDetail)Session["ChitaleUser"]; List <ParticipantList> lstparticipantLists = new List <ParticipantList>(); lstparticipantLists = pr.GetParticipantList(UserSession.CustomerId, UserSession.Type); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(ParticipantList)); foreach (PropertyDescriptor prop in properties) { table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); } if (UserSession.Type == "SuperStockiest") { foreach (ParticipantList item in lstparticipantLists) { DataRow row = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; } table.Rows.Add(row); List <ParticipantList> lstRetailerLists = new List <ParticipantList>(); lstRetailerLists = pr.GetParticipantList(item.Id, item.ParticipantType); foreach (ParticipantList itemRetailer in lstRetailerLists) { DataRow row1 = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row1[prop.Name] = prop.GetValue(itemRetailer) ?? DBNull.Value; } table.Rows.Add(row1); } } } else { foreach (ParticipantList item in lstparticipantLists) { DataRow row = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; } table.Rows.Add(row); } } var count = table.Rows.Count; string ReportName = "Participant List"; string fileName = ReportName + ".xlsx"; using (XLWorkbook wb = new XLWorkbook()) { table.TableName = ReportName; wb.Worksheets.Add(table); using (MemoryStream stream = new MemoryStream()) { wb.SaveAs(stream); return(File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName)); } } } catch (Exception ex) { newexception.AddException(ex); return(null); } }
//public PropertyCollection(object instance) // : this(instance, false) //{ } public PropertyCollection(object instance, bool noCategory, bool automaticlyExpandObjects, string filter) { var groups = new Dictionary <string, PropertyCategory>(); bool useCustomTypeConverter = false; PropertyDescriptorCollection properties; if (instance != null) { TypeConverter tc = TypeDescriptor.GetConverter(instance); if (tc == null || !tc.GetPropertiesSupported()) { if (instance is ICustomTypeDescriptor) { properties = ((ICustomTypeDescriptor)instance).GetProperties(); } else { properties = TypeDescriptor.GetProperties(instance.GetType()); //I changed here from instance to instance.GetType, so that only the Direct Properties are shown! } } else { properties = tc.GetProperties(instance); useCustomTypeConverter = true; } } else { properties = new PropertyDescriptorCollection(new PropertyDescriptor[] {}); } var propertyCollection = new List <Property>(); foreach (PropertyDescriptor propertyDescriptor in properties) { if (useCustomTypeConverter) { Property property = new Property(instance, propertyDescriptor); propertyCollection.Add(property); } else { CollectProperties(instance, propertyDescriptor, propertyCollection, automaticlyExpandObjects, filter); if (noCategory) { propertyCollection.Sort(Property.CompareByName); } else { propertyCollection.Sort(Property.CompareByCategoryThenByName); } } } if (noCategory) { foreach (Property property in propertyCollection) { if (filter == "" || property.Name.ToLower().Contains(filter)) { Items.Add(property); } } } else { foreach (Property property in propertyCollection) { if (filter == "" || property.Name.ToLower().Contains(filter)) { PropertyCategory propertyCategory; var category = property.Category ?? string.Empty; // null category handled here if (groups.ContainsKey(category)) { propertyCategory = groups[category]; } else { propertyCategory = new PropertyCategory(property.Category); groups[category] = propertyCategory; Items.Add(propertyCategory); } propertyCategory.Items.Add(property); } } } }
/// <summary> /// Adds a boolean property. /// </summary> /// <param name="propertyName"> /// The name of the property. /// </param> /// <param name="value"> /// The property value. /// </param> /// <param name="properties"> /// The collection of properties. /// </param> /// <param name="propertyDescriptors"> /// The collection of property descriptors. /// </param> private static void AddBooleanProperty(string propertyName, bool value, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { Param.AssertValidString(propertyName, "propertyName"); Param.Ignore(value); Param.AssertNotNull(properties, "properties"); Param.AssertNotNull(propertyDescriptors, "propertyDescriptors"); // Get the property descriptor. PropertyDescriptor<bool> descriptor = propertyDescriptors[propertyName] as PropertyDescriptor<bool>; if (descriptor != null) { // Create and add the property. properties.Add(new BooleanProperty(descriptor, value)); } }
private static void LoadBooleanProperty(string propertyName, XmlNode propertyNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors, string legacyAnalyzerId) { bool flag; if (bool.TryParse(propertyNode.InnerText, out flag)) { if (string.IsNullOrEmpty(legacyAnalyzerId)) { AddBooleanProperty(propertyName, flag, properties, propertyDescriptors); } else if (propertyName == "Enabled") { ICollection<string> is2 = MapAnalyzerToRules(legacyAnalyzerId); if (is2 != null) { foreach (string str in is2) { AddBooleanProperty(str + "#Enabled", flag, properties, propertyDescriptors); } } } else if (legacyAnalyzerId == "Microsoft.SourceAnalysis.CSharp.Documentation") { if (propertyName == "PublicAndProtectedOnly") { AddBooleanProperty("IgnorePrivates", flag, properties, propertyDescriptors); AddBooleanProperty("IgnoreInternals", flag, properties, propertyDescriptors); } else if (propertyName == "RequireValueTags") { AddOrUpdateLegacyBooleanProperty("PropertyDocumentationMustHaveValue", flag, properties, propertyDescriptors); AddOrUpdateLegacyBooleanProperty("PropertyDocumentationMustHaveValueText", flag, properties, propertyDescriptors); } else if (propertyName == "RequireCapitalLetter") { AddOrUpdateLegacyBooleanProperty("DocumentationTextMustBeginWithACapitalLetter", flag, properties, propertyDescriptors); } else if (propertyName == "RequirePeriod") { AddOrUpdateLegacyBooleanProperty("DocumentationTextMustEndWithAPeriod", flag, properties, propertyDescriptors); } else if (propertyName != "RequireProperFormatting") { AddBooleanProperty(propertyName, flag, properties, propertyDescriptors); } else { AddOrUpdateLegacyBooleanProperty("DocumentationTextMustContainWhitespace", flag, properties, propertyDescriptors); AddOrUpdateLegacyBooleanProperty("DocumentationMustMeetCharacterPercentage", flag, properties, propertyDescriptors); AddOrUpdateLegacyBooleanProperty("DocumentationTextMustMeetMinimumCharacterLength", flag, properties, propertyDescriptors); if (!flag) { AddOrUpdateLegacyBooleanProperty("DocumentationTextMustEndWithAPeriod", flag, properties, propertyDescriptors); AddOrUpdateLegacyBooleanProperty("DocumentationTextMustBeginWithACapitalLetter", flag, properties, propertyDescriptors); } } } else if (legacyAnalyzerId == "Microsoft.SourceAnalysis.CSharp.FileHeaders") { if (propertyName == "RequireSummary") { AddOrUpdateLegacyBooleanProperty("FileHeaderMustHaveSummary", flag, properties, propertyDescriptors); } else { AddBooleanProperty(propertyName, flag, properties, propertyDescriptors); } } else { AddBooleanProperty(propertyName, flag, properties, propertyDescriptors); } } }
/// <summary> /// Loads and stores a boolean property. /// </summary> /// <param name="propertyName"> /// The name of the property to load. /// </param> /// <param name="propertyNode"> /// The node containing the property. /// </param> /// <param name="properties"> /// The collection in which to store the property. /// </param> /// <param name="propertyDescriptors"> /// The collection of property descriptors. /// </param> /// <param name="legacyAnalyzerId"> /// If the settings node comes from a legacy, pre-4.2 analyzer, /// this parameter contains the ID of the legacy analyzer. /// </param> private static void LoadBooleanProperty( string propertyName, XmlNode propertyNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors, string legacyAnalyzerId) { Param.AssertValidString(propertyName, "propertyName"); Param.AssertNotNull(propertyNode, "propertyNode"); Param.AssertNotNull(properties, "properties"); Param.AssertNotNull(propertyDescriptors, "propertyDescriptors"); Param.Ignore(legacyAnalyzerId); // Skip corrupted properties. bool value; if (bool.TryParse(propertyNode.InnerText, out value)) { if (string.IsNullOrEmpty(legacyAnalyzerId)) { AddBooleanProperty(propertyName, value, properties, propertyDescriptors); } else { if (propertyName == "Enabled") { // Enable or disable all rules mapping to the legacy analyzer. ICollection<string> rules = MapAnalyzerToRules(legacyAnalyzerId); if (rules != null) { foreach (string rule in rules) { AddBooleanProperty(rule + "#Enabled", value, properties, propertyDescriptors); } } } else if (legacyAnalyzerId == "Microsoft.SourceAnalysis.CSharp.Documentation") { if (propertyName == "PublicAndProtectedOnly") { AddBooleanProperty("IgnorePrivates", value, properties, propertyDescriptors); AddBooleanProperty("IgnoreInternals", value, properties, propertyDescriptors); } else if (propertyName == "RequireValueTags") { AddOrUpdateLegacyBooleanProperty("PropertyDocumentationMustHaveValue", value, properties, propertyDescriptors); AddOrUpdateLegacyBooleanProperty("PropertyDocumentationMustHaveValueText", value, properties, propertyDescriptors); } else if (propertyName == "RequireCapitalLetter") { AddOrUpdateLegacyBooleanProperty("DocumentationTextMustBeginWithACapitalLetter", value, properties, propertyDescriptors); } else if (propertyName == "RequirePeriod") { AddOrUpdateLegacyBooleanProperty("DocumentationTextMustEndWithAPeriod", value, properties, propertyDescriptors); } else if (propertyName == "RequireProperFormatting") { AddOrUpdateLegacyBooleanProperty("DocumentationTextMustContainWhitespace", value, properties, propertyDescriptors); AddOrUpdateLegacyBooleanProperty("DocumentationMustMeetCharacterPercentage", value, properties, propertyDescriptors); AddOrUpdateLegacyBooleanProperty("DocumentationTextMustMeetMinimumCharacterLength", value, properties, propertyDescriptors); if (!value) { AddOrUpdateLegacyBooleanProperty("DocumentationTextMustEndWithAPeriod", value, properties, propertyDescriptors); AddOrUpdateLegacyBooleanProperty("DocumentationTextMustBeginWithACapitalLetter", value, properties, propertyDescriptors); } } else { AddBooleanProperty(propertyName, value, properties, propertyDescriptors); } } else if (legacyAnalyzerId == "Microsoft.SourceAnalysis.CSharp.FileHeaders") { if (propertyName == "RequireSummary") { AddOrUpdateLegacyBooleanProperty("FileHeaderMustHaveSummary", value, properties, propertyDescriptors); } else { AddBooleanProperty(propertyName, value, properties, propertyDescriptors); } } else { AddBooleanProperty(propertyName, value, properties, propertyDescriptors); } } } }
private static void LoadPropertyCollection(XmlNode propertyCollectionNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors, string legacyAnalyzerId) { foreach (XmlNode node in propertyCollectionNode.ChildNodes) { string str; XmlAttribute attribute = node.Attributes["Name"]; if (((attribute != null) && !string.IsNullOrEmpty(attribute.Value)) && ((str = node.Name) != null)) { if (!(str == "BooleanProperty")) { if (str == "IntegerProperty") { goto Label_0092; } if (str == "StringProperty") { goto Label_00A2; } if (str == "CollectionProperty") { goto Label_00B2; } } else { LoadBooleanProperty(attribute.InnerText, node, properties, propertyDescriptors, legacyAnalyzerId); } } continue; Label_0092: LoadIntProperty(attribute.InnerText, node, properties, propertyDescriptors); continue; Label_00A2: LoadStringProperty(attribute.InnerText, node, properties, propertyDescriptors); continue; Label_00B2: LoadCollectionProperty(attribute.InnerText, node, properties, propertyDescriptors); } }
/// <summary> /// Loads and stores an integer property. /// </summary> /// <param name="propertyName"> /// The name of the property to load. /// </param> /// <param name="propertyNode"> /// The node containing the property. /// </param> /// <param name="properties"> /// The collection in which to store the property. /// </param> /// <param name="propertyDescriptors"> /// The collection of property descriptors. /// </param> private static void LoadIntProperty(string propertyName, XmlNode propertyNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { Param.AssertValidString(propertyName, "propertyName"); Param.AssertNotNull(propertyNode, "propertyNode"); Param.AssertNotNull(properties, "properties"); Param.AssertNotNull(propertyDescriptors, "propertyDescriptors"); // Skip corrupted properties. int value; if (int.TryParse(propertyNode.InnerText, NumberStyles.Any, CultureInfo.InvariantCulture, out value)) { // Get the property descriptor. PropertyDescriptor<int> descriptor = propertyDescriptors[propertyName] as PropertyDescriptor<int>; // Create and add the property. properties.Add(new IntProperty(descriptor, value)); } }
private static void LoadStringProperty(string propertyName, XmlNode propertyNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { PropertyDescriptor<string> propertyDescriptor = propertyDescriptors[propertyName] as PropertyDescriptor<string>; properties.Add(new StringProperty(propertyDescriptor, propertyNode.InnerText)); }
/// <summary> /// Loads settings for rules. /// </summary> /// <param name="addInNode"> /// The add-in containing the rules. /// </param> /// <param name="properties"> /// The collection of properties to add the rules settings into. /// </param> /// <param name="propertyDescriptors"> /// The collection of property descriptors for the add-in. /// </param> private static void LoadRulesSettings(XmlNode addInNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { Param.AssertNotNull(addInNode, "addInNode"); Param.AssertNotNull(properties, "properties"); Param.AssertNotNull(propertyDescriptors, "propertyDescriptors"); XmlNode rulesNode = addInNode["Rules"]; if (rulesNode != null) { foreach (XmlNode child in rulesNode.ChildNodes) { if (string.Equals(child.Name, "Rule", StringComparison.Ordinal)) { XmlAttribute name = child.Attributes["Name"]; if (name != null && !string.IsNullOrEmpty(name.Value)) { string ruleName = name.Value; XmlNode ruleSettings = child["RuleSettings"]; if (ruleSettings != null) { LoadPropertyCollection(ruleSettings, properties, propertyDescriptors, ruleName); } } } } } }
//Export Functions for Employee Category public ActionResult ExportParticipantListEmployee(string Cluster, string SubCluster, string City) { try { if (string.IsNullOrEmpty(Cluster)) { Cluster = "0"; } if (string.IsNullOrEmpty(SubCluster)) { SubCluster = "0"; } if (string.IsNullOrEmpty(City)) { City = "0"; } var UserSession = (CustomerDetail)Session["ChitaleEmployee"]; System.Data.DataTable table = new System.Data.DataTable(); List <ParticipantListForManagement> lstSuperStockiest = new List <ParticipantListForManagement>(); lstSuperStockiest = ER.GetParticipantListForEmp(Cluster, SubCluster, City, UserSession.CustomerId, UserSession.CustomerType); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(ParticipantListForManagement)); foreach (PropertyDescriptor prop in properties) { table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); } foreach (ParticipantListForManagement item1 in lstSuperStockiest) { DataRow row1 = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row1[prop.Name] = prop.GetValue(item1) ?? DBNull.Value; } table.Rows.Add(row1); List <ParticipantListForManagement> lstDistributor = new List <ParticipantListForManagement>(); lstDistributor = ER.GetSubParticipantListForEmp(item1.Id, item1.ParticipantType, UserSession.CustomerType, UserSession.CustomerId); foreach (ParticipantListForManagement item2 in lstDistributor) { DataRow row2 = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row2[prop.Name] = prop.GetValue(item2) ?? DBNull.Value; } table.Rows.Add(row2); List <ParticipantListForManagement> lstRetailer = new List <ParticipantListForManagement>(); lstRetailer = ER.GetSubParticipantListForEmp(item2.Id, item2.ParticipantType, UserSession.CustomerType, UserSession.CustomerId); foreach (ParticipantListForManagement item3 in lstRetailer) { DataRow row3 = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row3[prop.Name] = prop.GetValue(item3) ?? DBNull.Value; } table.Rows.Add(row3); } } } System.Data.DataTable tableToExport = new System.Data.DataTable(); tableToExport.Columns.Add("Type"); tableToExport.Columns.Add("ID"); tableToExport.Columns.Add("Name"); tableToExport.Columns.Add("Current Rank"); tableToExport.Columns.Add("Last Month Rank"); tableToExport.Columns.Add("Purchase Points"); tableToExport.Columns.Add("Sale Points"); tableToExport.Columns.Add("Add On Points"); tableToExport.Columns.Add("Lost Opp Points"); tableToExport.Columns.Add("Redeemed Points"); tableToExport.Columns.Add("Balanced Points"); foreach (DataRow dr in table.Rows) { DataRow drExport = tableToExport.NewRow(); drExport["Type"] = dr["ParticipantType"]; drExport["ID"] = dr["Id"]; drExport["Name"] = dr["ParticipantName"]; drExport["Current Rank"] = dr["CurrentRank"]; drExport["Last Month Rank"] = dr["LastMonthRank"]; drExport["Purchase Points"] = dr["PurchasePoints"]; drExport["Sale Points"] = dr["SalePoints"]; drExport["Add On Points"] = dr["AddOnPoints"]; drExport["Lost Opp Points"] = dr["LostOppPoints"]; drExport["Redeemed Points"] = dr["RedeemedPoints"]; drExport["Balanced Points"] = dr["BalancedPoints"]; tableToExport.Rows.Add(drExport); } string ReportName = "Participant List Management"; string fileName = ReportName + ".xlsx"; using (XLWorkbook wb = new XLWorkbook()) { tableToExport.TableName = ReportName; wb.Worksheets.Add(tableToExport); using (MemoryStream stream = new MemoryStream()) { wb.SaveAs(stream); return(File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName)); } } } catch (Exception ex) { newexception.AddException(ex); return(null); } }
public DataTable ConvertToDataTable(List <Product> data) { try { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(Product)); DataTable table = new DataTable(); foreach (PropertyDescriptor prop in properties) { table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); } foreach (Product item in data) { DataRow row = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; } table.Rows.Add(row); } if (table.AsEnumerable().All(dr => dr.IsNull("Store_Id"))) { table.Columns.Remove("Store_Id"); } if (table.AsEnumerable().All(dr => dr.IsNull("SubCategory"))) { table.Columns.Remove("SubCategory"); } if (table.AsEnumerable().All(dr => dr.IsNull("ProductBanner"))) { table.Columns.Remove("ProductBanner"); } if (table.AsEnumerable().All(dr => dr.IsNull("Store"))) { table.Columns.Remove("Store"); } if (table.AsEnumerable().All(dr => dr.IsNull("Administrators_Id"))) { table.Columns.Remove("Administrators_Id"); } if (table.AsEnumerable().All(dr => dr.IsNull("Admin"))) { table.Columns.Remove("Admin"); } if (table.AsEnumerable().All(dr => dr.IsNull("ProductFlow"))) { table.Columns.Remove("ProductFlow"); } if (table.AsEnumerable().All(dr => dr.IsNull("Cart"))) { table.Columns.Remove("Cart"); } if (table.AsEnumerable().All(dr => dr.IsNull("Order"))) { table.Columns.Remove("Order"); } if (table.AsEnumerable().All(dr => dr.IsNull("ProdComments"))) { table.Columns.Remove("ProdComments"); } return(table); } catch { throw; } }
/// <summary> /// Adds or updates a property to enable or disable a rule depending on the value of a /// legacy property. /// </summary> /// <param name="ruleName"> /// The name of the rule to enable or disable. /// </param> /// <param name="value"> /// The value of the legacy property. /// </param> /// <param name="properties"> /// The collection of properties. /// </param> /// <param name="propertyDescriptors"> /// The collection of property descriptors. /// </param> private static void AddOrUpdateLegacyBooleanProperty(string ruleName, bool value, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { Param.AssertValidString(ruleName, "ruleName"); Param.Ignore(value); Param.AssertNotNull(properties, "properties"); Param.AssertNotNull(propertyDescriptors, "propertyDescriptors"); // Determine whethere is already an Enabled property for this rule. string propertyName = ruleName + "#Enabled"; BooleanProperty property = properties[propertyName] as BooleanProperty; if (property == null) { // Add a new property which enables or disables this rule depending on the // value of the legacy property. AddBooleanProperty(propertyName, value, properties, propertyDescriptors); } else if (!value) { // The rule has already been explictely enabled or disabled. In this case we // never enable the rule, but we may disable it if the legacy property is set to false. property.Value = false; } }
public static Assimp.Material ConvertToAssimpMaterial(TextureBundle bundle, Document doc) { // Create new material with base props // from the Revit material var newmat = new Assimp.Material() { Opacity = bundle.Material.GetOpacity(), Reflectivity = 0f, Name = bundle.Material.Name, ColorDiffuse = bundle.Material.ToColor4D() }; // Extract base properties from revit material ElementId appearanceAssetId = bundle.Material.AppearanceAssetId; AppearanceAssetElement appearanceAsset = doc.GetElement(appearanceAssetId) as AppearanceAssetElement; Asset renderingAsset = appearanceAsset.GetRenderingAsset(); RenderAppearanceDescriptor rad = new RenderAppearanceDescriptor(renderingAsset); PropertyDescriptorCollection collection = rad.GetProperties(); List <PropertyDescriptor> orderableCollection = new List <PropertyDescriptor>(collection.Count); List <string> allPropNames = orderableCollection.Select(f => f.Name).ToList(); foreach (PropertyDescriptor descr in collection) { orderableCollection.Add(descr); switch (descr.Name) { #region Notes // The commented out properties aren't in use yet, // but do work with revit materials as expected. //case "texture_UScale": // var uScale = renderingAsset["texture_UScale"] as AssetPropertyDouble; // break; //case "texture_VScale": // break; //case "texture_UOffset": // break; //case "texture_VOffset": // break; //case "texture_RealWorldScaleX": // var xScale = renderingAsset["texture_RealWorldScaleX"] as AssetPropertyDistance; // break; //case "texture_RealWorldScaleY": // break; #endregion case "generic_diffuse": var prop = renderingAsset.GetAssetProperty <AssetPropertyDoubleArray4d>("generic_diffuse"); newmat.ColorDiffuse = ColorFromAssetDoubleArray4d(prop); break; case "glazing_reflectance": // This is glass, so we should reduce the transparency. var refl = renderingAsset.GetAssetProperty <AssetPropertyDouble>("glazing_reflectance"); if (refl == null) { var reflFloat = renderingAsset.GetAssetProperty <AssetPropertyFloat>("glazing_reflectance"); newmat.Reflectivity = reflFloat?.Value ?? 0f; } else { newmat.Reflectivity = (float)refl.Value; } newmat.Opacity = Math.Abs(0f - newmat.Reflectivity); break; case "common_Tint_color": // Tint shouldn't be used if generic diffuse is set if ( renderingAsset.GetAssetProperty <AssetPropertyDoubleArray4d>("generic_diffuse") != null ) { continue; } var tintProp = renderingAsset.GetAssetProperty <AssetPropertyDoubleArray4d>("common_Tint_color"); newmat.ColorDiffuse = ColorFromAssetDoubleArray4d(tintProp); break; default: break; } } // Set textures foreach (var tx in bundle.TexturePaths) { // Get the filename var txFileName = tx.Value.SafeFileName; if (tx.Key == RevitTextureType.Color) { newmat.TextureDiffuse = new TextureSlot( $"Textures/{txFileName}", TextureType.Diffuse, 0, // Texture index in the material TextureMapping.Box, 0, // 0.5f, // Blend mode TextureOperation.Add, TextureWrapMode.Clamp, TextureWrapMode.Clamp, 0 // Flags, ); } else if (tx.Key == RevitTextureType.Bump) { newmat.TextureHeight = new TextureSlot( $"Textures/{txFileName}", TextureType.Diffuse, 0, // Texture index in the material TextureMapping.Box, 0, // 0.5f, // Blend mode TextureOperation.Add, TextureWrapMode.Clamp, TextureWrapMode.Clamp, 0 // Flags, ); } } return(newmat); }
/// <summary> /// Loads and stores a collection property. /// </summary> /// <param name="propertyName"> /// The name of the property to load. /// </param> /// <param name="propertyNode"> /// The node containing the property. /// </param> /// <param name="properties"> /// The collection in which to store the property. /// </param> /// <param name="propertyDescriptors"> /// The collection of property descriptors. /// </param> private static void LoadCollectionProperty( string propertyName, XmlNode propertyNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { Param.AssertValidString(propertyName, "propertyName"); Param.AssertNotNull(propertyNode, "propertyNode"); Param.AssertNotNull(properties, "properties"); Param.AssertNotNull(propertyDescriptors, "propertyDescriptors"); // Create and load the inner property collection. List<string> innerCollection = new List<string>(); // Load the value list. XmlNodeList valueNodes = propertyNode.SelectNodes("Value"); if (valueNodes != null && valueNodes.Count > 0) { foreach (XmlNode valueNode in valueNodes) { if (!string.IsNullOrEmpty(valueNode.InnerText)) { innerCollection.Add(valueNode.InnerText); } } } // If at least one value was loaded, save the proeprty. if (innerCollection.Count > 0) { // Get the property descriptor. CollectionPropertyDescriptor descriptor = propertyDescriptors[propertyName] as CollectionPropertyDescriptor; // Create the collection node and pass in the inner collection. CollectionProperty collectionProperty = new CollectionProperty(descriptor, innerCollection); // Add this property to the parent collection. properties.Add(collectionProperty); } }
/// <summary>Build the list of the properties to be displayed in the PropertyGrid, following the filters defined the Browsable and Hidden properties.</summary> private void RefreshProperties() { if (m_Wrapper == null) { return; } // Clear the list of properties to be displayed. m_PropertyDescriptors.Clear(); // Check whether the list is filtered if (m_BrowsableAttributes != null && m_BrowsableAttributes.Count > 0) { // Add to the list the attributes that need to be displayed. foreach (Attribute attribute in m_BrowsableAttributes) { ShowAttribute(attribute); } } else { // Fill the collection with all the properties. PropertyDescriptorCollection originalpropertydescriptors = TypeDescriptor.GetProperties(m_Wrapper.SelectedObject); foreach (PropertyDescriptor propertydescriptor in originalpropertydescriptors) { m_PropertyDescriptors.Add(propertydescriptor); } // Remove from the list the attributes that mustn't be displayed. if (m_HiddenAttributes != null) { foreach (Attribute attribute in m_HiddenAttributes) { HideAttribute(attribute); } } } // Get all the properties of the SelectedObject PropertyDescriptorCollection allproperties = TypeDescriptor.GetProperties(m_Wrapper.SelectedObject); // Hide if necessary, some properties if (m_HiddenProperties != null && m_HiddenProperties.Length > 0) { // Remove from the list the properties that mustn't be displayed. foreach (string propertyname in m_HiddenProperties) { try { PropertyDescriptor property = allproperties[propertyname]; // Remove from the list the property HideProperty(property); } catch (Exception ex) { Runtime.MessageCollector.AddExceptionMessage("FilteredPropertyGrid: Could not hide Property.", ex); } } } // Display if necessary, some properties if (m_BrowsableProperties != null && m_BrowsableProperties.Length > 0) { foreach (string propertyname in m_BrowsableProperties) { try { ShowProperty(allproperties[propertyname]); } catch (Exception knfe) { Runtime.MessageCollector.AddExceptionMessage("FilteredPropertyGrid: Property not found", knfe); } } } }
/// <summary> /// Loads a property collection from the settings file. /// </summary> /// <param name="propertyCollectionNode"> /// The node containing the property collection. /// </param> /// <param name="properties"> /// The property collection storage object. /// </param> /// <param name="propertyDescriptors"> /// The collection of property descriptors. /// </param> /// <param name="legacyAnalyzerId"> /// If the settings node comes from a legacy, pre-4.2 analyzer, /// this parameter contains the ID of the legacy analyzer. /// </param> private static void LoadPropertyCollection( XmlNode propertyCollectionNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors, string legacyAnalyzerId) { Param.AssertNotNull(propertyCollectionNode, "settingsNode"); Param.AssertNotNull(properties, "properties"); Param.AssertNotNull(propertyDescriptors, "propertyDescriptors"); Param.Ignore(legacyAnalyzerId); foreach (XmlNode propertyNode in propertyCollectionNode.ChildNodes) { // Get the property name. XmlAttribute propertyName = propertyNode.Attributes["Name"]; if (propertyName != null && !string.IsNullOrEmpty(propertyName.Value)) { // Load the property. switch (propertyNode.Name) { case "BooleanProperty": LoadBooleanProperty(propertyName.InnerText, propertyNode, properties, propertyDescriptors, legacyAnalyzerId); break; case "IntegerProperty": LoadIntProperty(propertyName.InnerText, propertyNode, properties, propertyDescriptors); break; case "StringProperty": LoadStringProperty(propertyName.InnerText, propertyNode, properties, propertyDescriptors); break; case "CollectionProperty": LoadCollectionProperty(propertyName.InnerText, propertyNode, properties, propertyDescriptors); break; default: // Ignore any unexpected settings. break; } } } }
private static void SetFileData(List <string> lines, ObservableCollection <T> dataSource) { PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(typeof(T)); for (int i = 1; i < lines.Count; ++i) { string[] cols = lines[i].Split(new char[] { ',' }); T bo = new T(); int k = 0; foreach (PropertyDescriptor pd in pdc) { if (pd.Name == "PID_CLR_SIZ") { continue; //skip this on as it is a composite column } if (!pd.Name.StartsWith("Test")) //skip added test fields that are not in the data { ProcessLine(bo, cols[k++], pd); } else if (bo is BO) { switch (pd.Name) { case "TestInt": pd.SetValue(bo, (bo as BO).Color); break; case "TestStr": pd.SetValue(bo, "S" + (bo as BO).Color); break; case "TestDouble": // Console.WriteLine(1d + r.NextDouble() / 5d); pd.SetValue(bo, 1d + r.NextDouble() / 5d); // pd.SetValue(bo,(double) ((bo as BO).Color) ); break; case "TestSortA": // Console.WriteLine(1d + r.NextDouble() / 5d); pd.SetValue(bo, r.Next(2)); // pd.SetValue(bo,(double) ((bo as BO).Color) ); break; case "TestSortB": // Console.WriteLine(1d + r.NextDouble() / 5d); pd.SetValue(bo, r.Next(3)); // pd.SetValue(bo,(double) ((bo as BO).Color) ); break; case "TestSortC": // Console.WriteLine(1d + r.NextDouble() / 5d); pd.SetValue(bo, r.Next(4)); // pd.SetValue(bo,(double) ((bo as BO).Color) ); break; } } } dataSource.Add(bo); } }
/// <summary> /// Loads and stores a string property. /// </summary> /// <param name="propertyName"> /// The name of the property to load. /// </param> /// <param name="propertyNode"> /// The node containing the property. /// </param> /// <param name="properties"> /// The collection in which to store the property. /// </param> /// <param name="propertyDescriptors"> /// The collection of property descriptors. /// </param> private static void LoadStringProperty(string propertyName, XmlNode propertyNode, PropertyCollection properties, PropertyDescriptorCollection propertyDescriptors) { Param.AssertValidString(propertyName, "propertyName"); Param.AssertNotNull(propertyNode, "propertyNode"); Param.AssertNotNull(properties, "properties"); Param.AssertNotNull(propertyDescriptors, "propertyDescriptors"); // Get the property descriptor. PropertyDescriptor<string> descriptor = propertyDescriptors[propertyName] as PropertyDescriptor<string>; // Create and add the property. properties.Add(new StringProperty(descriptor, propertyNode.InnerText)); }
protected virtual void SetVariables() { if (_scenario != null) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(this); if (_outputProperties != null) { PropertyDescriptor foundProp = null; foreach (string name in _outputProperties.Keys) { foundProp = props.Find(name, false); string variableName = _outputProperties[name]; if (foundProp != null) { object val = foundProp.GetValue(this); DataTable table = val as DataTable; ICollection list = val as ICollection; if (table != null) { ScenarioVariable <DataTable> tableVar = _scenario.Tables[variableName]; if (tableVar != null) { tableVar.Value = table; } else { _scenario.Tables.AddOrReplace(new ScenarioTable(variableName, table, this)); } } else if (list != null) { string[] stringList = list.Cast <object>().Select( obj => (obj == null) ? "(null)" : obj.ToString()).ToArray(); ScenarioVariable <string[]> l = _scenario.Lists[variableName]; if (l != null) { l.Value = stringList; } else { _scenario.Lists.AddOrReplace(new ScenarioVariable <string[]>(variableName, stringList, this)); } } else if (val != null) { ScenarioVariable <string> v = _scenario.Variables[variableName]; if (v != null) { v.Value = val.ToString(); } else { _scenario.Variables.AddOrReplace(new ScenarioVariable <string>(variableName, val.ToString(), this)); } } } } } } }