public void DataSourcePropertyChanged_ThreeDeep()
        {
            Control c = new Control();

            c.BindingContext = new BindingContext();
            c.CreateControl();

            MockItem item   = new MockItem("A", 0);
            One      parent = new One();

            parent.Two                = new Two();
            parent.Two.Three          = new Three();
            parent.Two.Three.MockItem = item;
            Binding binding = new Binding("Text", parent, "Two.Three.MockItem.Text");

            c.DataBindings.Add(binding);
            Console.WriteLine("c.Text: " + c.Text);
            Assert.AreEqual("A", c.Text, "#A1");

            item.Text = "B";
            Assert.AreEqual("B", c.Text, "#B1");

            Assert.AreEqual(1, c.DataBindings.Count, "c.DataBindings.Count");
            BindingMemberInfo bmi = c.DataBindings[0].BindingMemberInfo;

            Assert.AreEqual("Two.Three.MockItem", bmi.BindingPath, "bmi.BindingPath");
            Assert.AreEqual("Two.Three.MockItem.Text", bmi.BindingMember, "bmi.BindingMember");
            Assert.AreEqual("Text", bmi.BindingField, "bmi.BindingField");
        }
        public void Should_return_PropertyType_for_properties_or_fields()
        {
            // Given
            var properties = BindingMemberInfo.Collect <TestModel>();

            // When

            // Then
            properties.ShouldHaveCount(4);

            foreach (var propInfo in properties)
            {
                if (propInfo.Name.StartsWith("Int"))
                {
                    propInfo.PropertyType.ShouldEqual(typeof(int));
                }
                else if (propInfo.Name.StartsWith("String"))
                {
                    propInfo.PropertyType.ShouldEqual(typeof(string));
                }
                else
                {
                    throw new AssertException("Internal error in unit test: Test model property/field name does not follow the expected convention: " + propInfo.Name);
                }
            }
        }
Example #3
0
        private static IEnumerable <BindingMemberInfo> GetBindingMembers(Type modelType, Type genericType, IEnumerable <string> blackList)
        {
            var blackListHash = new HashSet <string>(blackList, StringComparer.InvariantCulture);

            return(BindingMemberInfo.Collect(genericType ?? modelType)
                   .Where(member => !blackListHash.Contains(member.Name)));
        }
Example #4
0
        public void Should_deserialize_nullable_enum(TestEnum?propertyValue)
        {
            var context = new BindingContext()
            {
                DestinationType          = typeof(TestModel),
                ValidModelBindingMembers = BindingMemberInfo.Collect <TestModel>().ToList(),
            };

            var model = new TestModel {
                NullableEnumProperty = propertyValue
            };

            var s          = new JavaScriptSerializer();
            var serialized = s.Serialize(model);
            var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(serialized));

            // When
            var result = (TestModel)this.deserialize.Deserialize(
                "application/json",
                bodyStream,
                context);

            // Then
            result.NullableEnumProperty.ShouldEqual(propertyValue);
        }
 private static bool ValidDataMember(object dataSource, string dataMember)
 {
     if (!string.IsNullOrEmpty(dataMember))
     {
         BindingManagerBase base2;
         if (bc == null)
         {
             bc = new BindingContext();
         }
         BindingMemberInfo            info           = new BindingMemberInfo(dataMember);
         PropertyDescriptorCollection itemProperties = null;
         try
         {
             base2 = bc[dataSource, info.BindingPath];
         }
         catch (ArgumentException)
         {
             return(false);
         }
         if (base2 == null)
         {
             return(false);
         }
         itemProperties = base2.GetItemProperties();
         if (itemProperties == null)
         {
             return(false);
         }
         if (itemProperties[info.BindingField] == null)
         {
             return(false);
         }
     }
     return(true);
 }
Example #6
0
        /// <summary>
        /// Gets the bound property.
        /// </summary>
        /// <returns></returns>
        protected PropertyDescriptor GetBoundProperty()
        {
            if (propertyDescriptor != null)
            {
                return(propertyDescriptor);
            }

            if (DataGridView.DataSource == null)
            {
                return(null);
            }

            BindingMemberInfo binding     = new BindingMemberInfo(DataPropertyName);
            CurrencyManager   dataManager = DataGridView.BindingContext[DataGridView.DataSource, binding.BindingPath] as CurrencyManager;

            if (dataManager == null)
            {
                return(null);
            }

            PropertyDescriptor property = dataManager.GetItemProperties().Find(binding.BindingField, true);

            if (property == null)
            {
                throw new ArgumentException(DataPropertyName);
            }

            return(property);
        }
Example #7
0
        private bool BindingMemberInfoInDataManager(BindingMemberInfo bindingMemberInfo)
        {
            if (_dataManager != null)
            {
                PropertyDescriptorCollection itemProperties = _dataManager.GetItemProperties();
                int count = itemProperties.Count;

                for (int i = 0; i < count; i++)
                {
                    if (!typeof(IList).IsAssignableFrom(itemProperties[i].PropertyType) && itemProperties[i].Name.Equals(bindingMemberInfo.BindingField))
                    {
                        return(true);
                    }
                }

                for (int j = 0; j < count; j++)
                {
                    if (!typeof(IList).IsAssignableFrom(itemProperties[j].PropertyType) && (string.Compare(itemProperties[j].Name, bindingMemberInfo.BindingField, true, CultureInfo.CurrentCulture) == 0))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Example #8
0
        public void Ctor_Default()
        {
            var info = new BindingMemberInfo();

            Assert.Empty(info.BindingPath);
            Assert.Empty(info.BindingField);
            Assert.Empty(info.BindingMember);
        }
        public void CtorNullTest()
        {
            BindingMemberInfo bmi = new BindingMemberInfo(null);

            Assert.AreEqual(bmi.BindingMember, String.Empty, "CTORNULL1");
            Assert.AreEqual(bmi.BindingField, String.Empty, "CTORNULL2");
            Assert.AreEqual(bmi.BindingPath, String.Empty, "CTORNULL3");
        }
        public void CtorMemberOnly()
        {
            BindingMemberInfo bmi = new BindingMemberInfo("Member");

            Assert.AreEqual(bmi.BindingMember, "Member", "CTORMEMBER1");
            Assert.AreEqual(bmi.BindingField, "Member", "CTORMEMBER2");
            Assert.AreEqual(bmi.BindingPath, String.Empty, "CTORMEMBER3");
        }
        public void CtorMemberAndPathOnly()
        {
            BindingMemberInfo bmi = new BindingMemberInfo("Member.Path");

            Assert.AreEqual(bmi.BindingMember, "Member.Path", "CTMAF1");
            Assert.AreEqual(bmi.BindingPath, "Member", "CTMAF2");
            Assert.AreEqual(bmi.BindingField, "Path", "CTMAF3");
        }
Example #12
0
        public void Ctor_String(string dataMember, string expectedPath, string expectedField, string expectedMember)
        {
            var info = new BindingMemberInfo(dataMember);

            Assert.Equal(expectedPath, info.BindingPath);
            Assert.Equal(expectedField, info.BindingField);
            Assert.Equal(expectedMember, info.BindingMember);
        }
        public void CtorAll()
        {
            BindingMemberInfo bmi = new BindingMemberInfo("Member.Path.Field");

            Assert.AreEqual(bmi.BindingMember, "Member.Path.Field", "CTALL1");
            Assert.AreEqual(bmi.BindingPath, "Member.Path", "CTALL2");
            Assert.AreEqual(bmi.BindingField, "Field", "CTALL3");
        }
        public void CtorEmpty()
        {
            BindingMemberInfo bmi = new BindingMemberInfo("...");

            Assert.AreEqual(bmi.BindingMember, "...", "CTEMPTY1");
            Assert.AreEqual(bmi.BindingPath, "..", "CTEMPTY2");
            Assert.AreEqual(bmi.BindingField, String.Empty, "CTEMPTY3");
        }
        public void CtorSpecialChars()
        {
            BindingMemberInfo bmi = new BindingMemberInfo(",/';.[]-=!.$%&*~");

            Assert.AreEqual(bmi.BindingMember, ",/';.[]-=!.$%&*~", "CTORSPECIAL1");
            Assert.AreEqual(bmi.BindingPath, ",/';.[]-=!", "CTORSPECIAL2");
            Assert.AreEqual(bmi.BindingField, "$%&*~", "CTORSPECIAL3");
        }
Example #16
0
        public void Should_deserialize_list_of_complex_objects()
        {
            // Given
            var context = new BindingContext()
            {
                DestinationType          = typeof(TestModel),
                ValidModelBindingMembers = BindingMemberInfo.Collect <TestModel>().ToList(),
            };

            var model =
                new TestModel
            {
                ListOfComplexObjectsProperty = new List <ModelWithStringValues>
                {
                    new ModelWithStringValues()
                    {
                        Value1 = "one", Value2 = "two"
                    },
                    new ModelWithStringValues()
                    {
                        Value1 = "three", Value2 = "four"
                    }
                },
                ListOfComplexObjectsField = new List <ModelWithStringValues>
                {
                    new ModelWithStringValues()
                    {
                        Value1 = "five", Value2 = "six"
                    },
                    new ModelWithStringValues()
                    {
                        Value1 = "seven", Value2 = "eight"
                    }
                }
            };

            var s          = new JavaScriptSerializer();
            var serialized = s.Serialize(model);
            var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(serialized));

            // When
            var result = (TestModel)this.deserialize.Deserialize(
                "application/json",
                bodyStream,
                context);

            // Then
            result.ListOfComplexObjectsProperty.ShouldHaveCount(2);
            result.ListOfComplexObjectsProperty[0].Value1.ShouldEqual("one");
            result.ListOfComplexObjectsProperty[0].Value2.ShouldEqual("two");
            result.ListOfComplexObjectsProperty[1].Value1.ShouldEqual("three");
            result.ListOfComplexObjectsProperty[1].Value2.ShouldEqual("four");
            result.ListOfComplexObjectsField.ShouldHaveCount(2);
            result.ListOfComplexObjectsField[0].Value1.ShouldEqual("five");
            result.ListOfComplexObjectsField[0].Value2.ShouldEqual("six");
            result.ListOfComplexObjectsField[1].Value1.ShouldEqual("seven");
            result.ListOfComplexObjectsField[1].Value2.ShouldEqual("eight");
        }
Example #17
0
        public void Equals_Invoke_ReturnsExpected(BindingMemberInfo info, object other, bool expected)
        {
            if (other is BindingMemberInfo otherInfo)
            {
                Assert.Equal(expected, info == otherInfo);
                Assert.Equal(!expected, info != otherInfo);
            }

            Assert.Equal(expected, info.Equals(other));
        }
        public void EqualsTest()
        {
            BindingMemberInfo a = new BindingMemberInfo("A.B.C");
            BindingMemberInfo b = new BindingMemberInfo("A.B.C");

            Assert.AreEqual(a, b, "EQUALS1");

            b = new BindingMemberInfo("A.B");
            Assert.IsFalse(a.Equals(b), "EQUALS2");
        }
        //Attempt to create 28/3/2005
        //issue base class doesn't have public indexer, and have to pass NameValueCollection
        // so see NameValueCollectionAsString
        //		public static string NameObjectCollectionAsString(NameValueCollection coll,  string sComment /* = "" */)
        //		{
        //			string sRet = "";
        //			if (!String.IsNullOrEmpty(sComment))
        //			{
        //				sRet +=  sComment+Environment.NewLine ;
        //			}
        //			if (coll == null)
        //			{
        //				sRet +=("Collection is null: ")+Environment.NewLine ;
        //			}
        //			else
        //			{
        //				string sEntry="";
        //				sRet +=("NameObjectCollection Count: " + StringType.FromInteger(coll.Count));
        //				//ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.1033/cpref/html/frlrfsystemcollectionsspecializednameobjectcollectionbaseclasstopic.htm
        //				foreach ( String sKey in coll.Keys )
        //				{
        //					sEntry =String.Format( "{0}, {1}", sKey, coll[sKey] );
        //					sRet +=(sEntry);
        //				}
        //			}
        //			return sRet;
        //		}
#if WINFORMS_TRACES_REQUIRED //not used at the moment
        public static string TraceString(BindingMemberInfo bInfo, [Optional] string sComment /* = "" */)
        {
            string text2 = "";

            if (!DataHelper.IsNullOrEmpty(sComment))
            {
                text2 = text2 + sComment;
            }
            text2 = text2 + " BindingPath: " + bInfo.BindingPath + "\r\n";
            text2 = text2 + " BindingField: " + bInfo.BindingField + "\r\n";
            text2 = text2 + " BindingMember: " + bInfo.BindingMember + "\r\n";
            //Debug.WriteLine(text2);
            return(text2);
        }
Example #20
0
// <Snippet1>
    private void PrintBindingMemberInfo()
    {
        foreach (Control c in this.Controls)
        {
            foreach (Binding b in c.DataBindings)
            {
                Console.WriteLine("\n" + c.ToString());
                BindingMemberInfo bInfo = b.BindingMemberInfo;
                Console.WriteLine("Binding Path \t" + bInfo.BindingPath);
                Console.WriteLine("Binding Field \t" + bInfo.BindingField);
                Console.WriteLine("Binding Member \t" + bInfo.BindingMember);
            }
        }
    }
Example #21
0
        public void Should_be_able_to_use_except_on_two_lists_of_bindingMemberInfos()
        {
            // Given
            var properties = BindingMemberInfo.Collect <TestModel>();
            var except     = BindingMemberInfo.Collect <TestModel>().Where(i => i.Name.Contains("Property"));

            // When
            var res = properties.Except(except).ToList();

            // Then
            res.Count.ShouldEqual(2);
            res[0].Name.ShouldEqual("IntField");
            res[1].Name.ShouldEqual("StringField");
        }
        public void Should_return_Name_for_properties_or_fields()
        {
            // Given
            var type = typeof(TestModel);
            var underlyingFieldInfo    = type.GetFields().First();
            var underlyingPropertyInfo = type.GetProperties().First();

            // When
            var fieldInfo    = new BindingMemberInfo(underlyingFieldInfo);
            var propertyInfo = new BindingMemberInfo(underlyingPropertyInfo);

            // Then
            fieldInfo.Name.ShouldEqual(underlyingFieldInfo.Name);
            propertyInfo.Name.ShouldEqual(underlyingPropertyInfo.Name);
        }
        public void Should_return_Name_for_properties_or_fields()
        {
            // Given
            var type = typeof(TestModel);
            var underlyingFieldInfo = type.GetFields().First();
            var underlyingPropertyInfo = type.GetProperties().First();

            // When
            var fieldInfo = new BindingMemberInfo(underlyingFieldInfo);
            var propertyInfo = new BindingMemberInfo(underlyingPropertyInfo);

            // Then
            fieldInfo.Name.ShouldEqual(underlyingFieldInfo.Name);
            propertyInfo.Name.ShouldEqual(underlyingPropertyInfo.Name);
        }
        public void Should_collect_all_bindable_members_and_skip_all_others()
        {
            // Given

            // When
            var properties = BindingMemberInfo.Collect <BiggerTestModel>();

            // Then
            properties.ShouldHaveCount(16);

            foreach (var property in properties)
            {
                property.Name.ShouldStartWith("Bindable");
            }
        }
Example #25
0
// <Snippet1>
    private void PrintBindingMemberInfo()
    {
        foreach (Control thisControl in this.Controls)
        {
            foreach (Binding thisBinding in thisControl.DataBindings)
            {
                // Print the control's name and Binding information.
                Console.WriteLine("\n" + thisControl.ToString());
                BindingMemberInfo bInfo = thisBinding.BindingMemberInfo;
                Console.WriteLine("Binding Path \t" + bInfo.BindingPath);
                Console.WriteLine("Binding Field \t" + bInfo.BindingField);
                Console.WriteLine("Binding Member \t" + bInfo.BindingMember);
            }
        }
    }
Example #26
0
// <Snippet1>
    private void PrintBindingMemberInfo()
    {
        Console.WriteLine("\n BindingMemberInfo");
        foreach (Control thisControl in this.Controls)
        {
            foreach (Binding thisBinding in thisControl.DataBindings)
            {
                BindingMemberInfo bInfo = thisBinding.BindingMemberInfo;
                Console.WriteLine("\t BindingPath: " + bInfo.BindingPath);
                Console.WriteLine("\t BindingField: " + bInfo.BindingField);
                Console.WriteLine("\t BindingMember: " +
                                  bInfo.BindingMember);
                Console.WriteLine();
            }
        }
    }
        public void Should_set_properties()
        {
            // Given
            var propInfo = BindingMemberInfo.Collect <TestModel>().Where(prop => prop.Name.EndsWith("Property"));
            var model    = new TestModel();

            // When
            propInfo.Single(prop => prop.PropertyType == typeof(int))
            .SetValue(model, 2600);

            propInfo.Single(prop => prop.PropertyType == typeof(string))
            .SetValue(model, "R2D2");

            // Then
            model.IntProperty.ShouldEqual(2600);
            model.StringProperty.ShouldEqual("R2D2");
        }
        public void Should_set_fields()
        {
            // Given
            var propInfo = BindingMemberInfo.Collect <TestModel>().Where(prop => prop.Name.EndsWith("Field"));
            var model    = new TestModel();

            // When
            propInfo.Single(prop => prop.PropertyType == typeof(int))
            .SetValue(model, 42);

            propInfo.Single(prop => prop.PropertyType == typeof(string))
            .SetValue(model, "nineteen");

            // Then
            model.IntField.ShouldEqual(42);
            model.StringField.ShouldEqual("nineteen");
        }
        public void Should_get_properties()
        {
            // Given
            var propInfo = BindingMemberInfo.Collect <TestModel>().Where(prop => prop.Name.EndsWith("Property"));
            var model    = new TestModel();

            // When
            model.IntProperty    = 1701;
            model.StringProperty = "NancyFX Unit Testing";

            // Then
            propInfo.Single(prop => prop.PropertyType == typeof(int))
            .GetValue(model)
            .ShouldEqual(1701);

            propInfo.Single(prop => prop.PropertyType == typeof(string))
            .GetValue(model)
            .ShouldEqual("NancyFX Unit Testing");
        }
        public void Should_get_fields()
        {
            // Given
            var propInfo = BindingMemberInfo.Collect <TestModel>().Where(prop => prop.Name.EndsWith("Field"));
            var model    = new TestModel();

            // When
            model.IntField    = 669;
            model.StringField = "testing";

            // Then
            propInfo.Single(prop => prop.PropertyType == typeof(int))
            .GetValue(model)
            .ShouldEqual(669);

            propInfo.Single(prop => prop.PropertyType == typeof(string))
            .GetValue(model)
            .ShouldEqual("testing");
        }
Example #31
0
        public void Should_deserialize_enum()
        {
            // Given
            var json       = this.serializer.Serialize(TestEnum.One);
            var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(json));
            var context    = new BindingContext()
            {
                DestinationType          = typeof(TestEnum),
                ValidModelBindingMembers = BindingMemberInfo.Collect <TestEnum>().ToList(),
            };

            // When
            var result = (TestEnum)this.deserialize.Deserialize(
                "application/json",
                bodyStream,
                context);

            // Then
            result.ShouldEqual(TestEnum.One);
        }
Example #32
0
 private static void BindValue(BindingMemberInfo modelProperty, string stringValue, BindingContext context)
 {
     BindValue(modelProperty, stringValue, context, context.Model);
 }
Example #33
0
 private bool BindingValueIsValid(string bindingValue, object existingValue, BindingMemberInfo modelProperty, BindingContext bindingContext)
 {
     return (!String.IsNullOrEmpty(bindingValue) &&
             (IsDefaultValue(existingValue, modelProperty.PropertyType) ||
              bindingContext.Configuration.Overwrite));
 }
Example #34
0
        private static void CopyValue(BindingMemberInfo modelProperty, object source, object destination)
        {
            var newValue = modelProperty.GetValue(source);

            modelProperty.SetValue(destination, newValue);
        }
Example #35
0
        private bool BindingValueIsValid(string bindingValue, object existingValue, BindingMemberInfo modelProperty, BindingContext bindingContext)
        {
            var passedValueContainsSomething = !String.IsNullOrEmpty(bindingValue);
            var passedValueNotNull = bindingValue != null;
            var doNotConvertEmptyStringsToNull = !bindingContext.Configuration.ConvertEmptyStringToNull && passedValueNotNull;
            var passedValueIsTheDefaultValue = IsDefaultValue(existingValue, modelProperty.PropertyType);
            var overwriteValuesThatDoNotHaveADefaultValue = bindingContext.Configuration.Overwrite;

            return ((passedValueContainsSomething || doNotConvertEmptyStringsToNull) && (passedValueIsTheDefaultValue || overwriteValuesThatDoNotHaveADefaultValue));
        }
Example #36
0
        protected virtual void BindValue(BindingMemberInfo modelProperty, object obj, BindingContext context)
        {
            if(obj == null)
            {
                return;
            }

            Type dictionaryType = typeof(Dictionary<string, object>);

            //If the type is a dictionary and the PropertyType isn't then we'll bind.
            if (obj.GetType() == dictionaryType && modelProperty.PropertyType != dictionaryType)
            {
                //We have a sub dictionary, attempt to bind it to the class
                var model = Bind(obj, modelProperty.PropertyType);

                modelProperty.SetValue(context.Model, model);
            }
            //If both types are collections then we'll bind
            else if (obj.GetType().IsCollectionOrArray() && modelProperty.PropertyType.IsCollectionOrArray())
            {
                //We have a sub dictionary, attempt to bind it to the class
                var model = Bind(obj, modelProperty.PropertyType);

                modelProperty.SetValue(context.Model, model);
            }
            else
            {
                //Simply set the property
                modelProperty.SetValue(context.Model, obj);
            }
        }
Example #37
0
        private static void BindValue(BindingMemberInfo modelProperty, string stringValue, BindingContext context, object targetInstance)
        {
            var destinationType = modelProperty.PropertyType;

            var typeConverter =
                context.TypeConverters.FirstOrDefault(c => c.CanConvertTo(destinationType, context));

            if (typeConverter != null)
            {
                try
                {
                    SetBindingMemberValue(modelProperty, targetInstance, typeConverter.Convert(stringValue, destinationType, context));
                }
                catch (Exception e)
                {
                    throw new PropertyBindingException(modelProperty.Name, stringValue, e);
                }
            }
            else if (destinationType == typeof(string))
            {
                SetBindingMemberValue(modelProperty, targetInstance, stringValue);
            }
        }
        /// <summary>
        /// Cleans the blacklisted properties from the <see cref="deserializedObject"/>.
        /// If it is a an <see cref="IEnumerable"/>, the blacklisted properties from each element are cleaned.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="deserializedObject">The deserialized object.</param>
        /// <param name="cachedBindingMemberInfo">The cached property information.</param>
        /// <returns></returns>
        private static object CleanBlacklistedMembers(BindingContext context, object deserializedObject, BindingMemberInfo[] cachedBindingMemberInfo)
        {
            if (context.DestinationType.IsCollection())
            {
                foreach (var enumerableElement in (IEnumerable)deserializedObject)
                {
                    CleanPropertyValues(context, enumerableElement, cachedBindingMemberInfo);
                }
            }
            else
            {
                CleanPropertyValues(context, deserializedObject, cachedBindingMemberInfo);
            }

            return deserializedObject;
        }
 private void CopyPropertyValue(BindingMemberInfo property, object sourceObject, object destinationObject)
 {
     property.SetValue(destinationObject, property.GetValue(sourceObject));
 }
Example #40
0
 private static void SetBindingMemberValue(BindingMemberInfo modelProperty, object model, object value)
 {
     // TODO - catch reflection exceptions?
     modelProperty.SetValue(model, value);
 }
	public static bool op_Inequality(BindingMemberInfo a, BindingMemberInfo b) {}