public abstract GetValue ( object component ) : object | ||
component | object | |
Résultat | object |
/// <summary> /// Processes the property. /// </summary> /// <param name="value">The value.</param> /// <param name="property">The property.</param> private static void ProcessProperty(object value, PropertyDescriptor property) { if (property.Attributes.Contains(AntiXssHtmlText)) { property.SetValue(value, Sanitizer.GetSafeHtmlFragment((string) property.GetValue(value))); } else if (property.Attributes.Contains(AntiXssIgnore)) { // do nothing this contains special text } else { property.SetValue(value, HttpUtility.HtmlDecode(HttpUtility.HtmlEncode((string)property.GetValue(value)))); } }
/// <summary> /// Processes the property. /// </summary> /// <param name="value">The value.</param> /// <param name="property">The property.</param> private static void ProcessProperty(object value, PropertyDescriptor property) { if (property.Attributes.Contains(AntiXssHtmlText)) { property.SetValue(value, AntiXss.GetSafeHtmlFragment((string) property.GetValue(value))); } }
/// <summary> /// Returns the index of the row that has the given PropertyDescriptor. /// </summary> /// <param name="property">Returns the index of the row that has the given PropertyDescriptor.</param> /// <param name="key">The value of the property parameter to search for. </param> /// <returns>The index of the row that has the given PropertyDescriptor.</returns> internal int Find(System.ComponentModel.PropertyDescriptor property, object key) { int idx = 0; int result = -1; for (idx = 0; idx <= this.Count - 1; idx++) { object value = property.GetValue(this[idx]); switch (property.Name) { case "ValueToString": if ((value == key)) { result = idx; } break; default: if ((value == key)) { result = idx; } break; } if ((result != -1)) { return(result); } } return(0); }
public EnumPropertyItem(PropertyDescriptor property, object instance, IEnumerable values) : base(property, instance) { EnumValues = CollectionViewSource.GetDefaultView(values); EnumValues.MoveCurrentTo(property.GetValue(instance)); EnumValues.CurrentChanged += OnEnumValueChanged; }
private IEnumerable<ValidationError> GetValidationErrorsForProperty(PropertyDescriptor property, object model) { return property.Attributes .OfType<ValidationAttribute>() .Where(x => !x.IsValid(property.GetValue(model))) .Select(x => new ValidationError(property.Name, x.FormatErrorMessage(string.Empty), model)); }
private object GetPropertyValue(IDesignerSerializationManager manager, PropertyDescriptor property, object value, out bool validValue) { object obj2 = null; validValue = true; try { if (!property.ShouldSerializeValue(value)) { AmbientValueAttribute attribute = (AmbientValueAttribute) property.Attributes[typeof(AmbientValueAttribute)]; if (attribute != null) { return attribute.Value; } DefaultValueAttribute attribute2 = (DefaultValueAttribute) property.Attributes[typeof(DefaultValueAttribute)]; if (attribute2 != null) { return attribute2.Value; } validValue = false; } obj2 = property.GetValue(value); } catch (Exception exception) { validValue = false; manager.ReportError(System.Design.SR.GetString("SerializerPropertyGenFailed", new object[] { property.Name, exception.Message })); } return obj2; }
internal bool IsSelectable() { Object runtimeComp = this.RuntimeComponent; Debug.Assert(runtimeComp != null); // the selected datasource must not be private MemberAttributes modifiers = 0; PropertyDescriptor modifiersProp = TypeDescriptor.GetProperties(runtimeComp)["Modifiers"]; if (modifiersProp != null) { modifiers = (MemberAttributes)modifiersProp.GetValue(runtimeComp); } if (modifiers == MemberAttributes.Private) { String message = String.Format(SR.GetString(SR.ListGeneralPage_PrivateMemberMessage), dataSourceName); String caption = SR.GetString(SR.ListGeneralPage_PrivateMemberCaption); MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } // ok to select return(true); }
/// <summary> /// Publish Dependant Component Changes /// </summary> /// <typeparam name="T">Type of property</typeparam> /// <param name="propertyName">Property Name that has changed</param> /// <param name="value">new value for Property</param> private void PublishDependentComponentChanges <T>(string propertyName, T value) { System.ComponentModel.Design.IComponentChangeService changeService = null; System.ComponentModel.PropertyDescriptor property = null; T currentValue = default(T); if (DesignMode && this.Site != null) { property = System.ComponentModel.TypeDescriptor.GetProperties(this)[propertyName]; changeService = (System.ComponentModel.Design.IComponentChangeService) this.Site.GetService(typeof(System.ComponentModel.Design.IComponentChangeService)); if (changeService != null) { currentValue = (T)property.GetValue(this); if (currentValue == null) { currentValue = default(T); } // Trap any error and ignore it changeService.OnComponentChanging(this, property); // try to set new value property.SetValue(this, value); changeService.OnComponentChanged(this, property, currentValue, value); } } }
public EnumPropertyItem(PropertyDescriptor property, object instance) : base(property, instance) { EnumValues = new ListCollectionView(Enum.GetValues(property.PropertyType)); EnumValues.MoveCurrentTo(property.GetValue(instance)); EnumValues.CurrentChanged += OnEnumValueChanged; }
public RelatedCurrencyManager(BindingManagerBase parent, PropertyDescriptor prop_desc) : base(prop_desc.GetValue (parent.Current)) { this.parent = parent; this.prop_desc = prop_desc; parent.PositionChanged += new EventHandler (parent_PositionChanged); }
public OverlayEditBox(object Obj, string propName, Point position) { InitializeComponent(); obj = Obj; prop = TypeDescriptor.GetProperties(obj).Find(propName, true); Location = position; editor.Text = prop.GetValue(obj).ToString(); InputHook.MouseDown += OnGlobalMouseDown; }
public EnumPropertyItem(PropertyDescriptor property, object instance, Type enumsType) : base(property, instance) { var properties = enumsType.GetProperties(); var values = properties.Select(propertyInfo => propertyInfo.GetValue(instance, null)).ToList(); EnumValues = new ListCollectionView(values); EnumValues.MoveCurrentTo(property.GetValue(instance)); EnumValues.CurrentChanged += OnEnumValueChanged; }
public CommandPropertyItem(PropertyDescriptor property, object instance) : base(property, instance) { _command = property.GetValue(instance) as ICommand; if (_command != null) { _command.CanExecuteChanged += CanExecuteChanged; } _executeCommand = new Command<object>(o => _command.Execute(GetCommandParameter()), o => _command != null && _command.CanExecute(GetCommandParameter())); }
public static Func<object,bool> Contains(PropertyDescriptor property, string text) { if (string.IsNullOrEmpty(text)) { return True; } return row => { var value = property.GetValue(row); return value != null && value.ToString().IndexOf(text) >= 0; }; }
internal static System.Globalization.CultureInfo GetDesignModeCulture(System.ComponentModel.IComponent component) { if ((component != null) && (component.Site != null) && component.Site.DesignMode) { System.ComponentModel.Design.IDesignerHost idesignerHost = (System.ComponentModel.Design.IDesignerHost)component.Site.GetService(typeof(System.ComponentModel.Design.IDesignerHost)); System.ComponentModel.PropertyDescriptor propertyDescriptor = System.ComponentModel.TypeDescriptor.GetProperties(idesignerHost.RootComponent)["Language"]; if ((propertyDescriptor != null) && (propertyDescriptor.PropertyType == typeof(System.Globalization.CultureInfo))) { return(propertyDescriptor.GetValue(idesignerHost.RootComponent) as System.Globalization.CultureInfo); } } return(System.Globalization.CultureInfo.InvariantCulture); }
protected override int FindCore(System.ComponentModel.PropertyDescriptor prop, object key) { for (int i = 0; i <= this.Count - 1; i++) { T item = base.Items[i]; if (prop.GetValue(item).Equals(key)) { return(i); } } return(-1); }
private void SerializeNormalProperty (IDesignerSerializationManager manager, object value, PropertyDescriptor descriptor, CodeStatementCollection statements) { CodeExpression leftSide = base.SerializeToExpression (manager, value); CodeExpression rightSide = null; MemberRelationship relationship = GetRelationship (manager, value, descriptor); if (!relationship.IsEmpty) rightSide = new CodePropertyReferenceExpression (base.SerializeToExpression (manager, relationship.Owner), relationship.Member.Name); else rightSide = base.SerializeToExpression (manager, descriptor.GetValue (value)); statements.Add (new CodeAssignStatement (leftSide, rightSide)); }
/// <summary> /// Binds a IEnumerable{SelectList} /// </summary> /// <param name="binder">The binder.</param> /// <param name="controllerContext">The controller context.</param> /// <param name="bindingContext">The binding context.</param> /// <param name="propertyDescriptor">The property descriptor.</param> public static void BindSelectList(this StandardModelBinder binder, ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) { var selectList = (IEnumerable<SelectListItem>)propertyDescriptor.GetValue(bindingContext.Model); if (selectList != null) { //first, need to zero out all selections selectList.UnSelectItems(); binder.SetPropertyValue(controllerContext, bindingContext, propertyDescriptor, val => { selectList.SelectItems(val.Split(',')); return selectList; }); } }
public static object GetValue(object instance, string property) { object value = null; try { PropertyDescriptorCollection propertyDescriptor = TypeDescriptor.GetProperties(instance); System.ComponentModel.PropertyDescriptor myProperty = propertyDescriptor.Find(property, false); value = myProperty.GetValue(instance); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } return(value); }
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) { ModelMetadata propertyMetadata = bindingContext.PropertyMetadata[propertyDescriptor.Name]; propertyMetadata.Model = value; string modelStateKey = CreateSubPropertyName(bindingContext.ModelName, propertyMetadata.PropertyName); // Try to set a value into the property unless we know it will fail (read-only // properties and null values with non-nullable types) if (!propertyDescriptor.IsReadOnly) { try { if (value == null) { propertyDescriptor.SetValue(bindingContext.Model, value); } else { Type valueType = value.GetType(); if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { IListSource ls = (IListSource)propertyDescriptor.GetValue(bindingContext.Model); IList list = ls.GetList(); foreach (var item in (IEnumerable)value) { list.Add(item); } } else { propertyDescriptor.SetValue(bindingContext.Model, value); } } } catch (Exception ex) { // Only add if we're not already invalid if (bindingContext.ModelState.IsValidField(modelStateKey)) { bindingContext.ModelState.AddModelError(modelStateKey, ex); } } } }
public void SetEditValue(System.ComponentModel.PropertyDescriptor property, object value) { if (mEditItem == null) { throw new DevAgeApplicationException("There isn't a row in editing state, call BeginAddNew or BeginEdit first"); } //Save the previous value to enable the restore if the user cancel the editing if (mPreviousValues.ContainsKey(property) == false) { mPreviousValues.Add(property, property.GetValue(mEditItem)); } property.SetValue(mEditItem, value); OnListChanged(new System.ComponentModel.ListChangedEventArgs(System.ComponentModel.ListChangedType.ItemChanged, mEditIndex, property)); }
/// <summary> /// Sets the property value to the new value</summary> /// <param name="owner">Object whose property is set</param> /// <param name="descriptor">Property descriptor</param> /// <param name="value">New property value</param> public static void SetProperty(object owner, PropertyDescriptor descriptor, object value) { try { TypeConverter converter = descriptor.Converter; if (converter != null && value != null && converter.CanConvertFrom(value.GetType())) { value = converter.ConvertFrom(value); } bool notifyChange = false; object oldValue = null; EventHandler <PropertyEditedEventArgs> handler = PropertyEdited; if (handler != null) { oldValue = descriptor.GetValue(owner); notifyChange = !PropertyUtils.AreEqual(oldValue, value); } descriptor.SetValue(owner, value); if (notifyChange) { PropertyEditedEventArgs eventArgs = new PropertyEditedEventArgs(owner, descriptor, oldValue, value); handler(null, eventArgs); } } catch (InvalidTransactionException) { // The transaction needs to be cancelled. throw; } catch (Exception ex) { PropertyErrorEventArgs eventArgs = new PropertyErrorEventArgs(owner, descriptor, ex); PropertyError.Raise(null, eventArgs); if (!eventArgs.Cancel) { Outputs.WriteLine(OutputMessageType.Error, ex.Message); } } }
/// <inheritdoc/> protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) { string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name); // Only bind properties that are part of the request if (bindingContext.ValueProvider.DoesAnyKeyHavePrefix(fullPropertyKey)) { var innerContext = new ModelBindingContext() { Model = propertyDescriptor.GetValue(bindingContext.Model), ModelName = fullPropertyKey, ModelState = bindingContext.ModelState, ModelType = propertyDescriptor.PropertyType, ValueProvider = bindingContext.ValueProvider }; IModelBinder binder = Binders.GetBinder(propertyDescriptor.PropertyType); object newPropertyValue = ConvertValue(propertyDescriptor, binder.BindModel(controllerContext, innerContext)); ModelState modelState = bindingContext.ModelState[fullPropertyKey]; // Only validate and bind if the property itself has no errors if (modelState.Errors.Count == 0) { if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue)) { SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue); OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue); } } // There was an error getting the value from the binder, which was probably a format // exception (meaning, the data wasn't appropriate for the field) else { foreach (var error in modelState.Errors.Where(err => err.ErrorMessage == "" && err.Exception != null).ToList()) { for (var exception = error.Exception; exception != null; exception = exception.InnerException) { if (exception is FormatException) { string displayName = GetDisplayName(propertyDescriptor); string errorMessage = InvalidValueFormatter(propertyDescriptor, modelState.Value.AttemptedValue, displayName); modelState.Errors.Remove(error); modelState.Errors.Add(errorMessage); break; } } } } } }
private object GetAttributeValue(object obj, string attributeName) { Check.Require(obj != null, string.Format(CommonStrings.XMustNotBeNull, "obj")); System.ComponentModel.PropertyDescriptorCollection propertyDescriptorCollection = System.ComponentModel.TypeDescriptor.GetProperties(obj); System.ComponentModel.PropertyDescriptor property = propertyDescriptorCollection.Find(attributeName, true); if (property == null) { return(null); } object attributeObj = property.GetValue(obj); return(attributeObj); }
public override IDataValue GetDataValue(PropertyDescriptor propertyDescriptor, object data) { if (propertyDescriptor.PropertyType.IsArray && propertyDescriptor.PropertyType.GetElementType().Equals(typeof(byte))) { byte[] value = propertyDescriptor.GetValue(data) as byte[]; if (value != null) { return new DataValue(propertyDescriptor.Name, MySqlFunctions.Unhex(ByteArrayToHexString(value)), false); } else { return new DataValue(propertyDescriptor.Name, null); } } else { return base.GetDataValue(propertyDescriptor, data); } }
/// <summary> /// Validates the given instance. /// </summary> /// <param name="instance">The instance that should be validated.</param> /// <param name="attribute">The <see cref="ValidationAttribute"/> that should be handled.</param> /// <param name="descriptor">A <see cref="PropertyDescriptor"/> instance for the property that is being validated.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="ModelValidationRule"/> instances.</returns> public virtual IEnumerable<ModelValidationError> Validate(object instance, ValidationAttribute attribute, PropertyDescriptor descriptor) { var context = new ValidationContext(instance, null, null) { MemberName = descriptor == null ? null : descriptor.Name }; if(descriptor != null) { instance = descriptor.GetValue(instance); } var result = attribute.GetValidationResult(instance, context); if (result != null) { yield return new ModelValidationError(result.MemberNames, string.Join(" ", result.MemberNames.Select(attribute.FormatErrorMessage))); } }
public PropertyChangedHistoryEntry(object ATarget, List<PropertyDescriptor> PropertyChain, object AOldValue) { destSlide = PresentationController.Instance.SelectedSlide; _Target = ATarget; OldValue = AOldValue; SingleProperty = PropertyChain[0]; if (PropertyChain.Count == 1) { NewValue = SingleProperty.GetValue(_Target); } else { object value = null; object target = _Target; //Chain = new Dictionary<PropertyDescriptor, object>(); NewChain = new List<ValueTypeChainItem>(); bool shouldContinue = true; for (int i = PropertyChain.Count - 1; i >= 1 && shouldContinue; --i) { value = PropertyChain[i].GetValue(target); if (PropertyChain[i].PropertyType.IsValueType) { //Chain.Add(PropertyChain[i], value); NewChain.Add(new ValueTypeChainItem(PropertyChain[i], value, target)); shouldContinue = false; //break; } target = value; } //Chain.Add(PropertyChain[0], OldValue); NewChain.Add(new ValueTypeChainItem(PropertyChain[0], OldValue, target)); if (value != null) NewValue = PropertyChain[0].GetValue(value); _ComponentChangedValue = target; } }
/// <summary> /// Gets culture formatted text representing the property's value</summary> /// <param name="owner">Object whose property text is obtained</param> /// <param name="descriptor">Property descriptor</param> /// <returns>Culture formatted text representing the property's value</returns> public static string GetPropertyText(object owner, PropertyDescriptor descriptor) { string result = string.Empty; // With reflected child property descriptors it is possible to get descriptors // that are supposed to operate on a referenced child rather than the object itself // Using a PropertyDescriptor on an object type it's not designed for often // leads to an exception, which this check safeguards against. if (owner != null && !owner.Is <ICustomTypeDescriptor>() && !descriptor.ComponentType.IsAssignableFrom(owner.GetType())) { return(result); } object value = descriptor.GetValue(owner); if (value != null) { TypeConverter converter = descriptor.Converter; if (converter != null && converter.CanConvertTo(typeof(string))) { result = converter.ConvertTo(value, typeof(string)) as string; } if (string.IsNullOrEmpty(result)) { IFormattable formattable = value as IFormattable; if (formattable != null) { result = formattable.ToString(null, CultureInfo.CurrentUICulture); } else { result = value.ToString(); } } } return(result); }
public ComponentChangeDispatcher(IServiceProvider serviceProvider, object component, PropertyDescriptor propertyDescriptor) { this.serviceProvider = serviceProvider; this.component = component; this.property = propertyDescriptor; IComponentChangeService service = serviceProvider.GetService(typeof(IComponentChangeService)) as IComponentChangeService; if (service != null) { try { this.newValue = this.oldValue = propertyDescriptor.GetValue(component); propertyDescriptor.AddValueChanged(component, new EventHandler(this.OnValueChanged)); service.OnComponentChanging(component, propertyDescriptor); } catch (CheckoutException exception) { if (exception != CheckoutException.Canceled) { throw exception; } } } }
/// <summary> /// Serializes a specific property to code. /// </summary> /// <param name="instanceHolder">The parent expression that holds the instance.</param> /// <param name="instance">The instance to take away the values from.</param> /// <param name="property">The property to serialize.</param> /// <returns>A collection of code statements initiating the given property of the given object to its value.</returns> public CodeStatementCollection SerializeProperty(CodeExpression instanceHolder, object instance, PropertyDescriptor property) { CodeStatementCollection statements = new CodeStatementCollection(); var propertyExpression = new CodePropertyReferenceExpression( instanceHolder, property.Name); object propertyValue = property.GetValue(instance); if (property.PropertyType.HasInterface(typeof(ICollection))) { // If collection, create property.Add(...) statements. statements.AddRange(CreateCollectionInitialization(propertyExpression, instance, property)); } else if (CodeDomTypeFormatter.IsFormattableWithAssignment(property.PropertyType)) { // else, create normal property = value statement. statements.Add(CreatePropertyAssignmentExpression(propertyExpression, instance, property)); } if (!CodeDomTypeFormatter.IsFormattableWithAssignment(property.PropertyType)) { // serialize child properties. if (property.PropertyType.IsValueType) { // value types uses a temp var.to access properties. statements.AddRange(CreateValueTypeInitialization(propertyExpression, instance, property)); } else { // access properties directly. statements.AddRange(SerializeProperties(propertyExpression, propertyValue)); } } return statements; }
/// <summary> /// Validates the given instance. /// </summary> /// <param name="instance">The instance that should be validated.</param> /// <param name="attribute">The <see cref="ValidationAttribute"/> that should be handled.</param> /// <param name="descriptor">A <see cref="PropertyDescriptor"/> instance for the property that is being validated.</param> /// <param name="context">The <see cref="NancyContext"/> of the current request.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="ModelValidationRule"/> instances.</returns> public virtual IEnumerable<ModelValidationError> Validate(object instance, ValidationAttribute attribute, PropertyDescriptor descriptor, NancyContext context) { var validationContext = new ValidationContext(instance, null, null) { MemberName = descriptor == null ? null : descriptor.Name }; // When running on Mono the Display attribute is not auto populated so for now we do it ourselves if (IsRunningOnMono) { var displayName = this.GetDisplayNameForMember(instance, validationContext.MemberName); if (!string.IsNullOrEmpty(displayName)) { validationContext.DisplayName = displayName; } } if (descriptor != null) { // Display(Name) will auto populate the context, while DisplayName() needs to be manually set if (validationContext.MemberName == validationContext.DisplayName && !string.IsNullOrEmpty(descriptor.DisplayName)) { validationContext.DisplayName = descriptor.DisplayName; } instance = descriptor.GetValue(instance); } var result = attribute.GetValidationResult(instance, validationContext); if (result != null) { yield return this.GetValidationError(result, validationContext, attribute); } }
protected void BindProperty(BindingContext context, PropertyDescriptor property) { string propertyKey = CreateSubMemberName(context.ModelName, property.Name); // В случае с типом значения нужно задать значение по умолчанию, // иначе частичная инициализация объекта не удастся. object value = property.PropertyType.CreateInstance(); if (context.Contains(propertyKey)) { BindingContext inner = new BindingContext(context, property.PropertyType, propertyKey, context.ValueProvider, context.ModelState) { Model = property.GetValue(context.Model) }; value = GetPropertyValue(inner, property); } if (OnPropertyUpdating(context, property, value)) { SetProperty(context, property, value); OnPropertyUpdated(context, property, value); } }
private void ApplyChangesToRuntimeChoice_helper( PropertyDescriptor property, Object sourceTarget, Object destTarget, String prefix ) { Object oldValue = property.GetValue(sourceTarget); Object newValue = property.GetValue(destTarget); String propertyName = prefix + property.Name; if(property.Converter is ExpandableObjectConverter) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties( newValue.GetType() ); foreach(PropertyDescriptor embeddedProperty in properties) { if(IsDeviceOverridable(embeddedProperty)) { ApplyChangesToRuntimeChoice_helper( embeddedProperty, oldValue, newValue, propertyName + "-" ); } } } else if(IsDeviceOverridable(property)) { IAttributeAccessor overrides = (IAttributeAccessor)_choice; String oldValueString = property.Converter.ConvertToInvariantString( oldValue ); String newValueString = property.Converter.ConvertToInvariantString( newValue ); if(newValueString != oldValueString) { overrides.SetAttribute(propertyName, newValueString); } else { // Clear any previous values we might have loaded overrides.SetAttribute(propertyName, null); } } }
private void ApplyChoiceToRuntimeControl_helper( PropertyDescriptor property, Object target, String prefix ) { String propertyName = prefix + property.Name; String value = ((IAttributeAccessor)_choice).GetAttribute(propertyName) as String; if(property.Converter is ExpandableObjectConverter) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties( property.PropertyType ); foreach(PropertyDescriptor embeddedProperty in properties) { if(IsDeviceOverridable(embeddedProperty)) { ApplyChoiceToRuntimeControl_helper( embeddedProperty, property.GetValue(target), propertyName + "-" ); } } return; } if(value != null) { try { property.SetValue( target, property.Converter.ConvertFromString(value) ); } catch { GenericUI.ShowWarningMessage( SR.GetString(SR.PropertyOverridesDialog_Title), SR.GetString( SR.PropertyOverridesDialog_InvalidPropertyValue, value, propertyName ) ); } } }
public object GetItemValue(int index, System.ComponentModel.PropertyDescriptor property) { return(property.GetValue(this[index])); }
public override object GetValue(object component) { return(Descriptor.GetValue(component)); }
private void WriteProperty(object valueProvider, bool firstParameter, MemoryStream result, PropertyDescriptor property) { if (!firstParameter) result.WriteByte(and); UrlEncodeAndWrite(property.Name, result); result.WriteByte(@equals); var propertyValue = property.GetValue(valueProvider); var formattableValue = propertyValue as IFormattable; string stringValue = null; if (formattableValue != null) stringValue = formattableValue.ToString(null, CultureInfo.InvariantCulture); else if (propertyValue != null) stringValue = propertyValue.ToString(); if (stringValue != null) { UrlEncodeAndWrite(stringValue, result); } }
protected virtual object GetValue(Control controlContainer, string fieldName, ref PropertyDescriptor cachedDescriptor) { object obj2 = null; object component = null; if (controlContainer == null) { throw new HttpException(System.Web.SR.GetString("DataControlField_NoContainer")); } component = DataBinder.GetDataItem(controlContainer); if ((component == null) && !base.DesignMode) { throw new HttpException(System.Web.SR.GetString("DataItem_Not_Found")); } if ((cachedDescriptor == null) && !fieldName.Equals(ThisExpression)) { cachedDescriptor = TypeDescriptor.GetProperties(component).Find(fieldName, true); if ((cachedDescriptor == null) && !base.DesignMode) { throw new HttpException(System.Web.SR.GetString("Field_Not_Found", new object[] { fieldName })); } } if ((cachedDescriptor != null) && (component != null)) { return cachedDescriptor.GetValue(component); } if (!base.DesignMode) { obj2 = component; } return obj2; }
/// <summary> /// Helper method for writing the XML element. /// </summary> /// <param name="writer">The writer.</param> /// <param name="property">The property.</param> /// <param name="flow">The flow.</param> private void WriteXmlElement(XmlWriter writer, PropertyDescriptor property, object flow) { IEnumerable<System.Xml.Serialization.XmlElementAttribute> attribs = property.Attributes.OfType<System.Xml.Serialization.XmlElementAttribute>(); System.Xml.Serialization.XmlElementAttribute xmlAttrib = attribs.ElementAtOrDefault(0); if (xmlAttrib != null) { object prop = property.GetValue(flow); if (prop != null) { var serializer = Serialization.XmlSerializerFactory.GetSerializer(prop.GetType(), null); serializer.Serialize(writer, prop); } } }
public override bool ValidValue(object dataValue) { Check.Require(dataValue != null, string.Format(CommonStrings.XMustNotBeNull, "dataValue")); IRmType rmType = dataValue as IRmType; Check.Require(rmType != null, string.Format(AmValidationStrings.ValueMustImplementIRmType, dataValue.GetType().ToString())); bool result = true; rmType.Constraint = this; if (!IsSameRmType(rmType)) { result = false; ValidationContext.AcceptValidationError(this, string.Format(AmValidationStrings.IncorrectRmType, RmTypeName, rmType.GetRmTypeName())); } if (!result || !AnyAllowed()) { OpenEhr.RM.Common.Archetyped.Impl.Locatable locatable = dataValue as OpenEhr.RM.Common.Archetyped.Impl.Locatable; if (locatable != null) { ValidationUtility.PopulateLocatableAttributes(this, locatable); if (Parent != null && ArchetypeNodeId != locatable.ArchetypeNodeId) { result = false; ValidationContext.AcceptValidationError(this, string.Format(AmValidationStrings.IncorrectNodeId, ArchetypeNodeId, locatable.ArchetypeNodeId)); } } System.ComponentModel.PropertyDescriptorCollection propertyDescriptorCollection = System.ComponentModel.TypeDescriptor.GetProperties(dataValue); if (Attributes != null) { foreach (CAttribute cAttribute in Attributes) { object attributeObject = null; string attributeName = RmFactory.GetOpenEhrV1RmName(cAttribute.RmAttributeName); System.ComponentModel.PropertyDescriptor property = propertyDescriptorCollection.Find(attributeName, true); // if the attributeName is not a class property, it must be a class function. if (property == null) { System.Reflection.MethodInfo method = dataValue.GetType().GetMethod(attributeName); if (method == null) { result = false; ValidationContext.AcceptValidationError(this, string.Format(AmValidationStrings.UnexpectedAttributeX, attributeName)); continue; } else { attributeObject = method.Invoke(dataValue, null); } } else { attributeObject = property.GetValue(dataValue); } if (attributeObject == null) { if (cAttribute.Existence.Lower > 0) { result = false; ValidationContext.AcceptValidationError(this, string.Format(AmValidationStrings.TmExpectedConstraintMissing, cAttribute.RmAttributeName)); } } else if (cAttribute.Existence.Upper == 0) { result = false; ValidationContext.AcceptValidationError(this, string.Format(AmValidationStrings.TmForbiddenConstraint, cAttribute.RmAttributeName)); } else if (!cAttribute.ValidValue(attributeObject)) { result = false; } else { DvCodedText codedText = dataValue as DvCodedText; if (codedText != null && cAttribute.RmAttributeName == "defining_code") { // validate the code string before validating the coded value if (codedText.DefiningCode.TerminologyId.Value == "local") { CObject parentObject = cAttribute.parent; CArchetypeRoot cArchetypeRoot = ValidationUtility.GetCArchetypeRoot(parentObject); if (!cArchetypeRoot.TermDefinitions.HasKey(codedText.DefiningCode.CodeString)) { result = false; string code = codedText.DefiningCode == null ? "" : codedText.DefiningCode.CodeString; ValidationContext.AcceptValidationError(this, string.Format("code {0} is not existing archetype term", code)); } } if (result && !ValidationUtility.ValidValueTermDef(codedText, cAttribute, ValidationContext.TerminologyService)) { result = false; string code = codedText.DefiningCode == null ? "" : codedText.DefiningCode.CodeString; ValidationContext.AcceptValidationError(this, string.Format(AmValidationStrings.TextValueXInvalidForCodeY, codedText.Value, code)); } } } } } } return(result); }
public InheritedPropertyDescriptor(System.ComponentModel.PropertyDescriptor propertyDescriptor, object component, bool rootComponent) : base(propertyDescriptor, new Attribute[0]) { this.propertyDescriptor = propertyDescriptor; this.InitInheritedDefaultValue(component, rootComponent); bool flag = false; if (typeof(ICollection).IsAssignableFrom(propertyDescriptor.PropertyType) && propertyDescriptor.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content)) { ICollection instance = propertyDescriptor.GetValue(component) as ICollection; if ((instance != null) && (instance.Count > 0)) { bool flag2 = false; bool flag3 = false; foreach (MethodInfo info in TypeDescriptor.GetReflectionType(instance).GetMethods(BindingFlags.Public | BindingFlags.Instance)) { ParameterInfo[] parameters = info.GetParameters(); if (parameters.Length == 1) { string name = info.Name; Type c = null; if (name.Equals("AddRange") && parameters[0].ParameterType.IsArray) { c = parameters[0].ParameterType.GetElementType(); } else if (name.Equals("Add")) { c = parameters[0].ParameterType; } if (c != null) { if (!typeof(IComponent).IsAssignableFrom(c)) { flag3 = true; } else { flag2 = true; break; } } } } if (flag3 && !flag2) { ArrayList list = new ArrayList(this.AttributeArray); list.Add(DesignerSerializationVisibilityAttribute.Hidden); list.Add(ReadOnlyAttribute.Yes); list.Add(new EditorAttribute(typeof(UITypeEditor), typeof(UITypeEditor))); list.Add(new TypeConverterAttribute(typeof(ReadOnlyCollectionConverter))); Attribute[] attributeArray = (Attribute[])list.ToArray(typeof(Attribute)); this.AttributeArray = attributeArray; flag = true; } } } if (!flag && (this.defaultValue != noDefault)) { ArrayList list2 = new ArrayList(this.AttributeArray); list2.Add(new DefaultValueAttribute(this.defaultValue)); Attribute[] array = new Attribute[list2.Count]; list2.CopyTo(array, 0); this.AttributeArray = array; } }
private void AddNodes(int currGroupIndex, ref int currentListIndex, TreeNodeCollection currNodes, String prevGroupByField) { IList innerList = this.m_currencyManager.List; System.ComponentModel.PropertyDescriptor pdPrevGroupBy = null; string prevGroupByValue = null;; Group currGroup; if (prevGroupByField != "") { pdPrevGroupBy = this.m_currencyManager.GetItemProperties()[prevGroupByField]; } currGroupIndex += 1; if (treeGroups.Count > currGroupIndex) { currGroup = ( Group)treeGroups[currGroupIndex]; PropertyDescriptor pdGroupBy = null; PropertyDescriptor pdValue = null; PropertyDescriptor pdDisplay = null; pdGroupBy = this.m_currencyManager.GetItemProperties()[currGroup.GroupBy]; pdValue = this.m_currencyManager.GetItemProperties()[currGroup.ValueMember]; pdDisplay = this.m_currencyManager.GetItemProperties()[currGroup.DisplayMember]; string currGroupBy = null; if (innerList.Count > currentListIndex) { if (pdPrevGroupBy != null) { prevGroupByValue = pdPrevGroupBy.GetValue(innerList[currentListIndex]).ToString(); } dbTreeNode myFirstNode = null; object currObject = null; while ((currentListIndex < innerList.Count) && (pdPrevGroupBy != null) && (pdPrevGroupBy.GetValue(innerList[currentListIndex]).ToString() == prevGroupByValue)) { currObject = innerList[currentListIndex]; if (pdGroupBy.GetValue(currObject).ToString() != currGroupBy) { currGroupBy = pdGroupBy.GetValue(currObject).ToString(); myFirstNode = new dbTreeNode(currGroup.Name, pdDisplay.GetValue(currObject).ToString(), currObject, pdValue.GetValue(innerList[currentListIndex]), currGroup.ImageIndex, currGroup.SelectedImageIndex, currentListIndex); currNodes.Add((TreeNode)myFirstNode); } else { AddNodes(currGroupIndex, ref currentListIndex, myFirstNode.Nodes, currGroup.GroupBy); } } } } else { dbTreeNode myNewLeafNode; object currObject = this.m_currencyManager.List[currentListIndex]; if ((this.DisplayMember != null) && (this.ValueMember != null) && (this.DisplayMember != "") && (this.ValueMember != "")) { PropertyDescriptor pdDisplayloc = this.m_currencyManager.GetItemProperties()[this.DisplayMember]; PropertyDescriptor pdValueloc = this.m_currencyManager.GetItemProperties()[this.ValueMember]; myNewLeafNode = new dbTreeNode(this.Tag == null ? "" : this.Tag.ToString(), pdDisplayloc.GetValue(currObject).ToString(), currObject, pdValueloc.GetValue(currObject), currentListIndex); } else { myNewLeafNode = new dbTreeNode("", currentListIndex.ToString(), currObject, currObject, this.ImageIndex, this.SelectedImageIndex, currentListIndex); } currNodes.Add((TreeNode)myNewLeafNode); currentListIndex += 1; } }
private static Func<object> GetPropertyValueAccessor(object container, PropertyDescriptor property) { return () => property.GetValue(container); }
protected virtual object GetValue(RowItem rowItem, PropertyDescriptor propertyDescriptor) { return propertyDescriptor.GetValue(rowItem); }
private void CopyProperty(PropertyDescriptor property, Object source, Object dest) { Object value = property.GetValue(source); if(property.Converter is ExpandableObjectConverter) { if(value is ICloneable) { value = ((ICloneable)value).Clone(); } else { throw new Exception( SR.GetString( SR.PropertyOverridesDialog_NotICloneable, property.Name, property.PropertyType.FullName ) ); } } property.SetValue(dest, value); }