SetValue() public abstract method

When overridden in a derived class, sets the value of the component to a different value.

public abstract SetValue ( object component, object value ) : void
component object
value object
return void
コード例 #1
0
ファイル: AntiXssAttribute.cs プロジェクト: vlko/vlko
 /// <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))));
     }
 }
コード例 #2
0
ファイル: AntiXssAttribute.cs プロジェクト: vlko/jobs
 /// <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)));
     }
 }
コード例 #3
0
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            var performValidation = controllerContext.Controller.ValidateRequest &&
                                    bindingContext.ModelMetadata.RequestValidationEnabled;

            var propertyBinderAttribute = propertyDescriptor
                .Attributes
                .OfType<DataMemberAttribute>()
                .FirstOrDefault();

            var modelName = propertyBinderAttribute == null ? bindingContext.ModelName : propertyBinderAttribute.Name;

            var result = performValidation 
                ? bindingContext.ValueProvider.GetValue(modelName) 
                : bindingContext.GetUnvalidatedValue(modelName);

            if (result == null)
            {
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
            else
            {
                propertyDescriptor.SetValue(bindingContext.Model, result.AttemptedValue);
            }
        }
コード例 #4
0
        /// <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);
                }
            }
        }
コード例 #5
0
ファイル: JsonModelBinder.cs プロジェクト: softgears/kartel
 /// <summary>
 /// Binds the specified property by using the specified controller context and binding context and the specified property descriptor.
 /// </summary>
 /// <param name="controllerContext">The context within which the controller operates. The context information includes the controller, HTTP content, request context, and route data.</param><param name="bindingContext">The context within which the model is bound. The context includes information such as the model object, model name, model type, property filter, and value provider.</param><param name="propertyDescriptor">Describes a property to be bound. The descriptor provides information such as the component type, property type, and property value. It also provides methods to get or set the property value.</param>
 protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
 {
     var jsonAttribute = (JsonPropertyAttribute) propertyDescriptor.Attributes.Cast<Attribute>().FirstOrDefault(a => a is JsonPropertyAttribute);
     if (jsonAttribute != null)
     {
         var propertyName = jsonAttribute.PropertyName;
         var form = controllerContext.HttpContext.Request.Unvalidated().Form;
         if (form.AllKeys.Contains(propertyName) && propertyDescriptor.Converter != null)
         {
             var propertyValue = form[propertyName];
             if (propertyDescriptor.PropertyType == typeof(bool) || propertyDescriptor.PropertyType == typeof(bool?))
             {
                 if (propertyValue != null && propertyValue == "on")
                 {
                     propertyValue = "true";
                 } else
                 {
                     propertyValue = "false";
                 }
             }
             propertyDescriptor.SetValue(bindingContext.Model, propertyDescriptor.Converter.ConvertFrom(propertyValue));
         }
     }
     else
     {
         base.BindProperty(controllerContext,bindingContext,propertyDescriptor);
     }
 }
コード例 #6
0
ファイル: CustomModelBinder.cs プロジェクト: Webalap/W-ALAP
 protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
 {
     // Check if the property has the PropertyBinderAttribute, meaning it's specifying a different binder to use.
     try
     {
         var propertyBinderAttribute = TryFindPropertyBinderAttribute(propertyDescriptor);
         if (propertyBinderAttribute != null)
         {
             var binder = CreateBinder(propertyBinderAttribute);
             var value  = binder.BindModel(controllerContext, bindingContext);
             try
             {
                 propertyDescriptor.SetValue(bindingContext.Model, value);
             }
             catch { }
         }
         else // revert to the default behavior.
         {
             base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
         }
     }
     catch (Exception)
     {
     }
 }
コード例 #7
0
        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);
                    }
                }
            }
        }
コード例 #8
0
 // Helper method to safely set a component’s property
 private void SetProperty(string propertyName, object value)
 {
     // Get property
     System.ComponentModel.PropertyDescriptor property
         = System.ComponentModel.TypeDescriptor.GetProperties(this.Panel)[propertyName];
     // Set property value
     property.SetValue(this.Panel, value);
 }
コード例 #9
0
ファイル: UserBinder.cs プロジェクト: Ordojan/Electronix
        protected override void BindProperty(ControllerContext controllerContext,
                                            ModelBindingContext bindingContext,
                                            PropertyDescriptor propertyDescriptor)
        {
            if (propertyDescriptor.Name == "Password") {
                var password = controllerContext.HttpContext.Request.Form["Password"];
                var confirmPassword = controllerContext.HttpContext.Request.Form["ConfirmPassword"];

                if (password == confirmPassword)
                    propertyDescriptor.SetValue(bindingContext.Model, password);
                else
                    propertyDescriptor.SetValue(bindingContext.Model, "");

                return;
            }

            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
        }
コード例 #10
0
 public static void SetValue(object instance, string property, object value)
 {
     try
     {
         PropertyDescriptorCollection             propertyDescriptor = TypeDescriptor.GetProperties(instance);
         System.ComponentModel.PropertyDescriptor myProperty         = propertyDescriptor.Find(property, false);
         myProperty.SetValue(instance, value);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message.ToString());
     }
 }
コード例 #11
0
 /// <summary>
 /// Привязывает указанное свойство, используя заданные контекст контроллера и контекст привязки, а также заданный дескриптор свойства.
 /// </summary>
 /// <param name="controllerContext">Контекст, в котором функционирует контроллер.Сведения о контексте включают информацию о контроллере, HTTP-содержимом, контексте запроса и данных маршрута.</param><param name="bindingContext">Контекст, в котором привязана модель.Контекст содержит такие сведения, как объект модели, имя модели, тип модели, фильтр свойств и поставщик значений.</param><param name="propertyDescriptor">Описывает свойство, которое требуется привязать.Дескриптор предоставляет информацию, такую как тип компонента, тип свойства и значение свойства.Также предоставляет методы для получения или задания значения свойства.</param>
 protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
 {
     if (propertyDescriptor.PropertyType == typeof(DateTime))
     {
         var submittedVal = controllerContext.HttpContext.Request[propertyDescriptor.Name];
         if (!String.IsNullOrEmpty(submittedVal))
         {
             DateTime val = DateTime.MinValue;
             try
             {
                 val = Convert.ToDateTime(submittedVal);
             }
             catch (Exception)
             {
             }
             propertyDescriptor.SetValue(bindingContext.Model, val);
         }
     }
     else if (propertyDescriptor.PropertyType == typeof(DateTime?))
     {
         var submittedVal = controllerContext.HttpContext.Request[propertyDescriptor.Name];
         if (!String.IsNullOrEmpty(submittedVal))
         {
             DateTime? val = null;
             try
             {
                 val = Convert.ToDateTime(controllerContext.HttpContext.Request[propertyDescriptor.Name]);
             }
             catch (Exception)
             {
                 val = null;
             }
             propertyDescriptor.SetValue(bindingContext.Model, val);
         }
     } else
     {
         base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
     }
 }
コード例 #12
0
        protected override void BindProperty(ControllerContext controllerContext,
                                             ModelBindingContext bindingContext,
                                             PropertyDescriptor propertyDescriptor)
        {
            if (propertyDescriptor.Name == CategoryPDN) {
                var input = controllerContext.HttpContext.Request.Form[CategoryKey];
                var category = new Category { Id = Guid.Parse(input) };
                propertyDescriptor.SetValue(bindingContext.Model, category);

                return;
            }

            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
        }
コード例 #13
0
 protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
 {
     // Check if the property has the PropertyBinderAttribute, meaning
     // it's specifying a different binder to use.
     var propertyBinderAttribute = TryFindPropertyBinderAttribute(propertyDescriptor);
     if (propertyBinderAttribute != null) {
         var binder = propertyBinderAttribute.GetPropertyBinder();
         var value = binder.BindProperty(controllerContext, bindingContext, propertyDescriptor);
         propertyDescriptor.SetValue(bindingContext.Model, value);
     } else // revert to the default behavior.
     {
         base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
     }
 }
コード例 #14
0
        void BindParentProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            //var binder = ModelBinders.Binders.GetBinder(propertyDescriptor.PropertyType, true);
            var parentBindingContext = new ModelBindingContext
            {
                //ModelType = propertyDescriptor.PropertyType,  - not valid in .Net 4 replaced with following
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, propertyDescriptor.PropertyType),

                ValueProvider = bindingContext.ValueProvider
            };
            //var parent = binder.BindModel(controllerContext, parentBindingContext);
            var parent = BindModel(controllerContext, parentBindingContext);
            propertyDescriptor.SetValue(bindingContext.Model, parent);
        }
コード例 #15
0
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            var model = (RichTextBoxPreValueModel) bindingContext.Model;

            switch (propertyDescriptor.Name)
            {               
                case "Features":
                    var features = model.GetFeatures().ToArray();
                    foreach (var e in features)
                    {
                        //get the values from the value provider for each element
                        var valueName = string.Concat(bindingContext.ModelName, ".", propertyDescriptor.Name, ".", e.Value);
                        var value = bindingContext.ValueProvider.GetValue(valueName);
                        if(value != null)
                            e.Selected = bool.Parse(((string[])value.RawValue)[0]);
                    }
                    propertyDescriptor.SetValue(bindingContext.Model, features);
                    break;
                case "Stylesheets":
                    var stylesheets = model.GetStylesheets().ToArray();
                    foreach (var e in stylesheets)
                    {
                        //get the values from the value provider for each element
                        var valueName = string.Concat(bindingContext.ModelName, ".", propertyDescriptor.Name, ".", e.Value);
                        var value = bindingContext.ValueProvider.GetValue(valueName);
                        if (value != null)
                            e.Selected = bool.Parse(((string[])value.RawValue)[0]);
                    }
                    propertyDescriptor.SetValue(bindingContext.Model, stylesheets);
                    break;
                default:
                    base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
                    break;
            }

        }
コード例 #16
0
ファイル: ExtendedModelBinder.cs プロジェクト: dnmsk/rProject
 protected override void BindProperty(
     ControllerContext controllerContext,
     ModelBindingContext bindingContext,
     PropertyDescriptor propertyDescriptor)
 {
     var propertyBinderAttribute = TryFindPropertyBinderAttribute(propertyDescriptor);
     if (propertyBinderAttribute != null) {
         var binder = CreateBinder(propertyBinderAttribute);
         var value = binder.BindModel(propertyBinderAttribute.BindParam, controllerContext, bindingContext, propertyDescriptor);
         propertyDescriptor.SetValue(bindingContext.Model, value);
     } else // revert to the default behavior.
       {
         base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
     }
 }
コード例 #17
0
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);
              if (propertyDescriptor.PropertyType == typeof(double?) || propertyDescriptor.PropertyType == typeof(double)) {
            var valueProvider = bindingContext.ValueProvider.GetValue(fullPropertyKey);

            if (valueProvider != null) {
              double value = 0;
              if (double.TryParse(valueProvider.AttemptedValue, NumberStyles.Number, new CultureInfo("pt-BR").NumberFormat, out value)) {
            propertyDescriptor.SetValue(bindingContext.Model, value);
              }
            }

              } else
            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
        }
コード例 #18
0
        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));
        }
コード例 #19
0
 protected override void BindProperty(
     ControllerContext controllerContext,
     ModelBindingContext bindingContext,
     PropertyDescriptor propertyDescriptor)
 {
     var propertyBinderAttribute = propertyDescriptor.TryFindPropertyBinderAttribute();
     if (propertyBinderAttribute != null)
     {
         var binder = this.CreateBinder(propertyBinderAttribute);
         var value = binder.BindModel(controllerContext, bindingContext, propertyDescriptor);
         propertyDescriptor.SetValue(bindingContext.Model, value);
     }
     else
     {
         base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
     }
 }
コード例 #20
0
        /// <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);
                }
            }
        }
コード例 #21
0
        protected override void BindProperty(
            ControllerContext controllerContext,
            ModelBindingContext bindingContext,
            PropertyDescriptor propertyDescriptor)
        {
            bool isTypeBool = GetIsTypeBoolean(propertyDescriptor.PropertyType);
            if (isTypeBool)
            {
                var valueProviderResult = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);

                bool? value = GetBooleanValue(valueProviderResult);
                if (value.HasValue)
                {
                    propertyDescriptor.SetValue(bindingContext.Model, value.Value);
                }
            }

            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
        }
コード例 #22
0
            protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
            {
                //Bypass the built in validation entirely.
                bool isNonNullableValueTypeWithNullValue = (value == null) && !TypeAllowsNullValue(propertyDescriptor.PropertyType);

                var metadata = bindingContext.PropertyMetadata[propertyDescriptor.Name];
                string key = CreateSubPropertyName(bindingContext.ModelName, metadata.PropertyName);

                if (!propertyDescriptor.IsReadOnly && !isNonNullableValueTypeWithNullValue) {
                    try {
                        propertyDescriptor.SetValue(bindingContext.Model, value);
                    }
                    catch (Exception exception) {
                        if (bindingContext.ModelState.IsValidField(key)) {
                            bindingContext.ModelState.AddModelError(key, exception);
                        }
                    }
                }
            }
 internal static void SetPropertyValue(IServiceProvider serviceProvider, PropertyDescriptor propertyDescriptor, object component, object value)
 {
     ComponentChangeDispatcher dispatcher = new ComponentChangeDispatcher(serviceProvider, component, propertyDescriptor);
     try
     {
         propertyDescriptor.SetValue(component, value);
     }
     catch (Exception exception)
     {
         if ((exception is TargetInvocationException) && (exception.InnerException != null))
         {
             throw exception.InnerException;
         }
         throw exception;
     }
     finally
     {
         dispatcher.Dispose();
     }
 }
コード例 #24
0
        // Methods
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            #region Contracts

            if (controllerContext == null) throw new ArgumentNullException();
            if (bindingContext == null) throw new ArgumentNullException();
            if (propertyDescriptor == null) throw new ArgumentNullException();

            #endregion

            // PropertyModelBinderAttribute
            var propertyModelBinderAttribute = propertyDescriptor.Attributes.OfType<CustomModelBinderAttribute>().FirstOrDefault();
            if (propertyModelBinderAttribute == null)
            {
                // BindProperty
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
            else
            {
                // PropertyModelBinder
                var propertyModelBinder = propertyModelBinderAttribute.GetBinder();
                if (propertyModelBinder == null) return;

                // PropertyModelBindingContext
                var propertyModelBindingContext = new ModelBindingContext()
                {
                    ModelMetadata = bindingContext.PropertyMetadata[propertyDescriptor.Name],
                    ModelName = this.CreatePropertyName(bindingContext.ModelName, propertyDescriptor.Name),
                    ModelState = bindingContext.ModelState,
                    ValueProvider = bindingContext.ValueProvider
                };

                // BindProperty
                var value = propertyModelBinder.BindModel(controllerContext, propertyModelBindingContext);
                if (value == null) return;

                // SetValue
                propertyDescriptor.SetValue(bindingContext.Model, value);
            }
        }
コード例 #25
0
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            var model = (UserGroupPickerPreValueModel)bindingContext.Model;

            switch (propertyDescriptor.Name)
            {
                case "AvailableTypes":
                    var types = model.GetAvailableTypes().ToArray();
                    var valueName = string.Concat(bindingContext.ModelName, ".", propertyDescriptor.Name);
                    var value = bindingContext.ValueProvider.GetValue(valueName);
                    if (value != null)
                    {
                        var item = types.SingleOrDefault(x => x.Value == value.AttemptedValue);
                        if (item != null)
                            item.Selected = true;
                    }
                    propertyDescriptor.SetValue(bindingContext.Model, types);
                    break;
                default:
                    base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
                    break;
            }

        }
コード例 #26
0
        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);
        }
コード例 #27
0
        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
                        )
                    );
                }
            }
        }
コード例 #28
0
        /// <summary>
        /// Adds the specified associated entities to the specified association member for the specified entity.
        /// </summary>
        /// <param name="entity">The entity</param>
        /// <param name="associationProperty">The association member (singleton or collection)</param>
        /// <param name="associatedEntities">Collection of associated entities</param>
        private static void SetAssociationMember(object entity, PropertyDescriptor associationProperty, IEnumerable<object> associatedEntities)
        {
            if (associatedEntities.Count() == 0)
            {
                return;
            }

            object associationValue = associationProperty.GetValue(entity);
            if (typeof(IEnumerable).IsAssignableFrom(associationProperty.PropertyType))
            {
                if (associationValue == null)
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resource.DomainService_AssociationCollectionPropertyIsNull, associationProperty.ComponentType.Name, associationProperty.Name));
                }

                IList list = associationValue as IList;
                IEnumerable<object> associationSequence = null;
                MethodInfo addMethod = null;
                if (list == null)
                {
                    // not an IList, so we have to use reflection
                    Type associatedEntityType = TypeUtility.GetElementType(associationValue.GetType());
                    addMethod = associationValue.GetType().GetMethod("Add", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { associatedEntityType }, null);
                    if (addMethod == null)
                    {
                        throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resource.DomainService_InvalidCollectionMember, associationProperty.Name));
                    }
                    associationSequence = ((IEnumerable)associationValue).Cast<object>();
                }

                foreach (object associatedEntity in associatedEntities)
                {
                    // add the entity to the collection if it's not already there
                    if (list != null)
                    {
                        if (!list.Contains(associatedEntity))
                        {
                            list.Add(associatedEntity);
                        }
                    }
                    else
                    {
                        if (!associationSequence.Contains(associatedEntity))
                        {
                            addMethod.Invoke(associationValue, new object[] { associatedEntity });
                        }
                    }
                }
            }
            else
            {
                // set the reference if it's not already set
                object associatedEntity = associatedEntities.Single();
                object currentValue = associationProperty.GetValue(entity);
                if (!object.Equals(currentValue, associatedEntity))
                {
                    associationProperty.SetValue(entity, associatedEntity);
                }
            }
        }
コード例 #29
0
ファイル: CustomPropertyGrid.cs プロジェクト: wshanshan/DDD
 private void UpdateValue(PropertyDescriptor thisProperty, XPathNavigator current, String value, Object onObject)
 {
     if (!(thisProperty.Converter is ArrayConverter))
     {
         // set value
         if (value.Length > 0)
         {
             if (thisProperty.Converter is EnumConverter) // enums are a special case
             {
                 StringEnum stringEnum = new StringEnum(thisProperty.PropertyType);
                 Boolean pass = stringEnum.IsStringDefined(value);
                 if (!pass) // normal case, no string value
                 {
                     thisProperty.SetValue(onObject,
                         thisProperty.Converter.ConvertFromString(value));
                 }
                 else // string value, reverse to the enum value
                 {
                     thisProperty.SetValue(onObject, thisProperty.Converter.ConvertFromString(stringEnum.GetEnumValue(value))); 
                 }
             }
             else // everyone else
             {
                 thisProperty.SetValue(onObject,
                     thisProperty.Converter.ConvertFromString(value));
             }
         }
         else
         {
             if (thisProperty.PropertyType == typeof(String)) // replace with empty string
             {
                 thisProperty.SetValue(onObject,
                     thisProperty.Converter.ConvertFromString(String.Empty));
             }
         }
     }
     else
     {
         if (thisProperty.Converter is ArrayConverter)
         {
             // select collection children
             XPathNodeIterator collectionChildren = current.Select("Parameter");
             int index = 0;
             Type elementType = thisProperty.PropertyType.GetElementType();
             Array newValue = Array.CreateInstance(elementType, collectionChildren.Count);
             foreach (XPathNavigator collectionChild in collectionChildren)
             {
                 String xmlValue = collectionChild.GetAttribute(ConfigFileConstants.Value, "");
                 Object result = Convert.ChangeType(xmlValue, elementType);
                 newValue.SetValue(result, index);
                 index++;
             }
             thisProperty.SetValue(onObject, newValue);
         }
     }
 }
コード例 #30
0
 /// <summary>
 /// The set value.
 /// </summary>
 /// <param name="prop">
 /// The prop.
 /// </param>
 /// <param name="component">
 /// The component.
 /// </param>
 /// <param name="value">
 /// The value.
 /// </param>
 protected virtual void SetValue(PropertyDescriptor prop, object component, object value)
 {
     prop.SetValue(component, value);
 }
コード例 #31
0
        /// <include file='doc\ComponentResourceManager.uex' path='docs/doc[@for="ComponentResourceManager.ApplyResources1"]/*' />
        /// <devdoc>
        ///     This method examines all the resources for the provided culture.
        ///     When it finds a resource with a key in the format of
        ///     &quot[objectName].[property name]&quot; it will apply that resource's value
        ///     to the corresponding property on the object.  If there is no matching
        ///     property the resource will be ignored.
        /// </devdoc>
        public virtual void ApplyResources(object value, string objectName, CultureInfo culture)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (objectName == null)
            {
                throw new ArgumentNullException("objectName");
            }
            if (culture == null)
            {
                culture = CultureInfo.CurrentUICulture;
            }

            // The general case here will be to always use the same culture, so optimize for
            // that.  The resourceSets hashtable uses culture as a key.  It's value is
            // another hashtable that contains ALL the culture values (so it traverses up
            // the parent culture chain) for that culture.  This means that if ApplyResources
            // is called with different cultures there could be some redundancy in the
            // table, but it allows the normal case of calling with a single culture to
            // be much faster.
            //
            Hashtable resources;

            if (resourceSets == null)
            {
                ResourceSet dummy;
                resourceSets          = new Hashtable();
                resources             = FillResources(culture, out dummy);
                resourceSets[culture] = resources;
            }
            else
            {
                resources = (Hashtable)resourceSets[culture];
                if (resources == null || ((resources is CaseInsensitiveHashtable) != IgnoreCase))
                {
                    ResourceSet dummy;
                    resources             = FillResources(culture, out dummy);
                    resourceSets[culture] = resources;
                }
            }

            BindingFlags flags = BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance;

            if (IgnoreCase)
            {
                flags |= BindingFlags.IgnoreCase;
            }

            bool componentReflect = false;

            if (value is IComponent)
            {
                ISite site = ((IComponent)value).Site;
                if (site != null && site.DesignMode)
                {
                    componentReflect = true;
                }
            }

            foreach (DictionaryEntry de in resources)
            {
                // See if this key matches our object.
                //
                string key = de.Key as string;
                if (key == null)
                {
                    continue;
                }

                if (IgnoreCase)
                {
                    if (string.Compare(key, 0, objectName, 0, objectName.Length, true, CultureInfo.InvariantCulture) != 0)
                    {
                        continue;
                    }
                }
                else
                {
                    if (string.CompareOrdinal(key, 0, objectName, 0, objectName.Length) != 0)
                    {
                        continue;
                    }
                }

                // Character after objectName.Length should be a ".", or else we should continue.
                //
                int idx = objectName.Length;
                if (key.Length <= idx || key[idx] != '.')
                {
                    continue;
                }

                // Bypass type descriptor if we are not in design mode.  TypeDescriptor does an attribute
                // scan which is quite expensive.
                //
                string propName = key.Substring(idx + 1);

                if (componentReflect)
                {
                    PropertyDescriptor prop = TypeDescriptor.GetProperties(value).Find(propName, IgnoreCase);

                    if (prop != null && !prop.IsReadOnly && (de.Value == null || prop.PropertyType.IsInstanceOfType(de.Value)))
                    {
                        prop.SetValue(value, de.Value);
                    }
                }
                else
                {
                    PropertyInfo prop = value.GetType().GetProperty(propName, flags);

                    if (prop != null && prop.CanWrite && (de.Value == null || prop.PropertyType.IsInstanceOfType(de.Value)))
                    {
                        prop.SetValue(value, de.Value, null);
                    }
                }
            }
        }
コード例 #32
0
ファイル: DetailView.cs プロジェクト: north0808/haina
 private void ReadCollection(XmlReader reader, object obj, PropertyDescriptor pd)
 {
     IList list = null;
     if (!pd.IsReadOnly)
     {
         ConstructorInfo info = this.ReadGetType(reader).GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[0], null);
         if (info != null)
         {
             list = (IList) info.Invoke(new object[0]);
         }
         pd.SetValue(obj, list);
     }
     else
     {
         list = (IList) pd.GetValue(obj);
     }
     while (reader.Read())
     {
         try
         {
             object obj2;
             string str;
             if (((str = reader.Name) == null) || (str == ""))
             {
                 continue;
             }
             if (!(str == "Collection"))
             {
                 if (str == "Object")
                 {
                     goto Label_008A;
                 }
                 continue;
             }
             break;
         Label_008A:
             obj2 = this.ReadObject(reader);
             list.Add(obj2);
             continue;
         }
         catch
         {
             continue;
         }
     }
 }
コード例 #33
0
        /// <devdoc>
        ///     This method examines all the resources for the provided culture.
        ///     When it finds a resource with a key in the format of
        ///     &quot[objectName].[property name]&quot; it will apply that resource's value
        ///     to the corresponding property on the object.  If there is no matching
        ///     property the resource will be ignored.
        /// </devdoc>
        public virtual void ApplyResources(object value, string objectName, CultureInfo culture)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (objectName == null)
            {
                throw new ArgumentNullException("objectName");
            }
            if (culture == null)
            {
                culture = CultureInfo.CurrentUICulture;
            }

            // The general case here will be to always use the same culture, so optimize for
            // that.  The resourceSets hashtable uses culture as a key.  It's value is
            // a sorted dictionary that contains ALL the culture values (so it traverses up
            // the parent culture chain) for that culture.  This means that if ApplyResources
            // is called with different cultures there could be some redundancy in the
            // table, but it allows the normal case of calling with a single culture to
            // be much faster.
            //

            // The reason we use a SortedDictionary here is to ensure the resources are applied
            // in an order consistent with codedom deserialization.
            SortedList <string, object> resources;

            if (_resourceSets == null)
            {
                ResourceSet dummy;
                _resourceSets          = new Hashtable();
                resources              = FillResources(culture, out dummy);
                _resourceSets[culture] = resources;
            }
            else
            {
                resources = (SortedList <string, object>)_resourceSets[culture];
                if (resources == null || (resources.Comparer.Equals(StringComparer.OrdinalIgnoreCase) != IgnoreCase))
                {
                    ResourceSet dummy;
                    resources = FillResources(culture, out dummy);
                    _resourceSets[culture] = resources;
                }
            }

            BindingFlags flags = BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance;

            if (IgnoreCase)
            {
                flags |= BindingFlags.IgnoreCase;
            }

            bool componentReflect = false;

            if (value is IComponent)
            {
                ISite site = ((IComponent)value).Site;
                if (site != null && site.DesignMode)
                {
                    componentReflect = true;
                }
            }

            foreach (KeyValuePair <string, object> kvp in resources)
            {
                // See if this key matches our object.
                //
                string key = kvp.Key;
                if (key == null)
                {
                    continue;
                }

                if (IgnoreCase)
                {
                    if (string.Compare(key, 0, objectName, 0, objectName.Length, StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        continue;
                    }
                }
                else
                {
                    if (string.CompareOrdinal(key, 0, objectName, 0, objectName.Length) != 0)
                    {
                        continue;
                    }
                }

                // Character after objectName.Length should be a ".", or else we should continue.
                //
                int idx = objectName.Length;
                if (key.Length <= idx || key[idx] != '.')
                {
                    continue;
                }

                // Bypass type descriptor if we are not in design mode.  TypeDescriptor does an attribute
                // scan which is quite expensive.
                //
                string propName = key.Substring(idx + 1);

                if (componentReflect)
                {
                    PropertyDescriptor prop = TypeDescriptor.GetProperties(value).Find(propName, IgnoreCase);

                    if (prop != null && !prop.IsReadOnly && (kvp.Value == null || prop.PropertyType.IsInstanceOfType(kvp.Value)))
                    {
                        prop.SetValue(value, kvp.Value);
                    }
                }
                else
                {
                    PropertyInfo prop = null;

                    try {
                        prop = value.GetType().GetProperty(propName, flags);
                    }
                    catch (AmbiguousMatchException) {
                        // Looks like we ran into a conflict between a declared property and an inherited one.
                        // In such cases, we choose the most declared one.
                        Type t = value.GetType();
                        do
                        {
                            prop = t.GetProperty(propName, flags | BindingFlags.DeclaredOnly);
                            t    = t.BaseType;
                        } while(prop == null && t != null && t != typeof(object));
                    }

                    if (prop != null && prop.CanWrite && (kvp.Value == null || prop.PropertyType.IsInstanceOfType(kvp.Value)))
                    {
                        prop.SetValue(value, kvp.Value, null);
                    }
                }
            }
        }
コード例 #34
0
 internal static void SetPropertyValue(IServiceProvider serviceProvider, PropertyDescriptor propertyDescriptor, object component, object value)
 {
     ComponentChangeDispatcher componentChange = new ComponentChangeDispatcher(serviceProvider, component, propertyDescriptor);
     try
     {
         propertyDescriptor.SetValue(component, value);
     }
     catch (Exception t)
     {
         // If there was a problem setting the controls property then we get:
         // ArgumentException (from properties set method)
         // ==> Becomes inner exception of TargetInvocationException
         // ==> caught here
         // Propagate the original exception up
         if (t is TargetInvocationException && t.InnerException != null)
             throw t.InnerException;
         else
             throw t;
     }
     finally
     {
         componentChange.Dispose();
     }
 }
コード例 #35
0
 protected virtual void BindProperty(PropertyDescriptor prop, string value)
 {
     object convertedValue = ConvertPropertyValue(prop, value);
     prop.SetValue(this, convertedValue);
 }
コード例 #36
0
        protected void SetProperty(BindingContext context, PropertyDescriptor property, object value)
        {
            string propertyKey = CreateSubMemberName(context.ModelName, property.Name);
            if (property.IsReadOnly)
                return;

            try
            {
                property.SetValue(context.Model, value);
            }
            catch (Exception ex)
            {
                context.ModelState.Add(propertyKey, new ValidationError(ex.Message, value, ex));
            }
        }
コード例 #37
0
 private void SetProperty(string propertyName, object value)
 {
     System.ComponentModel.PropertyDescriptor property
         = System.ComponentModel.TypeDescriptor.GetProperties(this.ExpondPanelList)[propertyName];
     property.SetValue(this.ExpondPanelList, value);
 }
コード例 #38
0
 private void UpdateEffectProperty(PropertyDescriptor descriptor, Element element, Object value)
 {
     descriptor.SetValue(element.EffectNode.Effect, value);
     element.UpdateNotifyContentChanged();
     SequenceModified();
 }
コード例 #39
0
        protected virtual void SetPropertyValueCore(object target, object value, PropertyDescriptor propertyDescriptor)
        {
            ValidatePropertyValue(target, value, propertyDescriptor);

            bool useCreateInstance = false;
            PropertyNode parent = this.Parent as PropertyNode;
            if (parent != null)
            {
                TypeConverter parentConverter = parent.TypeConverter;
                if (parentConverter != null && parentConverter.GetCreateInstanceSupported(this))
                    useCreateInstance = true;
            }

            if (useCreateInstance)
            {
                if (target is ICustomTypeDescriptor)
                {
                    target = ((ICustomTypeDescriptor)target).GetPropertyOwner(propertyDescriptor);
                }

                object valueOwner = parent.GetTargetComponent();
                TypeConverter parentTypeConverter = parent.TypeConverter;
                PropertyDescriptorCollection properties = parentTypeConverter.GetProperties(parent, valueOwner);
                Dictionary<string, object> propertyValues = new Dictionary<string, object>(properties.Count);
                object newValueInstance = null;
                for (int i = 0; i < properties.Count; i++)
                {
                    string propertyName = GetPropertyName();
                    if (propertyName != null && propertyName.Equals(properties[i].Name))
                    {
                        propertyValues[properties[i].Name] = value;
                    }
                    else
                    {
                        propertyValues[properties[i].Name] = properties[i].GetValue(target);
                    }
                }
                try
                {
                    newValueInstance = parentTypeConverter.CreateInstance(parent, propertyValues);
                }
                catch (Exception exception)
                {
                    if (string.IsNullOrEmpty(exception.Message))
                    {
                        throw new TargetInvocationException("Exception Creating New Instance Of Object For Property " + this.Text + " " + parent.PropertyType.FullName + " " + exception.ToString(), exception);
                    }
                    throw;
                }
                if (newValueInstance != null)
                {
                    parent.PropertyValue = newValueInstance;
                }
            }
            else
            {
                if (target is ICustomTypeDescriptor)
                {
                    target = ((ICustomTypeDescriptor)target).GetPropertyOwner(propertyDescriptor);
                }
                try
                {
                    propertyDescriptor.SetValue(target, value);
                }
                catch
                {
                    throw;
                }
            }

            AdvPropertyGrid grid = this.AdvPropertyGrid;
            if (grid != null)
                grid.InvokePropertyValueChanged(GetPropertyName(), value, null);
        }
コード例 #40
0
 public override void SetValue(object component, object value)
 {
     Descriptor.SetValue(component, value);
 }