public virtual CodeTypeDeclaration Serialize (IDesignerSerializationManager manager, object root, ICollection members)
		{
			if (root == null)
				throw new ArgumentNullException ("root");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			RootContext rootContext = new RootContext (new CodeThisReferenceExpression (), root);
			StatementContext statementContext = new StatementContext ();
			if (members != null)
				statementContext.StatementCollection.Populate (members);
			statementContext.StatementCollection.Populate (root);
			CodeTypeDeclaration declaration = new CodeTypeDeclaration (manager.GetName (root));

			manager.Context.Push (rootContext);
			manager.Context.Push (statementContext);
			manager.Context.Push (declaration);

			if (members != null) {
				foreach (object member in members)
					base.SerializeToExpression (manager, member);
			}
			base.SerializeToExpression (manager, root);

			manager.Context.Pop ();
			manager.Context.Pop ();
			manager.Context.Pop ();

			return declaration;
		}
Exemple #2
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            ICollection originalCollection = value as ICollection;

            if (originalCollection == null)
            {
                throw new ArgumentException("originalCollection is not an ICollection");
            }

            CodeExpression targetExpression = null;

            ExpressionContext exprContext = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
            RootContext       root        = manager.Context[typeof(RootContext)] as RootContext;

            if (exprContext != null && exprContext.PresetValue == value)
            {
                targetExpression = exprContext.Expression;
            }
            else if (root != null)
            {
                targetExpression = root.Expression;
            }

            ArrayList valuesToSerialize = new ArrayList();

            foreach (object o in originalCollection)
            {
                valuesToSerialize.Add(o);
            }

            return(this.SerializeCollection(manager, targetExpression, value.GetType(), originalCollection, valuesToSerialize));
        }
Exemple #3
0
        private CultureInfo GetLocalizationLanguage(IDesignerSerializationManager manager)
        {
            if (localizationLanguage is null)
            {
                // Check to see if our base component's localizable prop is true
                RootContext rootCtx = manager.Context[typeof(RootContext)] as RootContext;

                if (rootCtx is not null)
                {
                    object             comp = rootCtx.Value;
                    PropertyDescriptor prop = TypeDescriptor.GetProperties(comp)["LoadLanguage"];

                    if (prop is not null && prop.PropertyType == typeof(CultureInfo))
                    {
                        localizationLanguage = (CultureInfo)prop.GetValue(comp);
                    }
                }
            }

            return(localizationLanguage);
        }
        public virtual CodeTypeDeclaration Serialize(IDesignerSerializationManager manager, object root, ICollection members)
        {
            if (root == null)
            {
                throw new ArgumentNullException("root");
            }
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

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

            if (members != null)
            {
                statementContext.StatementCollection.Populate(members);
            }
            statementContext.StatementCollection.Populate(root);
            CodeTypeDeclaration declaration = new CodeTypeDeclaration(manager.GetName(root));

            manager.Context.Push(rootContext);
            manager.Context.Push(statementContext);
            manager.Context.Push(declaration);

            if (members != null)
            {
                foreach (object member in members)
                {
                    base.SerializeToExpression(manager, member);
                }
            }
            base.SerializeToExpression(manager, root);

            manager.Context.Pop();
            manager.Context.Pop();
            manager.Context.Pop();

            return(declaration);
        }
Exemple #5
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (_codeMap == null)
            {
                _codeMap = new CodeMap(value.GetType(), manager.GetName(value));
            }
            _codeMap.Clear();

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

            manager.Context.Push(rootContext);

            this.SerializeComponents(manager, ((IComponent)value).Site.Container.Components, (IComponent)value);

            // Serialize root component
            //
            CodeStatementCollection statements = new CodeStatementCollection();

            statements.Add(new CodeCommentStatement(String.Empty));
            statements.Add(new CodeCommentStatement(manager.GetName(value)));
            statements.Add(new CodeCommentStatement(String.Empty));
            // Note that during the serialization process below ComponentCodeDomSerializer
            // will be invoked to serialize the rootcomponent during expression serialization.
            // It will check for RootContext and return that.
            base.SerializeProperties(manager, statements, value, new Attribute[0]);
            base.SerializeEvents(manager, statements, value, new Attribute[0]);
            _codeMap.Add(statements);

            manager.Context.Pop();
            return(_codeMap.GenerateClass());
        }
        protected CodeExpression SerializeToReferenceExpression(IDesignerSerializationManager manager, object value)
        {
            CodeExpression expression = null;

            using (CodeDomSerializerBase.TraceScope("CodeDomSerializer::SerializeToReferenceExpression"))
            {
                expression = base.GetExpression(manager, value);
                if ((expression != null) || !(value is IComponent))
                {
                    return(expression);
                }
                string name = manager.GetName(value);
                bool   flag = false;
                if (name == null)
                {
                    IReferenceService service = (IReferenceService)manager.GetService(typeof(IReferenceService));
                    if (service != null)
                    {
                        name = service.GetName(value);
                        flag = name != null;
                    }
                }
                if (name == null)
                {
                    return(expression);
                }
                RootContext context = (RootContext)manager.Context[typeof(RootContext)];
                if ((context != null) && (context.Value == value))
                {
                    return(context.Expression);
                }
                if (flag && (name.IndexOf('.') != -1))
                {
                    int index = name.IndexOf('.');
                    return(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(_thisRef, name.Substring(0, index)), name.Substring(index + 1)));
                }
                return(new CodeFieldReferenceExpression(_thisRef, name));
            }
        }
        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);
        }
Exemple #8
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");
                            }
                        }
                    }
Exemple #9
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            RootContext rootContext = manager.Context[typeof(RootContext)] as RootContext;

            if (rootContext != null && rootContext.Value == value)
            {
                return(rootContext.Expression);
            }

            CodeStatementCollection statements = new CodeStatementCollection();

            if (((IComponent)value).Site == null)
            {
                ReportError(manager, "Component of type '" + value.GetType().Name + "' not sited");
                return(statements);
            }

            // the trick with the nested components is that GetName will return the full name
            // e.g splitter1.Panel1 and thus the code below will create a reference to that.
            //
            string name = manager.GetName(value);

            CodeExpression componentRef = null;

            if (rootContext != null)
            {
                componentRef = new CodeFieldReferenceExpression(rootContext.Expression, name);
            }
            else
            {
                componentRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), name);
            }

            base.SetExpression(manager, value, componentRef);

            ExpressionContext context = manager.Context[typeof(ExpressionContext)] as ExpressionContext;

            // Perform some heuristics here.
            //
            // If there is an ExpressionContext of PropertyReference where PresetValue == this
            // partial serialization doesn't make sense, so perform full. E.g in the case of:
            //
            // PropertyCodeDomSerializer.SerializeContentProperty and splitContainer1.*Panel1*
            //
            if (context == null || context.PresetValue != value ||
                (context.PresetValue == value && (context.Expression is CodeFieldReferenceExpression ||
                                                  context.Expression is CodePropertyReferenceExpression)))
            {
                bool isComplete = true;
                statements.Add(new CodeCommentStatement(String.Empty));
                statements.Add(new CodeCommentStatement(name));
                statements.Add(new CodeCommentStatement(String.Empty));

                // Do not serialize a creation expression for Nested components
                //
                if (!(((IComponent)value).Site is INestedSite))
                {
                    CodeStatement assignment = new CodeAssignStatement(componentRef,
                                                                       base.SerializeCreationExpression(manager, value,
                                                                                                        out isComplete));
                    assignment.UserData["statement-order"] = "initializer";
                    statements.Add(assignment);
                }

                base.SerializeProperties(manager, statements, value, new Attribute[0]);
                base.SerializeEvents(manager, statements, value);
            }

            return(statements);
        }
 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;
 }
 public virtual CodeTypeDeclaration Serialize(IDesignerSerializationManager manager, object root, ICollection members)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (root == null)
     {
         throw new ArgumentNullException("root");
     }
     CodeTypeDeclaration declaration = new CodeTypeDeclaration(manager.GetName(root));
     CodeThisReferenceExpression expression = new CodeThisReferenceExpression();
     RootContext context = new RootContext(expression, root);
     StatementContext context2 = new StatementContext();
     context2.StatementCollection.Populate(root);
     if (members != null)
     {
         context2.StatementCollection.Populate(members);
     }
     declaration.BaseTypes.Add(root.GetType());
     manager.Context.Push(declaration);
     manager.Context.Push(context);
     manager.Context.Push(context2);
     try
     {
         if (members != null)
         {
             foreach (object obj2 in members)
             {
                 if (obj2 != root)
                 {
                     base.SerializeToExpression(manager, obj2);
                 }
             }
         }
         base.SerializeToExpression(manager, root);
         this.IntegrateStatements(manager, root, members, context2, declaration);
     }
     finally
     {
         manager.Context.Pop();
         manager.Context.Pop();
         manager.Context.Pop();
     }
     return declaration;
 }
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            if ((manager == null) || (value == null))
            {
                throw new ArgumentNullException((manager == null) ? "manager" : "value");
            }
            CodeTypeDeclaration declaration = new CodeTypeDeclaration(manager.GetName(value));
            RootContext         context     = new RootContext(new CodeThisReferenceExpression(), value);

            using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::Serialize"))
            {
                declaration.BaseTypes.Add(value.GetType());
                this.containerRequired = false;
                manager.Context.Push(context);
                manager.Context.Push(this);
                manager.Context.Push(declaration);
                if (!(manager is DesignerSerializationManager))
                {
                    manager.AddSerializationProvider(new CodeDomSerializationProvider());
                }
                try
                {
                    if (value is IComponent)
                    {
                        ISite site = ((IComponent)value).Site;
                        if (site == null)
                        {
                            return(declaration);
                        }
                        ICollection      components = site.Container.Components;
                        StatementContext context2   = new StatementContext();
                        context2.StatementCollection.Populate(components);
                        manager.Context.Push(context2);
                        try
                        {
                            foreach (IComponent component in components)
                            {
                                if ((component != value) && !base.IsSerialized(manager, component))
                                {
                                    if (base.GetSerializer(manager, component) != null)
                                    {
                                        base.SerializeToExpression(manager, component);
                                    }
                                    else
                                    {
                                        manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { component.GetType().FullName }));
                                    }
                                }
                            }
                            manager.Context.Push(value);
                            try
                            {
                                if ((base.GetSerializer(manager, value) != null) && !base.IsSerialized(manager, value))
                                {
                                    base.SerializeToExpression(manager, value);
                                }
                                else
                                {
                                    manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { value.GetType().FullName }));
                                }
                            }
                            finally
                            {
                                manager.Context.Pop();
                            }
                        }
                        finally
                        {
                            manager.Context.Pop();
                        }
                        CodeMemberMethod method = new CodeMemberMethod {
                            Name       = this.InitMethodName,
                            Attributes = MemberAttributes.Private
                        };
                        declaration.Members.Add(method);
                        ArrayList elements = new ArrayList();
                        foreach (object obj2 in components)
                        {
                            if (obj2 != value)
                            {
                                elements.Add(context2.StatementCollection[obj2]);
                            }
                        }
                        if (context2.StatementCollection[value] != null)
                        {
                            elements.Add(context2.StatementCollection[value]);
                        }
                        if (this.ContainerRequired)
                        {
                            this.SerializeContainerDeclaration(manager, method.Statements);
                        }
                        this.SerializeElementsToStatements(elements, method.Statements);
                    }
                    return(declaration);
                }
                finally
                {
                    manager.Context.Pop();
                    manager.Context.Pop();
                    manager.Context.Pop();
                }
            }
            return(declaration);
        }
        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);
        }
Exemple #14
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);
        }
Exemple #15
0
        /// <summary>
        ///  Serializes the given object into a CodeDom object.  This uses the stock
        ///  resource serialization scheme and retains the expression it provides.
        /// </summary>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            PropertyDescriptor desc = (PropertyDescriptor)manager.Context[typeof(PropertyDescriptor)];
            ExpressionContext  tree = (ExpressionContext)manager.Context[typeof(ExpressionContext)];
            bool isSerializable     = (value is not null) ? GetReflectionTypeHelper(manager, value).IsSerializable : true;

            // If value is not serializable, we have no option but to call the original serializer,
            // since we cannot push this into resources.
            bool callExistingSerializer = !isSerializable;

            // Compat: If we are serializing content, we need to skip property reflection to preserve compatibility,
            //         since tools like WinRes expect items in collections (like TreeNodes and ListViewItems)
            //         to be serialized as binary blobs.
            bool serializingContent = (desc is not null && desc.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content));

            // We also skip back to the original serializer if there is a preset value for this object.
            if (!callExistingSerializer)
            {
                callExistingSerializer = tree is not null && tree.PresetValue is not null && tree.PresetValue == value;
            }

            if (_model == CodeDomLocalizationModel.PropertyReflection && !serializingContent && !callExistingSerializer)
            {
                // For a property reflecting model, we need to do more work.  Here we need to find
                // the object we are serializing against and inject an "ApplyResources" method
                // against the object and its name.  If any of this machinery fails we will
                // just return the existing expression which will default to the original behavior.
                CodeStatementCollection statements = (CodeStatementCollection)manager.Context[typeof(CodeStatementCollection)];

                // In the case of extender properties, we don't want to serialize using the property
                // reflecting model.  In this case we'll skip it and fall through to the
                // property assignment model.
                bool skipPropertyReflect = false;

                if (desc is not null)
                {
                    var attr = desc.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute;
                    if (attr is not null && attr.ExtenderProperty is not null)
                    {
                        skipPropertyReflect = true;
                    }
                }

                if (!skipPropertyReflect && tree is not null && statements is not null)
                {
                    string         name            = manager.GetName(tree.Owner);
                    CodeExpression ownerExpression = SerializeToExpression(manager, tree.Owner);

                    if (name is not null && ownerExpression is not null)
                    {
                        RootContext rootCtx = manager.Context[typeof(RootContext)] as RootContext;

                        if (rootCtx is not null && rootCtx.Value == tree.Owner)
                        {
                            name = "$this";
                        }

                        // Ok, if we got here it means we have enough data to emit
                        // using the reflection model.
                        SerializeToResourceExpression(manager, value, false);

                        if (EmitApplyMethod(manager, tree.Owner))
                        {
                            ResourceManager rm = manager.Context[typeof(ResourceManager)] as ResourceManager;
                            Debug.Assert(rm is not null, "No resource manager available in context.");
                            CodeExpression rmExpression = GetExpression(manager, rm);
                            Debug.Assert(rmExpression is not null, "No expression available for resource manager.");

                            CodeMethodReferenceExpression methodRef    = new CodeMethodReferenceExpression(rmExpression, "ApplyResources");
                            CodeMethodInvokeExpression    methodInvoke = new CodeMethodInvokeExpression();

                            methodInvoke.Method = methodRef;
                            methodInvoke.Parameters.Add(ownerExpression);
                            methodInvoke.Parameters.Add(new CodePrimitiveExpression(name));
                            statements.Add(methodInvoke);
                        }

                        return(null);    // we have already worked our statements into the tree.
                    }
                }
            }

            if (callExistingSerializer)
            {
                return(_currentSerializer.Serialize(manager, value));
            }

            return(SerializeToResourceExpression(manager, value));
        }
        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)
		{
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (value == null)
				throw new ArgumentNullException ("value");

			if (_codeMap == null)
				_codeMap = new CodeMap (value.GetType (), manager.GetName (value));
			_codeMap.Clear ();

			RootContext rootContext = new RootContext (new CodeThisReferenceExpression (), value);
			manager.Context.Push (rootContext);

			this.SerializeComponents (manager, ((IComponent) value).Site.Container.Components, (IComponent) value);

			// Serialize root component
			// 
			CodeStatementCollection statements = new CodeStatementCollection ();
			statements.Add (new CodeCommentStatement (String.Empty));
			statements.Add (new CodeCommentStatement (manager.GetName (value)));
			statements.Add (new CodeCommentStatement (String.Empty));
			// Note that during the serialization process below ComponentCodeDomSerializer
			// will be invoked to serialize the rootcomponent during expression serialization.
			// It will check for RootContext and return that.
			base.SerializeProperties (manager, statements, value, new Attribute[0]);
			base.SerializeEvents (manager, statements, value, new Attribute[0]);
			_codeMap.Add (statements);

			manager.Context.Pop ();
			return _codeMap.GenerateClass ();
		}
		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;
		}
 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;
 }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     if ((manager == null) || (value == null))
     {
         throw new ArgumentNullException((manager == null) ? "manager" : "value");
     }
     CodeTypeDeclaration declaration = new CodeTypeDeclaration(manager.GetName(value));
     RootContext context = new RootContext(new CodeThisReferenceExpression(), value);
     using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::Serialize"))
     {
         declaration.BaseTypes.Add(value.GetType());
         this.containerRequired = false;
         manager.Context.Push(context);
         manager.Context.Push(this);
         manager.Context.Push(declaration);
         if (!(manager is DesignerSerializationManager))
         {
             manager.AddSerializationProvider(new CodeDomSerializationProvider());
         }
         try
         {
             if (value is IComponent)
             {
                 ISite site = ((IComponent) value).Site;
                 if (site == null)
                 {
                     return declaration;
                 }
                 ICollection components = site.Container.Components;
                 StatementContext context2 = new StatementContext();
                 context2.StatementCollection.Populate(components);
                 manager.Context.Push(context2);
                 try
                 {
                     foreach (IComponent component in components)
                     {
                         if ((component != value) && !base.IsSerialized(manager, component))
                         {
                             if (base.GetSerializer(manager, component) != null)
                             {
                                 base.SerializeToExpression(manager, component);
                             }
                             else
                             {
                                 manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { component.GetType().FullName }));
                             }
                         }
                     }
                     manager.Context.Push(value);
                     try
                     {
                         if ((base.GetSerializer(manager, value) != null) && !base.IsSerialized(manager, value))
                         {
                             base.SerializeToExpression(manager, value);
                         }
                         else
                         {
                             manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { value.GetType().FullName }));
                         }
                     }
                     finally
                     {
                         manager.Context.Pop();
                     }
                 }
                 finally
                 {
                     manager.Context.Pop();
                 }
                 CodeMemberMethod method = new CodeMemberMethod {
                     Name = this.InitMethodName,
                     Attributes = MemberAttributes.Private
                 };
                 declaration.Members.Add(method);
                 ArrayList elements = new ArrayList();
                 foreach (object obj2 in components)
                 {
                     if (obj2 != value)
                     {
                         elements.Add(context2.StatementCollection[obj2]);
                     }
                 }
                 if (context2.StatementCollection[value] != null)
                 {
                     elements.Add(context2.StatementCollection[value]);
                 }
                 if (this.ContainerRequired)
                 {
                     this.SerializeContainerDeclaration(manager, method.Statements);
                 }
                 this.SerializeElementsToStatements(elements, method.Statements);
             }
             return declaration;
         }
         finally
         {
             manager.Context.Pop();
             manager.Context.Pop();
             manager.Context.Pop();
         }
     }
     return declaration;
 }
        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);
        }
 private object Serialize(IDesignerSerializationManager manager, object value, bool forceInvariant, bool shouldSerializeInvariant, bool ensureInvariant)
 {
     using (CodeDomSerializerBase.TraceScope("ResourceCodeDomSerializer::Serialize"))
     {
         bool   flag;
         string str3;
         SerializationResourceManager resourceManager = this.GetResourceManager(manager);
         CodeStatementCollection      statements      = (CodeStatementCollection)manager.Context[typeof(CodeStatementCollection)];
         if (!forceInvariant)
         {
             if (!resourceManager.DeclarationAdded)
             {
                 resourceManager.DeclarationAdded = true;
                 RootContext context = manager.Context[typeof(RootContext)] as RootContext;
                 if (statements != null)
                 {
                     CodeExpression[] expressionArray;
                     if (context != null)
                     {
                         string name = manager.GetName(context.Value);
                         expressionArray = new CodeExpression[] { new CodeTypeOfExpression(name) };
                     }
                     else
                     {
                         expressionArray = new CodeExpression[] { new CodePrimitiveExpression(this.ResourceManagerName) };
                     }
                     CodeExpression initExpression = new CodeObjectCreateExpression(typeof(ComponentResourceManager), expressionArray);
                     statements.Add(new CodeVariableDeclarationStatement(typeof(ComponentResourceManager), this.ResourceManagerName, initExpression));
                     base.SetExpression(manager, resourceManager, new CodeVariableReferenceExpression(this.ResourceManagerName));
                     resourceManager.ExpressionAdded = true;
                 }
             }
             else if (!resourceManager.ExpressionAdded)
             {
                 if (base.GetExpression(manager, resourceManager) == null)
                 {
                     base.SetExpression(manager, resourceManager, new CodeVariableReferenceExpression(this.ResourceManagerName));
                 }
                 resourceManager.ExpressionAdded = true;
             }
         }
         ExpressionContext tree = (ExpressionContext)manager.Context[typeof(ExpressionContext)];
         string            str2 = resourceManager.SetValue(manager, tree, value, forceInvariant, shouldSerializeInvariant, ensureInvariant, false);
         if ((value is string) || ((tree != null) && (tree.ExpressionType == typeof(string))))
         {
             flag = false;
             str3 = "GetString";
         }
         else
         {
             flag = true;
             str3 = "GetObject";
         }
         CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression {
             Method = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(this.ResourceManagerName), str3)
         };
         expression.Parameters.Add(new CodePrimitiveExpression(str2));
         if (flag)
         {
             System.Type castType = this.GetCastType(manager, value);
             if (castType != null)
             {
                 return(new CodeCastExpression(castType, expression));
             }
             return(expression);
         }
         return(expression);
     }
 }