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");
		}
 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);
 }
		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");
		}
 public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
 {
     if(value is MobileTolerance) {
         if(destinationType == typeof(string)) {
             value.ToString();
         }
         if(destinationType == typeof(InstanceDescriptor)) {
             MobileTolerance tolerance = value as MobileTolerance;
             ConstructorInfo constructor = typeof(MobileTolerance).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) });
             InstanceDescriptor instance = new InstanceDescriptor(constructor, new object[] { tolerance.Top, tolerance.Right, tolerance.Bottom, tolerance.Left });
             return instance;
         }
     }
     return base.ConvertTo(context, culture, value, destinationType);
 }
 public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType)
 {
     ConstructorInfo constructor;
     if (destinationType == null)
     {
         throw new ArgumentNullException("destinationType");
     }
     if (!(destinationType == typeof(InstanceDescriptor)) || !(value is ColumnHeader))
     {
         return base.ConvertTo(context, culture, value, destinationType);
     }
     ColumnHeader header = (ColumnHeader) value;
     System.Type reflectionType = TypeDescriptor.GetReflectionType(value);
     InstanceDescriptor descriptor = null;
     if (header.ImageIndex != -1)
     {
         constructor = reflectionType.GetConstructor(new System.Type[] { typeof(int) });
         if (constructor != null)
         {
             descriptor = new InstanceDescriptor(constructor, new object[] { header.ImageIndex }, false);
         }
     }
     if ((descriptor == null) && !string.IsNullOrEmpty(header.ImageKey))
     {
         constructor = reflectionType.GetConstructor(new System.Type[] { typeof(string) });
         if (constructor != null)
         {
             descriptor = new InstanceDescriptor(constructor, new object[] { header.ImageKey }, false);
         }
     }
     if (descriptor != null)
     {
         return descriptor;
     }
     constructor = reflectionType.GetConstructor(new System.Type[0]);
     if (constructor == null)
     {
         throw new ArgumentException(System.Windows.Forms.SR.GetString("NoDefaultConstructor", new object[] { reflectionType.FullName }));
     }
     return new InstanceDescriptor(constructor, new object[0], false);
 }
示例#6
0
        /// <include file='doc\ColumnHeaderConverter.uex' path='docs/doc[@for="ColumnHeaderConverter.ConvertTo"]/*' />
        /// <devdoc>
        ///      Converts the given object to another type.  The most common types to convert
        ///      are to and from a string object.  The default implementation will make a call
        ///      to ToString on the object if the object is valid and if the destination
        ///      type is string.  If this cannot convert to the desitnation type, this will
        ///      throw a NotSupportedException.
        /// </devdoc>
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
            if (destinationType == null) {
                throw new ArgumentNullException("destinationType");
            }

            if (destinationType == typeof(InstanceDescriptor) && value is ColumnHeader) {
                ColumnHeader col = (ColumnHeader) value;
                ConstructorInfo ctor;

                Type t = TypeDescriptor.GetReflectionType(value);
                InstanceDescriptor id = null;
                
                if (col.ImageIndex != -1) {
                    ctor = t.GetConstructor(new Type[]{typeof(int)});
                    if (ctor != null) {
                        id = new InstanceDescriptor(ctor, new object[]{col.ImageIndex}, false);
                    }
                    
                } 

                if (id == null && !String.IsNullOrEmpty(col.ImageKey)) {
                    ctor = t.GetConstructor(new Type[]{typeof(string)});
                    if (ctor != null) {
                        id = new InstanceDescriptor(ctor, new object[]{col.ImageKey}, false);
                    }
                } 

                if (id == null) {
                    ctor = t.GetConstructor(new Type[0]);
                    if (ctor != null) {
                        return new InstanceDescriptor(ctor, new object[0], false);
                    }
                    else {
                        throw new ArgumentException(SR.GetString(SR.NoDefaultConstructor, t.FullName));
                    }
                }
                return id;                
            }
            
            return base.ConvertTo(context, culture, value, destinationType);
        }
 private System.ComponentModel.TypeConverter.StandardValuesCollection GetCachedStandardValues(System.ComponentModel.ITypeDescriptorContext context)
 {
     if (_StandardValues == null)
     {
         FriendlyNameToInstanceDescriptorMap = new System.Collections.Hashtable();
         System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
         arrayList.Add(DefaultRenderer);
         FriendlyNameToInstanceDescriptorMap["(Default)"] = CreateInstanceDescriptor(DefaultRenderer);
         System.Type[] typeArr = RendererType.Assembly.GetExportedTypes();
         for (int i = 0; i < typeArr.Length; i++)
         {
             System.Type type = typeArr[i];
             if (((type == RendererType) || type.IsSubclassOf(RendererType)) && !type.IsAbstract)
             {
                 string s = Skybound.ComponentModel.DisplayNameAttribute.GetFriendlyName(type);
                 FriendlyNameToInstanceDescriptorMap[s] = new System.ComponentModel.Design.Serialization.InstanceDescriptor(type.GetConstructor(System.Type.EmptyTypes), null, true);
                 arrayList.Add(System.Activator.CreateInstance(type, null));
             }
         }
         arrayList.Sort(this);
         _StandardValues = new System.ComponentModel.TypeConverter.StandardValuesCollection(arrayList);
     }
     return _StandardValues;
 }
示例#8
0
 private System.ComponentModel.TypeConverter.StandardValuesCollection GetCachedStandardValues(System.ComponentModel.ITypeDescriptorContext context)
 {
     if (_StandardValues == null)
     {
         FriendlyNameToInstanceDescriptorMap = new System.Collections.Hashtable();
         System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
         arrayList.Add(DefaultRenderer);
         FriendlyNameToInstanceDescriptorMap["(Default)"] = CreateInstanceDescriptor(DefaultRenderer);
         System.Type[] typeArr = RendererType.Assembly.GetExportedTypes();
         for (int i = 0; i < typeArr.Length; i++)
         {
             System.Type type = typeArr[i];
             if (((type == RendererType) || type.IsSubclassOf(RendererType)) && !type.IsAbstract)
             {
                 string s = Skybound.ComponentModel.DisplayNameAttribute.GetFriendlyName(type);
                 FriendlyNameToInstanceDescriptorMap[s] = new System.ComponentModel.Design.Serialization.InstanceDescriptor(type.GetConstructor(System.Type.EmptyTypes), null, true);
                 arrayList.Add(System.Activator.CreateInstance(type, null));
             }
         }
         arrayList.Sort(this);
         _StandardValues = new System.ComponentModel.TypeConverter.StandardValuesCollection(arrayList);
     }
     return(_StandardValues);
 }
		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) {
			}
		}
		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");
		}
示例#11
0
		CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
		{
			CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
			int n = 0;
			foreach (object ob in idesc.Arguments) {
				CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
				if (exp == null) return null;
				parameters [n++] = exp;
			}
			
			switch (idesc.MemberInfo.MemberType) {
			case MemberTypes.Constructor:
				CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
				return new CodeObjectCreateExpression (tob, parameters);

			case MemberTypes.Method:
				CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
				return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);

			case MemberTypes.Field:
				CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
				return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);

			case MemberTypes.Property:
				CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
				return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
			}
			throw new ParseException (currentLocation, "Invalid instance type.");
		}
		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");
		}
 private XmlNode WriteInstanceDescriptor(XmlDocument document, InstanceDescriptor desc, object value)
 {
     XmlNode node = document.CreateElement("InstanceDescriptor");
     BinaryFormatter formatter = new BinaryFormatter();
     MemoryStream stream = new MemoryStream();
     formatter.Serialize(stream, desc.MemberInfo);
     XmlAttribute memberAttr = document.CreateAttribute("member");
     memberAttr.Value = Convert.ToBase64String(stream.ToArray());
     node.Attributes.Append(memberAttr);
     foreach (object arg in desc.Arguments)
     {
         XmlNode argNode = document.CreateElement("Argument");
         if (this.WriteValue(document, arg, argNode))
         {
             node.AppendChild(argNode);
         }
     }
     if (!desc.IsComplete)
     {
         PropertyDescriptorCollection props = TypeDescriptor.GetProperties(value, propertyAttributes);
         this.WriteProperties(document, props, value, node, "Property");
     }
     return node;
 }
		private CodeExpression SerializeInstanceDescriptor (IDesignerSerializationManager manager, InstanceDescriptor descriptor)
		{
			CodeExpression expression = null;
			MemberInfo member = descriptor.MemberInfo;
			CodeExpression target = new CodeTypeReferenceExpression (member.DeclaringType);

			if (member is PropertyInfo) {
				expression = new CodePropertyReferenceExpression (target, member.Name);
			} else if (member is FieldInfo) {
				expression = new CodeFieldReferenceExpression (target, member.Name);
			} else if (member is MethodInfo) {
				expression = new CodeMethodReferenceExpression (target, member.Name);
			} else if (member is ConstructorInfo) {
				CodeExpression[] paramExpressions = null;

				// process ctor params' expressions
				if (descriptor.Arguments != null && descriptor.Arguments.Count > 0) {
					paramExpressions = new CodeExpression[descriptor.Arguments.Count];
					object[] arguments = new object [descriptor.Arguments.Count];
					descriptor.Arguments.CopyTo (arguments, 0);

					for (int i=0; i < paramExpressions.Length; i++) {
						ExpressionContext parentContext = manager.Context[typeof (ExpressionContext)] as ExpressionContext;
						if (parentContext != null) { // check if there is an expression context to add to
							ExpressionContext currentContext = new ExpressionContext (parentContext.Expression, arguments[i].GetType (), parentContext.Owner);
							manager.Context.Push (currentContext);
						}

						paramExpressions[i] = this.SerializeToExpression (manager, arguments[i]);

						manager.Context.Pop ();
					}
				}

				expression = new CodeObjectCreateExpression (member.DeclaringType, paramExpressions);
			}

			return expression;
		}
 private CodeExpression SerializeInstanceDescriptor(IDesignerSerializationManager manager, object value, InstanceDescriptor descriptor)
 {
     CodeExpression expression = null;
     using (TraceScope("CodeDomSerializerBase::SerializeInstanceDescriptor"))
     {
         CodeExpression[] parameters = new CodeExpression[descriptor.Arguments.Count];
         object[] array = new object[parameters.Length];
         ParameterInfo[] infoArray = null;
         if (parameters.Length > 0)
         {
             descriptor.Arguments.CopyTo(array, 0);
             MethodBase memberInfo = descriptor.MemberInfo as MethodBase;
             if (memberInfo != null)
             {
                 infoArray = memberInfo.GetParameters();
             }
         }
         bool flag = true;
         for (int i = 0; i < parameters.Length; i++)
         {
             object obj2 = array[i];
             CodeExpression expression2 = null;
             ExpressionContext context = null;
             ExpressionContext context2 = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
             if (context2 != null)
             {
                 context = new ExpressionContext(context2.Expression, infoArray[i].ParameterType, context2.Owner);
                 manager.Context.Push(context);
             }
             try
             {
                 expression2 = this.SerializeToExpression(manager, obj2);
             }
             finally
             {
                 if (context != null)
                 {
                     manager.Context.Pop();
                 }
             }
             if (expression2 != null)
             {
                 if ((obj2 != null) && !infoArray[i].ParameterType.IsAssignableFrom(obj2.GetType()))
                 {
                     expression2 = new CodeCastExpression(infoArray[i].ParameterType, expression2);
                 }
                 parameters[i] = expression2;
             }
             else
             {
                 flag = false;
                 break;
             }
         }
         if (!flag)
         {
             return expression;
         }
         Type declaringType = descriptor.MemberInfo.DeclaringType;
         CodeTypeReference createType = new CodeTypeReference(declaringType);
         if (descriptor.MemberInfo is ConstructorInfo)
         {
             expression = new CodeObjectCreateExpression(createType, parameters);
         }
         else if (descriptor.MemberInfo is MethodInfo)
         {
             CodeTypeReferenceExpression targetObject = new CodeTypeReferenceExpression(createType);
             CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(targetObject, descriptor.MemberInfo.Name);
             expression = new CodeMethodInvokeExpression(method, parameters);
             declaringType = ((MethodInfo) descriptor.MemberInfo).ReturnType;
         }
         else if (descriptor.MemberInfo is PropertyInfo)
         {
             CodeTypeReferenceExpression expression5 = new CodeTypeReferenceExpression(createType);
             CodePropertyReferenceExpression expression6 = new CodePropertyReferenceExpression(expression5, descriptor.MemberInfo.Name);
             expression = expression6;
             declaringType = ((PropertyInfo) descriptor.MemberInfo).PropertyType;
         }
         else if (descriptor.MemberInfo is FieldInfo)
         {
             CodeTypeReferenceExpression expression7 = new CodeTypeReferenceExpression(createType);
             expression = new CodeFieldReferenceExpression(expression7, descriptor.MemberInfo.Name);
             declaringType = ((FieldInfo) descriptor.MemberInfo).FieldType;
         }
         Type type = value.GetType();
         while (!type.IsPublic)
         {
             type = type.BaseType;
         }
         if (!type.IsAssignableFrom(declaringType))
         {
             expression = new CodeCastExpression(type, expression);
         }
     }
     return expression;
 }
		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");
		}
示例#17
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");
		}
        public void Property_Arguments_Mismatch()
        {
            PropertyInfo pi = typeof(Thread).GetProperty("CurrentThread");

            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());
        }
示例#19
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) {
			}
		}
示例#20
0
        /// <include file='doc\InstanceDescriptorCodeDomSerializer.uex' path='docs/doc[@for="InstanceDescriptorCodeDomSerializer.SerializeInstanceDescriptor"]/*' />
        /// <devdoc>
        ///     Serializes the given instance descriptor into a code model expression.
        /// </devdoc>
        private object SerializeInstanceDescriptor(IDesignerSerializationManager manager, object value, InstanceDescriptor descriptor)
        {
            Debug.WriteLineIf(traceSerialization.TraceVerbose, "InstanceDescriptorCodeDomSerializer::SerializeInstanceDescriptor");
            Debug.Indent();

            Debug.WriteLineIf(traceSerialization.TraceVerbose, "Member: " + descriptor.MemberInfo.Name);
            Debug.WriteLineIf(traceSerialization.TraceVerbose, "Argument count: " + descriptor.Arguments.Count);

            // Serialize all of the arguments.
            //
            CodeExpression[] arguments = new CodeExpression[descriptor.Arguments.Count];
            int  i        = 0;
            bool paramsOk = true;

            foreach (object argument in descriptor.Arguments)
            {
                CodeValueExpression codeValue = new CodeValueExpression(null, argument, (argument != null ? argument.GetType() : null));
                manager.Context.Push(codeValue);
                try {
                    arguments[i] = SerializeToExpression(manager, argument);
                    if (arguments[i] == null)
                    {
                        Debug.WriteLineIf(traceSerialization.TraceWarning, "WARNING: Parameter " + i.ToString() + " in instance descriptor call " + descriptor.GetType().Name + " could not be serialized.");
                        paramsOk = false;
                        break;
                    }
                }
                finally {
                    manager.Context.Pop();
                }
                i++;
            }

            CodeExpression expression = null;

            if (paramsOk)
            {
                Type expressionType       = descriptor.MemberInfo.DeclaringType;
                CodeTypeReference typeRef = new CodeTypeReference(expressionType);

                if (descriptor.MemberInfo is ConstructorInfo)
                {
                    expression = new CodeObjectCreateExpression(typeRef, arguments);
                }
                else if (descriptor.MemberInfo is MethodInfo)
                {
                    CodeTypeReferenceExpression   typeRefExp = new CodeTypeReferenceExpression(typeRef);
                    CodeMethodReferenceExpression methodRef  = new CodeMethodReferenceExpression(typeRefExp, descriptor.MemberInfo.Name);
                    expression     = new CodeMethodInvokeExpression(methodRef, arguments);
                    expressionType = ((MethodInfo)descriptor.MemberInfo).ReturnType;
                }
                else if (descriptor.MemberInfo is PropertyInfo)
                {
                    CodeTypeReferenceExpression     typeRefExp  = new CodeTypeReferenceExpression(typeRef);
                    CodePropertyReferenceExpression propertyRef = new CodePropertyReferenceExpression(typeRefExp, descriptor.MemberInfo.Name);
                    Debug.Assert(arguments.Length == 0, "Property serialization does not support arguments");
                    expression     = propertyRef;
                    expressionType = ((PropertyInfo)descriptor.MemberInfo).PropertyType;
                }
                else if (descriptor.MemberInfo is FieldInfo)
                {
                    Debug.Assert(arguments.Length == 0, "Field serialization does not support arguments");
                    CodeTypeReferenceExpression typeRefExp = new CodeTypeReferenceExpression(typeRef);
                    expression     = new CodeFieldReferenceExpression(typeRefExp, descriptor.MemberInfo.Name);
                    expressionType = ((FieldInfo)descriptor.MemberInfo).FieldType;
                }
                else
                {
                    Debug.Fail("Unrecognized reflection type in instance descriptor: " + descriptor.MemberInfo.GetType().Name);
                }

                // Finally, check to see if our value is assignable from the expression type.  If not,
                // then supply a cast.  The value may be an internal or protected type; if it is,
                // then walk up its hierarchy until we find one that is public.
                //
                Type targetType = value.GetType();
                while (!targetType.IsPublic)
                {
                    targetType = targetType.BaseType;
                }

                if (!targetType.IsAssignableFrom(expressionType))
                {
                    Debug.WriteLineIf(traceSerialization.TraceVerbose, "Target type of " + targetType.Name + " is not assignable from " + expressionType.Name + ".  Supplying cast.");
                    expression = new CodeCastExpression(targetType, expression);
                }
            }

            Debug.Unindent();
            return(expression);
        }
示例#21
0
        /// <include file='doc\InstanceDescriptorCodeDomSerializer.uex' path='docs/doc[@for="InstanceDescriptorCodeDomSerializer.Serialize"]/*' />
        /// <devdoc>
        ///     Serializes the given object into a CodeDom object.
        /// </devdoc>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            object expression = null;

            Debug.WriteLineIf(traceSerialization.TraceVerbose, "InstanceDescriptorCodeDomSerializer::Serialize");
            Debug.Indent();

            // To serialize a primitive type, we must assign its value to the current statement.  We get the current
            // statement by asking the context.

            object statement = manager.Context.Current;

            Debug.Assert(statement != null, "Statement is null -- we need a context to be pushed for instance descriptors to serialize");

            Debug.WriteLineIf(traceSerialization.TraceVerbose, "Value: " + value.ToString());
            Debug.WriteLineIf(traceSerialization.TraceVerbose && statement != null, "Statement: " + statement.GetType().Name);

            TypeConverter      converter  = TypeDescriptor.GetConverter(value);
            InstanceDescriptor descriptor = (InstanceDescriptor)converter.ConvertTo(value, typeof(InstanceDescriptor));

            if (descriptor != null)
            {
                expression = SerializeInstanceDescriptor(manager, value, descriptor);
            }
            else
            {
                Debug.WriteLineIf(traceSerialization.TraceError, "*** Converter + " + converter.GetType().Name + " failed to give us an instance descriptor");
            }

            // Ok, we have the "new Foo(arg, arg, arg)" done.  Next, check to see if the instance
            // descriptor has given us a complete representation of the object.  If not, we must
            // go through the additional work of creating a local variable and saving properties.
            //
            if (descriptor != null && !descriptor.IsComplete)
            {
                Debug.WriteLineIf(traceSerialization.TraceVerbose, "Incomplete instance descriptor; creating local variable declaration and serializing properties.");
                CodeStatementCollection statements = (CodeStatementCollection)manager.Context[typeof(CodeStatementCollection)];
                Debug.WriteLineIf(traceSerialization.TraceError && statements == null, "*** No CodeStatementCollection on context stack so we can generate a local variable statement.");

                if (statements != null)
                {
                    MemberInfo mi = descriptor.MemberInfo;
                    Type       targetType;

                    if (mi is PropertyInfo)
                    {
                        targetType = ((PropertyInfo)mi).PropertyType;
                    }
                    else if (mi is MethodInfo)
                    {
                        targetType = ((MethodInfo)mi).ReturnType;
                    }
                    else
                    {
                        targetType = mi.DeclaringType;
                    }

                    string localName = manager.GetName(value);

                    if (localName == null)
                    {
                        string baseName;

                        INameCreationService ns = (INameCreationService)manager.GetService(typeof(INameCreationService));
                        Debug.WriteLineIf(traceSerialization.TraceWarning && (ns == null), "WARNING: Need to generate name for local variable but we have no service.");

                        if (ns != null)
                        {
                            baseName = ns.CreateName(null, targetType);
                        }
                        else
                        {
                            baseName = targetType.Name.ToLower(CultureInfo.InvariantCulture);
                        }

                        int suffixIndex = 1;

                        // Declare this name to the serializer.  If there is already a name defined,
                        // keep trying.
                        //
                        while (true)
                        {
                            localName = baseName + suffixIndex.ToString();

                            if (manager.GetInstance(localName) == null)
                            {
                                manager.SetName(value, localName);
                                break;
                            }

                            suffixIndex++;
                        }
                    }

                    Debug.WriteLineIf(traceSerialization.TraceVerbose, "Named local variable " + localName);

                    CodeVariableDeclarationStatement localStatement = new CodeVariableDeclarationStatement(targetType, localName);
                    localStatement.InitExpression = (CodeExpression)expression;
                    statements.Add(localStatement);

                    expression = new CodeVariableReferenceExpression(localName);

                    // Create a CodeValueExpression to place on the context stack.
                    CodeValueExpression cve = new CodeValueExpression((CodeExpression)expression, value);

                    manager.Context.Push(cve);

                    try {
                        // Now that we have hooked the return expression up and declared the local,
                        // it's time to save off the properties for the object.
                        //
                        SerializeProperties(manager, statements, value, runTimeProperties);
                    }
                    finally {
                        Debug.Assert(manager.Context.Current == cve, "Context stack corrupted");
                        manager.Context.Pop();
                    }
                }
            }

            Debug.Unindent();
            return(expression);
        }
        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());
        }
示例#23
0
		public void Property_LinkDemand_PermitOnly_Unrestricted ()
		{
			InstanceDescriptor id = new InstanceDescriptor (null, new object[] { });
			// denying anything -> not unrestricted
			Type[] types = new Type[3] { typeof (MemberInfo), typeof (ICollection), typeof (bool) };
			MethodInfo mi = typeof (InstanceDescriptor).GetProperty ("IsComplete").GetGetMethod ();
			Assert.IsNotNull (mi, "IsComplete)");
			Assert.IsTrue ((bool) mi.Invoke (id, null), "invoke");
		}
        public void Property_Arguments_Null()
        {
            PropertyInfo pi = typeof(Thread).GetProperty("CurrentThread");

            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());
        }
示例#25
0
		private object ReadInstanceDescriptor(XmlNode node, ArrayList errors)
		{
			// First, need to deserialize the member
			//
			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;

			// 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), 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();

			// 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, errors);
				}
			}

			return instance;
		}
 private 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 (!this.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;
         }
     }
     object instance = new InstanceDescriptor(mi, args).Invoke();
     foreach (XmlNode prop in node.ChildNodes)
     {
         if (prop.Name.Equals("Property"))
         {
             this.ReadProperty(prop, instance, errors);
         }
     }
     return instance;
 }
		private CodeExpression SerializeInstanceDescriptor (IDesignerSerializationManager manager, InstanceDescriptor descriptor)
		{
			CodeExpression expression = null;
			MemberInfo member = descriptor.MemberInfo;
			CodeExpression target = new CodeTypeReferenceExpression (member.DeclaringType);

			if (member is PropertyInfo) {
				expression = new CodePropertyReferenceExpression (target, member.Name);
			} else if (member is FieldInfo) {
				expression = new CodeFieldReferenceExpression (target, member.Name);
			} else if (member is MethodInfo) {
				CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression (target, member.Name);
				if (descriptor.Arguments != null && descriptor.Arguments.Count > 0)
					methodInvoke.Parameters.AddRange (SerializeParameters (manager, descriptor.Arguments));
				expression = methodInvoke;
			} else if (member is ConstructorInfo) {
				CodeObjectCreateExpression createExpr = new CodeObjectCreateExpression (member.DeclaringType);
				if (descriptor.Arguments != null && descriptor.Arguments.Count > 0)
					createExpr.Parameters.AddRange (SerializeParameters (manager, descriptor.Arguments));
				expression = createExpr;
			}

			return expression;
		}
    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
      object result;

      if (destinationType == null)
        throw new ArgumentNullException("destinationType");

      if (value is ZoomLevelCollection)
      {
        if (destinationType == typeof(string))
        {
          ZoomLevelCollection collection;
          StringBuilder data;
          string separator;
          TypeConverter converter;

          collection = (ZoomLevelCollection)value;
          if (culture == null)
            culture = CultureInfo.CurrentCulture;
          separator = culture.TextInfo.ListSeparator + " ";
          converter = TypeDescriptor.GetConverter(typeof(int));
          data = new StringBuilder();

          foreach (int item in collection)
          {
            if (data.Length != 0)
              data.Append(separator);

            data.Append(converter.ConvertToString(context, culture, item));
          }

          result = data.ToString();
        }
        else if (destinationType == typeof(InstanceDescriptor))
        {
          ZoomLevelCollection collection;
          ConstructorInfo constructor;

          collection = (ZoomLevelCollection)value;
          constructor = typeof(ZoomLevelCollection).GetConstructor(new Type[] { typeof(IList<int>) });

          result = new InstanceDescriptor(constructor, new object[] { collection.ToArray() });
        }
        else
          result = null;
      }
      else
        result = null;

      if (result == null)
        result = base.ConvertTo(context, culture, value, destinationType);

      return result;
    }
示例#29
0
文件: VECTOR3D.cs 项目: zulis/Sandbox
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
                                         Type destinationType)
        {
            object retVal = null;
            var VECTOR3D = (VECTOR3D) value;

            if (destinationType == typeof (InstanceDescriptor))
            {
                var argTypes = new Type[3];

                argTypes[0] = typeof (float);
                argTypes[1] = typeof (float);
                argTypes[2] = typeof (float);

                ConstructorInfo constructor = typeof (VECTOR3D).GetConstructor(argTypes);

                var arguments = new object[3];

                arguments[0] = VECTOR3D.X;
                arguments[1] = VECTOR3D.Y;
                arguments[2] = VECTOR3D.Z;

                retVal = new InstanceDescriptor(constructor, arguments);
            }
            else if (destinationType == typeof (string))
            {
                if (null == culture)
                    culture = CultureInfo.CurrentCulture;

                var values = new string[3];

                TypeConverter numberConverter = TypeDescriptor.GetConverter(typeof (float));

                values[0] = VECTOR3D.X.ToString();
                values[1] = VECTOR3D.Y.ToString();
                values[2] = VECTOR3D.Z.ToString();

                retVal = String.Join(culture.TextInfo.ListSeparator + " ", values);
            }
            else
                retVal = base.ConvertTo(context, culture, value, destinationType);

            return retVal;
        }