Exemplo n.º 1
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (!CanConvertTo(context, value.GetType()))
            {
                throw new NotSupportedException(Locale.GetText("Cannot convert from value."));
            }

            if (value is Uri)
            {
                return(value);
            }

            string s = (value as string);

            if (s != null)
            {
                return(new Uri(s, UriKind.RelativeOrAbsolute));
            }

            InstanceDescriptor id = (value as InstanceDescriptor);

            if (id != null)
            {
                return(id.Invoke());
            }

            return(base.ConvertFrom(context, culture, value));
        }
Exemplo n.º 2
0
        private static object ReadInstanceDescriptor(XmlNode node, ArrayList errors)
        {
            XmlAttribute memberAttr = node.Attributes["member"];

            if (memberAttr == null)
            {
                errors.Add("No member attribute on instance descriptor");
                return(null);
            }

            byte[]          data      = Convert.FromBase64String(memberAttr.Value);
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream    stream    = new MemoryStream(data);
            MemberInfo      mi        = (MemberInfo)formatter.Deserialize(stream);

            object[] args = null;

            if (mi is MethodBase)
            {
                ParameterInfo[] paramInfos = ((MethodBase)mi).GetParameters();

                args = new object[paramInfos.Length];

                int idx = 0;

                foreach (XmlNode child in node.ChildNodes)
                {
                    if (child.Name.Equals("Argument"))
                    {
                        object value;

                        if (!ReadValue(child, TypeDescriptor.GetConverter(paramInfos[idx].ParameterType), errors, out value))
                        {
                            return(null);
                        }

                        args[idx++] = value;
                    }
                }

                if (idx != paramInfos.Length)
                {
                    errors.Add(string.Format("Member {0} requires {1} arguments, not {2}.", mi.Name, args.Length, idx));
                    return(null);
                }
            }

            InstanceDescriptor id       = new InstanceDescriptor(mi, args);
            object             instance = id.Invoke();

            foreach (XmlNode prop in node.ChildNodes)
            {
                if (prop.Name.Equals("Property"))
                {
                    ReadProperty(prop, instance, errors);
                }
            }

            return(instance);
        }
Exemplo n.º 3
0
        public void ConvertTo_InstanceDescriptor()
        {
            PaddingConverter   c = new PaddingConverter();
            Padding            originalPadding    = new Padding(1, 10, 5, 9);
            InstanceDescriptor instanceDescriptor = (InstanceDescriptor)c.ConvertTo(originalPadding,
                                                                                    typeof(InstanceDescriptor));
            Padding resultedPadding = (Padding)instanceDescriptor.Invoke();

            Assert.AreEqual(originalPadding, resultedPadding, "#1");

            originalPadding    = new Padding(99);
            instanceDescriptor = (InstanceDescriptor)c.ConvertTo(originalPadding,
                                                                 typeof(InstanceDescriptor));
            resultedPadding = (Padding)instanceDescriptor.Invoke();
            Assert.AreEqual(originalPadding, resultedPadding, "#2");
        }
Exemplo n.º 4
0
        public void Constructor_Null_ICollection()
        {
            InstanceDescriptor id = new InstanceDescriptor(null, new object[] { });

            Assert.AreEqual(0, id.Arguments.Count, "#1");
            Assert.IsTrue(id.IsComplete, "#2");
            Assert.IsNull(id.MemberInfo, "#3");
            Assert.IsNull(id.Invoke(), "#4");
        }
Exemplo n.º 5
0
        public void Invoke_ArgumentInstanceDescriptor_InvokesArgument()
        {
            MethodInfo argumentMethod             = typeof(MethodClass).GetMethod(nameof(MethodClass.IntMethod));
            var        argumentInstanceDescriptor = new InstanceDescriptor(argumentMethod, null);

            MethodInfo method             = typeof(MethodClass).GetMethod(nameof(MethodClass.StaticMethod));
            var        instanceDescriptor = new InstanceDescriptor(method, new object[] { argumentInstanceDescriptor });

            Assert.Equal("1", instanceDescriptor.Invoke());
        }
Exemplo n.º 6
0
        /// <devdoc>
        ///    <para>Converts the given object to the converter's native type.</para>
        /// </devdoc>
        public virtual object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            InstanceDescriptor id = value as InstanceDescriptor;

            if (id != null)
            {
                return(id.Invoke());
            }
            throw GetConvertFromException(value);
        }
        public virtual object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            InstanceDescriptor descriptor = value as InstanceDescriptor;

            if (descriptor == null)
            {
                throw this.GetConvertFromException(value);
            }
            return(descriptor.Invoke());
        }
Exemplo n.º 8
0
        public void Ctor_FieldInfo_ICollection(object[] arguments)
        {
            FieldInfo fi = typeof(StaticField).GetField(nameof(StaticField.Field));

            InstanceDescriptor id = new InstanceDescriptor(fi, arguments);

            Assert.Equal(0, id.Arguments.Count);
            Assert.True(id.IsComplete);
            Assert.Same(fi, id.MemberInfo);
            Assert.NotNull(id.Invoke());
        }
Exemplo n.º 9
0
        public void Ctor_PropertyInfo_ICollection(object[] arguments)
        {
            PropertyInfo pi = typeof(StaticProperty).GetProperty(nameof(StaticProperty.Property));

            InstanceDescriptor id = new InstanceDescriptor(pi, arguments);

            Assert.Equal(0, id.Arguments.Count);
            Assert.True(id.IsComplete);
            Assert.Same(pi, id.MemberInfo);
            Assert.NotNull(id.Invoke());
        }
Exemplo n.º 10
0
        public void Field_Arguments_Empty()
        {
            FieldInfo fi = typeof(Uri).GetField("SchemeDelimiter");

            InstanceDescriptor id = new InstanceDescriptor(fi, new object[0]);

            Assert.Equal(0, id.Arguments.Count);
            Assert.True(id.IsComplete);
            Assert.Same(fi, id.MemberInfo);
            Assert.NotNull(id.Invoke());
        }
Exemplo n.º 11
0
        public void Constructor_MemberInfo_ICollection_Boolean()
        {
            InstanceDescriptor id = new InstanceDescriptor(ci, new object[] { url }, false);

            Assert.Equal(1, id.Arguments.Count);
            Assert.False(id.IsComplete);
            Assert.Same(ci, id.MemberInfo);
            Uri uri = (Uri)id.Invoke();

            Assert.Equal(url, uri.AbsoluteUri);
        }
Exemplo n.º 12
0
        public void Field_Arguments_Null()
        {
            FieldInfo fi = typeof(Uri).GetField("SchemeDelimiter");

            InstanceDescriptor id = new InstanceDescriptor(fi, null);

            Assert.AreEqual(0, id.Arguments.Count, "#1");
            Assert.IsTrue(id.IsComplete, "#2");
            Assert.AreSame(fi, id.MemberInfo, "#3");
            Assert.IsNotNull(id.Invoke(), "#4");
        }
Exemplo n.º 13
0
        public void ConvertTo_InstanceDescriptor()
        {
            DateTimeOffset     dto        = new DateTimeOffset(new DateTime(2010, 10, 11), new TimeSpan(3, 6, 0));
            InstanceDescriptor descriptor = (InstanceDescriptor)converter.ConvertTo(dto, typeof(InstanceDescriptor));

            Assert.AreEqual(".ctor", descriptor.MemberInfo.Name, "#A0");
            Assert.AreEqual(8, descriptor.Arguments.Count, "#A1");
            DateTimeOffset dto2 = (DateTimeOffset)descriptor.Invoke();

            Assert.AreEqual(dto, dto2, "#A2");
        }
Exemplo n.º 14
0
        public void Property_Arguments_Null()
        {
            PropertyInfo pi = typeof(Thread).GetProperty("CurrentPrincipal");

            InstanceDescriptor id = new InstanceDescriptor(pi, null);

            Assert.AreEqual(0, id.Arguments.Count, "#1");
            Assert.IsTrue(id.IsComplete, "#2");
            Assert.AreSame(pi, id.MemberInfo, "#3");
            Assert.IsNotNull(id.Invoke(), "#4");
        }
Exemplo n.º 15
0
        public void Constructor_MemberInfo_ICollection()
        {
            InstanceDescriptor id = new InstanceDescriptor(ci, new object[] { url });

            Assert.AreEqual(1, id.Arguments.Count, "Arguments");
            Assert.IsTrue(id.IsComplete, "IsComplete");
            Assert.AreSame(ci, id.MemberInfo, "MemberInfo");
            Uri uri = (Uri)id.Invoke();

            Assert.AreEqual(url, uri.AbsoluteUri, "Invoke");
        }
Exemplo n.º 16
0
        public void Constructor0_MemberInfo_Type()
        {
            Type type             = typeof(Uri);
            InstanceDescriptor id = new InstanceDescriptor(type,
                                                           new object [] { url });

            Assert.AreEqual(1, id.Arguments.Count, "#1");
            Assert.IsTrue(id.IsComplete, "#2");
            Assert.AreSame(type, id.MemberInfo, "#3");
            Assert.IsNull(id.Invoke(), "#4");
        }
Exemplo n.º 17
0
        /// <summary>
        /// Converts the given object to the type of this converter, using the specified culture
        /// information.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <param name="culture">
        /// The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture.
        /// </param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert. </param>
        /// <param name="propertyType">The property type that the converter will convert to.</param>
        /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed.</exception>
        public virtual object ConvertFrom(CultureInfo culture, object value, Type propertyType)
        {
            InstanceDescriptor id = value as InstanceDescriptor;

            if (id != null)
            {
                return(id.Invoke());
            }

            throw this.GetConvertFromException(value);
        }
Exemplo n.º 18
0
        public void Property_Arguments_Null()
        {
            PropertyInfo pi = typeof(StaticProperty).GetProperty(nameof(StaticProperty.Property));

            InstanceDescriptor id = new InstanceDescriptor(pi, null);

            Assert.Equal(0, id.Arguments.Count);
            Assert.True(id.IsComplete);
            Assert.Same(pi, id.MemberInfo);
            Assert.NotNull(id.Invoke());
        }
Exemplo n.º 19
0
        public void Field_Arguments_Null()
        {
            FieldInfo fi = typeof(StaticField).GetField(nameof(StaticField.Field));

            InstanceDescriptor id = new InstanceDescriptor(fi, null);

            Assert.Equal(0, id.Arguments.Count);
            Assert.True(id.IsComplete);
            Assert.Same(fi, id.MemberInfo);
            Assert.NotNull(id.Invoke());
        }
Exemplo n.º 20
0
        public void Constructor_ConstructorInfo_ICollection_Boolean()
        {
            ConstructorInfo ci = typeof(Uri).GetConstructor(new Type[] { typeof(string) });

            InstanceDescriptor id = new InstanceDescriptor(ci, new object[] { Url }, false);

            Assert.Equal(1, id.Arguments.Count);
            Assert.False(id.IsComplete);
            Assert.Same(ci, id.MemberInfo);
            Uri uri = (Uri)id.Invoke();

            Assert.Equal(Url, uri.AbsoluteUri);
        }
Exemplo n.º 21
0
        public void Ctor_MethodInfo_ICollection()
        {
            MethodInfo method    = typeof(MethodClass).GetMethod(nameof(MethodClass.StaticMethod));
            var        arguments = new object[] { 1 };

            var instanceDescriptor = new InstanceDescriptor(method, arguments);

            Assert.Same(method, instanceDescriptor.MemberInfo);
            Assert.Equal(arguments, instanceDescriptor.Arguments);
            Assert.NotSame(arguments, instanceDescriptor.Arguments);
            Assert.True(instanceDescriptor.IsComplete);

            Assert.Equal("1", instanceDescriptor.Invoke());
        }
Exemplo n.º 22
0
        public void Property_Arguments_Null()
        {
#if MOBILE
            // ensure the property is not linked out of the application since it make the test fails
            Assert.NotNull(Thread.CurrentPrincipal, "pre-test");
#endif
            PropertyInfo pi = typeof(Thread).GetProperty("CurrentPrincipal");

            InstanceDescriptor id = new InstanceDescriptor(pi, null);
            Assert.AreEqual(0, id.Arguments.Count, "#1");
            Assert.IsTrue(id.IsComplete, "#2");
            Assert.AreSame(pi, id.MemberInfo, "#3");
            Assert.IsNotNull(id.Invoke(), "#4");
        }
Exemplo n.º 23
0
        public void Ctor_EventInfo_ICollection()
        {
            EventInfo eventInfo = typeof(EventClass).GetEvent(nameof(EventClass.Event));
            var       arguments = new object[] { 1 };

            var instanceDescriptor = new InstanceDescriptor(eventInfo, arguments);

            Assert.Same(eventInfo, instanceDescriptor.MemberInfo);
            Assert.Equal(arguments, instanceDescriptor.Arguments);
            Assert.NotSame(arguments, instanceDescriptor.Arguments);
            Assert.True(instanceDescriptor.IsComplete);

            Assert.Null(instanceDescriptor.Invoke());
        }
Exemplo n.º 24
0
 private object CopyValue(object value)
 {
     if (value != null)
     {
         Type type = value.GetType();
         if (type.IsValueType)
         {
             return(value);
         }
         object     obj2      = null;
         ICloneable cloneable = value as ICloneable;
         if (cloneable != null)
         {
             obj2 = cloneable.Clone();
         }
         if (obj2 == null)
         {
             // TODO: Reuse ObjectServices here?
             TypeConverter converter = TypeDescriptor.GetConverter(value);
             if (converter.CanConvertTo(typeof(InstanceDescriptor)))
             {
                 InstanceDescriptor descriptor =
                     (InstanceDescriptor)converter.ConvertTo(null, CultureInfo.InvariantCulture, value, typeof(InstanceDescriptor));
                 if ((descriptor != null) && descriptor.IsComplete)
                 {
                     obj2 = descriptor.Invoke();
                 }
             }
             if (((obj2 == null) && converter.CanConvertTo(typeof(string))) && converter.CanConvertFrom(typeof(string)))
             {
                 object obj3 = converter.ConvertToInvariantString(value);
                 obj2 = converter.ConvertFromInvariantString((string)obj3);
             }
         }
         if ((obj2 == null) && type.IsSerializable)
         {
             BinaryFormatter formatter           = new BinaryFormatter();
             MemoryStream    serializationStream = new MemoryStream();
             formatter.Serialize(serializationStream, value);
             serializationStream.Position = 0L;
             obj2 = formatter.Deserialize(serializationStream);
         }
         if (obj2 != null)
         {
             return(obj2);
         }
     }
     return(value);
 }
Exemplo n.º 25
0
        public void Property_Arguments_Mismatch()
        {
            PropertyInfo pi = typeof(StaticProperty).GetProperty(nameof(StaticProperty.Property));

            InstanceDescriptor id = new InstanceDescriptor(pi, new object[] { url });

            Assert.Equal(1, id.Arguments.Count);
            object[] arguments = new object[id.Arguments.Count];
            id.Arguments.CopyTo(arguments, 0);
            Assert.Same(url, arguments[0]);
            Assert.True(id.IsComplete);
            Assert.Same(pi, id.MemberInfo);

            Assert.Throws <TargetParameterCountException>(() => id.Invoke());
        }
Exemplo n.º 26
0
        public void ConvertTo_PositiveTests()
        {
            ExtendedProtectionPolicy policy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);

            InstanceDescriptor       instanceDescriptor = converter.ConvertTo(null, CultureInfo.InvariantCulture, policy, typeof(InstanceDescriptor)) as InstanceDescriptor;
            ExtendedProtectionPolicy instanceResult     = instanceDescriptor.Invoke() as ExtendedProtectionPolicy;

            Assert.NotNull(instanceDescriptor);
            Assert.NotNull(instanceResult);
            Assert.Equal(PolicyEnforcement.Never, instanceResult.PolicyEnforcement);
            Assert.Equal(policy.ProtectionScenario, instanceResult.ProtectionScenario);
            Assert.Null(instanceResult.CustomServiceNames);

            Assert.Equal(string.Empty,
                         converter.ConvertTo(null, CultureInfo.InvariantCulture, null, typeof(string)) as string);
            Assert.Equal(policy.ToString(),
                         converter.ConvertTo(null, CultureInfo.InvariantCulture, policy, typeof(string)) as string);
        }
Exemplo n.º 27
0
        public void Property_Arguments_Mismatch()
        {
            PropertyInfo pi = typeof(Thread).GetProperty("CurrentPrincipal");

            InstanceDescriptor id = new InstanceDescriptor(pi, new object [] { url });

            Assert.AreEqual(1, id.Arguments.Count, "#1");
            object [] arguments = new object [id.Arguments.Count];
            id.Arguments.CopyTo(arguments, 0);
            Assert.AreSame(url, arguments [0], "#2");
            Assert.IsTrue(id.IsComplete, "#3");
            Assert.AreSame(pi, id.MemberInfo, "#4");
            try {
                id.Invoke();
                Assert.Fail("#5");
            } catch (TargetParameterCountException) {
            }
        }
Exemplo n.º 28
0
        public void Property_Arguments_Mismatch()
        {
#if MOBILE
            // ensure the property is not linked out of the application since it make the test fails
            Assert.NotNull(Thread.CurrentPrincipal, "pre-test");
#endif
            PropertyInfo pi = typeof(Thread).GetProperty("CurrentPrincipal");

            InstanceDescriptor id = new InstanceDescriptor(pi, new object [] { url });
            Assert.AreEqual(1, id.Arguments.Count, "#1");
            object [] arguments = new object [id.Arguments.Count];
            id.Arguments.CopyTo(arguments, 0);
            Assert.AreSame(url, arguments [0], "#2");
            Assert.IsTrue(id.IsComplete, "#3");
            Assert.AreSame(pi, id.MemberInfo, "#4");
            try {
                id.Invoke();
                Assert.Fail("#5");
            } catch (TargetParameterCountException) {
            }
        }
        /// <summary>
        ///  This method attempts to copy the given value so unique values are
        ///  always passed to each object.  If the object cannot be copied it
        ///  will be returned.
        /// </summary>
        private object CopyValue(object value)
        {
            // null is always OK
            if (value == null)
            {
                return(value);
            }

            Type type = value.GetType();

            // value types are always copies
            if (type.IsValueType)
            {
                return(value);
            }

            object clonedValue = null;

            // ICloneable is the next easiest thing
            if (value is ICloneable clone)
            {
                clonedValue = clone.Clone();
            }

            // Next, access the type converter
            if (clonedValue == null)
            {
                TypeConverter converter = TypeDescriptor.GetConverter(value);
                if (converter.CanConvertTo(typeof(InstanceDescriptor)))
                {
                    // Instance descriptors provide full fidelity unless
                    // they are marked as incomplete.
                    InstanceDescriptor desc = (InstanceDescriptor)converter.ConvertTo(null, CultureInfo.InvariantCulture, value, typeof(InstanceDescriptor));
                    if (desc != null && desc.IsComplete)
                    {
                        clonedValue = desc.Invoke();
                    }
                }

                // If that didn't work, try conversion to/from string
                if (clonedValue == null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string)))
                {
                    object stringRep = converter.ConvertToInvariantString(value);
                    clonedValue = converter.ConvertFromInvariantString((string)stringRep);
                }
            }

            // How about serialization?
            if (clonedValue == null && type.IsSerializable)
            {
                BinaryFormatter f  = new BinaryFormatter();
                MemoryStream    ms = new MemoryStream();
                f.Serialize(ms, value);
                ms.Position = 0;
                clonedValue = f.Deserialize(ms);
            }

            if (clonedValue != null)
            {
                return(clonedValue);
            }

            // we failed.  This object's reference will be set on each property.
            return(value);
        }
Exemplo n.º 30
0
        private object ReadInstanceDescriptor(XmlNode node)
        {
            // First, need to deserialize the member
            //
            XmlAttribute memberAttr = node.Attributes["member"];

            if (memberAttr == null)
            {
                MessageBox.Show("No member attribute on instance descriptor", "错误2");
                return(null);
            }

            byte[]          data      = Convert.FromBase64String(memberAttr.Value);
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream    stream    = new MemoryStream(data);
            MemberInfo      mi        = (MemberInfo)formatter.Deserialize(stream);

            object[] args = null;

            // Check to see if this member needs arguments.  If so, gather
            // them from the XML.
            if (mi is MethodBase)
            {
                ParameterInfo[] paramInfos = ((MethodBase)mi).GetParameters();

                args = new object[paramInfos.Length];

                int idx = 0;

                foreach (XmlNode child in node.ChildNodes)
                {
                    if (child.Name.Equals("Argument"))
                    {
                        object value;

                        if (!ReadValue(child, TypeDescriptor.GetConverter(paramInfos[idx].ParameterType), out value))
                        {
                            return(null);
                        }

                        args[idx++] = value;
                    }
                }

                if (idx != paramInfos.Length)
                {
                    MessageBox.Show(string.Format("Member {0} requires {1} arguments, not {2}.", mi.Name, args.Length, idx), "错误3");
                    return(null);
                }
            }

            InstanceDescriptor id       = new InstanceDescriptor(mi, args);
            object             instance = id.Invoke();

            // Ok, we have our object.  Now, check to see if there are any properties, and if there are,
            // set them.
            //
            foreach (XmlNode prop in node.ChildNodes)
            {
                if (prop.Name.Equals("Property"))
                {
                    ReadProperty(prop, instance);
                }
            }

            return(instance);
        }