protected CodeDomSerializer GetSerializer(IDesignerSerializationManager manager, object instance)
        {
            DesignerSerializerAttribute attrInstance, attrType;

            attrType = attrInstance = null;

            CodeDomSerializer serializer = null;

            if (instance == null)
            {
                serializer = this.GetSerializer(manager, null);
            }
            else
            {
                AttributeCollection attributes = TypeDescriptor.GetAttributes(instance);
                foreach (Attribute a in attributes)
                {
                    DesignerSerializerAttribute designerAttr = a as DesignerSerializerAttribute;
                    if (designerAttr != null && manager.GetType(designerAttr.SerializerBaseTypeName) == typeof(CodeDomSerializer))
                    {
                        attrInstance = designerAttr;
                        break;
                    }
                }

                attributes = TypeDescriptor.GetAttributes(instance.GetType());
                foreach (Attribute a in attributes)
                {
                    DesignerSerializerAttribute designerAttr = a as DesignerSerializerAttribute;
                    if (designerAttr != null && manager.GetType(designerAttr.SerializerBaseTypeName) == typeof(CodeDomSerializer))
                    {
                        attrType = designerAttr;
                        break;
                    }
                }

                // if there is metadata modification in the instance then create the specified serializer instead of the one
                // in the Type.
                if (attrType != null && attrInstance != null && attrType.SerializerTypeName != attrInstance.SerializerTypeName)
                {
                    serializer = Activator.CreateInstance(manager.GetType(attrInstance.SerializerTypeName)) as CodeDomSerializer;
                }
                else
                {
                    serializer = this.GetSerializer(manager, instance.GetType());
                }
            }

            return(serializer);
        }
        // Used to remove the ctor from the statement colletion in order for the ctor statement to be moved.
        //
        private CodeStatement ExtractCtorStatement(IDesignerSerializationManager manager, CodeStatementCollection statements,
                                                   object component)
        {
            CodeStatement              result     = null;
            CodeAssignStatement        assignment = null;
            CodeObjectCreateExpression ctor       = null;
            int toRemove = -1;

            for (int i = 0; i < statements.Count; i++)
            {
                assignment = statements[i] as CodeAssignStatement;
                if (assignment != null)
                {
                    ctor = assignment.Right as CodeObjectCreateExpression;
                    if (ctor != null && manager.GetType(ctor.CreateType.BaseType) == component.GetType())
                    {
                        result   = assignment;
                        toRemove = i;
                    }
                }
            }

            if (toRemove != -1)
            {
                statements.RemoveAt(toRemove);
            }

            return(result);
        }
Ejemplo n.º 3
0
        protected override void PerformLoad(IDesignerSerializationManager manager)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            CodeCompileUnit document = this.Parse();

            if (document == null)
            {
                throw new NotSupportedException("The language did not provide a code parser for this file");
            }

            string namespaceName             = null;
            CodeTypeDeclaration rootDocument = GetFirstCodeTypeDecl(document, out namespaceName);

            if (rootDocument == null)
            {
                throw new InvalidOperationException("Cannot find a declaration in a namespace to load.");
            }

            _rootSerializer = manager.GetSerializer(manager.GetType(rootDocument.BaseTypes[0].BaseType),
                                                    typeof(RootCodeDomSerializer)) as CodeDomSerializer;
            if (_rootSerializer == null)
            {
                throw new InvalidOperationException("Serialization not supported for this class");
            }

            _rootSerializer.Deserialize(manager, rootDocument);

            base.SetBaseComponentClassName(namespaceName + "." + rootDocument.Name);
        }
Ejemplo n.º 4
0
        public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
        {
            CodeTypeDeclaration declaration = (CodeTypeDeclaration)codeObject;
            Type   rootType = manager.GetType(declaration.BaseTypes[0].BaseType);
            object root     = manager.CreateInstance(rootType, null, declaration.Name, true);

            RootContext rootContext = new RootContext(new CodeThisReferenceExpression(), root);

            manager.Context.Push(rootContext);

            CodeMemberMethod initComponentMethod = GetInitializeMethod(declaration);

            if (initComponentMethod == null)
            {
                throw new InvalidOperationException("InitializeComponent method is missing in: " + declaration.Name);
            }

            foreach (CodeStatement statement in initComponentMethod.Statements)
            {
                base.DeserializeStatement(manager, statement);
            }

            manager.Context.Pop();
            return(root);
        }
		protected override void PerformLoad (IDesignerSerializationManager manager)
		{
			if (manager == null)
				throw new ArgumentNullException ("manager");

			CodeCompileUnit document = this.Parse ();
			if (document == null)
				throw new NotSupportedException ("The language did not provide a code parser for this file");

			string namespaceName = null;
			CodeTypeDeclaration rootDocument = ExtractFirstCodeTypeDecl (document, out namespaceName);
			if (rootDocument == null)
				throw new InvalidOperationException ("Cannot find a declaration in a namespace to load.");

			_rootSerializer = manager.GetSerializer (manager.GetType (rootDocument.Name), 
													 typeof (RootCodeDomSerializer)) as CodeDomSerializer;
			if (_rootSerializer == null)
				throw new InvalidOperationException ("Serialization not supported for this class");
			_rootSerializer.Deserialize (manager, rootDocument);

			base.SetBaseComponentClassName (namespaceName + "." + rootDocument.Name);
		}
        private object DeserializeName(IDesignerSerializationManager manager, string name)
        {
            string typeName   = null;
            Type   objectType = null;
            object obj2       = this.nameTable[name];

            using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::DeserializeName"))
            {
                CodeMemberField field = null;
                CodeObject      obj3  = obj2 as CodeObject;
                if (obj3 != null)
                {
                    obj2 = null;
                    this.nameTable[name] = null;
                    if (obj3 is CodeVariableDeclarationStatement)
                    {
                        CodeVariableDeclarationStatement statement = (CodeVariableDeclarationStatement)obj3;
                        typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, statement.Type);
                    }
                    else if (obj3 is CodeMemberField)
                    {
                        field    = (CodeMemberField)obj3;
                        typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type);
                    }
                }
                else
                {
                    if (obj2 != null)
                    {
                        return(obj2);
                    }
                    IContainer service = (IContainer)manager.GetService(typeof(IContainer));
                    if (service != null)
                    {
                        IComponent component = service.Components[name];
                        if (component != null)
                        {
                            typeName             = component.GetType().FullName;
                            this.nameTable[name] = component;
                        }
                    }
                }
                if (name.Equals(this.ContainerName))
                {
                    IContainer container2 = (IContainer)manager.GetService(typeof(IContainer));
                    if (container2 != null)
                    {
                        obj2 = container2;
                    }
                }
                else if (typeName != null)
                {
                    objectType = manager.GetType(typeName);
                    if (objectType == null)
                    {
                        manager.ReportError(new SerializationException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeName })));
                    }
                    else
                    {
                        CodeStatementCollection codeObject = (CodeStatementCollection)this.statementTable[name];
                        if ((codeObject != null) && (codeObject.Count > 0))
                        {
                            CodeDomSerializer serializer = (CodeDomSerializer)manager.GetSerializer(objectType, typeof(CodeDomSerializer));
                            if (serializer == null)
                            {
                                manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { objectType.FullName }));
                            }
                            else
                            {
                                try
                                {
                                    obj2 = serializer.Deserialize(manager, codeObject);
                                    if ((obj2 != null) && (field != null))
                                    {
                                        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj2)["Modifiers"];
                                        if ((descriptor != null) && (descriptor.PropertyType == typeof(MemberAttributes)))
                                        {
                                            MemberAttributes attributes = field.Attributes & MemberAttributes.AccessMask;
                                            descriptor.SetValue(obj2, attributes);
                                        }
                                    }
                                }
                                catch (Exception exception)
                                {
                                    manager.ReportError(exception);
                                }
                            }
                        }
                    }
                }
                this.nameTable[name] = obj2;
            }
            return(obj2);
        }
        public virtual object Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (declaration == null)
            {
                throw new ArgumentNullException("declaration");
            }
            object obj2 = null;

            using (CodeDomSerializerBase.TraceScope("TypeCodeDomSerializer::Deserialize"))
            {
                bool            caseInsensitive = false;
                CodeDomProvider service         = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
                if (service != null)
                {
                    caseInsensitive = (service.LanguageOptions & LanguageOptions.CaseInsensitive) != LanguageOptions.None;
                }
                Type   type = null;
                string name = declaration.Name;
                foreach (CodeTypeReference reference in declaration.BaseTypes)
                {
                    Type type2 = manager.GetType(CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, reference));
                    name = reference.BaseType;
                    if ((type2 != null) && !type2.IsInterface)
                    {
                        type = type2;
                        break;
                    }
                }
                if (type == null)
                {
                    CodeDomSerializerBase.Error(manager, System.Design.SR.GetString("SerializerTypeNotFound", new object[] { name }), "SerializerTypeNotFound");
                }
                if (CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, type).IsAbstract)
                {
                    CodeDomSerializerBase.Error(manager, System.Design.SR.GetString("SerializerTypeAbstract", new object[] { type.FullName }), "SerializerTypeAbstract");
                }
                ResolveNameEventHandler handler = new ResolveNameEventHandler(this.OnResolveName);
                manager.ResolveName += handler;
                obj2 = manager.CreateInstance(type, null, declaration.Name, true);
                int count = declaration.Members.Count;
                this._nameTable      = new HybridDictionary(count, caseInsensitive);
                this._statementTable = new Dictionary <string, CodeDomSerializerBase.OrderedCodeStatementCollection>(count);
                Dictionary <string, string> names = new Dictionary <string, string>(count);
                RootContext context = new RootContext(new CodeThisReferenceExpression(), obj2);
                manager.Context.Push(context);
                try
                {
                    StringComparison comparisonType = caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
                    foreach (CodeTypeMember member in declaration.Members)
                    {
                        CodeMemberField field = member as CodeMemberField;
                        if ((field != null) && !string.Equals(field.Name, declaration.Name, comparisonType))
                        {
                            this._nameTable[field.Name] = field;
                            if ((field.Type != null) && !string.IsNullOrEmpty(field.Type.BaseType))
                            {
                                names[field.Name] = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type);
                            }
                        }
                    }
                    CodeMemberMethod[] initializeMethods = this.GetInitializeMethods(manager, declaration);
                    if (initializeMethods == null)
                    {
                        throw new InvalidOperationException();
                    }
                    foreach (CodeMemberMethod method in initializeMethods)
                    {
                        foreach (CodeStatement statement in method.Statements)
                        {
                            CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement;
                            if (statement2 != null)
                            {
                                this._nameTable[statement2.Name] = statement;
                            }
                        }
                    }
                    this._nameTable[declaration.Name] = context.Expression;
                    foreach (CodeMemberMethod method2 in initializeMethods)
                    {
                        CodeDomSerializerBase.FillStatementTable(manager, this._statementTable, names, method2.Statements, declaration.Name);
                    }
                    PropertyDescriptor descriptor = manager.Properties["SupportsStatementGeneration"];
                    if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool)descriptor.GetValue(manager)))
                    {
                        foreach (string str2 in this._nameTable.Keys)
                        {
                            if (!this._statementTable.ContainsKey(str2))
                            {
                                continue;
                            }
                            CodeStatementCollection statements = this._statementTable[str2];
                            bool flag2 = false;
                            foreach (CodeStatement statement3 in statements)
                            {
                                object obj3 = statement3.UserData["GeneratedStatement"];
                                if (((obj3 == null) || !(obj3 is bool)) || !((bool)obj3))
                                {
                                    flag2 = true;
                                    break;
                                }
                            }
                            if (!flag2)
                            {
                                this._statementTable.Remove(str2);
                            }
                        }
                    }
                    base.DeserializePropertiesFromResources(manager, obj2, _designTimeFilter);
                    CodeDomSerializerBase.OrderedCodeStatementCollection[] array = new CodeDomSerializerBase.OrderedCodeStatementCollection[this._statementTable.Count];
                    this._statementTable.Values.CopyTo(array, 0);
                    Array.Sort(array, StatementOrderComparer.Default);
                    CodeDomSerializerBase.OrderedCodeStatementCollection statements2 = null;
                    foreach (CodeDomSerializerBase.OrderedCodeStatementCollection statements3 in array)
                    {
                        if (statements3.Name.Equals(declaration.Name))
                        {
                            statements2 = statements3;
                        }
                        else
                        {
                            this.DeserializeName(manager, statements3.Name, statements3);
                        }
                    }
                    if (statements2 != null)
                    {
                        this.DeserializeName(manager, statements2.Name, statements2);
                    }
                }
                finally
                {
                    this._nameTable      = null;
                    this._statementTable = null;
                    manager.ResolveName -= handler;
                    manager.Context.Pop();
                }
            }
            return(obj2);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// This method deserializes a previously serialized code type declaration. The default implementation performs the following tasks:
        /// • Case Sensitivity Checks: It looks for a CodeDomProvider service to decide if it should treat members as case sensitive or case insensitive.
        /// • Statement Sorting:  All member variables and local variables from init methods are stored in a table. Then each statement in an init method is added to a statement collection grouped according to its left hand side. So all statements assigning or operating on a particular variable are grouped under that variable.  Variables that have no statements are discarded.
        /// • Deserialization: Finally, the statement collections for each variable are deserialized according to the variable. Deserialize returns an instance of the root object.
        /// </summary>
        public virtual object Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            if (declaration == null)
            {
                throw new ArgumentNullException("declaration");
            }

            object rootObject = null;

            using (TraceScope("TypeCodeDomSerializer::Deserialize"))
            {
                // Determine case-sensitivity
                bool            caseInsensitive = false;
                CodeDomProvider provider        = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
                TraceWarningIf(provider == null, "Unable to determine case sensitivity. Make sure CodeDomProvider is a service of the manager.");
                if (provider != null)
                {
                    caseInsensitive = ((provider.LanguageOptions & LanguageOptions.CaseInsensitive) != 0);
                }

                // Get and initialize the document type.
                Type   baseType     = null;
                string baseTypeName = declaration.Name;

                foreach (CodeTypeReference typeRef in declaration.BaseTypes)
                {
                    Type t = manager.GetType(GetTypeNameFromCodeTypeReference(manager, typeRef));
                    baseTypeName = typeRef.BaseType;
                    if (t != null && !(t.IsInterface))
                    {
                        baseType = t;
                        break;
                    }
                }

                if (baseType == null)
                {
                    TraceError("Base type for type declaration {0} could not be loaded.  Closest base type name: {1}", declaration.Name, baseTypeName);
                    Error(manager, string.Format(SR.SerializerTypeNotFound, baseTypeName), SR.SerializerTypeNotFound);
                }

                if (GetReflectionTypeFromTypeHelper(manager, baseType).IsAbstract)
                {
                    TraceError("Base type {0} is abstract, which isn't allowed", baseType.FullName);
                    Error(manager, string.Format(SR.SerializerTypeAbstract, baseType.FullName), SR.SerializerTypeAbstract);
                }

                ResolveNameEventHandler onResolveName = new ResolveNameEventHandler(OnResolveName);
                manager.ResolveName += onResolveName;
                rootObject           = manager.CreateInstance(baseType, null, declaration.Name, true);

                // Now that we have the root object, we create a nametable and fill it with member declarations.
                int count = declaration.Members.Count;
                _nameTable      = new HybridDictionary(count, caseInsensitive);
                _statementTable = new Dictionary <string, OrderedCodeStatementCollection>(count);
                Dictionary <string, string> names = new Dictionary <string, string>(count);
                RootContext rootCxt = new RootContext(new CodeThisReferenceExpression(), rootObject);
                manager.Context.Push(rootCxt);
                try
                {
                    StringComparison compare = caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
                    foreach (CodeTypeMember typeMember in declaration.Members)
                    {
                        if (typeMember is CodeMemberField member)
                        {
                            if (!string.Equals(member.Name, declaration.Name, compare))
                            {
                                // always skip members with the same name as the type -- because that's the name we use when we resolve "base" and "this" items...
                                _nameTable[member.Name] = member;

                                if (member.Type != null && !string.IsNullOrEmpty(member.Type.BaseType))
                                {
                                    names[member.Name] = GetTypeNameFromCodeTypeReference(manager, member.Type);
                                }
                            }
                        }
                    }

                    CodeMemberMethod[] methods = GetInitializeMethods(manager, declaration);
                    if (methods == null)
                    {
                        throw new InvalidOperationException();
                    }

                    Trace("Members to deserialize: {0}", _nameTable.Keys.Count);
                    Trace("Methods to deserialize: {0}", methods.Length);
                    TraceWarningIf(methods.Length == 0, "Serializer did not find any methods to deserialize.");
                    // Walk through all of our methods and search for local variables.  These guys get added to our nametable too.
                    foreach (CodeMemberMethod method in methods)
                    {
                        foreach (CodeStatement statement in method.Statements)
                        {
                            if (statement is CodeVariableDeclarationStatement local)
                            {
                                _nameTable[local.Name] = statement;
                            }
                        }
                    }

                    // The name table should come pre-populated with our root expression.
                    _nameTable[declaration.Name] = rootCxt.Expression;

                    // We fill a "statement table" for everything in our init methods. This statement table is a dictionary whose keys contain object names and whose values contain a statement collection of all statements with a LHS resolving to an object by that name. If supportGenerate is true, FillStatementTable will skip methods that are marked with the tag "GeneratedStatement".
                    foreach (CodeMemberMethod method in methods)
                    {
                        FillStatementTable(manager, _statementTable, names, method.Statements, declaration.Name);
                    }

                    // Interesting problem.  The CodeDom parser may auto generate statements that are associated with other methods. VB does this, for example, to  create statements automatically for Handles clauses.  The problem with this technique is that we will end up with statements that are related to variables that live solely in user code and not in InitializeComponent. We will attempt to construct instances of these objects with limited success. To guard against this, we check to see if the manager even supports this feature, and if it does, we must look out for these statements while filling the statement collections.
                    PropertyDescriptor supportGenerate = manager.Properties["SupportsStatementGeneration"];
                    if (supportGenerate != null && supportGenerate.PropertyType == typeof(bool) && ((bool)supportGenerate.GetValue(manager)) == true)
                    {
                        // Ok, we must do the more expensive work of validating the statements we get.
                        foreach (string name in _nameTable.Keys)
                        {
                            if (!name.Equals(declaration.Name) && _statementTable.ContainsKey(name))
                            {
                                CodeStatementCollection statements = _statementTable[name];
                                bool acceptStatement = false;
                                foreach (CodeStatement statement in statements)
                                {
                                    object genFlag = statement.UserData["GeneratedStatement"];
                                    if (genFlag == null || !(genFlag is bool) || !((bool)genFlag))
                                    {
                                        acceptStatement = true;
                                        break;
                                    }
                                }

                                if (!acceptStatement)
                                {
                                    _statementTable.Remove(name);
                                }
                            }
                        }
                    }

                    // Design time properties must be resolved before runtime properties to make sure that properties like "language" get established before we need to read values out the resource bundle
                    Trace("--------------------------------------------------------------------");
                    Trace("     Beginning deserialization of {0} (design time)", declaration.Name);
                    Trace("--------------------------------------------------------------------");
                    // Deserialize design time properties for the root component.
                    DeserializePropertiesFromResources(manager, rootObject, s_designTimeFilter);
                    // sort by the order so we deserialize in the same order the objects were decleared in.
                    OrderedCodeStatementCollection[] statementArray = new OrderedCodeStatementCollection[_statementTable.Count];
                    _statementTable.Values.CopyTo(statementArray, 0);
                    Array.Sort(statementArray, StatementOrderComparer.s_default);
                    // make sure we have fully deserialized everything that is referenced in the statement table. Skip the root object for last
                    OrderedCodeStatementCollection rootStatements = null;
                    foreach (OrderedCodeStatementCollection statements in statementArray)
                    {
                        if (statements.Name.Equals(declaration.Name))
                        {
                            rootStatements = statements;
                        }
                        else
                        {
                            DeserializeName(manager, statements.Name, statements);
                        }
                    }
                    if (rootStatements != null)
                    {
                        DeserializeName(manager, rootStatements.Name, rootStatements);
                    }
                }
                finally
                {
                    _nameTable      = null;
                    _statementTable = null;
                    Debug.Assert(manager.Context.Current == rootCxt, "Context stack corrupted");
                    manager.ResolveName -= onResolveName;
                    manager.Context.Pop();
                }
            }
            return(rootObject);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///  Serializes the given object into a CodeDom object.
        /// </summary>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeStatementCollection      statements = null;
            PropertyDescriptorCollection props      = TypeDescriptor.GetProperties(value);

            using (TraceScope("ComponentCodeDomSerializer::Serialize"))
            {
                if (manager is null || value is null)
                {
                    throw new ArgumentNullException(manager is null ? "manager" : "value");
                }

                if (IsSerialized(manager, value))
                {
                    Debug.Fail("Serialize is being called twice for the same component");
                    return(GetExpression(manager, value));
                }

                // If the object is being inherited, we will will not emit a variable declaration.  Also, we won't
                // do any serialization at all if the object is privately inherited.
                InheritanceLevel     inheritanceLevel     = InheritanceLevel.NotInherited;
                InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)];

                if (inheritanceAttribute != null)
                {
                    inheritanceLevel = inheritanceAttribute.InheritanceLevel;
                }

                // First, skip everything if we're privately inherited.  We cannot write any code that would affect this
                // component.
                TraceIf(inheritanceLevel == InheritanceLevel.InheritedReadOnly, "Skipping read only inherited component");
                if (inheritanceLevel != InheritanceLevel.InheritedReadOnly)
                {
                    // Things we need to know:
                    //
                    // 1.  What expression should we use for the left hand side
                    //      a) already given to us via GetExpression?
                    //      b) a local variable?
                    //      c) a member variable?
                    //
                    // 2.  Should we generate an init expression for this
                    //     object?
                    //      a) Inherited or existing expression: no
                    //      b) otherwise, yes.

                    statements = new CodeStatementCollection();
                    CodeTypeDeclaration typeDecl  = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
                    RootContext         rootCtx   = manager.Context[typeof(RootContext)] as RootContext;
                    CodeExpression      assignLhs = null;
                    CodeExpression      assignRhs;

                    // Defaults for components
                    bool generateLocal  = false;
                    bool generateField  = true;
                    bool generateObject = true;
                    bool isComplete     = false;

                    assignLhs = GetExpression(manager, value);

                    if (assignLhs != null)
                    {
                        Trace("Existing expression for LHS of value");
                        generateLocal  = false;
                        generateField  = false;
                        generateObject = false;

                        // if we have an existing expression and this is not
                        // a sited component, do not serialize it.  We need this for Everett / 1.0
                        // backwards compat (even though it's wrong).
                        if (value is IComponent comp && comp.Site is null)
                        {
                            // We were in a serialize content
                            // property and would still serialize it.  This code reverses what the
                            // outer if block does for this specific case.  We also need this
                            // for Everett / 1.0 backwards compat.
                            if (!(manager.Context[typeof(ExpressionContext)] is ExpressionContext expCtx) || expCtx.PresetValue != value)
                            {
                                isComplete = true;
                            }
                        }
                    }
                    else
                    {
                        Trace("Creating LHS expression");
                        if (inheritanceLevel == InheritanceLevel.NotInherited)
                        {
                            // See if there is a "GenerateMember" property.  If so,
                            // we might want to generate a local variable.  Otherwise,
                            // we want to generate a field.
                            PropertyDescriptor generateProp = props["GenerateMember"];
                            if (generateProp != null && generateProp.PropertyType == typeof(bool) && !(bool)generateProp.GetValue(value))
                            {
                                Trace("Object GenerateMember property wants a local variable");
                                generateLocal = true;
                                generateField = false;
                            }
                        }
                        else
                        {
                            generateObject = false;
                        }

                        if (rootCtx is null)
                        {
                            generateLocal = true;
                            generateField = false;
                        }
                    }

                    // Push the component being serialized onto the stack.  It may be handy to
                    // be able to discover this.
                    manager.Context.Push(value);
                    manager.Context.Push(statements);

                    try
                    {
                        string name = manager.GetName(value);

                        string typeName = TypeDescriptor.GetClassName(value);

                        // Output variable / field declarations if we need to
                        if ((generateField || generateLocal) && name != null)
                        {
                            if (generateField)
                            {
                                if (inheritanceLevel == InheritanceLevel.NotInherited)
                                {
                                    // We need to generate the field declaration.  See if there is a modifiers property on
                                    // the object.  If not, look for a DefaultModifies, and finally assume it's private.
                                    CodeMemberField    field         = new CodeMemberField(typeName, name);
                                    PropertyDescriptor modifiersProp = props["Modifiers"];
                                    MemberAttributes   fieldAttrs;

                                    if (modifiersProp is null)
                                    {
                                        modifiersProp = props["DefaultModifiers"];
                                    }

                                    if (modifiersProp != null && modifiersProp.PropertyType == typeof(MemberAttributes))
                                    {
                                        fieldAttrs = (MemberAttributes)modifiersProp.GetValue(value);
                                    }
                                    else
                                    {
                                        TraceWarning("No Modifiers or DefaultModifiers property on component {0}. We must assume private.", name);
                                        fieldAttrs = MemberAttributes.Private;
                                    }

                                    field.Attributes = fieldAttrs;
                                    typeDecl.Members.Add(field);
                                    Trace("Field {0} {1} {2} created.", fieldAttrs, typeName, name);
                                }

                                // Next, create a nice LHS for our pending assign statement, when we hook up the variable.
                                assignLhs = new CodeFieldReferenceExpression(rootCtx.Expression, name);
                            }
                            else
                            {
                                if (inheritanceLevel == InheritanceLevel.NotInherited)
                                {
                                    CodeVariableDeclarationStatement local = new CodeVariableDeclarationStatement(typeName, name);

                                    statements.Add(local);
                                    Trace("Local {0} {1} created.", typeName, name);
                                }

                                assignLhs = new CodeVariableReferenceExpression(name);
                            }
                        }

                        // Now output an object create if we need to.  We always see if there is a
                        // type converter that can provide us guidance

                        if (generateObject)
                        {
                            // Ok, now that we've decided if we have a local or a member variable, its now time to serialize the rest of the code.
                            // The first step is to create an assign statement to "new" the object.  For that, we need to know if
                            // the component wants a special IContainer constructor or not.  For that to be valid we must also know
                            // that we can get to an actual IContainer.
                            IContainer      container = manager.GetService(typeof(IContainer)) as IContainer;
                            ConstructorInfo ctor      = null;
                            if (container != null)
                            {
                                ctor = GetReflectionTypeHelper(manager, value).GetConstructor(BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, GetContainerConstructor(manager), null);
                            }

                            if (ctor != null)
                            {
                                Trace("Component has IContainer constructor.");
                                assignRhs = new CodeObjectCreateExpression(typeName, new CodeExpression[]
                                {
                                    SerializeToExpression(manager, container)
                                });
                            }
                            else
                            {
                                // For compat reasons we ignore the isCompleteOld value here.
                                assignRhs = SerializeCreationExpression(manager, value, out bool isCompleteOld);
                                Debug.Assert(isCompleteOld == isComplete, "CCDS Differing");
                            }

                            TraceErrorIf(assignRhs is null, "No RHS code assign for object {0}", value);
                            if (assignRhs != null)
                            {
                                if (assignLhs is null)
                                {
                                    // We cannot do much more for this object.  If isComplete is true,
                                    // then the RHS now becomes our LHS.  Otherwise, I'm afraid we have
                                    // just failed to serialize this object.
                                    if (isComplete)
                                    {
                                        assignLhs = assignRhs;
                                    }
                                    else
                                    {
                                        TraceError("Incomplete serialization of object, abandoning serialization.");
                                    }
                                }
                                else
                                {
                                    CodeAssignStatement assign = new CodeAssignStatement(assignLhs, assignRhs);
                                    statements.Add(assign);
                                }
                            }
                        }

                        if (assignLhs != null)
                        {
                            SetExpression(manager, value, assignLhs);
                        }

                        // It should practically be an assert that isComplete is false, but someone may
                        // have an unusual component.
                        if (assignLhs != null && !isComplete)
                        {
                            // .NET CF needs us to verify that the ISupportInitialize interface exists
                            // (they do not support this interface and will modify their DSM to resolve the type to null).

                            bool supportInitialize = (value is ISupportInitialize);
                            if (supportInitialize)
                            {
                                string fullName = typeof(ISupportInitialize).FullName;
                                supportInitialize = manager.GetType(fullName) != null;
                            }

                            Type reflectionType = null;
                            if (supportInitialize)
                            {
                                // Now verify that this control implements ISupportInitialize in the project target framework
                                // Don't use operator "is" but rather use IsAssignableFrom on the reflection types.
                                // We have other places where we use operator "is", for example "is IComponent" to generate
                                // specific CodeDOM objects, however we don't have cases of objects which were not an IComponent
                                // in a downlevel framework and became an IComponent in a newer framework, so I'm not replacing
                                // all instances of operator "is" by IsAssignableFrom.
                                reflectionType    = GetReflectionTypeHelper(manager, value);
                                supportInitialize = GetReflectionTypeFromTypeHelper(manager, typeof(ISupportInitialize)).IsAssignableFrom(reflectionType);
                            }

                            bool persistSettings = (value is IPersistComponentSettings) && ((IPersistComponentSettings)value).SaveSettings;
                            if (persistSettings)
                            {
                                string fullName = typeof(IPersistComponentSettings).FullName;
                                persistSettings = manager.GetType(fullName) != null;
                            }

                            if (persistSettings)
                            {
                                reflectionType  = reflectionType ?? GetReflectionTypeHelper(manager, value);
                                persistSettings = GetReflectionTypeFromTypeHelper(manager, typeof(IPersistComponentSettings)).IsAssignableFrom(reflectionType);
                            }

                            // We implement statement caching only for the main code generation phase.  We don't implement it for other
                            // serialization managers.  How do we tell the difference?  The main serialization manager exists as a service.
                            IDesignerSerializationManager mainManager = manager.GetService(typeof(IDesignerSerializationManager)) as IDesignerSerializationManager;

                            if (supportInitialize)
                            {
                                Trace("Object implements ISupportInitialize.");
                                SerializeSupportInitialize(manager, statements, assignLhs, value, "BeginInit");
                            }

                            SerializePropertiesToResources(manager, statements, value, _designTimeFilter);

                            // Writing out properties is expensive.  But, we're very smart and we cache the results
                            // in ComponentCache.  See if we have cached results.  If so, use 'em.  If not, generate
                            // code and then see if we can cache the results for later.
                            ComponentCache       cache = manager.GetService(typeof(ComponentCache)) as ComponentCache;
                            ComponentCache.Entry entry = null;
                            if (cache is null)
                            {
                                if (manager.GetService(typeof(IServiceContainer)) is ServiceContainer sc)
                                {
                                    cache = new ComponentCache(manager);
                                    sc.AddService(typeof(ComponentCache), cache);
                                }
                            }
                            else
                            {
                                if (manager == mainManager && cache.Enabled)
                                {
                                    entry = cache[value];
                                }
                            }

                            if (entry is null || entry.Tracking)
                            {
                                // Pushing the entry here allows it to be found by the resource code dom serializer,
                                // which will add data to the ResourceBlob property on the entry.
                                if (entry is null)
                                {
                                    entry = new ComponentCache.Entry(cache);

                                    // We cache components even if they're not valid so dependencies are
                                    // still tracked correctly (see comment below).  The problem is, we will create a
                                    // new entry object even if there is still an existing one that is just invalid, and it
                                    // might have dependencies that will be lost.
                                    // we need to make sure we copy over any dependencies that are also tracked.
                                    ComponentCache.Entry oldEntry = cache?.GetEntryAll(value);
                                    if (oldEntry != null && oldEntry.Dependencies != null && oldEntry.Dependencies.Count > 0)
                                    {
                                        foreach (object dependency in oldEntry.Dependencies)
                                        {
                                            entry.AddDependency(dependency);
                                        }
                                    }
                                }

                                entry.Component = value;
                                // we need to link the cached entry with its corresponding component right away, before it's put in the context
                                // see CodeDomSerializerBase.cs::GetExpression for usage

                                // This entry will only be used if the valid bit is set.
                                // This is useful because we still need to setup dependency relationships
                                // between components even if they are not cached.  See VSWhidbey 263053.
                                bool correctManager = manager == mainManager;
                                entry.Valid = correctManager && CanCacheComponent(manager, value, props);

                                if (correctManager && cache != null && cache.Enabled)
                                {
                                    manager.Context.Push(cache);
                                    manager.Context.Push(entry);
                                }

                                try
                                {
                                    entry.Statements = new CodeStatementCollection();
                                    SerializeProperties(manager, entry.Statements, value, _runTimeFilter);
                                    SerializeEvents(manager, entry.Statements, value, null);

                                    foreach (CodeStatement statement in entry.Statements)
                                    {
                                        if (statement is CodeVariableDeclarationStatement local)
                                        {
                                            entry.Tracking = true;
                                            break;
                                        }
                                    }

                                    if (entry.Statements.Count > 0)
                                    {
                                        // if we added some statements, insert the comments
                                        //
                                        entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));
                                        entry.Statements.Insert(0, new CodeCommentStatement(name));
                                        entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));

                                        //
                                        // cache the statements for future usage if possible. We only do this for the main serialization manager, not
                                        // for any other serialization managers that may be calling us for undo or clipboard functions.
                                        if (correctManager && cache != null && cache.Enabled)
                                        {
                                            cache[value] = entry;
                                        }
                                    }
                                }
                                finally
                                {
                                    if (correctManager && cache != null && cache.Enabled)
                                    {
                                        Debug.Assert(manager.Context.Current == entry, "Context stack corrupted");
                                        manager.Context.Pop();
                                        manager.Context.Pop();
                                    }
                                }
                            }
                            else
                            {
                                // If we got a cache entry, we will need to take all the resources out of
                                // it and apply them too.
                                if ((entry.Resources != null || entry.Metadata != null) && cache != null && cache.Enabled)
                                {
                                    ResourceCodeDomSerializer res = ResourceCodeDomSerializer.Default;
                                    res.ApplyCacheEntry(manager, entry);
                                }
                            }

                            // Regardless, apply statements.  Either we created them or we got them
                            // out of the cache.
                            statements.AddRange(entry.Statements);

                            if (persistSettings)
                            {
                                SerializeLoadComponentSettings(manager, statements, assignLhs, value);
                            }

                            if (supportInitialize)
                            {
                                SerializeSupportInitialize(manager, statements, assignLhs, value, "EndInit");
                            }
                        }
                    }
 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 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;
		}
 public virtual object Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (declaration == null)
     {
         throw new ArgumentNullException("declaration");
     }
     object obj2 = null;
     using (CodeDomSerializerBase.TraceScope("TypeCodeDomSerializer::Deserialize"))
     {
         bool caseInsensitive = false;
         CodeDomProvider service = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
         if (service != null)
         {
             caseInsensitive = (service.LanguageOptions & LanguageOptions.CaseInsensitive) != LanguageOptions.None;
         }
         Type type = null;
         string name = declaration.Name;
         foreach (CodeTypeReference reference in declaration.BaseTypes)
         {
             Type type2 = manager.GetType(CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, reference));
             name = reference.BaseType;
             if ((type2 != null) && !type2.IsInterface)
             {
                 type = type2;
                 break;
             }
         }
         if (type == null)
         {
             CodeDomSerializerBase.Error(manager, System.Design.SR.GetString("SerializerTypeNotFound", new object[] { name }), "SerializerTypeNotFound");
         }
         if (CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, type).IsAbstract)
         {
             CodeDomSerializerBase.Error(manager, System.Design.SR.GetString("SerializerTypeAbstract", new object[] { type.FullName }), "SerializerTypeAbstract");
         }
         ResolveNameEventHandler handler = new ResolveNameEventHandler(this.OnResolveName);
         manager.ResolveName += handler;
         obj2 = manager.CreateInstance(type, null, declaration.Name, true);
         int count = declaration.Members.Count;
         this._nameTable = new HybridDictionary(count, caseInsensitive);
         this._statementTable = new Dictionary<string, CodeDomSerializerBase.OrderedCodeStatementCollection>(count);
         Dictionary<string, string> names = new Dictionary<string, string>(count);
         RootContext context = new RootContext(new CodeThisReferenceExpression(), obj2);
         manager.Context.Push(context);
         try
         {
             StringComparison comparisonType = caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
             foreach (CodeTypeMember member in declaration.Members)
             {
                 CodeMemberField field = member as CodeMemberField;
                 if ((field != null) && !string.Equals(field.Name, declaration.Name, comparisonType))
                 {
                     this._nameTable[field.Name] = field;
                     if ((field.Type != null) && !string.IsNullOrEmpty(field.Type.BaseType))
                     {
                         names[field.Name] = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type);
                     }
                 }
             }
             CodeMemberMethod[] initializeMethods = this.GetInitializeMethods(manager, declaration);
             if (initializeMethods == null)
             {
                 throw new InvalidOperationException();
             }
             foreach (CodeMemberMethod method in initializeMethods)
             {
                 foreach (CodeStatement statement in method.Statements)
                 {
                     CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement;
                     if (statement2 != null)
                     {
                         this._nameTable[statement2.Name] = statement;
                     }
                 }
             }
             this._nameTable[declaration.Name] = context.Expression;
             foreach (CodeMemberMethod method2 in initializeMethods)
             {
                 CodeDomSerializerBase.FillStatementTable(manager, this._statementTable, names, method2.Statements, declaration.Name);
             }
             PropertyDescriptor descriptor = manager.Properties["SupportsStatementGeneration"];
             if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool) descriptor.GetValue(manager)))
             {
                 foreach (string str2 in this._nameTable.Keys)
                 {
                     if (str2.Equals(declaration.Name) || !this._statementTable.ContainsKey(str2))
                     {
                         continue;
                     }
                     CodeStatementCollection statements = this._statementTable[str2];
                     bool flag2 = false;
                     foreach (CodeStatement statement3 in statements)
                     {
                         object obj3 = statement3.UserData["GeneratedStatement"];
                         if (((obj3 == null) || !(obj3 is bool)) || !((bool) obj3))
                         {
                             flag2 = true;
                             break;
                         }
                     }
                     if (!flag2)
                     {
                         this._statementTable.Remove(str2);
                     }
                 }
             }
             base.DeserializePropertiesFromResources(manager, obj2, _designTimeFilter);
             CodeDomSerializerBase.OrderedCodeStatementCollection[] array = new CodeDomSerializerBase.OrderedCodeStatementCollection[this._statementTable.Count];
             this._statementTable.Values.CopyTo(array, 0);
             Array.Sort(array, StatementOrderComparer.Default);
             CodeDomSerializerBase.OrderedCodeStatementCollection statements2 = null;
             foreach (CodeDomSerializerBase.OrderedCodeStatementCollection statements3 in array)
             {
                 if (statements3.Name.Equals(declaration.Name))
                 {
                     statements2 = statements3;
                 }
                 else
                 {
                     this.DeserializeName(manager, statements3.Name, statements3);
                 }
             }
             if (statements2 != null)
             {
                 this.DeserializeName(manager, statements2.Name, statements2);
             }
         }
         finally
         {
             this._nameTable = null;
             this._statementTable = null;
             manager.ResolveName -= handler;
             manager.Context.Pop();
         }
     }
     return obj2;
 }
 private object DeserializeName(IDesignerSerializationManager manager, string name)
 {
     string typeName = null;
     Type objectType = null;
     object obj2 = this.nameTable[name];
     using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::DeserializeName"))
     {
         CodeMemberField field = null;
         CodeObject obj3 = obj2 as CodeObject;
         if (obj3 != null)
         {
             obj2 = null;
             this.nameTable[name] = null;
             if (obj3 is CodeVariableDeclarationStatement)
             {
                 CodeVariableDeclarationStatement statement = (CodeVariableDeclarationStatement) obj3;
                 typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, statement.Type);
             }
             else if (obj3 is CodeMemberField)
             {
                 field = (CodeMemberField) obj3;
                 typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type);
             }
         }
         else
         {
             if (obj2 != null)
             {
                 return obj2;
             }
             IContainer service = (IContainer) manager.GetService(typeof(IContainer));
             if (service != null)
             {
                 IComponent component = service.Components[name];
                 if (component != null)
                 {
                     typeName = component.GetType().FullName;
                     this.nameTable[name] = component;
                 }
             }
         }
         if (name.Equals(this.ContainerName))
         {
             IContainer container2 = (IContainer) manager.GetService(typeof(IContainer));
             if (container2 != null)
             {
                 obj2 = container2;
             }
         }
         else if (typeName != null)
         {
             objectType = manager.GetType(typeName);
             if (objectType == null)
             {
                 manager.ReportError(new SerializationException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeName })));
             }
             else
             {
                 CodeStatementCollection codeObject = (CodeStatementCollection) this.statementTable[name];
                 if ((codeObject != null) && (codeObject.Count > 0))
                 {
                     CodeDomSerializer serializer = (CodeDomSerializer) manager.GetSerializer(objectType, typeof(CodeDomSerializer));
                     if (serializer == null)
                     {
                         manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { objectType.FullName }));
                     }
                     else
                     {
                         try
                         {
                             obj2 = serializer.Deserialize(manager, codeObject);
                             if ((obj2 != null) && (field != null))
                             {
                                 PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj2)["Modifiers"];
                                 if ((descriptor != null) && (descriptor.PropertyType == typeof(MemberAttributes)))
                                 {
                                     MemberAttributes attributes = field.Attributes & MemberAttributes.AccessMask;
                                     descriptor.SetValue(obj2, attributes);
                                 }
                             }
                         }
                         catch (Exception exception)
                         {
                             manager.ReportError(exception);
                         }
                     }
                 }
             }
         }
         this.nameTable[name] = obj2;
     }
     return obj2;
 }
 public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
 {
     if ((manager == null) || (codeObject == null))
     {
         throw new ArgumentNullException((manager == null) ? "manager" : "codeObject");
     }
     object obj2 = null;
     using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::Deserialize"))
     {
         if (!(codeObject is CodeTypeDeclaration))
         {
             throw new ArgumentException(System.Design.SR.GetString("SerializerBadElementType", new object[] { typeof(CodeTypeDeclaration).FullName }));
         }
         bool caseInsensitive = false;
         CodeDomProvider service = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
         if (service != null)
         {
             caseInsensitive = (service.LanguageOptions & LanguageOptions.CaseInsensitive) != LanguageOptions.None;
         }
         CodeTypeDeclaration declaration = (CodeTypeDeclaration) codeObject;
         CodeTypeReference reference = null;
         Type type = null;
         foreach (CodeTypeReference reference2 in declaration.BaseTypes)
         {
             Type type2 = manager.GetType(CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, reference2));
             if ((type2 != null) && !type2.IsInterface)
             {
                 reference = reference2;
                 type = type2;
                 break;
             }
         }
         if (type == null)
         {
             Exception exception = new SerializationException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { reference.BaseType })) {
                 HelpLink = "SerializerTypeNotFound"
             };
             throw exception;
         }
         if (type.IsAbstract)
         {
             Exception exception2 = new SerializationException(System.Design.SR.GetString("SerializerTypeAbstract", new object[] { type.FullName })) {
                 HelpLink = "SerializerTypeAbstract"
             };
             throw exception2;
         }
         ResolveNameEventHandler handler = new ResolveNameEventHandler(this.OnResolveName);
         manager.ResolveName += handler;
         if (!(manager is DesignerSerializationManager))
         {
             manager.AddSerializationProvider(new CodeDomSerializationProvider());
         }
         obj2 = manager.CreateInstance(type, null, declaration.Name, true);
         this.nameTable = new HybridDictionary(declaration.Members.Count, caseInsensitive);
         this.statementTable = new HybridDictionary(declaration.Members.Count, caseInsensitive);
         this.initMethod = null;
         RootContext context = new RootContext(new CodeThisReferenceExpression(), obj2);
         manager.Context.Push(context);
         try
         {
             foreach (CodeTypeMember member in declaration.Members)
             {
                 if (member is CodeMemberField)
                 {
                     if (string.Compare(member.Name, declaration.Name, caseInsensitive, CultureInfo.InvariantCulture) != 0)
                     {
                         this.nameTable[member.Name] = member;
                     }
                 }
                 else if ((this.initMethod == null) && (member is CodeMemberMethod))
                 {
                     CodeMemberMethod method = (CodeMemberMethod) member;
                     if ((string.Compare(method.Name, this.InitMethodName, caseInsensitive, CultureInfo.InvariantCulture) == 0) && (method.Parameters.Count == 0))
                     {
                         this.initMethod = method;
                     }
                 }
             }
             if (this.initMethod != null)
             {
                 foreach (CodeStatement statement in this.initMethod.Statements)
                 {
                     CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement;
                     if (statement2 != null)
                     {
                         this.nameTable[statement2.Name] = statement;
                     }
                 }
             }
             if (this.nameTable[declaration.Name] != null)
             {
                 this.nameTable[declaration.Name] = obj2;
             }
             if (this.initMethod != null)
             {
                 this.FillStatementTable(this.initMethod, declaration.Name);
             }
             PropertyDescriptor descriptor = manager.Properties["SupportsStatementGeneration"];
             if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool) descriptor.GetValue(manager)))
             {
                 foreach (string str in this.nameTable.Keys)
                 {
                     CodeDomSerializerBase.OrderedCodeStatementCollection statements = (CodeDomSerializerBase.OrderedCodeStatementCollection) this.statementTable[str];
                     if (statements != null)
                     {
                         bool flag2 = false;
                         foreach (CodeStatement statement3 in statements)
                         {
                             object obj3 = statement3.UserData["GeneratedStatement"];
                             if (((obj3 == null) || !(obj3 is bool)) || !((bool) obj3))
                             {
                                 flag2 = true;
                                 break;
                             }
                         }
                         if (!flag2)
                         {
                             this.statementTable.Remove(str);
                         }
                     }
                 }
             }
             IContainer container = (IContainer) manager.GetService(typeof(IContainer));
             if (container != null)
             {
                 foreach (object obj4 in container.Components)
                 {
                     base.DeserializePropertiesFromResources(manager, obj4, designTimeProperties);
                 }
             }
             object[] array = new object[this.statementTable.Values.Count];
             this.statementTable.Values.CopyTo(array, 0);
             Array.Sort(array, StatementOrderComparer.Default);
             foreach (CodeDomSerializerBase.OrderedCodeStatementCollection statements2 in array)
             {
                 string name = statements2.Name;
                 if ((name != null) && !name.Equals(declaration.Name))
                 {
                     this.DeserializeName(manager, name);
                 }
             }
             CodeStatementCollection statements3 = (CodeStatementCollection) this.statementTable[declaration.Name];
             if ((statements3 != null) && (statements3.Count > 0))
             {
                 foreach (CodeStatement statement4 in statements3)
                 {
                     base.DeserializeStatement(manager, statement4);
                 }
             }
             return obj2;
         }
         finally
         {
             manager.ResolveName -= handler;
             this.initMethod = null;
             this.nameTable = null;
             this.statementTable = null;
             manager.Context.Pop();
         }
     }
     return obj2;
 }
 private static string GetTypeNameFromCodeTypeReferenceHelper(IDesignerSerializationManager manager, CodeTypeReference typeref)
 {
     if ((typeref.TypeArguments == null) || (typeref.TypeArguments.Count == 0))
     {
         Type type = manager.GetType(typeref.BaseType);
         if (type != null)
         {
             return GetReflectionTypeFromTypeHelper(manager, type).AssemblyQualifiedName;
         }
         return typeref.BaseType;
     }
     StringBuilder builder = new StringBuilder(typeref.BaseType);
     if (!typeref.BaseType.Contains("`"))
     {
         builder.Append("`");
         builder.Append(typeref.TypeArguments.Count);
     }
     builder.Append("[");
     bool flag = true;
     foreach (CodeTypeReference reference in typeref.TypeArguments)
     {
         if (!flag)
         {
             builder.Append(",");
         }
         builder.Append("[");
         builder.Append(GetTypeNameFromCodeTypeReferenceHelper(manager, reference));
         builder.Append("]");
         flag = false;
     }
     builder.Append("]");
     return builder.ToString();
 }
        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;
		}
Ejemplo n.º 18
0
 /// <summary>
 /// Gets the type given its name.
 /// </summary>
 public Type GetType(string typeName)
 {
     return(serializationManager.GetType(typeName));
 }
 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;
 }
        public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
        {
            if ((manager == null) || (codeObject == null))
            {
                throw new ArgumentNullException((manager == null) ? "manager" : "codeObject");
            }
            object obj2 = null;

            using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::Deserialize"))
            {
                if (!(codeObject is CodeTypeDeclaration))
                {
                    throw new ArgumentException(System.Design.SR.GetString("SerializerBadElementType", new object[] { typeof(CodeTypeDeclaration).FullName }));
                }
                bool            caseInsensitive = false;
                CodeDomProvider service         = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
                if (service != null)
                {
                    caseInsensitive = (service.LanguageOptions & LanguageOptions.CaseInsensitive) != LanguageOptions.None;
                }
                CodeTypeDeclaration declaration = (CodeTypeDeclaration)codeObject;
                CodeTypeReference   reference   = null;
                Type type = null;
                foreach (CodeTypeReference reference2 in declaration.BaseTypes)
                {
                    Type type2 = manager.GetType(CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, reference2));
                    if ((type2 != null) && !type2.IsInterface)
                    {
                        reference = reference2;
                        type      = type2;
                        break;
                    }
                }
                if (type == null)
                {
                    Exception exception = new SerializationException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { reference.BaseType }))
                    {
                        HelpLink = "SerializerTypeNotFound"
                    };
                    throw exception;
                }
                if (type.IsAbstract)
                {
                    Exception exception2 = new SerializationException(System.Design.SR.GetString("SerializerTypeAbstract", new object[] { type.FullName }))
                    {
                        HelpLink = "SerializerTypeAbstract"
                    };
                    throw exception2;
                }
                ResolveNameEventHandler handler = new ResolveNameEventHandler(this.OnResolveName);
                manager.ResolveName += handler;
                if (!(manager is DesignerSerializationManager))
                {
                    manager.AddSerializationProvider(new CodeDomSerializationProvider());
                }
                obj2                = manager.CreateInstance(type, null, declaration.Name, true);
                this.nameTable      = new HybridDictionary(declaration.Members.Count, caseInsensitive);
                this.statementTable = new HybridDictionary(declaration.Members.Count, caseInsensitive);
                this.initMethod     = null;
                RootContext context = new RootContext(new CodeThisReferenceExpression(), obj2);
                manager.Context.Push(context);
                try
                {
                    foreach (CodeTypeMember member in declaration.Members)
                    {
                        if (member is CodeMemberField)
                        {
                            if (string.Compare(member.Name, declaration.Name, caseInsensitive, CultureInfo.InvariantCulture) != 0)
                            {
                                this.nameTable[member.Name] = member;
                            }
                        }
                        else if ((this.initMethod == null) && (member is CodeMemberMethod))
                        {
                            CodeMemberMethod method = (CodeMemberMethod)member;
                            if ((string.Compare(method.Name, this.InitMethodName, caseInsensitive, CultureInfo.InvariantCulture) == 0) && (method.Parameters.Count == 0))
                            {
                                this.initMethod = method;
                            }
                        }
                    }
                    if (this.initMethod != null)
                    {
                        foreach (CodeStatement statement in this.initMethod.Statements)
                        {
                            CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement;
                            if (statement2 != null)
                            {
                                this.nameTable[statement2.Name] = statement;
                            }
                        }
                    }
                    if (this.nameTable[declaration.Name] != null)
                    {
                        this.nameTable[declaration.Name] = obj2;
                    }
                    if (this.initMethod != null)
                    {
                        this.FillStatementTable(this.initMethod, declaration.Name);
                    }
                    PropertyDescriptor descriptor = manager.Properties["SupportsStatementGeneration"];
                    if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool)descriptor.GetValue(manager)))
                    {
                        foreach (string str in this.nameTable.Keys)
                        {
                            CodeDomSerializerBase.OrderedCodeStatementCollection statements = (CodeDomSerializerBase.OrderedCodeStatementCollection) this.statementTable[str];
                            if (statements != null)
                            {
                                bool flag2 = false;
                                foreach (CodeStatement statement3 in statements)
                                {
                                    object obj3 = statement3.UserData["GeneratedStatement"];
                                    if (((obj3 == null) || !(obj3 is bool)) || !((bool)obj3))
                                    {
                                        flag2 = true;
                                        break;
                                    }
                                }
                                if (!flag2)
                                {
                                    this.statementTable.Remove(str);
                                }
                            }
                        }
                    }
                    IContainer container = (IContainer)manager.GetService(typeof(IContainer));
                    if (container != null)
                    {
                        foreach (object obj4 in container.Components)
                        {
                            base.DeserializePropertiesFromResources(manager, obj4, designTimeProperties);
                        }
                    }
                    object[] array = new object[this.statementTable.Values.Count];
                    this.statementTable.Values.CopyTo(array, 0);
                    Array.Sort(array, StatementOrderComparer.Default);
                    foreach (CodeDomSerializerBase.OrderedCodeStatementCollection statements2 in array)
                    {
                        string name = statements2.Name;
                        if ((name != null) && !name.Equals(declaration.Name))
                        {
                            this.DeserializeName(manager, name);
                        }
                    }
                    CodeStatementCollection statements3 = (CodeStatementCollection)this.statementTable[declaration.Name];
                    if ((statements3 != null) && (statements3.Count > 0))
                    {
                        foreach (CodeStatement statement4 in statements3)
                        {
                            base.DeserializeStatement(manager, statement4);
                        }
                    }
                    return(obj2);
                }
                finally
                {
                    manager.ResolveName -= handler;
                    this.initMethod      = null;
                    this.nameTable       = null;
                    this.statementTable  = null;
                    manager.Context.Pop();
                }
            }
            return(obj2);
        }
 protected CodeDomSerializer GetSerializer(IDesignerSerializationManager manager, object value)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (value != null)
     {
         AttributeCollection attributesHelper = GetAttributesHelper(manager, value);
         AttributeCollection attributesFromTypeHelper = GetAttributesFromTypeHelper(manager, value.GetType());
         if (attributesHelper.Count != attributesFromTypeHelper.Count)
         {
             string typeName = null;
             Type type = typeof(CodeDomSerializer);
             DesignerSerializationManager manager2 = manager as DesignerSerializationManager;
             foreach (Attribute attribute in attributesHelper)
             {
                 DesignerSerializerAttribute attribute2 = attribute as DesignerSerializerAttribute;
                 if (attribute2 != null)
                 {
                     Type runtimeType;
                     if (manager2 != null)
                     {
                         runtimeType = manager2.GetRuntimeType(attribute2.SerializerBaseTypeName);
                     }
                     else
                     {
                         runtimeType = manager.GetType(attribute2.SerializerBaseTypeName);
                     }
                     if (runtimeType == type)
                     {
                         typeName = attribute2.SerializerTypeName;
                         break;
                     }
                 }
             }
             if (typeName != null)
             {
                 foreach (Attribute attribute3 in attributesFromTypeHelper)
                 {
                     DesignerSerializerAttribute attribute4 = attribute3 as DesignerSerializerAttribute;
                     if (attribute4 != null)
                     {
                         Type type3;
                         if (manager2 != null)
                         {
                             type3 = manager2.GetRuntimeType(attribute4.SerializerBaseTypeName);
                         }
                         else
                         {
                             type3 = manager.GetType(attribute4.SerializerBaseTypeName);
                         }
                         if (type3 == type)
                         {
                             if (typeName.Equals(attribute4.SerializerTypeName))
                             {
                                 typeName = null;
                             }
                             break;
                         }
                     }
                 }
             }
             if (typeName != null)
             {
                 Type c = (manager2 != null) ? manager2.GetRuntimeType(typeName) : manager.GetType(typeName);
                 if ((c != null) && type.IsAssignableFrom(c))
                 {
                     return (CodeDomSerializer) Activator.CreateInstance(c);
                 }
             }
         }
     }
     Type objectType = null;
     if (value != null)
     {
         objectType = value.GetType();
     }
     return (CodeDomSerializer) manager.GetSerializer(objectType, typeof(CodeDomSerializer));
 }
		protected CodeDomSerializer GetSerializer (IDesignerSerializationManager manager, object instance)
		{
			DesignerSerializerAttribute attrInstance, attrType;
			attrType = attrInstance = null;

			CodeDomSerializer serializer = null;
			if (instance == null)
				serializer = this.GetSerializer (manager, null);
			else {		
				AttributeCollection attributes = TypeDescriptor.GetAttributes (instance);
				foreach (Attribute a in attributes) {
					DesignerSerializerAttribute designerAttr = a as DesignerSerializerAttribute;
					if (designerAttr != null && manager.GetType (designerAttr.SerializerBaseTypeName) == typeof (CodeDomSerializer)) {
						attrInstance = designerAttr;
						break;
					}
				}
	
				attributes = TypeDescriptor.GetAttributes (instance.GetType ());
				foreach (Attribute a in attributes) {
					DesignerSerializerAttribute designerAttr = a as DesignerSerializerAttribute;
					if (designerAttr != null && manager.GetType (designerAttr.SerializerBaseTypeName) == typeof (CodeDomSerializer)) {
						attrType = designerAttr;
						break;
					}
				}
	
				// if there is metadata modification in the instance then create the specified serializer instead of the one
				// in the Type.
				if (attrType != null && attrInstance != null && attrType.SerializerTypeName != attrInstance.SerializerTypeName)
					serializer = Activator.CreateInstance (manager.GetType (attrInstance.SerializerTypeName)) as CodeDomSerializer;
				else
					serializer = this.GetSerializer (manager, instance.GetType ());
			}

			return serializer;
		}
		public override object Deserialize (IDesignerSerializationManager manager, object codeObject)
		{
			CodeTypeDeclaration declaration = (CodeTypeDeclaration) codeObject;
			Type rootType = manager.GetType (declaration.BaseTypes[0].BaseType);
			object root = manager.CreateInstance (rootType, null, declaration.Name, true);

			CodeMemberMethod initComponentMethod = GetInitializeMethod (declaration);
			if (initComponentMethod == null)
				throw new InvalidOperationException ("InitializeComponent method is missing in: " + declaration.Name);

			foreach (CodeStatement statement in initComponentMethod.Statements)
				base.DeserializeStatement (manager, statement);

			return root;
		}
 private object DeserializeName(IDesignerSerializationManager manager, string name, CodeStatementCollection statements)
 {
     object obj2 = null;
     using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::DeserializeName"))
     {
         obj2 = this._nameTable[name];
         CodeObject obj3 = obj2 as CodeObject;
         string typeName = null;
         CodeMemberField field = null;
         if (obj3 != null)
         {
             obj2 = null;
             this._nameTable[name] = null;
             CodeVariableDeclarationStatement statement = obj3 as CodeVariableDeclarationStatement;
             if (statement != null)
             {
                 typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, statement.Type);
             }
             else
             {
                 field = obj3 as CodeMemberField;
                 if (field != null)
                 {
                     typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type);
                 }
                 else
                 {
                     CodeExpression expression = obj3 as CodeExpression;
                     RootContext context = manager.Context[typeof(RootContext)] as RootContext;
                     if (((context != null) && (expression != null)) && (context.Expression == expression))
                     {
                         obj2 = context.Value;
                         typeName = TypeDescriptor.GetClassName(obj2);
                     }
                 }
             }
         }
         else if (obj2 == null)
         {
             IContainer service = (IContainer) manager.GetService(typeof(IContainer));
             if (service != null)
             {
                 IComponent component = service.Components[name];
                 if (component != null)
                 {
                     typeName = component.GetType().FullName;
                     this._nameTable[name] = component;
                 }
             }
         }
         if (typeName == null)
         {
             return obj2;
         }
         Type valueType = manager.GetType(typeName);
         if (valueType == null)
         {
             manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeName }), manager));
             return obj2;
         }
         if ((statements == null) && this._statementTable.ContainsKey(name))
         {
             statements = this._statementTable[name];
         }
         if ((statements == null) || (statements.Count <= 0))
         {
             return obj2;
         }
         CodeDomSerializer serializer = base.GetSerializer(manager, valueType);
         if (serializer == null)
         {
             manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { valueType.FullName }), manager));
             return obj2;
         }
         try
         {
             obj2 = serializer.Deserialize(manager, statements);
             if ((obj2 != null) && (field != null))
             {
                 PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj2)["Modifiers"];
                 if ((descriptor != null) && (descriptor.PropertyType == typeof(MemberAttributes)))
                 {
                     MemberAttributes attributes = field.Attributes & MemberAttributes.AccessMask;
                     descriptor.SetValue(obj2, attributes);
                 }
             }
             this._nameTable[name] = obj2;
         }
         catch (Exception exception)
         {
             manager.ReportError(exception);
         }
     }
     return obj2;
 }
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeStatementCollection      statements = null;
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);

            using (CodeDomSerializerBase.TraceScope("ComponentCodeDomSerializer::Serialize"))
            {
                if ((manager == null) || (value == null))
                {
                    throw new ArgumentNullException((manager == null) ? "manager" : "value");
                }
                if (base.IsSerialized(manager, value))
                {
                    return(base.GetExpression(manager, value));
                }
                InheritanceLevel     notInherited = InheritanceLevel.NotInherited;
                InheritanceAttribute attribute    = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)];
                if (attribute != null)
                {
                    notInherited = attribute.InheritanceLevel;
                }
                if (notInherited == InheritanceLevel.InheritedReadOnly)
                {
                    return(statements);
                }
                statements = new CodeStatementCollection();
                CodeTypeDeclaration declaration = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
                RootContext         context     = manager.Context[typeof(RootContext)] as RootContext;
                CodeExpression      left        = null;
                bool flag  = false;
                bool flag2 = true;
                bool flag3 = true;
                bool flag4 = false;
                left = base.GetExpression(manager, value);
                if (left != null)
                {
                    flag  = false;
                    flag2 = false;
                    flag3 = false;
                    IComponent component = value as IComponent;
                    if ((component != null) && (component.Site == null))
                    {
                        ExpressionContext context2 = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
                        if ((context2 == null) || (context2.PresetValue != value))
                        {
                            flag4 = true;
                        }
                    }
                }
                else
                {
                    if (notInherited == InheritanceLevel.NotInherited)
                    {
                        PropertyDescriptor descriptor = properties["GenerateMember"];
                        if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && !((bool)descriptor.GetValue(value)))
                        {
                            flag  = true;
                            flag2 = false;
                        }
                    }
                    else
                    {
                        flag3 = false;
                    }
                    if (context == null)
                    {
                        flag  = true;
                        flag2 = false;
                    }
                }
                manager.Context.Push(value);
                manager.Context.Push(statements);
                try
                {
                    try
                    {
                        string name      = manager.GetName(value);
                        string className = TypeDescriptor.GetClassName(value);
                        if ((flag2 || flag) && (name != null))
                        {
                            if (flag2)
                            {
                                if (notInherited == InheritanceLevel.NotInherited)
                                {
                                    MemberAttributes   @private;
                                    CodeMemberField    field       = new CodeMemberField(className, name);
                                    PropertyDescriptor descriptor2 = properties["Modifiers"];
                                    if (descriptor2 == null)
                                    {
                                        descriptor2 = properties["DefaultModifiers"];
                                    }
                                    if ((descriptor2 != null) && (descriptor2.PropertyType == typeof(MemberAttributes)))
                                    {
                                        @private = (MemberAttributes)descriptor2.GetValue(value);
                                    }
                                    else
                                    {
                                        @private = MemberAttributes.Private;
                                    }
                                    field.Attributes = @private;
                                    declaration.Members.Add(field);
                                }
                                left = new CodeFieldReferenceExpression(context.Expression, name);
                            }
                            else
                            {
                                if (notInherited == InheritanceLevel.NotInherited)
                                {
                                    CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(className, name);
                                    statements.Add(statement);
                                }
                                left = new CodeVariableReferenceExpression(name);
                            }
                        }
                        if (flag3)
                        {
                            CodeExpression  expression2;
                            IContainer      service = manager.GetService(typeof(IContainer)) as IContainer;
                            ConstructorInfo info    = null;
                            if (service != null)
                            {
                                info = CodeDomSerializerBase.GetReflectionTypeHelper(manager, value).GetConstructor(BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, this.GetContainerConstructor(manager), null);
                            }
                            if (info != null)
                            {
                                expression2 = new CodeObjectCreateExpression(className, new CodeExpression[] { base.SerializeToExpression(manager, service) });
                            }
                            else
                            {
                                bool flag5;
                                expression2 = base.SerializeCreationExpression(manager, value, out flag5);
                            }
                            if (expression2 != null)
                            {
                                if (left == null)
                                {
                                    if (flag4)
                                    {
                                        left = expression2;
                                    }
                                }
                                else
                                {
                                    CodeAssignStatement statement2 = new CodeAssignStatement(left, expression2);
                                    statements.Add(statement2);
                                }
                            }
                        }
                        if (left != null)
                        {
                            base.SetExpression(manager, value, left);
                        }
                        if ((left != null) && !flag4)
                        {
                            bool flag6 = value is ISupportInitialize;
                            if (flag6)
                            {
                                string fullName = typeof(ISupportInitialize).FullName;
                                flag6 = manager.GetType(fullName) != null;
                            }
                            Type c = null;
                            if (flag6)
                            {
                                c     = CodeDomSerializerBase.GetReflectionTypeHelper(manager, value);
                                flag6 = CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, typeof(ISupportInitialize)).IsAssignableFrom(c);
                            }
                            bool flag7 = (value is IPersistComponentSettings) && ((IPersistComponentSettings)value).SaveSettings;
                            if (flag7)
                            {
                                string typeName = typeof(IPersistComponentSettings).FullName;
                                flag7 = manager.GetType(typeName) != null;
                            }
                            if (flag7)
                            {
                                c     = c ?? CodeDomSerializerBase.GetReflectionTypeHelper(manager, value);
                                flag7 = CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, typeof(IPersistComponentSettings)).IsAssignableFrom(c);
                            }
                            IDesignerSerializationManager manager2 = (IDesignerSerializationManager)manager.GetService(typeof(IDesignerSerializationManager));
                            if (flag6)
                            {
                                this.SerializeSupportInitialize(manager, statements, left, value, "BeginInit");
                            }
                            base.SerializePropertiesToResources(manager, statements, value, _designTimeFilter);
                            ComponentCache       serviceInstance = (ComponentCache)manager.GetService(typeof(ComponentCache));
                            ComponentCache.Entry entry           = null;
                            if (serviceInstance == null)
                            {
                                IServiceContainer container2 = (IServiceContainer)manager.GetService(typeof(IServiceContainer));
                                if (container2 != null)
                                {
                                    serviceInstance = new ComponentCache(manager);
                                    container2.AddService(typeof(ComponentCache), serviceInstance);
                                }
                            }
                            else if (((manager == manager2) && (serviceInstance != null)) && serviceInstance.Enabled)
                            {
                                entry = serviceInstance[value];
                            }
                            if ((entry == null) || entry.Tracking)
                            {
                                if (entry == null)
                                {
                                    entry = new ComponentCache.Entry(serviceInstance);
                                    ComponentCache.Entry entryAll = null;
                                    entryAll = serviceInstance.GetEntryAll(value);
                                    if (((entryAll != null) && (entryAll.Dependencies != null)) && (entryAll.Dependencies.Count > 0))
                                    {
                                        foreach (object obj2 in entryAll.Dependencies)
                                        {
                                            entry.AddDependency(obj2);
                                        }
                                    }
                                }
                                entry.Component = value;
                                bool flag8 = manager == manager2;
                                entry.Valid = flag8 && this.CanCacheComponent(manager, value, properties);
                                if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled)
                                {
                                    manager.Context.Push(serviceInstance);
                                    manager.Context.Push(entry);
                                }
                                try
                                {
                                    entry.Statements = new CodeStatementCollection();
                                    base.SerializeProperties(manager, entry.Statements, value, _runTimeFilter);
                                    base.SerializeEvents(manager, entry.Statements, value, null);
                                    foreach (CodeStatement statement3 in entry.Statements)
                                    {
                                        if (statement3 is CodeVariableDeclarationStatement)
                                        {
                                            entry.Tracking = true;
                                            break;
                                        }
                                    }
                                    if (entry.Statements.Count > 0)
                                    {
                                        entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));
                                        entry.Statements.Insert(0, new CodeCommentStatement(name));
                                        entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));
                                        if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled)
                                        {
                                            serviceInstance[value] = entry;
                                        }
                                    }
                                }
                                finally
                                {
                                    if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled)
                                    {
                                        manager.Context.Pop();
                                        manager.Context.Pop();
                                    }
                                }
                            }
                            else if (((entry.Resources != null) || (entry.Metadata != null)) && ((serviceInstance != null) && serviceInstance.Enabled))
                            {
                                ResourceCodeDomSerializer.Default.ApplyCacheEntry(manager, entry);
                            }
                            statements.AddRange(entry.Statements);
                            if (flag7)
                            {
                                this.SerializeLoadComponentSettings(manager, statements, left, value);
                            }
                            if (flag6)
                            {
                                this.SerializeSupportInitialize(manager, statements, left, value, "EndInit");
                            }
                        }
                        return(statements);
                    }
                    catch (CheckoutException)
                    {
                        throw;
                    }
                    catch (Exception exception)
                    {
                        manager.ReportError(exception);
                    }
                    return(statements);
                }
                finally
                {
                    manager.Context.Pop();
                    manager.Context.Pop();
                }
            }
            return(statements);
        }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     CodeStatementCollection statements = null;
     PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
     using (CodeDomSerializerBase.TraceScope("ComponentCodeDomSerializer::Serialize"))
     {
         if ((manager == null) || (value == null))
         {
             throw new ArgumentNullException((manager == null) ? "manager" : "value");
         }
         if (base.IsSerialized(manager, value))
         {
             return base.GetExpression(manager, value);
         }
         InheritanceLevel notInherited = InheritanceLevel.NotInherited;
         InheritanceAttribute attribute = (InheritanceAttribute) TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)];
         if (attribute != null)
         {
             notInherited = attribute.InheritanceLevel;
         }
         if (notInherited == InheritanceLevel.InheritedReadOnly)
         {
             return statements;
         }
         statements = new CodeStatementCollection();
         CodeTypeDeclaration declaration = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
         RootContext context = manager.Context[typeof(RootContext)] as RootContext;
         CodeExpression left = null;
         bool flag = false;
         bool flag2 = true;
         bool flag3 = true;
         bool flag4 = false;
         left = base.GetExpression(manager, value);
         if (left != null)
         {
             flag = false;
             flag2 = false;
             flag3 = false;
             IComponent component = value as IComponent;
             if ((component != null) && (component.Site == null))
             {
                 ExpressionContext context2 = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
                 if ((context2 == null) || (context2.PresetValue != value))
                 {
                     flag4 = true;
                 }
             }
         }
         else
         {
             if (notInherited == InheritanceLevel.NotInherited)
             {
                 PropertyDescriptor descriptor = properties["GenerateMember"];
                 if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && !((bool) descriptor.GetValue(value)))
                 {
                     flag = true;
                     flag2 = false;
                 }
             }
             else
             {
                 flag3 = false;
             }
             if (context == null)
             {
                 flag = true;
                 flag2 = false;
             }
         }
         manager.Context.Push(value);
         manager.Context.Push(statements);
         try
         {
             try
             {
                 string name = manager.GetName(value);
                 string className = TypeDescriptor.GetClassName(value);
                 if ((flag2 || flag) && (name != null))
                 {
                     if (flag2)
                     {
                         if (notInherited == InheritanceLevel.NotInherited)
                         {
                             MemberAttributes @private;
                             CodeMemberField field = new CodeMemberField(className, name);
                             PropertyDescriptor descriptor2 = properties["Modifiers"];
                             if (descriptor2 == null)
                             {
                                 descriptor2 = properties["DefaultModifiers"];
                             }
                             if ((descriptor2 != null) && (descriptor2.PropertyType == typeof(MemberAttributes)))
                             {
                                 @private = (MemberAttributes) descriptor2.GetValue(value);
                             }
                             else
                             {
                                 @private = MemberAttributes.Private;
                             }
                             field.Attributes = @private;
                             declaration.Members.Add(field);
                         }
                         left = new CodeFieldReferenceExpression(context.Expression, name);
                     }
                     else
                     {
                         if (notInherited == InheritanceLevel.NotInherited)
                         {
                             CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(className, name);
                             statements.Add(statement);
                         }
                         left = new CodeVariableReferenceExpression(name);
                     }
                 }
                 if (flag3)
                 {
                     CodeExpression expression2;
                     IContainer service = manager.GetService(typeof(IContainer)) as IContainer;
                     ConstructorInfo info = null;
                     if (service != null)
                     {
                         info = CodeDomSerializerBase.GetReflectionTypeHelper(manager, value).GetConstructor(BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, this.GetContainerConstructor(manager), null);
                     }
                     if (info != null)
                     {
                         expression2 = new CodeObjectCreateExpression(className, new CodeExpression[] { base.SerializeToExpression(manager, service) });
                     }
                     else
                     {
                         bool flag5;
                         expression2 = base.SerializeCreationExpression(manager, value, out flag5);
                     }
                     if (expression2 != null)
                     {
                         if (left == null)
                         {
                             if (flag4)
                             {
                                 left = expression2;
                             }
                         }
                         else
                         {
                             CodeAssignStatement statement2 = new CodeAssignStatement(left, expression2);
                             statements.Add(statement2);
                         }
                     }
                 }
                 if (left != null)
                 {
                     base.SetExpression(manager, value, left);
                 }
                 if ((left != null) && !flag4)
                 {
                     bool flag6 = value is ISupportInitialize;
                     if (flag6)
                     {
                         string fullName = typeof(ISupportInitialize).FullName;
                         flag6 = manager.GetType(fullName) != null;
                     }
                     Type c = null;
                     if (flag6)
                     {
                         c = CodeDomSerializerBase.GetReflectionTypeHelper(manager, value);
                         flag6 = CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, typeof(ISupportInitialize)).IsAssignableFrom(c);
                     }
                     bool flag7 = (value is IPersistComponentSettings) && ((IPersistComponentSettings) value).SaveSettings;
                     if (flag7)
                     {
                         string typeName = typeof(IPersistComponentSettings).FullName;
                         flag7 = manager.GetType(typeName) != null;
                     }
                     if (flag7)
                     {
                         c = c ?? CodeDomSerializerBase.GetReflectionTypeHelper(manager, value);
                         flag7 = CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, typeof(IPersistComponentSettings)).IsAssignableFrom(c);
                     }
                     IDesignerSerializationManager manager2 = (IDesignerSerializationManager) manager.GetService(typeof(IDesignerSerializationManager));
                     if (flag6)
                     {
                         this.SerializeSupportInitialize(manager, statements, left, value, "BeginInit");
                     }
                     base.SerializePropertiesToResources(manager, statements, value, _designTimeFilter);
                     ComponentCache serviceInstance = (ComponentCache) manager.GetService(typeof(ComponentCache));
                     ComponentCache.Entry entry = null;
                     if (serviceInstance == null)
                     {
                         IServiceContainer container2 = (IServiceContainer) manager.GetService(typeof(IServiceContainer));
                         if (container2 != null)
                         {
                             serviceInstance = new ComponentCache(manager);
                             container2.AddService(typeof(ComponentCache), serviceInstance);
                         }
                     }
                     else if (((manager == manager2) && (serviceInstance != null)) && serviceInstance.Enabled)
                     {
                         entry = serviceInstance[value];
                     }
                     if ((entry == null) || entry.Tracking)
                     {
                         if (entry == null)
                         {
                             entry = new ComponentCache.Entry(serviceInstance);
                             ComponentCache.Entry entryAll = null;
                             entryAll = serviceInstance.GetEntryAll(value);
                             if (((entryAll != null) && (entryAll.Dependencies != null)) && (entryAll.Dependencies.Count > 0))
                             {
                                 foreach (object obj2 in entryAll.Dependencies)
                                 {
                                     entry.AddDependency(obj2);
                                 }
                             }
                         }
                         entry.Component = value;
                         bool flag8 = manager == manager2;
                         entry.Valid = flag8 && this.CanCacheComponent(manager, value, properties);
                         if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled)
                         {
                             manager.Context.Push(serviceInstance);
                             manager.Context.Push(entry);
                         }
                         try
                         {
                             entry.Statements = new CodeStatementCollection();
                             base.SerializeProperties(manager, entry.Statements, value, _runTimeFilter);
                             base.SerializeEvents(manager, entry.Statements, value, null);
                             foreach (CodeStatement statement3 in entry.Statements)
                             {
                                 if (statement3 is CodeVariableDeclarationStatement)
                                 {
                                     entry.Tracking = true;
                                     break;
                                 }
                             }
                             if (entry.Statements.Count > 0)
                             {
                                 entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));
                                 entry.Statements.Insert(0, new CodeCommentStatement(name));
                                 entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));
                                 if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled)
                                 {
                                     serviceInstance[value] = entry;
                                 }
                             }
                         }
                         finally
                         {
                             if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled)
                             {
                                 manager.Context.Pop();
                                 manager.Context.Pop();
                             }
                         }
                     }
                     else if (((entry.Resources != null) || (entry.Metadata != null)) && ((serviceInstance != null) && serviceInstance.Enabled))
                     {
                         ResourceCodeDomSerializer.Default.ApplyCacheEntry(manager, entry);
                     }
                     statements.AddRange(entry.Statements);
                     if (flag7)
                     {
                         this.SerializeLoadComponentSettings(manager, statements, left, value);
                     }
                     if (flag6)
                     {
                         this.SerializeSupportInitialize(manager, statements, left, value, "EndInit");
                     }
                 }
                 return statements;
             }
             catch (CheckoutException)
             {
                 throw;
             }
             catch (Exception exception)
             {
                 manager.ReportError(exception);
             }
             return statements;
         }
         finally
         {
             manager.Context.Pop();
             manager.Context.Pop();
         }
     }
     return statements;
 }
        private object DeserializeName(IDesignerSerializationManager manager, string name, CodeStatementCollection statements)
        {
            object obj2 = null;

            using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::DeserializeName"))
            {
                obj2 = this._nameTable[name];
                CodeObject      obj3     = obj2 as CodeObject;
                string          typeName = null;
                CodeMemberField field    = null;
                if (obj3 != null)
                {
                    obj2 = null;
                    this._nameTable[name] = null;
                    CodeVariableDeclarationStatement statement = obj3 as CodeVariableDeclarationStatement;
                    if (statement != null)
                    {
                        typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, statement.Type);
                    }
                    else
                    {
                        field = obj3 as CodeMemberField;
                        if (field != null)
                        {
                            typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type);
                        }
                        else
                        {
                            CodeExpression expression = obj3 as CodeExpression;
                            RootContext    context    = manager.Context[typeof(RootContext)] as RootContext;
                            if (((context != null) && (expression != null)) && (context.Expression == expression))
                            {
                                obj2     = context.Value;
                                typeName = TypeDescriptor.GetClassName(obj2);
                            }
                        }
                    }
                }
                else if (obj2 == null)
                {
                    IContainer service = (IContainer)manager.GetService(typeof(IContainer));
                    if (service != null)
                    {
                        IComponent component = service.Components[name];
                        if (component != null)
                        {
                            typeName = component.GetType().FullName;
                            this._nameTable[name] = component;
                        }
                    }
                }
                if (typeName == null)
                {
                    return(obj2);
                }
                Type valueType = manager.GetType(typeName);
                if (valueType == null)
                {
                    manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeName }), manager));
                    return(obj2);
                }
                if ((statements == null) && this._statementTable.ContainsKey(name))
                {
                    statements = this._statementTable[name];
                }
                if ((statements == null) || (statements.Count <= 0))
                {
                    return(obj2);
                }
                CodeDomSerializer serializer = base.GetSerializer(manager, valueType);
                if (serializer == null)
                {
                    manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { valueType.FullName }), manager));
                    return(obj2);
                }
                try
                {
                    obj2 = serializer.Deserialize(manager, statements);
                    if ((obj2 != null) && (field != null))
                    {
                        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj2)["Modifiers"];
                        if ((descriptor != null) && (descriptor.PropertyType == typeof(MemberAttributes)))
                        {
                            MemberAttributes attributes = field.Attributes & MemberAttributes.AccessMask;
                            descriptor.SetValue(obj2, attributes);
                        }
                    }
                    this._nameTable[name] = obj2;
                }
                catch (Exception exception)
                {
                    manager.ReportError(exception);
                }
            }
            return(obj2);
        }
		// Used to remove the ctor from the statement colletion in order for the ctor statement to be moved.
		//
		private CodeStatement ExtractCtorStatement (IDesignerSerializationManager manager, CodeStatementCollection statements, 
													object component)
		{
			CodeStatement result = null;
			CodeAssignStatement assignment = null;
			CodeObjectCreateExpression ctor = null;
			int toRemove = -1;

			for (int i=0; i < statements.Count; i++) {
				assignment = statements[i] as CodeAssignStatement;
				if (assignment != null) {
					ctor = assignment.Right as CodeObjectCreateExpression;
					if (ctor != null && manager.GetType (ctor.CreateType.BaseType) == component.GetType ()) {
						result = assignment;
						toRemove = i;
					}
				}
			}

			if (toRemove != -1)
				statements.RemoveAt (toRemove);

			return result;
		}
 internal static Type GetType(IDesignerSerializationManager manager, string name, Dictionary<string, string> names)
 {
     Type type = null;
     if ((names != null) && names.ContainsKey(name))
     {
         string str = names[name];
         if ((manager != null) && !string.IsNullOrEmpty(str))
         {
             type = manager.GetType(str);
         }
     }
     return type;
 }