internal void ApplyCacheEntry(IDesignerSerializationManager manager, ComponentCache.Entry entry)
 {
     SerializationResourceManager resourceManager = this.GetResourceManager(manager);
     if (entry.Metadata != null)
     {
         foreach (ComponentCache.ResourceEntry entry2 in entry.Metadata)
         {
             resourceManager.SetMetadata(manager, entry2.Name, entry2.Value, entry2.ShouldSerializeValue, true);
         }
     }
     if (entry.Resources != null)
     {
         foreach (ComponentCache.ResourceEntry entry3 in entry.Resources)
         {
             manager.Context.Push(entry3.PropertyDescriptor);
             manager.Context.Push(entry3.ExpressionContext);
             try
             {
                 resourceManager.SetValue(manager, entry3.Name, entry3.Value, entry3.ForceInvariant, entry3.ShouldSerializeValue, entry3.EnsureInvariant, true);
             }
             finally
             {
                 manager.Context.Pop();
                 manager.Context.Pop();
             }
         }
     }
 }
Ejemplo n.º 2
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");
                            }
                        }
                    }
 public void AddResource(ComponentCache.ResourceEntry re)
 {
     if (this.resources == null)
     {
         this.resources = new List<ComponentCache.ResourceEntry>();
     }
     this.resources.Add(re);
 }
 public void AddMetadata(ComponentCache.ResourceEntry re)
 {
     if (this.metadata == null)
     {
         this.metadata = new List<ComponentCache.ResourceEntry>();
     }
     this.metadata.Add(re);
 }
 internal Entry(ComponentCache cache)
 {
     this.cache = cache;
     this.valid = true;
 }
        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);
        }
Ejemplo n.º 7
0
 internal Entry(ComponentCache cache)
 {
     this.cache = cache;
     this.valid = true;
 }
 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;
 }