protected CodeExpression GetExpression(IDesignerSerializationManager manager, object instance)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            CodeExpression expression = null;

            ExpressionTable expressions = manager.Context[typeof(ExpressionTable)] as ExpressionTable;

            if (expressions != null)             // 1st try: ExpressionTable
            {
                expression = expressions [instance] as CodeExpression;
            }

            if (expression == null)               // 2nd try: RootContext
            {
                RootContext context = manager.Context[typeof(RootContext)] as RootContext;
                if (context != null && context.Value == instance)
                {
                    expression = context.Expression;
                }
            }

            if (expression == null)               // 3rd try: IReferenceService (instnace.property.property.property
            {
                string name = manager.GetName(instance);
                if (name == null || name.IndexOf(".") == -1)
                {
                    IReferenceService service = manager.GetService(typeof(IReferenceService)) as IReferenceService;
                    if (service != null)
                    {
                        name = service.GetName(instance);
                        if (name != null && name.IndexOf(".") != -1)
                        {
                            string[] parts = name.Split(new char[] { ',' });
                            instance = manager.GetInstance(parts[0]);
                            if (instance != null)
                            {
                                expression = SerializeToExpression(manager, instance);
                                if (expression != null)
                                {
                                    for (int i = 1; i < parts.Length; i++)
                                    {
                                        expression = new CodePropertyReferenceExpression(expression, parts[i]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(expression);
        }
Пример #2
0
        /// <include file='doc\InstanceDescriptorCodeDomSerializer.uex' path='docs/doc[@for="InstanceDescriptorCodeDomSerializer.Deserialize"]/*' />
        /// <devdoc>
        ///     Deserilizes the given CodeDom object into a real object.  This
        ///     will use the serialization manager to create objects and resolve
        ///     data types.  The root of the object graph is returned.
        /// </devdoc>
        public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
        {
            if (manager == null || codeObject == null)
            {
                throw new ArgumentNullException(manager == null ? "manager" : "codeObject");
            }

            if (!(codeObject is CodeStatementCollection))
            {
                Debug.Fail("ComponentCodeDomSerializer::Deserialize requires a CodeStatementCollection to parse");
                throw new ArgumentException(SR.GetString(SR.SerializerBadElementType, typeof(CodeStatementCollection).FullName));
            }

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

            object instance = null;

            if (manager.Context[typeof(CodeExpression)] != null)
            {
                Debug.WriteLineIf(traceSerialization.TraceVerbose, "Retrieving instance from context stack");
                instance = DeserializeExpression(manager, null, (CodeExpression)manager.Context[typeof(CodeExpression)]);
                Debug.WriteLineIf(traceSerialization.TraceWarning && instance == null, "WARNING: CodeExpression on stack did not return an instance.");
            }
            // Now look for things we understand.
            //
            foreach (CodeStatement statement in (CodeStatementCollection)codeObject)
            {
                if (statement is CodeVariableDeclarationStatement)
                {
                    CodeVariableDeclarationStatement localRef = (CodeVariableDeclarationStatement)statement;
                    Debug.WriteLineIf(traceSerialization.TraceVerbose, "Creating instance of object: " + localRef.Name);
                    Debug.WriteLineIf(traceSerialization.TraceWarning && instance != null, "WARNING: Instance has already been established.");
                    instance = DeserializeExpression(manager, localRef.Name, localRef.InitExpression);

                    // make sure we pushed in the value of the variable
                    //
                    if (instance != null && null == manager.GetInstance(localRef.Name))
                    {
                        manager.SetName(instance, localRef.Name);
                    }

                    // Now that the object has been created, deserialize its design time properties.
                    //
                    DeserializePropertiesFromResources(manager, instance, designTimeProperties);
                }
                else
                {
                    DeserializeStatement(manager, statement);
                }
            }

            Debug.Unindent();
            return(instance);
        }
Пример #3
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeDomSerializer baseClassSerializer = (CodeDomSerializer)manager.
                                                    GetSerializer(typeof(MyComponent).BaseType, typeof(CodeDomSerializer));

            object codeObject = baseClassSerializer.Serialize(manager, value);

            if (codeObject is CodeStatementCollection)
            {
                CodeStatementCollection statements = (CodeStatementCollection)codeObject;
                // Initial MyList
                // Generate "myComponent1.MyList = new System.Collections.Generic.List<string>();"
                CodeObjectCreateExpression objectCreate1;
                objectCreate1 = new CodeObjectCreateExpression("System.Collections.Generic.List<string>", new CodeExpression[] { });
                CodeAssignStatement as2 =
                    new CodeAssignStatement(new CodeVariableReferenceExpression(manager.GetName(value) + ".MyList"),
                                            objectCreate1);
                statements.Insert(0, as2);

                // Add my generated code comment
                string commentText           = "MyList generation code";
                CodeCommentStatement comment = new CodeCommentStatement(commentText);
                statements.Insert(1, comment);

                // Add items to MyList
                // Generate the following code
                // this.myComponent1.MyList.Add("string5");
                // this.myComponent1.MyList.Add("string4");
                // this.myComponent1.MyList.Add("string3");
                // this.myComponent1.MyList.Add("string2");
                // this.myComponent1.MyList.Add("string1");
                MyComponent myCom = (MyComponent)manager.GetInstance(manager.GetName(value));
                for (int i = 0; i < myCom.MyList.Count; i++)
                {
                    CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(
                        // targetObject that contains the method to invoke.
                        new CodeThisReferenceExpression(),
                        // methodName indicates the method to invoke.
                        manager.GetName(value) + ".MyList.Add",
                        // parameters array contains the parameters for the method.
                        new CodeExpression[] { new CodePrimitiveExpression(myCom.MyList[i]) });
                    CodeExpressionStatement expressionStatement;
                    expressionStatement = new CodeExpressionStatement(methodInvoke);
                    statements.Insert(2, expressionStatement);
                }
                // Remove system generated code
                statements.RemoveAt(statements.Count - 1);
            }
            return(codeObject);
        }
Пример #4
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);
        }
        protected object DeserializeExpression(IDesignerSerializationManager manager, string name, CodeExpression expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            object deserialized = null;

            // CodeThisReferenceExpression
            //
            CodeThisReferenceExpression thisExpr = expression as CodeThisReferenceExpression;

            if (thisExpr != null)
            {
                RootContext context = manager.Context[typeof(RootContext)] as RootContext;
                if (context != null)
                {
                    deserialized = context.Value;
                }
                else
                {
                    IDesignerHost host = manager.GetService(typeof(IDesignerHost)) as IDesignerHost;
                    if (host != null)
                    {
                        deserialized = host.RootComponent;
                    }
                }
            }

            // CodeVariableReferenceExpression
            //

            CodeVariableReferenceExpression varRef = expression as CodeVariableReferenceExpression;

            if (deserialized == null && varRef != null)
            {
                deserialized = manager.GetInstance(varRef.VariableName);
            }

            // CodeFieldReferenceExpression
            //
            CodeFieldReferenceExpression fieldRef = expression as CodeFieldReferenceExpression;

            if (deserialized == null && fieldRef != null)
            {
                deserialized = manager.GetInstance(fieldRef.FieldName);
            }


            // CodePrimitiveExpression
            //
            CodePrimitiveExpression primitiveExp = expression as CodePrimitiveExpression;

            if (deserialized == null && primitiveExp != null)
            {
                deserialized = primitiveExp.Value;
            }

            // CodePropertyReferenceExpression
            //
            // Enum references are represented by a PropertyReferenceExpression, where
            // PropertyName is the enum field name and the target object is a TypeReference
            // to the enum's type
            //
            CodePropertyReferenceExpression propRef = expression as CodePropertyReferenceExpression;

            if (deserialized == null && propRef != null)
            {
                object target = DeserializeExpression(manager, null, propRef.TargetObject);
                if (target != null)
                {
                    if (target is Type)                       // Enum reference
                    {
                        FieldInfo field = ((Type)target).GetField(propRef.PropertyName,
                                                                  BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
                        if (field != null)
                        {
                            deserialized = field.GetValue(null);
                        }
                    }
                    else
                    {
                        PropertyDescriptor property = TypeDescriptor.GetProperties(target)[propRef.PropertyName];
                        if (property != null)
                        {
                            deserialized = property.GetValue(target);
                        }
                    }
                }
            }

            // CodeObjectCreateExpression
            //
            CodeObjectCreateExpression createExpr = expression as CodeObjectCreateExpression;

            if (deserialized == null && createExpr != null)
            {
                Type     type      = manager.GetType(createExpr.CreateType.BaseType);
                object[] arguments = new object[createExpr.Parameters.Count];
                for (int i = 0; i < createExpr.Parameters.Count; i++)
                {
                    arguments[i] = this.DeserializeExpression(manager, null, createExpr.Parameters[i]);
                }
                bool addToContainer = false;
                if (typeof(IComponent).IsAssignableFrom(type))
                {
                    addToContainer = true;
                }
                deserialized = this.DeserializeInstance(manager, type, arguments, name, addToContainer);
            }

            // CodeArrayCreateExpression
            //
            CodeArrayCreateExpression arrayCreateExpr = expression as CodeArrayCreateExpression;

            if (deserialized == null && arrayCreateExpr != null)
            {
                Type arrayType = manager.GetType(arrayCreateExpr.CreateType.BaseType);
                if (arrayType != null)
                {
                    ArrayList initializers = new ArrayList();
                    foreach (CodeExpression initExpression in arrayCreateExpr.Initializers)
                    {
                        initializers.Add(this.DeserializeExpression(manager, null, initExpression));
                    }
                    deserialized = Array.CreateInstance(arrayType, initializers.Count);
                    initializers.CopyTo((Array)deserialized, 0);
                }
            }

            // CodeMethodInvokeExpression
            //
            CodeMethodInvokeExpression methodExpr = expression as CodeMethodInvokeExpression;

            if (deserialized == null && methodExpr != null)
            {
                object   target     = this.DeserializeExpression(manager, null, methodExpr.Method.TargetObject);
                object[] parameters = new object[methodExpr.Parameters.Count];
                for (int i = 0; i < methodExpr.Parameters.Count; i++)
                {
                    parameters[i] = this.DeserializeExpression(manager, null, methodExpr.Parameters[i]);
                }

                MethodInfo method = null;
                if (target is Type)
                {
                    method = GetExactMethod((Type)target, methodExpr.Method.MethodName,
                                            BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
                                            parameters);
                }
                else
                {
                    method = GetExactMethod(target.GetType(), methodExpr.Method.MethodName,
                                            BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
                                            parameters);
                }

                if (method == null)
                {
                    Console.WriteLine("DeserializeExpression: Unable to find method: " + methodExpr.Method.MethodName);
                }
                else
                {
                    deserialized = method.Invoke(target, parameters);
                }
            }

            // CodeTypeReferenceExpression
            //
            CodeTypeReferenceExpression typeRef = expression as CodeTypeReferenceExpression;

            if (deserialized == null && typeRef != null)
            {
                deserialized = manager.GetType(typeRef.Type.BaseType);
            }

            // CodeBinaryOperatorExpression
            //
            CodeBinaryOperatorExpression binOperator = expression as CodeBinaryOperatorExpression;

            if (deserialized == null && binOperator != null)
            {
                switch (binOperator.Operator)
                {
                case CodeBinaryOperatorType.BitwiseOr:
                    IConvertible left  = DeserializeExpression(manager, null, binOperator.Left) as IConvertible;
                    IConvertible right = DeserializeExpression(manager, null, binOperator.Right) as IConvertible;
                    if (left is Enum)
                    {
                        deserialized = Enum.ToObject(left.GetType(), Convert.ToInt64(left) | Convert.ToInt64(right));
                    }
                    break;
                }
            }

            if (deserialized == null && methodExpr == null && primitiveExp == null)
            {
                Console.WriteLine("DeserializeExpression not supported for: " + expression);
            }

            return(deserialized);
        }
		protected object DeserializeExpression (IDesignerSerializationManager manager, string name, CodeExpression expression) 
		{
			if (expression == null)
				throw new ArgumentNullException ("expression");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			object deserialized = null;

			// CodeThisReferenceExpression
			//
			CodeThisReferenceExpression thisExpr = expression as CodeThisReferenceExpression;
			if (thisExpr != null) {
				RootContext context = manager.Context[typeof (RootContext)] as RootContext;
				if (context != null) {
					deserialized = context.Value;
				} else {
					IDesignerHost host = manager.GetService (typeof (IDesignerHost)) as IDesignerHost;
					if (host != null)
						deserialized = host.RootComponent;
				}
			}
			
			// CodeVariableReferenceExpression
			//

			CodeVariableReferenceExpression varRef = expression as CodeVariableReferenceExpression;
			if (deserialized == null && varRef != null)
					deserialized = manager.GetInstance (varRef.VariableName);

			// CodeFieldReferenceExpression
			//
			CodeFieldReferenceExpression fieldRef = expression as CodeFieldReferenceExpression;
			if (deserialized == null && fieldRef != null)
				deserialized = manager.GetInstance (fieldRef.FieldName);
				

			// CodePrimitiveExpression
			//
			CodePrimitiveExpression primitiveExp = expression as CodePrimitiveExpression;
			if (deserialized == null && primitiveExp != null)
				deserialized = primitiveExp.Value;

			// CodePropertyReferenceExpression
			//
			// Enum references are represented by a PropertyReferenceExpression, where 
			// PropertyName is the enum field name and the target object is a TypeReference
			// to the enum's type
			//
			CodePropertyReferenceExpression propRef = expression as CodePropertyReferenceExpression;
			if (deserialized == null && propRef != null) {
				object target = DeserializeExpression (manager, null, propRef.TargetObject);
				if (target != null) {
					if (target is Type) { // Enum reference
						FieldInfo field = ((Type)target).GetField (propRef.PropertyName,
																	BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
						if (field != null)
							deserialized = field.GetValue (null);
					} else {
						PropertyDescriptor property = TypeDescriptor.GetProperties (target)[propRef.PropertyName];
						if (property != null)
							deserialized = property.GetValue (target);
					}
				}
			}

			// CodeObjectCreateExpression
			//
			CodeObjectCreateExpression createExpr = expression as CodeObjectCreateExpression;
			if (deserialized == null && createExpr != null) {
				Type type = manager.GetType (createExpr.CreateType.BaseType);
				object[] arguments = new object[createExpr.Parameters.Count];
				for (int i=0; i < createExpr.Parameters.Count; i++)
					arguments[i] = this.DeserializeExpression (manager, null, createExpr.Parameters[i]);
				bool addToContainer = false;
				if (typeof(IComponent).IsAssignableFrom (type))
					addToContainer = true;
				deserialized = this.DeserializeInstance (manager, type, arguments, name, addToContainer);
			}

			// CodeArrayCreateExpression
			//
			CodeArrayCreateExpression arrayCreateExpr = expression as CodeArrayCreateExpression;
			if (deserialized == null && arrayCreateExpr != null) {
				Type arrayType = manager.GetType (arrayCreateExpr.CreateType.BaseType);
				if (arrayType != null) {
					ArrayList initializers = new ArrayList ();
					foreach (CodeExpression initExpression in arrayCreateExpr.Initializers) {
						initializers.Add (this.DeserializeExpression (manager, null, initExpression));
					}
					deserialized = Array.CreateInstance (arrayType, initializers.Count);
					initializers.CopyTo ((Array)deserialized, 0);
				}
			}

			// CodeMethodInvokeExpression
			//
			CodeMethodInvokeExpression methodExpr = expression as CodeMethodInvokeExpression;
			if (deserialized == null && methodExpr != null) {
				object target = this.DeserializeExpression (manager, null, methodExpr.Method.TargetObject);
				object[] parameters = new object[methodExpr.Parameters.Count];
				for (int i=0; i < methodExpr.Parameters.Count; i++)
					parameters[i] = this.DeserializeExpression (manager, null, methodExpr.Parameters[i]);

				MethodInfo method = null;
				if (target is Type) {
					method = GetExactMethod ((Type)target, methodExpr.Method.MethodName, 
											 BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
											 parameters);
				} else {
					method = GetExactMethod (target.GetType(), methodExpr.Method.MethodName, 
											 BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
											 parameters);
				}

				if (method == null)
					Console.WriteLine ("DeserializeExpression: Unable to find method: " + methodExpr.Method.MethodName);
				else
					deserialized = method.Invoke (target, parameters);
			}

			// CodeTypeReferenceExpression
			//
			CodeTypeReferenceExpression typeRef = expression as CodeTypeReferenceExpression;
			if (deserialized == null && typeRef != null)
				deserialized = manager.GetType (typeRef.Type.BaseType);
			
			// CodeBinaryOperatorExpression
			//
			CodeBinaryOperatorExpression binOperator = expression as CodeBinaryOperatorExpression;
			if (deserialized == null && binOperator != null) {
				switch (binOperator.Operator) {
					case CodeBinaryOperatorType.BitwiseOr:
						IConvertible left = DeserializeExpression (manager, null, binOperator.Left) as IConvertible;
						IConvertible right = DeserializeExpression (manager, null, binOperator.Right) as IConvertible;
						if (left is Enum) 
							deserialized = Enum.ToObject (left.GetType (), Convert.ToInt64 (left) | Convert.ToInt64 (right));
						break;
				}
			}

			if (deserialized == null && methodExpr == null && primitiveExp == null)
				Console.WriteLine ("DeserializeExpression not supported for: " + expression);

			return deserialized;
		}
 protected CodeExpression GetExpression(IDesignerSerializationManager manager, object value)
 {
     CodeExpression expression = null;
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     ExpressionTable table = manager.Context[typeof(ExpressionTable)] as ExpressionTable;
     if (table != null)
     {
         expression = table.GetExpression(value);
     }
     if (expression == null)
     {
         RootContext context = manager.Context[typeof(RootContext)] as RootContext;
         if ((context != null) && object.ReferenceEquals(context.Value, value))
         {
             expression = context.Expression;
         }
     }
     if (expression == null)
     {
         string name = manager.GetName(value);
         if ((name == null) || (name.IndexOf('.') != -1))
         {
             IReferenceService service = manager.GetService(typeof(IReferenceService)) as IReferenceService;
             if (service != null)
             {
                 name = service.GetName(value);
                 if ((name != null) && (name.IndexOf('.') != -1))
                 {
                     string[] strArray = name.Split(new char[] { '.' });
                     object instance = manager.GetInstance(strArray[0]);
                     if (instance != null)
                     {
                         CodeExpression targetObject = this.SerializeToExpression(manager, instance);
                         if (targetObject != null)
                         {
                             for (int i = 1; i < strArray.Length; i++)
                             {
                                 targetObject = new CodePropertyReferenceExpression(targetObject, strArray[i]);
                             }
                             expression = targetObject;
                         }
                     }
                 }
             }
         }
     }
     if (expression == null)
     {
         ExpressionContext context2 = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
         if ((context2 != null) && object.ReferenceEquals(context2.PresetValue, value))
         {
             expression = context2.Expression;
         }
     }
     if (expression != null)
     {
         ComponentCache.Entry entry = (ComponentCache.Entry) manager.Context[typeof(ComponentCache.Entry)];
         ComponentCache cache = (ComponentCache) manager.Context[typeof(ComponentCache)];
         if (((entry != null) && (entry.Component != value)) && (cache != null))
         {
             ComponentCache.Entry entryAll = null;
             entryAll = cache.GetEntryAll(value);
             if ((entryAll != null) && (entry.Component != null))
             {
                 entryAll.AddDependency(entry.Component);
             }
         }
     }
     return expression;
 }
		protected object DeserializeExpression (IDesignerSerializationManager manager, string name, CodeExpression expression) 
		{
			if (expression == null)
				throw new ArgumentNullException ("expression");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			bool errorOccurred = false;
			object deserialized = null;

			// CodeThisReferenceExpression
			//
			CodeThisReferenceExpression thisExpr = expression as CodeThisReferenceExpression;
			if (thisExpr != null) {
				RootContext context = manager.Context[typeof (RootContext)] as RootContext;
				if (context != null) {
					deserialized = context.Value;
				} else {
					IDesignerHost host = manager.GetService (typeof (IDesignerHost)) as IDesignerHost;
					if (host != null)
						deserialized = host.RootComponent;
				}
			}
			
			// CodeVariableReferenceExpression
			//
			CodeVariableReferenceExpression varRef = expression as CodeVariableReferenceExpression;
			if (deserialized == null && varRef != null) {
				deserialized = manager.GetInstance (varRef.VariableName);
				if (deserialized == null) {
					ReportError (manager, "Variable '" + varRef.VariableName + "' not initialized prior to reference");
					errorOccurred = true;
				}
			}

			// CodeFieldReferenceExpression (used for Enum references as well)
			//
			CodeFieldReferenceExpression fieldRef = expression as CodeFieldReferenceExpression;
			if (deserialized == null && fieldRef != null) {
				deserialized = manager.GetInstance (fieldRef.FieldName);
				if (deserialized == null) {
					object fieldHolder = DeserializeExpression (manager, null, fieldRef.TargetObject);
					FieldInfo field = null;
					if (fieldHolder is Type) // static field
						field = ((Type)fieldHolder).GetField (fieldRef.FieldName, 
										      BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
					else // instance field
						field = fieldHolder.GetType().GetField (fieldRef.FieldName, 
											BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance);
					if (field != null)
						deserialized = field.GetValue (fieldHolder);
				}
				if (deserialized == null)
					ReportError (manager, "Field '" + fieldRef.FieldName + "' not initialized prior to reference");
			}
				

			// CodePrimitiveExpression
			//
			CodePrimitiveExpression primitiveExp = expression as CodePrimitiveExpression;
			if (deserialized == null && primitiveExp != null)
				deserialized = primitiveExp.Value;

			// CodePropertyReferenceExpression
			//
			CodePropertyReferenceExpression propRef = expression as CodePropertyReferenceExpression;
			if (deserialized == null && propRef != null) {
				object target = DeserializeExpression (manager, null, propRef.TargetObject);
				if (target != null && target != _errorMarker) {
					bool found = false;
					if (target is Type) {
						PropertyInfo property = ((Type)target).GetProperty (propRef.PropertyName,
												    BindingFlags.GetProperty | 
												    BindingFlags.Public | BindingFlags.Static);
						if (property != null) {
							deserialized = property.GetValue (null, null);
							found = true;
						}

						// NRefactory seems to produce PropertyReferences to reference some fields and enums
						//
						FieldInfo field = ((Type)target).GetField (propRef.PropertyName,
											   BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
						if (field != null) {
							deserialized = field.GetValue (null);
							found = true;
						}
					} else {
						PropertyDescriptor property = TypeDescriptor.GetProperties (target)[propRef.PropertyName];
						if (property != null) {
							deserialized = property.GetValue (target);
							found = true;
						}

						FieldInfo field = target.GetType().GetField (propRef.PropertyName,
											     BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance);
						if (field != null) {
							deserialized = field.GetValue (null);
							found = true;
						}
					}
					
					if (!found) {
						ReportError (manager, "Missing field '" + propRef.PropertyName + " 'in type " + 
							     (target is Type ? ((Type)target).Name : target.GetType ().Name) + "'");
						errorOccurred = true;
					}
				}
			}

			// CodeObjectCreateExpression
			//
			CodeObjectCreateExpression createExpr = expression as CodeObjectCreateExpression;
			if (deserialized == null && createExpr != null) {
				Type type = manager.GetType (createExpr.CreateType.BaseType);
				if (type == null) {
					ReportError (manager, "Type '" + createExpr.CreateType.BaseType + "' not found." + 
						     "Are you missing a reference?");
					errorOccurred = true;
				} else {
					object[] arguments = new object[createExpr.Parameters.Count];
					for (int i=0; i < createExpr.Parameters.Count; i++) {
						arguments[i] = this.DeserializeExpression (manager, null, createExpr.Parameters[i]);
						if (arguments[i] == _errorMarker) {
							errorOccurred = true;
							break;
						}
					}
					if (!errorOccurred) {
						bool addToContainer = false;
						if (typeof(IComponent).IsAssignableFrom (type))
							addToContainer = true;
						deserialized = this.DeserializeInstance (manager, type, arguments, name, addToContainer);
						if (deserialized == _errorMarker || deserialized == null) {
							string info = "Type to create: " + createExpr.CreateType.BaseType + System.Environment.NewLine +
								"Name: " + name + System.Environment.NewLine +
								"addToContainer: " + addToContainer.ToString () + System.Environment.NewLine +
								"Parameters Count: " + createExpr.Parameters.Count + System.Environment.NewLine;
	
							for (int i=0; i < arguments.Length; i++) {
								info += "Parameter Number: " + i.ToString () + System.Environment.NewLine +
									"Parameter Type: " + (arguments[i] == null ? "null" : arguments[i].GetType ().Name) +
									System.Environment.NewLine +
									"Parameter '" + i.ToString () + "' Value: " + arguments[i].ToString () + System.Environment.NewLine;
							}
							ReportError (manager, 
								     "Unable to create an instance of type '" + createExpr.CreateType.BaseType + "'",
								     info);
							errorOccurred = true;
						}
					}
				}
			}

			// CodeArrayCreateExpression
			//
			CodeArrayCreateExpression arrayCreateExpr = expression as CodeArrayCreateExpression;
			if (deserialized == null && arrayCreateExpr != null) {
				Type arrayType = manager.GetType (arrayCreateExpr.CreateType.BaseType);
				if (arrayType == null) {
					ReportError (manager, "Type '" + arrayCreateExpr.CreateType.BaseType + "' not found." + 
						     "Are you missing a reference?");
					errorOccurred = true;
				} else {
					ArrayList initializers = new ArrayList ();
					Type elementType = arrayType.GetElementType ();
					deserialized = Array.CreateInstance (arrayType, arrayCreateExpr.Initializers.Count);
					for (int i = 0; i < arrayCreateExpr.Initializers.Count; i++) {
						object element = this.DeserializeExpression (manager, null, arrayCreateExpr.Initializers[i]);
						errorOccurred = (element == _errorMarker);
						if (!errorOccurred) {
							if (arrayType.IsInstanceOfType (element)) {
								initializers.Add (element);
							} else {
								ReportError (manager, 
									     "Array initializer element type incompatible with array type.",
									     "Array Type: " + arrayType.Name + System.Environment.NewLine +
									     "Array Element Type: " + elementType + System.Environment.NewLine +
									     "Initializer Type: " + (element == null ? "null" : element.GetType ().Name));
								errorOccurred = true;
							}
						}
					}
					if (!errorOccurred)
						initializers.CopyTo ((Array)deserialized, 0);
				}
			}

			// CodeMethodInvokeExpression
			//
			CodeMethodInvokeExpression methodExpr = expression as CodeMethodInvokeExpression;
			if (deserialized == null && methodExpr != null) {
				object target = this.DeserializeExpression (manager, null, methodExpr.Method.TargetObject);
				object[] parameters = null;
				if (target == _errorMarker || target == null) {
					errorOccurred = true;
				} else {
					parameters = new object[methodExpr.Parameters.Count];
					for (int i=0; i < methodExpr.Parameters.Count; i++) {
						parameters[i] = this.DeserializeExpression (manager, null, methodExpr.Parameters[i]);
						if (parameters[i] == _errorMarker) {
							errorOccurred = true;
							break;
						}
					}
				}

				if (!errorOccurred) {
					MethodInfo method = null;
					if (target is Type) {
						method = GetExactMethod ((Type)target, methodExpr.Method.MethodName, 
												 BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
												 parameters);
					} else {
						method = GetExactMethod (target.GetType(), methodExpr.Method.MethodName, 
												 BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
												 parameters);
					}
	
					if (method != null) {
						deserialized = method.Invoke (target, parameters);
					} else {
						string info = 
							"Method Name: " + methodExpr.Method.MethodName + System.Environment.NewLine +
							"Method is: " + (target is Type ? "static" : "instance") + System.Environment.NewLine +
							"Method Holder Type: " + (target is Type ? ((Type)target).Name : target.GetType ().Name) + System.Environment.NewLine +
							"Parameters Count: " + methodExpr.Parameters.Count + System.Environment.NewLine +
							System.Environment.NewLine;

						for (int i = 0; i < parameters.Length; i++) {
							info += "Parameter Number: " + i.ToString () + System.Environment.NewLine +
								"Parameter Type: " + (parameters[i] == null ? "null" : parameters[i].GetType ().Name) +
								System.Environment.NewLine +
								"Parameter " + i.ToString () + " Value: " + parameters[i].ToString () + System.Environment.NewLine;
						}
						ReportError (manager, 
							     "Method '" + methodExpr.Method.MethodName + "' missing in type '" + 
							     (target is Type ? ((Type)target).Name : target.GetType ().Name + "'"),
							     info);
						errorOccurred = true;
					}
				}
			}

			// CodeTypeReferenceExpression
			//
			CodeTypeReferenceExpression typeRef = expression as CodeTypeReferenceExpression;
			if (deserialized == null && typeRef != null) {
				deserialized = manager.GetType (typeRef.Type.BaseType);
				if (deserialized == null) {
					ReportError (manager, "Type '" + typeRef.Type.BaseType + "' not found." + 
						     "Are you missing a reference?");
					errorOccurred = true;
				}
			}

			// CodeCastExpression
			// 
			CodeCastExpression castExpr = expression as CodeCastExpression;
			if (deserialized == null && castExpr != null) {
				Type targetType = manager.GetType (castExpr.TargetType.BaseType);
				object instance = DeserializeExpression (manager, null, castExpr.Expression);
				if (instance != null && instance != _errorMarker && targetType != null) {
					IConvertible convertible = instance as IConvertible;
					if (convertible != null) {
						try {
							instance = convertible.ToType (targetType, null);
						} catch {
							errorOccurred = true;
						}
					} else {
						errorOccurred = true;
					}
					if (errorOccurred) {
						ReportError (manager, "Unable to convert type '" + instance.GetType ().Name + 
							     "' to type '" + castExpr.TargetType.BaseType + "'",
							     "Target Type: " + castExpr.TargetType.BaseType + System.Environment.NewLine +
							     "Instance Type: " + (instance == null ? "null" : instance.GetType ().Name) + System.Environment.NewLine +
							     "Instance Value: " + (instance == null ? "null" : instance.ToString()) + System.Environment.NewLine +
							     "Instance is IConvertible: " + (instance is IConvertible).ToString());
					}

					deserialized = instance;
				}
			}


			// CodeBinaryOperatorExpression
			//
			CodeBinaryOperatorExpression binOperator = expression as CodeBinaryOperatorExpression;
			if (deserialized == null && binOperator != null) {
				string errorText = null;
				IConvertible left = null;
				IConvertible right = null;
				switch (binOperator.Operator) {
					case CodeBinaryOperatorType.BitwiseOr:
						left = DeserializeExpression (manager, null, binOperator.Left) as IConvertible;
						right = DeserializeExpression (manager, null, binOperator.Right) as IConvertible;
						if (left is Enum && right is Enum) {
							deserialized = Enum.ToObject (left.GetType (), Convert.ToInt64 (left) | Convert.ToInt64 (right));
						} else {
							errorText = "CodeBinaryOperatorType.BitwiseOr allowed only on Enum types";
							errorOccurred = true;
						}
						break;
					default:
						errorText = "Unsupported CodeBinaryOperatorType: " + binOperator.Operator.ToString ();
						errorOccurred = true;
						break;
				}

				if (errorOccurred) {
					string info = "BinaryOperator Type: " + binOperator.Operator.ToString() + System.Environment.NewLine +
						"Left Type: " + (left == null ? "null" : left.GetType().Name) + System.Environment.NewLine +
						"Left Value: " + (left == null ? "null" : left.ToString ()) + System.Environment.NewLine +
						"Left Expression Type: " + binOperator.Left.GetType ().Name + System.Environment.NewLine +
						"Right Type: " + (right == null ? "null" : right.GetType().Name) + System.Environment.NewLine +
						"Right Value: " + (right == null ? "null" : right.ToString ()) + System.Environment.NewLine +
						"Right Expression Type: " + binOperator.Right.GetType ().Name;
					ReportError (manager, errorText, info);
				}
			}


			if (!errorOccurred) {
				if (deserialized == null && !(expression is CodePrimitiveExpression) && !(expression is CodeMethodInvokeExpression)) {
					ReportError (manager, "Unsupported Expression Type: " + expression.GetType ().Name);
					errorOccurred = true;
				}
			}

			if (errorOccurred)
				deserialized = _errorMarker;
			return deserialized;
		}
 private bool ResolveName(IDesignerSerializationManager manager, string name, bool canInvokeManager)
 {
     bool flag = false;
     CodeDomSerializerBase.OrderedCodeStatementCollection codeObject = this._statementsTable[name] as CodeDomSerializerBase.OrderedCodeStatementCollection;
     object[] objArray = (object[]) this._objectState[name];
     if (name.IndexOf('.') > 0)
     {
         string outerComponent = null;
         IComponent instance = this.ResolveNestedName(manager, name, ref outerComponent);
         if ((instance != null) && (outerComponent != null))
         {
             manager.SetName(instance, name);
             this.ResolveName(manager, outerComponent, canInvokeManager);
         }
     }
     if (codeObject == null)
     {
         flag = this._statementsTable[name] != null;
         if (!flag)
         {
             if (this._expressions.ContainsKey(name))
             {
                 ArrayList list2 = this._expressions[name];
                 foreach (CodeExpression expression2 in list2)
                 {
                     object obj3 = base.DeserializeExpression(manager, name, expression2);
                     if (((obj3 != null) && !flag) && (canInvokeManager && (manager.GetInstance(name) == null)))
                     {
                         manager.SetName(obj3, name);
                         flag = true;
                     }
                 }
             }
             if (!flag && canInvokeManager)
             {
                 flag = manager.GetInstance(name) != null;
             }
             if ((flag && (objArray != null)) && (objArray[2] != null))
             {
                 this.DeserializeDefaultProperties(manager, name, objArray[2]);
             }
             if ((flag && (objArray != null)) && (objArray[3] != null))
             {
                 this.DeserializeDesignTimeProperties(manager, name, objArray[3]);
             }
             if ((flag && (objArray != null)) && (objArray[4] != null))
             {
                 this.DeserializeEventResets(manager, name, objArray[4]);
             }
             if ((flag && (objArray != null)) && (objArray[5] != null))
             {
                 DeserializeModifier(manager, name, objArray[5]);
             }
         }
         if (!flag && (flag || canInvokeManager))
         {
             manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("CodeDomComponentSerializationServiceDeserializationError", new object[] { name }), manager));
         }
         return flag;
     }
     this._objectState[name] = null;
     this._statementsTable[name] = null;
     string typeName = null;
     foreach (CodeStatement statement in codeObject)
     {
         CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement;
         if (statement2 != null)
         {
             typeName = statement2.Type.BaseType;
             break;
         }
     }
     if (typeName != null)
     {
         Type valueType = manager.GetType(typeName);
         if (valueType == null)
         {
             manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeName }), manager));
             goto Label_01DA;
         }
         if ((codeObject == null) || (codeObject.Count <= 0))
         {
             goto Label_01DA;
         }
         CodeDomSerializer serializer = base.GetSerializer(manager, valueType);
         if (serializer == null)
         {
             manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { valueType.FullName }), manager));
             goto Label_01DA;
         }
         try
         {
             object obj2 = serializer.Deserialize(manager, codeObject);
             flag = obj2 != null;
             if (flag)
             {
                 this._statementsTable[name] = obj2;
             }
             goto Label_01DA;
         }
         catch (Exception exception)
         {
             manager.ReportError(exception);
             goto Label_01DA;
         }
     }
     foreach (CodeStatement statement3 in codeObject)
     {
         base.DeserializeStatement(manager, statement3);
     }
     flag = true;
 Label_01DA:
     if ((objArray != null) && (objArray[2] != null))
     {
         this.DeserializeDefaultProperties(manager, name, objArray[2]);
     }
     if ((objArray != null) && (objArray[3] != null))
     {
         this.DeserializeDesignTimeProperties(manager, name, objArray[3]);
     }
     if ((objArray != null) && (objArray[4] != null))
     {
         this.DeserializeEventResets(manager, name, objArray[4]);
     }
     if ((objArray != null) && (objArray[5] != null))
     {
         DeserializeModifier(manager, name, objArray[5]);
     }
     if (!this._expressions.ContainsKey(name))
     {
         return flag;
     }
     ArrayList list = this._expressions[name];
     foreach (CodeExpression expression in list)
     {
         base.DeserializeExpression(manager, name, expression);
     }
     this._expressions.Remove(name);
     return true;
 }
 private static void DeserializeModifier(IDesignerSerializationManager manager, string name, object state)
 {
     object instance = manager.GetInstance(name);
     if (instance != null)
     {
         MemberAttributes attributes = (MemberAttributes) state;
         PropertyDescriptor descriptor = TypeDescriptor.GetProperties(instance)["Modifiers"];
         if (descriptor != null)
         {
             descriptor.SetValue(instance, attributes);
         }
     }
 }
 private void DeserializeEventResets(IDesignerSerializationManager manager, string name, object state)
 {
     List<string> list = state as List<string>;
     if (((list != null) && (manager != null)) && !string.IsNullOrEmpty(name))
     {
         IEventBindingService service = manager.GetService(typeof(IEventBindingService)) as IEventBindingService;
         object instance = manager.GetInstance(name);
         if ((instance != null) && (service != null))
         {
             PropertyDescriptorCollection eventProperties = service.GetEventProperties(TypeDescriptor.GetEvents(instance));
             if (eventProperties != null)
             {
                 foreach (string str in list)
                 {
                     PropertyDescriptor descriptor = eventProperties[str];
                     if (descriptor != null)
                     {
                         descriptor.SetValue(instance, null);
                     }
                 }
             }
         }
     }
 }
 private void DeserializeDesignTimeProperties(IDesignerSerializationManager manager, string name, object state)
 {
     if (state != null)
     {
         object instance = manager.GetInstance(name);
         if (instance != null)
         {
             PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(instance);
             foreach (DictionaryEntry entry in (IDictionary) state)
             {
                 PropertyDescriptor descriptor = properties[(string) entry.Key];
                 if (descriptor != null)
                 {
                     descriptor.SetValue(instance, entry.Value);
                 }
             }
         }
     }
 }
 private void DeserializeDefaultProperties(IDesignerSerializationManager manager, string name, object state)
 {
     if ((state != null) && this.applyDefaults)
     {
         object instance = manager.GetInstance(name);
         if (instance != null)
         {
             PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(instance);
             string[] strArray = (string[]) state;
             MemberRelationshipService service = manager.GetService(typeof(MemberRelationshipService)) as MemberRelationshipService;
             foreach (string str in strArray)
             {
                 PropertyDescriptor descriptor = properties[str];
                 if ((descriptor != null) && descriptor.CanResetValue(instance))
                 {
                     if ((service != null) && (service[instance, descriptor] != MemberRelationship.Empty))
                     {
                         service[instance, descriptor] = MemberRelationship.Empty;
                     }
                     descriptor.ResetValue(instance);
                 }
             }
         }
     }
 }
 protected object DeserializeExpression(IDesignerSerializationManager manager, string name, CodeExpression expression)
 {
     object instance = expression;
     using (TraceScope("CodeDomSerializerBase::DeserializeExpression"))
     {
         while (instance != null)
         {
             CodePrimitiveExpression expression2 = instance as CodePrimitiveExpression;
             if (expression2 != null)
             {
                 return expression2.Value;
             }
             CodePropertyReferenceExpression propertyReferenceEx = instance as CodePropertyReferenceExpression;
             if (propertyReferenceEx != null)
             {
                 return this.DeserializePropertyReferenceExpression(manager, propertyReferenceEx, true);
             }
             if (instance is CodeThisReferenceExpression)
             {
                 RootContext context = (RootContext) manager.Context[typeof(RootContext)];
                 if (context != null)
                 {
                     instance = context.Value;
                 }
                 else
                 {
                     IDesignerHost host = manager.GetService(typeof(IDesignerHost)) as IDesignerHost;
                     if (host != null)
                     {
                         instance = host.RootComponent;
                     }
                 }
                 if (instance == null)
                 {
                     Error(manager, System.Design.SR.GetString("SerializerNoRootExpression"), "SerializerNoRootExpression");
                 }
                 return instance;
             }
             CodeTypeReferenceExpression expression4 = instance as CodeTypeReferenceExpression;
             if (expression4 != null)
             {
                 return manager.GetType(GetTypeNameFromCodeTypeReference(manager, expression4.Type));
             }
             CodeObjectCreateExpression expression5 = instance as CodeObjectCreateExpression;
             if (expression5 != null)
             {
                 instance = null;
                 Type c = manager.GetType(GetTypeNameFromCodeTypeReference(manager, expression5.CreateType));
                 if (c != null)
                 {
                     object[] parameters = new object[expression5.Parameters.Count];
                     bool flag = true;
                     for (int i = 0; i < parameters.Length; i++)
                     {
                         parameters[i] = this.DeserializeExpression(manager, null, expression5.Parameters[i]);
                         if (parameters[i] is CodeExpression)
                         {
                             if ((typeof(Delegate).IsAssignableFrom(c) && (parameters.Length == 1)) && (parameters[i] is CodeMethodReferenceExpression))
                             {
                                 CodeMethodReferenceExpression expression19 = (CodeMethodReferenceExpression) parameters[i];
                                 if (!(expression19.TargetObject is CodeThisReferenceExpression))
                                 {
                                     object obj3 = this.DeserializeExpression(manager, null, expression19.TargetObject);
                                     if (!(obj3 is CodeExpression))
                                     {
                                         MethodInfo method = c.GetMethod("Invoke");
                                         if (method != null)
                                         {
                                             ParameterInfo[] infoArray = method.GetParameters();
                                             Type[] types = new Type[infoArray.Length];
                                             for (int j = 0; j < types.Length; j++)
                                             {
                                                 types[j] = infoArray[i].ParameterType;
                                             }
                                             if (GetReflectionTypeHelper(manager, obj3).GetMethod(expression19.MethodName, types) != null)
                                             {
                                                 MethodInfo info2 = obj3.GetType().GetMethod(expression19.MethodName, types);
                                                 instance = Activator.CreateInstance(c, new object[] { obj3, info2.MethodHandle.GetFunctionPointer() });
                                             }
                                         }
                                     }
                                 }
                             }
                             flag = false;
                             break;
                         }
                     }
                     if (flag)
                     {
                         instance = this.DeserializeInstance(manager, c, parameters, name, name != null);
                     }
                     return instance;
                 }
                 Error(manager, System.Design.SR.GetString("SerializerTypeNotFound", new object[] { expression5.CreateType.BaseType }), "SerializerTypeNotFound");
                 return instance;
             }
             CodeArgumentReferenceExpression expression6 = instance as CodeArgumentReferenceExpression;
             if (expression6 != null)
             {
                 instance = manager.GetInstance(expression6.ParameterName);
                 if (instance == null)
                 {
                     Error(manager, System.Design.SR.GetString("SerializerUndeclaredName", new object[] { expression6.ParameterName }), "SerializerUndeclaredName");
                 }
                 return instance;
             }
             CodeFieldReferenceExpression expression7 = instance as CodeFieldReferenceExpression;
             if (expression7 != null)
             {
                 object obj4 = this.DeserializeExpression(manager, null, expression7.TargetObject);
                 if ((obj4 != null) && !(obj4 is CodeExpression))
                 {
                     FieldInfo field;
                     object obj6;
                     RootContext context2 = (RootContext) manager.Context[typeof(RootContext)];
                     if ((context2 != null) && (context2.Value == obj4))
                     {
                         object obj5 = manager.GetInstance(expression7.FieldName);
                         if (obj5 != null)
                         {
                             return obj5;
                         }
                         Error(manager, System.Design.SR.GetString("SerializerUndeclaredName", new object[] { expression7.FieldName }), "SerializerUndeclaredName");
                         return instance;
                     }
                     Type type = obj4 as Type;
                     if (type != null)
                     {
                         obj6 = null;
                         field = GetReflectionTypeFromTypeHelper(manager, type).GetField(expression7.FieldName, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
                     }
                     else
                     {
                         obj6 = obj4;
                         field = GetReflectionTypeHelper(manager, obj4).GetField(expression7.FieldName, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance);
                     }
                     if (field != null)
                     {
                         return field.GetValue(obj6);
                     }
                     CodePropertyReferenceExpression expression20 = new CodePropertyReferenceExpression {
                         TargetObject = expression7.TargetObject,
                         PropertyName = expression7.FieldName
                     };
                     instance = this.DeserializePropertyReferenceExpression(manager, expression20, false);
                     if (instance == expression7)
                     {
                         Error(manager, System.Design.SR.GetString("SerializerUndeclaredName", new object[] { expression7.FieldName }), "SerializerUndeclaredName");
                     }
                     return instance;
                 }
                 Error(manager, System.Design.SR.GetString("SerializerFieldTargetEvalFailed", new object[] { expression7.FieldName }), "SerializerFieldTargetEvalFailed");
                 return instance;
             }
             CodeMethodInvokeExpression expression8 = instance as CodeMethodInvokeExpression;
             if (expression8 != null)
             {
                 object component = this.DeserializeExpression(manager, null, expression8.Method.TargetObject);
                 if (component != null)
                 {
                     object[] args = new object[expression8.Parameters.Count];
                     bool flag2 = true;
                     for (int k = 0; k < args.Length; k++)
                     {
                         args[k] = this.DeserializeExpression(manager, null, expression8.Parameters[k]);
                         if (args[k] is CodeExpression)
                         {
                             flag2 = false;
                             break;
                         }
                     }
                     if (flag2)
                     {
                         IComponentChangeService service = (IComponentChangeService) manager.GetService(typeof(IComponentChangeService));
                         Type type3 = component as Type;
                         if (type3 != null)
                         {
                             return GetReflectionTypeFromTypeHelper(manager, type3).InvokeMember(expression8.Method.MethodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, args, null, null, null);
                         }
                         if (service != null)
                         {
                             service.OnComponentChanging(component, null);
                         }
                         try
                         {
                             instance = GetReflectionTypeHelper(manager, component).InvokeMember(expression8.Method.MethodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, component, args, null, null, null);
                         }
                         catch (MissingMethodException)
                         {
                             CodeCastExpression targetObject = expression8.Method.TargetObject as CodeCastExpression;
                             if (targetObject == null)
                             {
                                 throw;
                             }
                             Type type4 = manager.GetType(GetTypeNameFromCodeTypeReference(manager, targetObject.TargetType));
                             if ((type4 == null) || !type4.IsInterface)
                             {
                                 throw;
                             }
                             instance = GetReflectionTypeFromTypeHelper(manager, type4).InvokeMember(expression8.Method.MethodName, BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, component, args, null, null, null);
                         }
                         if (service != null)
                         {
                             service.OnComponentChanged(component, null, null, null);
                         }
                         return instance;
                     }
                     if ((args.Length == 1) && (args[0] is CodeDelegateCreateExpression))
                     {
                         string methodName = expression8.Method.MethodName;
                         if (methodName.StartsWith("add_"))
                         {
                             methodName = methodName.Substring(4);
                             this.DeserializeAttachEventStatement(manager, new CodeAttachEventStatement(expression8.Method.TargetObject, methodName, (CodeExpression) args[0]));
                             instance = null;
                         }
                     }
                 }
                 return instance;
             }
             CodeVariableReferenceExpression expression9 = instance as CodeVariableReferenceExpression;
             if (expression9 != null)
             {
                 instance = manager.GetInstance(expression9.VariableName);
                 if (instance == null)
                 {
                     Error(manager, System.Design.SR.GetString("SerializerUndeclaredName", new object[] { expression9.VariableName }), "SerializerUndeclaredName");
                 }
                 return instance;
             }
             CodeCastExpression expression10 = instance as CodeCastExpression;
             if (expression10 != null)
             {
                 instance = this.DeserializeExpression(manager, name, expression10.Expression);
                 IConvertible convertible = instance as IConvertible;
                 if (convertible != null)
                 {
                     Type conversionType = manager.GetType(GetTypeNameFromCodeTypeReference(manager, expression10.TargetType));
                     if (conversionType != null)
                     {
                         instance = convertible.ToType(conversionType, null);
                     }
                 }
                 return instance;
             }
             if (instance is CodeBaseReferenceExpression)
             {
                 RootContext context3 = (RootContext) manager.Context[typeof(RootContext)];
                 if (context3 != null)
                 {
                     return context3.Value;
                 }
                 return null;
             }
             CodeArrayCreateExpression expression11 = instance as CodeArrayCreateExpression;
             if (expression11 != null)
             {
                 Type type6 = manager.GetType(GetTypeNameFromCodeTypeReference(manager, expression11.CreateType));
                 Array array = null;
                 if (type6 != null)
                 {
                     if (expression11.Initializers.Count > 0)
                     {
                         ArrayList list = new ArrayList(expression11.Initializers.Count);
                         foreach (CodeExpression expression22 in expression11.Initializers)
                         {
                             try
                             {
                                 object o = this.DeserializeExpression(manager, null, expression22);
                                 if (!(o is CodeExpression))
                                 {
                                     if (!type6.IsInstanceOfType(o))
                                     {
                                         o = Convert.ChangeType(o, type6, CultureInfo.InvariantCulture);
                                     }
                                     list.Add(o);
                                 }
                             }
                             catch (Exception exception)
                             {
                                 manager.ReportError(exception);
                             }
                         }
                         array = Array.CreateInstance(type6, list.Count);
                         list.CopyTo(array, 0);
                     }
                     else if (expression11.SizeExpression != null)
                     {
                         IConvertible convertible2 = this.DeserializeExpression(manager, name, expression11.SizeExpression) as IConvertible;
                         if (convertible2 != null)
                         {
                             int length = convertible2.ToInt32(null);
                             array = Array.CreateInstance(type6, length);
                         }
                     }
                     else
                     {
                         array = Array.CreateInstance(type6, expression11.Size);
                     }
                 }
                 else
                 {
                     Error(manager, System.Design.SR.GetString("SerializerTypeNotFound", new object[] { expression11.CreateType.BaseType }), "SerializerTypeNotFound");
                 }
                 instance = array;
                 if ((instance != null) && (name != null))
                 {
                     manager.SetName(instance, name);
                 }
                 return instance;
             }
             CodeArrayIndexerExpression expression12 = instance as CodeArrayIndexerExpression;
             if (expression12 != null)
             {
                 instance = null;
                 Array array2 = this.DeserializeExpression(manager, name, expression12.TargetObject) as Array;
                 if (array2 != null)
                 {
                     int[] indices = new int[expression12.Indices.Count];
                     bool flag3 = true;
                     for (int m = 0; m < indices.Length; m++)
                     {
                         IConvertible convertible3 = this.DeserializeExpression(manager, name, expression12.Indices[m]) as IConvertible;
                         if (convertible3 != null)
                         {
                             indices[m] = convertible3.ToInt32(null);
                         }
                         else
                         {
                             flag3 = false;
                             break;
                         }
                     }
                     if (flag3)
                     {
                         instance = array2.GetValue(indices);
                     }
                 }
                 return instance;
             }
             CodeBinaryOperatorExpression expression13 = instance as CodeBinaryOperatorExpression;
             if (expression13 != null)
             {
                 object obj10 = this.DeserializeExpression(manager, null, expression13.Left);
                 object obj11 = this.DeserializeExpression(manager, null, expression13.Right);
                 instance = obj10;
                 IConvertible left = obj10 as IConvertible;
                 IConvertible right = obj11 as IConvertible;
                 if ((left != null) && (right != null))
                 {
                     instance = this.ExecuteBinaryExpression(left, right, expression13.Operator);
                 }
                 return instance;
             }
             CodeDelegateInvokeExpression expression14 = instance as CodeDelegateInvokeExpression;
             if (expression14 != null)
             {
                 Delegate delegate2 = this.DeserializeExpression(manager, null, expression14.TargetObject) as Delegate;
                 if (delegate2 != null)
                 {
                     object[] objArray3 = new object[expression14.Parameters.Count];
                     bool flag4 = true;
                     for (int n = 0; n < objArray3.Length; n++)
                     {
                         objArray3[n] = this.DeserializeExpression(manager, null, expression14.Parameters[n]);
                         if (objArray3[n] is CodeExpression)
                         {
                             flag4 = false;
                             break;
                         }
                     }
                     if (flag4)
                     {
                         delegate2.DynamicInvoke(objArray3);
                     }
                 }
                 return instance;
             }
             CodeDirectionExpression expression15 = instance as CodeDirectionExpression;
             if (expression15 != null)
             {
                 return this.DeserializeExpression(manager, name, expression15.Expression);
             }
             CodeIndexerExpression expression16 = instance as CodeIndexerExpression;
             if (expression16 != null)
             {
                 instance = null;
                 object target = this.DeserializeExpression(manager, null, expression16.TargetObject);
                 if (target != null)
                 {
                     object[] objArray4 = new object[expression16.Indices.Count];
                     bool flag5 = true;
                     for (int num7 = 0; num7 < objArray4.Length; num7++)
                     {
                         objArray4[num7] = this.DeserializeExpression(manager, null, expression16.Indices[num7]);
                         if (objArray4[num7] is CodeExpression)
                         {
                             flag5 = false;
                             break;
                         }
                     }
                     if (flag5)
                     {
                         instance = GetReflectionTypeHelper(manager, target).InvokeMember("Item", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, target, objArray4, null, null, null);
                     }
                 }
                 return instance;
             }
             if (instance is CodeSnippetExpression)
             {
                 return null;
             }
             CodeParameterDeclarationExpression expression17 = instance as CodeParameterDeclarationExpression;
             if (expression17 != null)
             {
                 return manager.GetType(GetTypeNameFromCodeTypeReference(manager, expression17.Type));
             }
             CodeTypeOfExpression expression18 = instance as CodeTypeOfExpression;
             if (expression18 != null)
             {
                 string typeNameFromCodeTypeReference = GetTypeNameFromCodeTypeReference(manager, expression18.Type);
                 for (int num8 = 0; num8 < expression18.Type.ArrayRank; num8++)
                 {
                     typeNameFromCodeTypeReference = typeNameFromCodeTypeReference + "[]";
                 }
                 instance = manager.GetType(typeNameFromCodeTypeReference);
                 if (instance == null)
                 {
                     Error(manager, System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeNameFromCodeTypeReference }), "SerializerTypeNotFound");
                 }
                 return instance;
             }
             if (((instance is CodeEventReferenceExpression) || (instance is CodeMethodReferenceExpression)) || !(instance is CodeDelegateCreateExpression))
             {
             }
             return instance;
         }
     }
     return instance;
 }
 protected string GetUniqueName(IDesignerSerializationManager manager, object value)
 {
     string str2;
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     string name = manager.GetName(value);
     if (name != null)
     {
         return name;
     }
     Type reflectionTypeHelper = GetReflectionTypeHelper(manager, value);
     INameCreationService service = manager.GetService(typeof(INameCreationService)) as INameCreationService;
     if (service != null)
     {
         str2 = service.CreateName(null, reflectionTypeHelper);
     }
     else
     {
         str2 = reflectionTypeHelper.Name.ToLower(CultureInfo.InvariantCulture);
     }
     int num = 1;
     ComponentCache cache = manager.Context[typeof(ComponentCache)] as ComponentCache;
     while (true)
     {
         name = string.Format(CultureInfo.CurrentCulture, "{0}{1}", new object[] { str2, num });
         if ((manager.GetInstance(name) == null) && ((cache == null) || !cache.ContainsLocalName(name)))
         {
             manager.SetName(value, name);
             ComponentCache.Entry entry = manager.Context[typeof(ComponentCache.Entry)] as ComponentCache.Entry;
             if (entry != null)
             {
                 entry.AddLocalName(name);
             }
             return name;
         }
         num++;
     }
 }
 private IComponent ResolveNestedName(IDesignerSerializationManager manager, string name, ref string outerComponent)
 {
     IComponent instance = null;
     if ((name != null) && (manager != null))
     {
         bool flag = true;
         int index = name.IndexOf('.', 0);
         outerComponent = name.Substring(0, index);
         instance = manager.GetInstance(outerComponent) as IComponent;
         int num2 = index;
         int length = name.IndexOf('.', index + 1);
         while (flag)
         {
             flag = length != -1;
             string str = flag ? name.Substring(num2 + 1, length) : name.Substring(num2 + 1);
             if ((instance != null) && (instance.Site != null))
             {
                 INestedContainer service = instance.Site.GetService(typeof(INestedContainer)) as INestedContainer;
                 if ((service != null) && !string.IsNullOrEmpty(str))
                 {
                     instance = service.Components[str];
                     goto Label_00B7;
                 }
             }
             return null;
         Label_00B7:
             if (flag)
             {
                 num2 = length;
                 length = name.IndexOf('.', length + 1);
             }
         }
     }
     return instance;
 }
		protected CodeExpression GetExpression (IDesignerSerializationManager manager, object instance)
		{
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (instance == null)
				throw new ArgumentNullException ("instance");

			CodeExpression expression = null;

			ExpressionTable expressions = manager.Context[typeof (ExpressionTable)] as ExpressionTable;
			if (expressions != null) // 1st try: ExpressionTable
				expression = expressions [instance] as CodeExpression;

			if (expression == null) { // 2nd try: RootContext
				RootContext context = manager.Context[typeof (RootContext)] as RootContext;
				if (context != null && context.Value == instance)
					expression = context.Expression;
			}

			if (expression == null) { // 3rd try: IReferenceService (instance.property.property.property
				string name = manager.GetName (instance);
				if (name == null || name.IndexOf (".") == -1) {
					IReferenceService service = manager.GetService (typeof (IReferenceService)) as IReferenceService;
					if (service != null) {
						name = service.GetName (instance);
						if (name != null && name.IndexOf (".") != -1) {
							string[] parts = name.Split (new char[] { ',' });
							instance = manager.GetInstance (parts[0]);
							if (instance != null) {
								expression = SerializeToExpression (manager, instance);
								if (expression != null) {
									for (int i=1; i < parts.Length; i++)
										expression = new CodePropertyReferenceExpression (expression, parts[i]);
								}
							}
						}
					}
				}
			}
			return expression;
		}
Пример #18
0
 /// <summary>
 /// Gets an instance by name.
 /// </summary>
 public object GetInstance(string name)
 {
     return(serializationManager.GetInstance(name));
 }
 bool IsInherited(string componentName)
 {
     return(IsInherited(serializationManager.GetInstance(componentName)));
 }
Пример #20
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeDomSerializer serial = GetBaseComponentSerializer(manager);

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

            CodeStatementCollection statements = (CodeStatementCollection)serial.Serialize(manager, value);

            //serializer for web controls.
            if (!(manager.GetSerializer(typeof(System.Web.UI.Control), typeof(CodeDomSerializer)) is WebControlSerializer))
            {
                manager.AddSerializationProvider(new WebControlSerializationProvider());
            }

            IDesignerHost host = (IDesignerHost)manager.GetService(typeof(IDesignerHost));

            if (host.RootComponent == value)
            {
                return(statements);
            }

            statements.AddRange(GetCommentHeader("Mapper code"));
            DataUIMapper   cn    = (DataUIMapper)value;
            CodeExpression cnref = SerializeToExpression(manager, value);

            #region Mapping property serialization

            CodePropertyReferenceExpression propref = new CodePropertyReferenceExpression(cnref, "Mappings");
            foreach (MapperInfo mi in cn.Mappings)
            {
                MapperInfo info = mi;
                if (info.ControlID != String.Empty && info.ControlProperty != null &&
                    info.DataProperty != String.Empty)
                {
                    object ctl = manager.GetInstance(info.ControlID);
                    //if (ctl == null)
                    //{
                    //    manager.ReportError(String.Format("Control '{0}' associated with the view mapping in controller '{1}' doesn't exist in the page.", info.ControlID, manager.GetName(value)));
                    //    continue;
                    //}
                    if (ctl.GetType().GetProperty(info.ControlProperty) == null)
                    {
                        manager.ReportError(String.Format("Control property '{0}' in control '{1}' associated with the view mapping in datauimapper '{2}' doesn't exist.", info.ControlProperty, info.ControlID, manager.GetName(value)));
                        continue;
                    }

                    statements.Add(
                        new CodeMethodInvokeExpression(
                            propref, "Add",
                            new CodeExpression[]
                    {
                        new CodeObjectCreateExpression(
                            typeof(MapperInfo),
                            new CodeExpression[] {
                            new CodePrimitiveExpression(info.ControlID),
                            new CodePrimitiveExpression(info.ControlProperty),
                            new CodePrimitiveExpression(info.DataProperty), new CodePrimitiveExpression((int)info.Format)
                        }
                            )
                    }
                            ));
                }
            }

            #endregion

            statements.Add(
                new CodeCommentStatement("Connect the host environment."));

            if (host.RootComponent as System.Windows.Forms.Form != null)
            {
                CodeObjectCreateExpression adapter = new CodeObjectCreateExpression(typeof(Adapter.WindowsFormsAdapter), new CodeExpression[0]);
                CodeExpression             connect = new CodeMethodInvokeExpression(adapter, "Connect",
                                                                                    new CodeExpression[] {
                    cnref,
                    new CodeThisReferenceExpression(),
                });
                statements.Add(connect);
            }
            else if (host.RootComponent as System.Web.UI.Page != null)
            {
                CodeObjectCreateExpression adapter = new CodeObjectCreateExpression(typeof(Adapter.WebFormsAdapter), new CodeExpression[0]);
                CodeExpression             connect = new CodeMethodInvokeExpression(adapter, "Connect",
                                                                                    new CodeExpression[] {
                    cnref,
                    new CodeThisReferenceExpression(),
                });
                statements.Add(connect);
            }

            return(statements);
        }