private object GetPropertyValue(IDesignerSerializationManager manager, PropertyDescriptor property, object value, out bool validValue)
 {
     object obj2 = null;
     validValue = true;
     try
     {
         if (!property.ShouldSerializeValue(value))
         {
             AmbientValueAttribute attribute = (AmbientValueAttribute) property.Attributes[typeof(AmbientValueAttribute)];
             if (attribute != null)
             {
                 return attribute.Value;
             }
             DefaultValueAttribute attribute2 = (DefaultValueAttribute) property.Attributes[typeof(DefaultValueAttribute)];
             if (attribute2 != null)
             {
                 return attribute2.Value;
             }
             validValue = false;
         }
         obj2 = property.GetValue(value);
     }
     catch (Exception exception)
     {
         validValue = false;
         manager.ReportError(System.Design.SR.GetString("SerializerPropertyGenFailed", new object[] { property.Name, exception.Message }));
     }
     return obj2;
 }
コード例 #2
0
        private object GetPropertyValue(IDesignerSerializationManager manager, PropertyDescriptor property, object value, out bool validValue)
        {
            object obj2 = null;

            validValue = true;
            try
            {
                if (!property.ShouldSerializeValue(value))
                {
                    AmbientValueAttribute attribute = (AmbientValueAttribute)property.Attributes[typeof(AmbientValueAttribute)];
                    if (attribute != null)
                    {
                        return(attribute.Value);
                    }
                    DefaultValueAttribute attribute2 = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];
                    if (attribute2 != null)
                    {
                        return(attribute2.Value);
                    }
                    validValue = false;
                }
                obj2 = property.GetValue(value);
            }
            catch (Exception exception)
            {
                validValue = false;
                manager.ReportError(System.Design.SR.GetString("SerializerPropertyGenFailed", new object[] { property.Name, exception.Message }));
            }
            return(obj2);
        }
コード例 #3
0
        /// <summary>
        ///  This method actually performs the serialization.  When the member is serialized
        ///  the necessary statements will be added to the statements collection.
        /// </summary>
        public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
        {
            if (manager is null)
            {
                throw new ArgumentNullException(nameof(manager));
            }
            if (value is null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (!(descriptor is EventDescriptor eventToSerialize))
            {
                throw new ArgumentNullException(nameof(descriptor));
            }
            if (statements is null)
            {
                throw new ArgumentNullException(nameof(statements));
            }

            try
            {
                // If the IEventBindingService is not available, we don't throw - we just don't do anything.
                if (manager.GetService(typeof(IEventBindingService)) is IEventBindingService eventBindings)
                {
                    PropertyDescriptor prop       = eventBindings.GetEventProperty(eventToSerialize);
                    string             methodName = (string)prop.GetValue(value);

                    if (methodName != null)
                    {
                        CodeDomSerializer.Trace("Event {0} bound to {1}", eventToSerialize.Name, methodName);
                        CodeExpression eventTarget = SerializeToExpression(manager, value);
                        CodeDomSerializer.TraceWarningIf(eventTarget is null, "Object has no name and no propery ref in context so we cannot serialize events: {0}", value);
                        if (eventTarget != null)
                        {
                            CodeTypeReference            delegateTypeRef = new CodeTypeReference(eventToSerialize.EventType);
                            CodeDelegateCreateExpression delegateCreate  = new CodeDelegateCreateExpression(delegateTypeRef, _thisRef, methodName);
                            CodeEventReferenceExpression eventRef        = new CodeEventReferenceExpression(eventTarget, eventToSerialize.Name);
                            CodeAttachEventStatement     attach          = new CodeAttachEventStatement(eventRef, delegateCreate);

                            attach.UserData[typeof(Delegate)] = eventToSerialize.EventType;
                            statements.Add(attach);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // Since we usually go through reflection, don't
                // show what our engine does, show what caused
                // the problem.
                //
                if (e is TargetInvocationException)
                {
                    e = e.InnerException;
                }

                manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, eventToSerialize.Name, e.Message), manager));
            }
        }
コード例 #4
0
        /// <summary>
        ///  This method actually performs the serialization.  When the member is serialized
        ///  the necessary statements will be added to the statements collection.
        /// </summary>
        public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
        {
            if (manager is null)
            {
                throw new ArgumentNullException(nameof(manager));
            }

            if (value is null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            if (!(descriptor is PropertyDescriptor propertyToSerialize))
            {
                throw new ArgumentNullException(nameof(descriptor));
            }

            if (statements is null)
            {
                throw new ArgumentNullException(nameof(statements));
            }

            try
            {
                ExtenderProvidedPropertyAttribute exAttr = (ExtenderProvidedPropertyAttribute)propertyToSerialize.Attributes[typeof(ExtenderProvidedPropertyAttribute)];
                bool isExtender        = (exAttr != null && exAttr.Provider != null);
                bool serializeContents = propertyToSerialize.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content);

                CodeDomSerializer.Trace("Serializing property {0}", propertyToSerialize.Name);
                if (serializeContents)
                {
                    SerializeContentProperty(manager, value, propertyToSerialize, isExtender, statements);
                }
                else if (isExtender)
                {
                    SerializeExtenderProperty(manager, value, propertyToSerialize, statements);
                }
                else
                {
                    SerializeNormalProperty(manager, value, propertyToSerialize, statements);
                }
            }
            catch (Exception e)
            {
                // Since we usually go through reflection, don't
                // show what our engine does, show what caused
                // the problem.
                if (e is TargetInvocationException)
                {
                    e = e.InnerException;
                }

                manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, propertyToSerialize.Name, e.Message), manager));
            }
        }
コード例 #5
0
        public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
        {
            EventDescriptor e = descriptor as EventDescriptor;

            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (e == null)
            {
                throw new ArgumentNullException("descriptor");
            }
            if (statements == null)
            {
                throw new ArgumentNullException("statements");
            }
            try
            {
                IEventBindingService service = (IEventBindingService)manager.GetService(typeof(IEventBindingService));
                if (service != null)
                {
                    string methodName = (string)service.GetEventProperty(e).GetValue(value);
                    if (methodName != null)
                    {
                        CodeExpression targetObject = base.SerializeToExpression(manager, value);
                        if (targetObject != null)
                        {
                            CodeTypeReference            delegateType = new CodeTypeReference(e.EventType);
                            CodeDelegateCreateExpression listener     = new CodeDelegateCreateExpression(delegateType, _thisRef, methodName);
                            CodeEventReferenceExpression eventRef     = new CodeEventReferenceExpression(targetObject, e.Name);
                            CodeAttachEventStatement     statement    = new CodeAttachEventStatement(eventRef, listener);
                            statement.UserData[typeof(Delegate)] = e.EventType;
                            statements.Add(statement);
                        }
                    }
                }
            }
            catch (Exception innerException)
            {
                if (innerException is TargetInvocationException)
                {
                    innerException = innerException.InnerException;
                }
                manager.ReportError(System.Design.SR.GetString("SerializerPropertyGenFailed", new object[] { e.Name, innerException.Message }));
            }
        }
 public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
 {
     EventDescriptor e = descriptor as EventDescriptor;
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     if (e == null)
     {
         throw new ArgumentNullException("descriptor");
     }
     if (statements == null)
     {
         throw new ArgumentNullException("statements");
     }
     try
     {
         IEventBindingService service = (IEventBindingService) manager.GetService(typeof(IEventBindingService));
         if (service != null)
         {
             string methodName = (string) service.GetEventProperty(e).GetValue(value);
             if (methodName != null)
             {
                 CodeExpression targetObject = base.SerializeToExpression(manager, value);
                 if (targetObject != null)
                 {
                     CodeTypeReference delegateType = new CodeTypeReference(e.EventType);
                     CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression(delegateType, _thisRef, methodName);
                     CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(targetObject, e.Name);
                     CodeAttachEventStatement statement = new CodeAttachEventStatement(eventRef, listener);
                     statement.UserData[typeof(Delegate)] = e.EventType;
                     statements.Add(statement);
                 }
             }
         }
     }
     catch (Exception innerException)
     {
         if (innerException is TargetInvocationException)
         {
             innerException = innerException.InnerException;
         }
         manager.ReportError(System.Design.SR.GetString("SerializerPropertyGenFailed", new object[] { e.Name, innerException.Message }));
     }
 }
コード例 #7
0
        public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
        {
            PropertyDescriptor property = descriptor as PropertyDescriptor;

            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (property == null)
            {
                throw new ArgumentNullException("descriptor");
            }
            if (statements == null)
            {
                throw new ArgumentNullException("statements");
            }
            try
            {
                ExtenderProvidedPropertyAttribute attribute = (ExtenderProvidedPropertyAttribute)property.Attributes[typeof(ExtenderProvidedPropertyAttribute)];
                bool isExtender = (attribute != null) && (attribute.Provider != null);
                if (property.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content))
                {
                    this.SerializeContentProperty(manager, value, property, isExtender, statements);
                }
                else if (isExtender)
                {
                    this.SerializeExtenderProperty(manager, value, property, statements);
                }
                else
                {
                    this.SerializeNormalProperty(manager, value, property, statements);
                }
            }
            catch (Exception innerException)
            {
                if (innerException is TargetInvocationException)
                {
                    innerException = innerException.InnerException;
                }
                manager.ReportError(System.Design.SR.GetString("SerializerPropertyGenFailed", new object[] { property.Name, innerException.Message }));
            }
        }
 public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
 {
     PropertyDescriptor property = descriptor as PropertyDescriptor;
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     if (property == null)
     {
         throw new ArgumentNullException("descriptor");
     }
     if (statements == null)
     {
         throw new ArgumentNullException("statements");
     }
     try
     {
         ExtenderProvidedPropertyAttribute attribute = (ExtenderProvidedPropertyAttribute) property.Attributes[typeof(ExtenderProvidedPropertyAttribute)];
         bool isExtender = (attribute != null) && (attribute.Provider != null);
         if (property.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content))
         {
             this.SerializeContentProperty(manager, value, property, isExtender, statements);
         }
         else if (isExtender)
         {
             this.SerializeExtenderProperty(manager, value, property, statements);
         }
         else
         {
             this.SerializeNormalProperty(manager, value, property, statements);
         }
     }
     catch (Exception innerException)
     {
         if (innerException is TargetInvocationException)
         {
             innerException = innerException.InnerException;
         }
         manager.ReportError(System.Design.SR.GetString("SerializerPropertyGenFailed", new object[] { property.Name, innerException.Message }));
     }
 }
コード例 #9
0
 private object DeserializeName(IDesignerSerializationManager manager, string name)
 {
     string typeName = null;
     Type objectType = null;
     object obj2 = this.nameTable[name];
     using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::DeserializeName"))
     {
         CodeMemberField field = null;
         CodeObject obj3 = obj2 as CodeObject;
         if (obj3 != null)
         {
             obj2 = null;
             this.nameTable[name] = null;
             if (obj3 is CodeVariableDeclarationStatement)
             {
                 CodeVariableDeclarationStatement statement = (CodeVariableDeclarationStatement) obj3;
                 typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, statement.Type);
             }
             else if (obj3 is CodeMemberField)
             {
                 field = (CodeMemberField) obj3;
                 typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type);
             }
         }
         else
         {
             if (obj2 != null)
             {
                 return obj2;
             }
             IContainer service = (IContainer) manager.GetService(typeof(IContainer));
             if (service != null)
             {
                 IComponent component = service.Components[name];
                 if (component != null)
                 {
                     typeName = component.GetType().FullName;
                     this.nameTable[name] = component;
                 }
             }
         }
         if (name.Equals(this.ContainerName))
         {
             IContainer container2 = (IContainer) manager.GetService(typeof(IContainer));
             if (container2 != null)
             {
                 obj2 = container2;
             }
         }
         else if (typeName != null)
         {
             objectType = manager.GetType(typeName);
             if (objectType == null)
             {
                 manager.ReportError(new SerializationException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeName })));
             }
             else
             {
                 CodeStatementCollection codeObject = (CodeStatementCollection) this.statementTable[name];
                 if ((codeObject != null) && (codeObject.Count > 0))
                 {
                     CodeDomSerializer serializer = (CodeDomSerializer) manager.GetSerializer(objectType, typeof(CodeDomSerializer));
                     if (serializer == null)
                     {
                         manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { objectType.FullName }));
                     }
                     else
                     {
                         try
                         {
                             obj2 = serializer.Deserialize(manager, codeObject);
                             if ((obj2 != null) && (field != null))
                             {
                                 PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj2)["Modifiers"];
                                 if ((descriptor != null) && (descriptor.PropertyType == typeof(MemberAttributes)))
                                 {
                                     MemberAttributes attributes = field.Attributes & MemberAttributes.AccessMask;
                                     descriptor.SetValue(obj2, attributes);
                                 }
                             }
                         }
                         catch (Exception exception)
                         {
                             manager.ReportError(exception);
                         }
                     }
                 }
             }
         }
         this.nameTable[name] = obj2;
     }
     return obj2;
 }
コード例 #10
0
        private void SerializeContentProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, bool isExtender, CodeStatementCollection statements)
        {
            bool              flag;
            object            presetValue = this.GetPropertyValue(manager, property, value, out flag);
            CodeDomSerializer serializer  = null;

            if (presetValue == null)
            {
                string name = manager.GetName(value);
                if (name == null)
                {
                    name = value.GetType().FullName;
                }
                manager.ReportError(System.Design.SR.GetString("SerializerNullNestedProperty", new object[] { name, property.Name }));
            }
            else
            {
                serializer = (CodeDomSerializer)manager.GetSerializer(presetValue.GetType(), typeof(CodeDomSerializer));
                if (serializer != null)
                {
                    CodeExpression targetObject = base.SerializeToExpression(manager, value);
                    if (targetObject != null)
                    {
                        CodeExpression expression = null;
                        if (isExtender)
                        {
                            ExtenderProvidedPropertyAttribute attribute = (ExtenderProvidedPropertyAttribute)property.Attributes[typeof(ExtenderProvidedPropertyAttribute)];
                            CodeExpression expression3 = base.SerializeToExpression(manager, attribute.Provider);
                            CodeExpression expression4 = base.SerializeToExpression(manager, value);
                            if ((expression3 != null) && (expression4 != null))
                            {
                                CodeMethodReferenceExpression expression5 = new CodeMethodReferenceExpression(expression3, "Get" + property.Name);
                                CodeMethodInvokeExpression    expression6 = new CodeMethodInvokeExpression {
                                    Method = expression5
                                };
                                expression6.Parameters.Add(expression4);
                                expression = expression6;
                            }
                        }
                        else
                        {
                            expression = new CodePropertyReferenceExpression(targetObject, property.Name);
                        }
                        if (expression != null)
                        {
                            ExpressionContext context = new ExpressionContext(expression, property.PropertyType, value, presetValue);
                            manager.Context.Push(context);
                            object obj3 = null;
                            try
                            {
                                SerializeAbsoluteContext context2 = (SerializeAbsoluteContext)manager.Context[typeof(SerializeAbsoluteContext)];
                                if (base.IsSerialized(manager, presetValue, context2 != null))
                                {
                                    obj3 = base.GetExpression(manager, presetValue);
                                }
                                else
                                {
                                    obj3 = serializer.Serialize(manager, presetValue);
                                }
                            }
                            finally
                            {
                                manager.Context.Pop();
                            }
                            CodeStatementCollection statements2 = obj3 as CodeStatementCollection;
                            if (statements2 == null)
                            {
                                CodeStatement statement2 = obj3 as CodeStatement;
                                if (statement2 != null)
                                {
                                    statements.Add(statement2);
                                }
                            }
                            else
                            {
                                foreach (CodeStatement statement in statements2)
                                {
                                    statements.Add(statement);
                                }
                            }
                        }
                    }
                }
                else
                {
                    manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { property.PropertyType.FullName }));
                }
            }
        }
コード例 #11
0
        private CodeArrayCreateExpression SerializeArray(IDesignerSerializationManager manager, Type targetType, ICollection array, ICollection valuesToSerialize)
        {
            CodeArrayCreateExpression expression = null;

            using (CodeDomSerializerBase.TraceScope("CollectionCodeDomSerializer::SerializeArray"))
            {
                if (((Array)array).Rank != 1)
                {
                    manager.ReportError(System.Design.SR.GetString("SerializerInvalidArrayRank", new object[] { ((Array)array).Rank.ToString(CultureInfo.InvariantCulture) }));
                    return(expression);
                }
                Type elementType = targetType.GetElementType();
                CodeTypeReference         reference   = new CodeTypeReference(elementType);
                CodeArrayCreateExpression expression2 = new CodeArrayCreateExpression {
                    CreateType = reference
                };
                bool flag = true;
                foreach (object obj2 in valuesToSerialize)
                {
                    if ((obj2 is IComponent) && TypeDescriptor.GetAttributes(obj2).Contains(InheritanceAttribute.InheritedReadOnly))
                    {
                        flag = false;
                        break;
                    }
                    CodeExpression    expression3 = null;
                    ExpressionContext context     = null;
                    ExpressionContext context2    = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
                    if (context2 != null)
                    {
                        context = new ExpressionContext(context2.Expression, elementType, context2.Owner);
                        manager.Context.Push(context);
                    }
                    try
                    {
                        expression3 = base.SerializeToExpression(manager, obj2);
                    }
                    finally
                    {
                        if (context != null)
                        {
                            manager.Context.Pop();
                        }
                    }
                    if (expression3 != null)
                    {
                        if ((obj2 != null) && (obj2.GetType() != elementType))
                        {
                            expression3 = new CodeCastExpression(elementType, expression3);
                        }
                        expression2.Initializers.Add(expression3);
                    }
                    else
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    expression = expression2;
                }
            }
            return(expression);
        }
 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;
 }
コード例 #13
0
        /// <summary>
        ///  This serializes the given property on this object as a content property.
        /// </summary>
        private void SerializeContentProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, bool isExtender, CodeStatementCollection statements)
        {
            CodeDomSerializer.Trace("Property is marked as Visibility.Content.  Recursing.");

            object propertyValue = GetPropertyValue(manager, property, value, out bool validValue);

            // For persist contents objects, we don't just serialize the properties on the object; we
            // serialize everything.
            //
            CodeDomSerializer serializer = null;

            if (propertyValue is null)
            {
                CodeDomSerializer.TraceError("Property {0} is marked as Visibility.Content but it is returning null.", property.Name);

                string name = manager.GetName(value);

                if (name is null)
                {
                    name = value.GetType().FullName;
                }

                manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerNullNestedProperty, name, property.Name), manager));
            }
            else
            {
                serializer = (CodeDomSerializer)manager.GetSerializer(propertyValue.GetType(), typeof(CodeDomSerializer));
                if (serializer != null)
                {
                    // Create a property reference expression and push it on the context stack.
                    // This allows the serializer to gain some context as to what it should be
                    // serializing.
                    CodeExpression target = SerializeToExpression(manager, value);

                    if (target is null)
                    {
                        CodeDomSerializer.TraceWarning("Unable to convert value to expression object");
                    }
                    else
                    {
                        CodeExpression propertyRef = null;

                        if (isExtender)
                        {
                            CodeDomSerializer.Trace("Content property is an extender.");
                            ExtenderProvidedPropertyAttribute exAttr = (ExtenderProvidedPropertyAttribute)property.Attributes[typeof(ExtenderProvidedPropertyAttribute)];

                            // Extender properties are method invokes on a target "extender" object.
                            //
                            CodeExpression extender = SerializeToExpression(manager, exAttr.Provider);
                            CodeExpression extended = SerializeToExpression(manager, value);

                            CodeDomSerializer.TraceWarningIf(extender is null, "Extender object {0} could not be serialized.", manager.GetName(exAttr.Provider));
                            CodeDomSerializer.TraceWarningIf(extended is null, "Extended object {0} could not be serialized.", manager.GetName(value));
                            if (extender != null && extended != null)
                            {
                                CodeMethodReferenceExpression methodRef    = new CodeMethodReferenceExpression(extender, "Get" + property.Name);
                                CodeMethodInvokeExpression    methodInvoke = new CodeMethodInvokeExpression
                                {
                                    Method = methodRef
                                };
                                methodInvoke.Parameters.Add(extended);
                                propertyRef = methodInvoke;
                            }
                        }
                        else
                        {
                            propertyRef = new CodePropertyReferenceExpression(target, property.Name);
                        }

                        if (propertyRef != null)
                        {
                            ExpressionContext tree = new ExpressionContext(propertyRef, property.PropertyType, value, propertyValue);
                            manager.Context.Push(tree);

                            object result = null;

                            try
                            {
                                SerializeAbsoluteContext absolute = (SerializeAbsoluteContext)manager.Context[typeof(SerializeAbsoluteContext)];

                                if (IsSerialized(manager, propertyValue, absolute != null))
                                {
                                    result = GetExpression(manager, propertyValue);
                                }
                                else
                                {
                                    result = serializer.Serialize(manager, propertyValue);
                                }
                            }
                            finally
                            {
                                Debug.Assert(manager.Context.Current == tree, "Serializer added a context it didn't remove.");
                                manager.Context.Pop();
                            }

                            if (result is CodeStatementCollection csc)
                            {
                                foreach (CodeStatement statement in csc)
                                {
                                    statements.Add(statement);
                                }
                            }
                            else
                            {
                                if (result is CodeStatement cs)
                                {
                                    statements.Add(cs);
                                }
                            }
                        }
                    }
                }
                else
                {
                    CodeDomSerializer.TraceError("Property {0} is marked as Visibilty.Content but there is no serializer for it.", property.Name);

                    manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerNoSerializerForComponent, property.PropertyType.FullName), manager));
                }
            }
        }
コード例 #14
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeStatementCollection      statements = null;
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);

            using (CodeDomSerializerBase.TraceScope("ComponentCodeDomSerializer::Serialize"))
            {
                if ((manager == null) || (value == null))
                {
                    throw new ArgumentNullException((manager == null) ? "manager" : "value");
                }
                if (base.IsSerialized(manager, value))
                {
                    return(base.GetExpression(manager, value));
                }
                InheritanceLevel     notInherited = InheritanceLevel.NotInherited;
                InheritanceAttribute attribute    = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)];
                if (attribute != null)
                {
                    notInherited = attribute.InheritanceLevel;
                }
                if (notInherited == InheritanceLevel.InheritedReadOnly)
                {
                    return(statements);
                }
                statements = new CodeStatementCollection();
                CodeTypeDeclaration declaration = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
                RootContext         context     = manager.Context[typeof(RootContext)] as RootContext;
                CodeExpression      left        = null;
                bool flag  = false;
                bool flag2 = true;
                bool flag3 = true;
                bool flag4 = false;
                left = base.GetExpression(manager, value);
                if (left != null)
                {
                    flag  = false;
                    flag2 = false;
                    flag3 = false;
                    IComponent component = value as IComponent;
                    if ((component != null) && (component.Site == null))
                    {
                        ExpressionContext context2 = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
                        if ((context2 == null) || (context2.PresetValue != value))
                        {
                            flag4 = true;
                        }
                    }
                }
                else
                {
                    if (notInherited == InheritanceLevel.NotInherited)
                    {
                        PropertyDescriptor descriptor = properties["GenerateMember"];
                        if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && !((bool)descriptor.GetValue(value)))
                        {
                            flag  = true;
                            flag2 = false;
                        }
                    }
                    else
                    {
                        flag3 = false;
                    }
                    if (context == null)
                    {
                        flag  = true;
                        flag2 = false;
                    }
                }
                manager.Context.Push(value);
                manager.Context.Push(statements);
                try
                {
                    try
                    {
                        string name      = manager.GetName(value);
                        string className = TypeDescriptor.GetClassName(value);
                        if ((flag2 || flag) && (name != null))
                        {
                            if (flag2)
                            {
                                if (notInherited == InheritanceLevel.NotInherited)
                                {
                                    MemberAttributes   @private;
                                    CodeMemberField    field       = new CodeMemberField(className, name);
                                    PropertyDescriptor descriptor2 = properties["Modifiers"];
                                    if (descriptor2 == null)
                                    {
                                        descriptor2 = properties["DefaultModifiers"];
                                    }
                                    if ((descriptor2 != null) && (descriptor2.PropertyType == typeof(MemberAttributes)))
                                    {
                                        @private = (MemberAttributes)descriptor2.GetValue(value);
                                    }
                                    else
                                    {
                                        @private = MemberAttributes.Private;
                                    }
                                    field.Attributes = @private;
                                    declaration.Members.Add(field);
                                }
                                left = new CodeFieldReferenceExpression(context.Expression, name);
                            }
                            else
                            {
                                if (notInherited == InheritanceLevel.NotInherited)
                                {
                                    CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(className, name);
                                    statements.Add(statement);
                                }
                                left = new CodeVariableReferenceExpression(name);
                            }
                        }
                        if (flag3)
                        {
                            CodeExpression  expression2;
                            IContainer      service = manager.GetService(typeof(IContainer)) as IContainer;
                            ConstructorInfo info    = null;
                            if (service != null)
                            {
                                info = CodeDomSerializerBase.GetReflectionTypeHelper(manager, value).GetConstructor(BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, this.GetContainerConstructor(manager), null);
                            }
                            if (info != null)
                            {
                                expression2 = new CodeObjectCreateExpression(className, new CodeExpression[] { base.SerializeToExpression(manager, service) });
                            }
                            else
                            {
                                bool flag5;
                                expression2 = base.SerializeCreationExpression(manager, value, out flag5);
                            }
                            if (expression2 != null)
                            {
                                if (left == null)
                                {
                                    if (flag4)
                                    {
                                        left = expression2;
                                    }
                                }
                                else
                                {
                                    CodeAssignStatement statement2 = new CodeAssignStatement(left, expression2);
                                    statements.Add(statement2);
                                }
                            }
                        }
                        if (left != null)
                        {
                            base.SetExpression(manager, value, left);
                        }
                        if ((left != null) && !flag4)
                        {
                            bool flag6 = value is ISupportInitialize;
                            if (flag6)
                            {
                                string fullName = typeof(ISupportInitialize).FullName;
                                flag6 = manager.GetType(fullName) != null;
                            }
                            Type c = null;
                            if (flag6)
                            {
                                c     = CodeDomSerializerBase.GetReflectionTypeHelper(manager, value);
                                flag6 = CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, typeof(ISupportInitialize)).IsAssignableFrom(c);
                            }
                            bool flag7 = (value is IPersistComponentSettings) && ((IPersistComponentSettings)value).SaveSettings;
                            if (flag7)
                            {
                                string typeName = typeof(IPersistComponentSettings).FullName;
                                flag7 = manager.GetType(typeName) != null;
                            }
                            if (flag7)
                            {
                                c     = c ?? CodeDomSerializerBase.GetReflectionTypeHelper(manager, value);
                                flag7 = CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, typeof(IPersistComponentSettings)).IsAssignableFrom(c);
                            }
                            IDesignerSerializationManager manager2 = (IDesignerSerializationManager)manager.GetService(typeof(IDesignerSerializationManager));
                            if (flag6)
                            {
                                this.SerializeSupportInitialize(manager, statements, left, value, "BeginInit");
                            }
                            base.SerializePropertiesToResources(manager, statements, value, _designTimeFilter);
                            ComponentCache       serviceInstance = (ComponentCache)manager.GetService(typeof(ComponentCache));
                            ComponentCache.Entry entry           = null;
                            if (serviceInstance == null)
                            {
                                IServiceContainer container2 = (IServiceContainer)manager.GetService(typeof(IServiceContainer));
                                if (container2 != null)
                                {
                                    serviceInstance = new ComponentCache(manager);
                                    container2.AddService(typeof(ComponentCache), serviceInstance);
                                }
                            }
                            else if (((manager == manager2) && (serviceInstance != null)) && serviceInstance.Enabled)
                            {
                                entry = serviceInstance[value];
                            }
                            if ((entry == null) || entry.Tracking)
                            {
                                if (entry == null)
                                {
                                    entry = new ComponentCache.Entry(serviceInstance);
                                    ComponentCache.Entry entryAll = null;
                                    entryAll = serviceInstance.GetEntryAll(value);
                                    if (((entryAll != null) && (entryAll.Dependencies != null)) && (entryAll.Dependencies.Count > 0))
                                    {
                                        foreach (object obj2 in entryAll.Dependencies)
                                        {
                                            entry.AddDependency(obj2);
                                        }
                                    }
                                }
                                entry.Component = value;
                                bool flag8 = manager == manager2;
                                entry.Valid = flag8 && this.CanCacheComponent(manager, value, properties);
                                if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled)
                                {
                                    manager.Context.Push(serviceInstance);
                                    manager.Context.Push(entry);
                                }
                                try
                                {
                                    entry.Statements = new CodeStatementCollection();
                                    base.SerializeProperties(manager, entry.Statements, value, _runTimeFilter);
                                    base.SerializeEvents(manager, entry.Statements, value, null);
                                    foreach (CodeStatement statement3 in entry.Statements)
                                    {
                                        if (statement3 is CodeVariableDeclarationStatement)
                                        {
                                            entry.Tracking = true;
                                            break;
                                        }
                                    }
                                    if (entry.Statements.Count > 0)
                                    {
                                        entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));
                                        entry.Statements.Insert(0, new CodeCommentStatement(name));
                                        entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));
                                        if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled)
                                        {
                                            serviceInstance[value] = entry;
                                        }
                                    }
                                }
                                finally
                                {
                                    if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled)
                                    {
                                        manager.Context.Pop();
                                        manager.Context.Pop();
                                    }
                                }
                            }
                            else if (((entry.Resources != null) || (entry.Metadata != null)) && ((serviceInstance != null) && serviceInstance.Enabled))
                            {
                                ResourceCodeDomSerializer.Default.ApplyCacheEntry(manager, entry);
                            }
                            statements.AddRange(entry.Statements);
                            if (flag7)
                            {
                                this.SerializeLoadComponentSettings(manager, statements, left, value);
                            }
                            if (flag6)
                            {
                                this.SerializeSupportInitialize(manager, statements, left, value, "EndInit");
                            }
                        }
                        return(statements);
                    }
                    catch (CheckoutException)
                    {
                        throw;
                    }
                    catch (Exception exception)
                    {
                        manager.ReportError(exception);
                    }
                    return(statements);
                }
                finally
                {
                    manager.Context.Pop();
                    manager.Context.Pop();
                }
            }
            return(statements);
        }
 private bool ResolveName(IDesignerSerializationManager manager, string name, bool canInvokeManager)
 {
     bool flag = false;
     CodeDomSerializerBase.OrderedCodeStatementCollection codeObject = this._statementsTable[name] as CodeDomSerializerBase.OrderedCodeStatementCollection;
     object[] objArray = (object[]) this._objectState[name];
     if (name.IndexOf('.') > 0)
     {
         string outerComponent = null;
         IComponent instance = this.ResolveNestedName(manager, name, ref outerComponent);
         if ((instance != null) && (outerComponent != null))
         {
             manager.SetName(instance, name);
             this.ResolveName(manager, outerComponent, canInvokeManager);
         }
     }
     if (codeObject == null)
     {
         flag = this._statementsTable[name] != null;
         if (!flag)
         {
             if (this._expressions.ContainsKey(name))
             {
                 ArrayList list2 = this._expressions[name];
                 foreach (CodeExpression expression2 in list2)
                 {
                     object obj3 = base.DeserializeExpression(manager, name, expression2);
                     if (((obj3 != null) && !flag) && (canInvokeManager && (manager.GetInstance(name) == null)))
                     {
                         manager.SetName(obj3, name);
                         flag = true;
                     }
                 }
             }
             if (!flag && canInvokeManager)
             {
                 flag = manager.GetInstance(name) != null;
             }
             if ((flag && (objArray != null)) && (objArray[2] != null))
             {
                 this.DeserializeDefaultProperties(manager, name, objArray[2]);
             }
             if ((flag && (objArray != null)) && (objArray[3] != null))
             {
                 this.DeserializeDesignTimeProperties(manager, name, objArray[3]);
             }
             if ((flag && (objArray != null)) && (objArray[4] != null))
             {
                 this.DeserializeEventResets(manager, name, objArray[4]);
             }
             if ((flag && (objArray != null)) && (objArray[5] != null))
             {
                 DeserializeModifier(manager, name, objArray[5]);
             }
         }
         if (!flag && (flag || canInvokeManager))
         {
             manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("CodeDomComponentSerializationServiceDeserializationError", new object[] { name }), manager));
         }
         return flag;
     }
     this._objectState[name] = null;
     this._statementsTable[name] = null;
     string typeName = null;
     foreach (CodeStatement statement in codeObject)
     {
         CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement;
         if (statement2 != null)
         {
             typeName = statement2.Type.BaseType;
             break;
         }
     }
     if (typeName != null)
     {
         Type valueType = manager.GetType(typeName);
         if (valueType == null)
         {
             manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeName }), manager));
             goto Label_01DA;
         }
         if ((codeObject == null) || (codeObject.Count <= 0))
         {
             goto Label_01DA;
         }
         CodeDomSerializer serializer = base.GetSerializer(manager, valueType);
         if (serializer == null)
         {
             manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { valueType.FullName }), manager));
             goto Label_01DA;
         }
         try
         {
             object obj2 = serializer.Deserialize(manager, codeObject);
             flag = obj2 != null;
             if (flag)
             {
                 this._statementsTable[name] = obj2;
             }
             goto Label_01DA;
         }
         catch (Exception exception)
         {
             manager.ReportError(exception);
             goto Label_01DA;
         }
     }
     foreach (CodeStatement statement3 in codeObject)
     {
         base.DeserializeStatement(manager, statement3);
     }
     flag = true;
 Label_01DA:
     if ((objArray != null) && (objArray[2] != null))
     {
         this.DeserializeDefaultProperties(manager, name, objArray[2]);
     }
     if ((objArray != null) && (objArray[3] != null))
     {
         this.DeserializeDesignTimeProperties(manager, name, objArray[3]);
     }
     if ((objArray != null) && (objArray[4] != null))
     {
         this.DeserializeEventResets(manager, name, objArray[4]);
     }
     if ((objArray != null) && (objArray[5] != null))
     {
         DeserializeModifier(manager, name, objArray[5]);
     }
     if (!this._expressions.ContainsKey(name))
     {
         return flag;
     }
     ArrayList list = this._expressions[name];
     foreach (CodeExpression expression in list)
     {
         base.DeserializeExpression(manager, name, expression);
     }
     this._expressions.Remove(name);
     return true;
 }
コード例 #16
0
        /// <include file='doc\CollectionCodeDomSerializer.uex' path='docs/doc[@for="CollectionCodeDomSerializer.SerializeArray"]/*' />
        /// <devdoc>
        ///     Serializes the given array.
        /// </devdoc>
        private object SerializeArray(IDesignerSerializationManager manager, CodePropertyReferenceExpression propRef, Type asType, Array array, object targetObject)
        {
            object result = null;

            Debug.WriteLineIf(traceSerialization.TraceVerbose, "CollectionCodeDomSerializer::SerializeArray");
            Debug.Indent();

            if (array.Rank != 1)
            {
                Debug.WriteLineIf(traceSerialization.TraceError, "*** Cannot serialize arrays with rank > 1. ***");
                manager.ReportError(SR.GetString(SR.SerializerInvalidArrayRank, array.Rank.ToString()));
            }
            else
            {
                // For an array, we need an array create expression.  First, get the array type
                //
                Type elementType = null;

                if (asType != null)
                {
                    elementType = asType;
                }
                else
                {
                    elementType = array.GetType().GetElementType();
                }

                CodeTypeReference elementTypeRef = new CodeTypeReference(elementType);

                Debug.WriteLineIf(traceSerialization.TraceVerbose, "Array type: " + elementType.Name);
                Debug.WriteLineIf(traceSerialization.TraceVerbose, "Length:" + array.Length.ToString());

                // Now create an ArrayCreateExpression, and fill its initializers.
                //
                CodeArrayCreateExpression arrayCreate = new CodeArrayCreateExpression();
                arrayCreate.CreateType = elementTypeRef;
                bool arrayOk = true;

                ICollection collection = array;

                bool       isTargetInherited = false;
                IComponent comp = targetObject as IComponent;
                if (comp != null)
                {
                    InheritanceAttribute ia = (InheritanceAttribute)TypeDescriptor.GetAttributes(comp)[typeof(InheritanceAttribute)];
                    isTargetInherited = (ia != null && ia.InheritanceLevel == InheritanceLevel.Inherited);
                }

                if (isTargetInherited)
                {
                    InheritedPropertyDescriptor inheritedDesc = manager.Context[typeof(PropertyDescriptor)] as InheritedPropertyDescriptor;
                    if (inheritedDesc != null)
                    {
                        collection = GetCollectionDelta(inheritedDesc.OriginalValue as ICollection, array);
                    }
                }

                CodeValueExpression codeValue = new CodeValueExpression(null, collection, elementType);
                manager.Context.Push(codeValue);

                try {
                    foreach (object o in collection)
                    {
                        // If this object is being privately inherited, it cannot be inside
                        // this collection.  Since we're writing an entire array here, we
                        // cannot write any of it.
                        //
                        if (o is IComponent && TypeDescriptor.GetAttributes(o).Contains(InheritanceAttribute.InheritedReadOnly))
                        {
                            arrayOk = false;
                            break;
                        }

                        object expression = SerializeToExpression(manager, o);
                        if (expression is CodeExpression)
                        {
                            arrayCreate.Initializers.Add((CodeExpression)expression);
                        }
                        else
                        {
                            arrayOk = false;
                            break;
                        }
                    }
                }
                finally {
                    manager.Context.Pop();
                }

                // if we weren't given a property, we're done.  Otherwise, we must create an assign statement for
                // the property.
                //
                if (arrayOk)
                {
                    if (propRef != null)
                    {
                        result = new CodeAssignStatement(propRef, arrayCreate);
                    }
                    else
                    {
                        result = arrayCreate;
                    }
                }
            }

            Debug.Unindent();
            return(result);
        }
コード例 #17
0
 protected object DeserializeExpression(IDesignerSerializationManager manager, string name, CodeExpression expression)
 {
     object instance = expression;
     using (TraceScope("CodeDomSerializerBase::DeserializeExpression"))
     {
         while (instance != null)
         {
             CodePrimitiveExpression expression2 = instance as CodePrimitiveExpression;
             if (expression2 != null)
             {
                 return expression2.Value;
             }
             CodePropertyReferenceExpression propertyReferenceEx = instance as CodePropertyReferenceExpression;
             if (propertyReferenceEx != null)
             {
                 return this.DeserializePropertyReferenceExpression(manager, propertyReferenceEx, true);
             }
             if (instance is CodeThisReferenceExpression)
             {
                 RootContext context = (RootContext) manager.Context[typeof(RootContext)];
                 if (context != null)
                 {
                     instance = context.Value;
                 }
                 else
                 {
                     IDesignerHost host = manager.GetService(typeof(IDesignerHost)) as IDesignerHost;
                     if (host != null)
                     {
                         instance = host.RootComponent;
                     }
                 }
                 if (instance == null)
                 {
                     Error(manager, System.Design.SR.GetString("SerializerNoRootExpression"), "SerializerNoRootExpression");
                 }
                 return instance;
             }
             CodeTypeReferenceExpression expression4 = instance as CodeTypeReferenceExpression;
             if (expression4 != null)
             {
                 return manager.GetType(GetTypeNameFromCodeTypeReference(manager, expression4.Type));
             }
             CodeObjectCreateExpression expression5 = instance as CodeObjectCreateExpression;
             if (expression5 != null)
             {
                 instance = null;
                 Type c = manager.GetType(GetTypeNameFromCodeTypeReference(manager, expression5.CreateType));
                 if (c != null)
                 {
                     object[] parameters = new object[expression5.Parameters.Count];
                     bool flag = true;
                     for (int i = 0; i < parameters.Length; i++)
                     {
                         parameters[i] = this.DeserializeExpression(manager, null, expression5.Parameters[i]);
                         if (parameters[i] is CodeExpression)
                         {
                             if ((typeof(Delegate).IsAssignableFrom(c) && (parameters.Length == 1)) && (parameters[i] is CodeMethodReferenceExpression))
                             {
                                 CodeMethodReferenceExpression expression19 = (CodeMethodReferenceExpression) parameters[i];
                                 if (!(expression19.TargetObject is CodeThisReferenceExpression))
                                 {
                                     object obj3 = this.DeserializeExpression(manager, null, expression19.TargetObject);
                                     if (!(obj3 is CodeExpression))
                                     {
                                         MethodInfo method = c.GetMethod("Invoke");
                                         if (method != null)
                                         {
                                             ParameterInfo[] infoArray = method.GetParameters();
                                             Type[] types = new Type[infoArray.Length];
                                             for (int j = 0; j < types.Length; j++)
                                             {
                                                 types[j] = infoArray[i].ParameterType;
                                             }
                                             if (GetReflectionTypeHelper(manager, obj3).GetMethod(expression19.MethodName, types) != null)
                                             {
                                                 MethodInfo info2 = obj3.GetType().GetMethod(expression19.MethodName, types);
                                                 instance = Activator.CreateInstance(c, new object[] { obj3, info2.MethodHandle.GetFunctionPointer() });
                                             }
                                         }
                                     }
                                 }
                             }
                             flag = false;
                             break;
                         }
                     }
                     if (flag)
                     {
                         instance = this.DeserializeInstance(manager, c, parameters, name, name != null);
                     }
                     return instance;
                 }
                 Error(manager, System.Design.SR.GetString("SerializerTypeNotFound", new object[] { expression5.CreateType.BaseType }), "SerializerTypeNotFound");
                 return instance;
             }
             CodeArgumentReferenceExpression expression6 = instance as CodeArgumentReferenceExpression;
             if (expression6 != null)
             {
                 instance = manager.GetInstance(expression6.ParameterName);
                 if (instance == null)
                 {
                     Error(manager, System.Design.SR.GetString("SerializerUndeclaredName", new object[] { expression6.ParameterName }), "SerializerUndeclaredName");
                 }
                 return instance;
             }
             CodeFieldReferenceExpression expression7 = instance as CodeFieldReferenceExpression;
             if (expression7 != null)
             {
                 object obj4 = this.DeserializeExpression(manager, null, expression7.TargetObject);
                 if ((obj4 != null) && !(obj4 is CodeExpression))
                 {
                     FieldInfo field;
                     object obj6;
                     RootContext context2 = (RootContext) manager.Context[typeof(RootContext)];
                     if ((context2 != null) && (context2.Value == obj4))
                     {
                         object obj5 = manager.GetInstance(expression7.FieldName);
                         if (obj5 != null)
                         {
                             return obj5;
                         }
                         Error(manager, System.Design.SR.GetString("SerializerUndeclaredName", new object[] { expression7.FieldName }), "SerializerUndeclaredName");
                         return instance;
                     }
                     Type type = obj4 as Type;
                     if (type != null)
                     {
                         obj6 = null;
                         field = GetReflectionTypeFromTypeHelper(manager, type).GetField(expression7.FieldName, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
                     }
                     else
                     {
                         obj6 = obj4;
                         field = GetReflectionTypeHelper(manager, obj4).GetField(expression7.FieldName, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance);
                     }
                     if (field != null)
                     {
                         return field.GetValue(obj6);
                     }
                     CodePropertyReferenceExpression expression20 = new CodePropertyReferenceExpression {
                         TargetObject = expression7.TargetObject,
                         PropertyName = expression7.FieldName
                     };
                     instance = this.DeserializePropertyReferenceExpression(manager, expression20, false);
                     if (instance == expression7)
                     {
                         Error(manager, System.Design.SR.GetString("SerializerUndeclaredName", new object[] { expression7.FieldName }), "SerializerUndeclaredName");
                     }
                     return instance;
                 }
                 Error(manager, System.Design.SR.GetString("SerializerFieldTargetEvalFailed", new object[] { expression7.FieldName }), "SerializerFieldTargetEvalFailed");
                 return instance;
             }
             CodeMethodInvokeExpression expression8 = instance as CodeMethodInvokeExpression;
             if (expression8 != null)
             {
                 object component = this.DeserializeExpression(manager, null, expression8.Method.TargetObject);
                 if (component != null)
                 {
                     object[] args = new object[expression8.Parameters.Count];
                     bool flag2 = true;
                     for (int k = 0; k < args.Length; k++)
                     {
                         args[k] = this.DeserializeExpression(manager, null, expression8.Parameters[k]);
                         if (args[k] is CodeExpression)
                         {
                             flag2 = false;
                             break;
                         }
                     }
                     if (flag2)
                     {
                         IComponentChangeService service = (IComponentChangeService) manager.GetService(typeof(IComponentChangeService));
                         Type type3 = component as Type;
                         if (type3 != null)
                         {
                             return GetReflectionTypeFromTypeHelper(manager, type3).InvokeMember(expression8.Method.MethodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, args, null, null, null);
                         }
                         if (service != null)
                         {
                             service.OnComponentChanging(component, null);
                         }
                         try
                         {
                             instance = GetReflectionTypeHelper(manager, component).InvokeMember(expression8.Method.MethodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, component, args, null, null, null);
                         }
                         catch (MissingMethodException)
                         {
                             CodeCastExpression targetObject = expression8.Method.TargetObject as CodeCastExpression;
                             if (targetObject == null)
                             {
                                 throw;
                             }
                             Type type4 = manager.GetType(GetTypeNameFromCodeTypeReference(manager, targetObject.TargetType));
                             if ((type4 == null) || !type4.IsInterface)
                             {
                                 throw;
                             }
                             instance = GetReflectionTypeFromTypeHelper(manager, type4).InvokeMember(expression8.Method.MethodName, BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, component, args, null, null, null);
                         }
                         if (service != null)
                         {
                             service.OnComponentChanged(component, null, null, null);
                         }
                         return instance;
                     }
                     if ((args.Length == 1) && (args[0] is CodeDelegateCreateExpression))
                     {
                         string methodName = expression8.Method.MethodName;
                         if (methodName.StartsWith("add_"))
                         {
                             methodName = methodName.Substring(4);
                             this.DeserializeAttachEventStatement(manager, new CodeAttachEventStatement(expression8.Method.TargetObject, methodName, (CodeExpression) args[0]));
                             instance = null;
                         }
                     }
                 }
                 return instance;
             }
             CodeVariableReferenceExpression expression9 = instance as CodeVariableReferenceExpression;
             if (expression9 != null)
             {
                 instance = manager.GetInstance(expression9.VariableName);
                 if (instance == null)
                 {
                     Error(manager, System.Design.SR.GetString("SerializerUndeclaredName", new object[] { expression9.VariableName }), "SerializerUndeclaredName");
                 }
                 return instance;
             }
             CodeCastExpression expression10 = instance as CodeCastExpression;
             if (expression10 != null)
             {
                 instance = this.DeserializeExpression(manager, name, expression10.Expression);
                 IConvertible convertible = instance as IConvertible;
                 if (convertible != null)
                 {
                     Type conversionType = manager.GetType(GetTypeNameFromCodeTypeReference(manager, expression10.TargetType));
                     if (conversionType != null)
                     {
                         instance = convertible.ToType(conversionType, null);
                     }
                 }
                 return instance;
             }
             if (instance is CodeBaseReferenceExpression)
             {
                 RootContext context3 = (RootContext) manager.Context[typeof(RootContext)];
                 if (context3 != null)
                 {
                     return context3.Value;
                 }
                 return null;
             }
             CodeArrayCreateExpression expression11 = instance as CodeArrayCreateExpression;
             if (expression11 != null)
             {
                 Type type6 = manager.GetType(GetTypeNameFromCodeTypeReference(manager, expression11.CreateType));
                 Array array = null;
                 if (type6 != null)
                 {
                     if (expression11.Initializers.Count > 0)
                     {
                         ArrayList list = new ArrayList(expression11.Initializers.Count);
                         foreach (CodeExpression expression22 in expression11.Initializers)
                         {
                             try
                             {
                                 object o = this.DeserializeExpression(manager, null, expression22);
                                 if (!(o is CodeExpression))
                                 {
                                     if (!type6.IsInstanceOfType(o))
                                     {
                                         o = Convert.ChangeType(o, type6, CultureInfo.InvariantCulture);
                                     }
                                     list.Add(o);
                                 }
                             }
                             catch (Exception exception)
                             {
                                 manager.ReportError(exception);
                             }
                         }
                         array = Array.CreateInstance(type6, list.Count);
                         list.CopyTo(array, 0);
                     }
                     else if (expression11.SizeExpression != null)
                     {
                         IConvertible convertible2 = this.DeserializeExpression(manager, name, expression11.SizeExpression) as IConvertible;
                         if (convertible2 != null)
                         {
                             int length = convertible2.ToInt32(null);
                             array = Array.CreateInstance(type6, length);
                         }
                     }
                     else
                     {
                         array = Array.CreateInstance(type6, expression11.Size);
                     }
                 }
                 else
                 {
                     Error(manager, System.Design.SR.GetString("SerializerTypeNotFound", new object[] { expression11.CreateType.BaseType }), "SerializerTypeNotFound");
                 }
                 instance = array;
                 if ((instance != null) && (name != null))
                 {
                     manager.SetName(instance, name);
                 }
                 return instance;
             }
             CodeArrayIndexerExpression expression12 = instance as CodeArrayIndexerExpression;
             if (expression12 != null)
             {
                 instance = null;
                 Array array2 = this.DeserializeExpression(manager, name, expression12.TargetObject) as Array;
                 if (array2 != null)
                 {
                     int[] indices = new int[expression12.Indices.Count];
                     bool flag3 = true;
                     for (int m = 0; m < indices.Length; m++)
                     {
                         IConvertible convertible3 = this.DeserializeExpression(manager, name, expression12.Indices[m]) as IConvertible;
                         if (convertible3 != null)
                         {
                             indices[m] = convertible3.ToInt32(null);
                         }
                         else
                         {
                             flag3 = false;
                             break;
                         }
                     }
                     if (flag3)
                     {
                         instance = array2.GetValue(indices);
                     }
                 }
                 return instance;
             }
             CodeBinaryOperatorExpression expression13 = instance as CodeBinaryOperatorExpression;
             if (expression13 != null)
             {
                 object obj10 = this.DeserializeExpression(manager, null, expression13.Left);
                 object obj11 = this.DeserializeExpression(manager, null, expression13.Right);
                 instance = obj10;
                 IConvertible left = obj10 as IConvertible;
                 IConvertible right = obj11 as IConvertible;
                 if ((left != null) && (right != null))
                 {
                     instance = this.ExecuteBinaryExpression(left, right, expression13.Operator);
                 }
                 return instance;
             }
             CodeDelegateInvokeExpression expression14 = instance as CodeDelegateInvokeExpression;
             if (expression14 != null)
             {
                 Delegate delegate2 = this.DeserializeExpression(manager, null, expression14.TargetObject) as Delegate;
                 if (delegate2 != null)
                 {
                     object[] objArray3 = new object[expression14.Parameters.Count];
                     bool flag4 = true;
                     for (int n = 0; n < objArray3.Length; n++)
                     {
                         objArray3[n] = this.DeserializeExpression(manager, null, expression14.Parameters[n]);
                         if (objArray3[n] is CodeExpression)
                         {
                             flag4 = false;
                             break;
                         }
                     }
                     if (flag4)
                     {
                         delegate2.DynamicInvoke(objArray3);
                     }
                 }
                 return instance;
             }
             CodeDirectionExpression expression15 = instance as CodeDirectionExpression;
             if (expression15 != null)
             {
                 return this.DeserializeExpression(manager, name, expression15.Expression);
             }
             CodeIndexerExpression expression16 = instance as CodeIndexerExpression;
             if (expression16 != null)
             {
                 instance = null;
                 object target = this.DeserializeExpression(manager, null, expression16.TargetObject);
                 if (target != null)
                 {
                     object[] objArray4 = new object[expression16.Indices.Count];
                     bool flag5 = true;
                     for (int num7 = 0; num7 < objArray4.Length; num7++)
                     {
                         objArray4[num7] = this.DeserializeExpression(manager, null, expression16.Indices[num7]);
                         if (objArray4[num7] is CodeExpression)
                         {
                             flag5 = false;
                             break;
                         }
                     }
                     if (flag5)
                     {
                         instance = GetReflectionTypeHelper(manager, target).InvokeMember("Item", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, target, objArray4, null, null, null);
                     }
                 }
                 return instance;
             }
             if (instance is CodeSnippetExpression)
             {
                 return null;
             }
             CodeParameterDeclarationExpression expression17 = instance as CodeParameterDeclarationExpression;
             if (expression17 != null)
             {
                 return manager.GetType(GetTypeNameFromCodeTypeReference(manager, expression17.Type));
             }
             CodeTypeOfExpression expression18 = instance as CodeTypeOfExpression;
             if (expression18 != null)
             {
                 string typeNameFromCodeTypeReference = GetTypeNameFromCodeTypeReference(manager, expression18.Type);
                 for (int num8 = 0; num8 < expression18.Type.ArrayRank; num8++)
                 {
                     typeNameFromCodeTypeReference = typeNameFromCodeTypeReference + "[]";
                 }
                 instance = manager.GetType(typeNameFromCodeTypeReference);
                 if (instance == null)
                 {
                     Error(manager, System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeNameFromCodeTypeReference }), "SerializerTypeNotFound");
                 }
                 return instance;
             }
             if (((instance is CodeEventReferenceExpression) || (instance is CodeMethodReferenceExpression)) || !(instance is CodeDelegateCreateExpression))
             {
             }
             return instance;
         }
     }
     return instance;
 }
コード例 #18
0
 internal static void FillStatementTable(IDesignerSerializationManager manager, IDictionary table, Dictionary<string, string> names, CodeStatementCollection statements, string className)
 {
     using (TraceScope("CodeDomSerializerBase::FillStatementTable"))
     {
         CodeExpressionStatement statement4 = null;
         foreach (CodeStatement statement6 in statements)
         {
             CodeCastExpression expression2;
             CodeExpression left = null;
             CodeAssignStatement statement = statement6 as CodeAssignStatement;
             if (statement != null)
             {
                 left = statement.Left;
             }
             else
             {
                 CodeAttachEventStatement statement2 = statement6 as CodeAttachEventStatement;
                 if (statement2 != null)
                 {
                     left = statement2.Event;
                 }
                 else
                 {
                     CodeRemoveEventStatement statement3 = statement6 as CodeRemoveEventStatement;
                     if (statement3 != null)
                     {
                         left = statement3.Event;
                     }
                     else
                     {
                         statement4 = statement6 as CodeExpressionStatement;
                         if (statement4 != null)
                         {
                             left = statement4.Expression;
                         }
                         else
                         {
                             CodeVariableDeclarationStatement statement5 = statement6 as CodeVariableDeclarationStatement;
                             if (statement5 != null)
                             {
                                 AddStatement(table, statement5.Name, statement5);
                                 if (((names != null) && (statement5.Type != null)) && !string.IsNullOrEmpty(statement5.Type.BaseType))
                                 {
                                     names[statement5.Name] = GetTypeNameFromCodeTypeReference(manager, statement5.Type);
                                 }
                                 left = null;
                             }
                         }
                     }
                 }
             }
             if (left == null)
             {
                 continue;
             }
         Label_00E4:
             while ((expression2 = left as CodeCastExpression) != null)
             {
                 left = expression2.Expression;
             }
             CodeDelegateCreateExpression expression3 = left as CodeDelegateCreateExpression;
             if (expression3 != null)
             {
                 left = expression3.TargetObject;
                 goto Label_00E4;
             }
             CodeDelegateInvokeExpression expression4 = left as CodeDelegateInvokeExpression;
             if (expression4 != null)
             {
                 left = expression4.TargetObject;
                 goto Label_00E4;
             }
             CodeDirectionExpression expression5 = left as CodeDirectionExpression;
             if (expression5 != null)
             {
                 left = expression5.Expression;
                 goto Label_00E4;
             }
             CodeEventReferenceExpression expression6 = left as CodeEventReferenceExpression;
             if (expression6 != null)
             {
                 left = expression6.TargetObject;
                 goto Label_00E4;
             }
             CodeMethodInvokeExpression expression7 = left as CodeMethodInvokeExpression;
             if (expression7 != null)
             {
                 left = expression7.Method;
                 goto Label_00E4;
             }
             CodeMethodReferenceExpression expression8 = left as CodeMethodReferenceExpression;
             if (expression8 != null)
             {
                 left = expression8.TargetObject;
                 goto Label_00E4;
             }
             CodeArrayIndexerExpression expression9 = left as CodeArrayIndexerExpression;
             if (expression9 != null)
             {
                 left = expression9.TargetObject;
                 goto Label_00E4;
             }
             CodeFieldReferenceExpression expression10 = left as CodeFieldReferenceExpression;
             if (expression10 != null)
             {
                 bool flag = false;
                 if (expression10.TargetObject is CodeThisReferenceExpression)
                 {
                     Type objectType = GetType(manager, expression10.FieldName, names);
                     if (objectType != null)
                     {
                         CodeDomSerializer serializer = manager.GetSerializer(objectType, typeof(CodeDomSerializer)) as CodeDomSerializer;
                         if (serializer != null)
                         {
                             string str = serializer.GetTargetComponentName(statement6, left, objectType);
                             if (!string.IsNullOrEmpty(str))
                             {
                                 AddStatement(table, str, statement6);
                                 flag = true;
                             }
                         }
                     }
                     if (!flag)
                     {
                         AddStatement(table, expression10.FieldName, statement6);
                     }
                     continue;
                 }
                 left = expression10.TargetObject;
                 goto Label_00E4;
             }
             CodePropertyReferenceExpression expression11 = left as CodePropertyReferenceExpression;
             if (expression11 != null)
             {
                 if ((expression11.TargetObject is CodeThisReferenceExpression) && ((names == null) || names.ContainsKey(expression11.PropertyName)))
                 {
                     AddStatement(table, expression11.PropertyName, statement6);
                     continue;
                 }
                 left = expression11.TargetObject;
                 goto Label_00E4;
             }
             CodeVariableReferenceExpression expression12 = left as CodeVariableReferenceExpression;
             if (expression12 != null)
             {
                 bool flag2 = false;
                 if (names != null)
                 {
                     Type type2 = GetType(manager, expression12.VariableName, names);
                     if (type2 != null)
                     {
                         CodeDomSerializer serializer2 = manager.GetSerializer(type2, typeof(CodeDomSerializer)) as CodeDomSerializer;
                         if (serializer2 != null)
                         {
                             string str2 = serializer2.GetTargetComponentName(statement6, left, type2);
                             if (!string.IsNullOrEmpty(str2))
                             {
                                 AddStatement(table, str2, statement6);
                                 flag2 = true;
                             }
                         }
                     }
                 }
                 else
                 {
                     AddStatement(table, expression12.VariableName, statement6);
                     flag2 = true;
                 }
                 if (!flag2)
                 {
                     manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("SerializerUndeclaredName", new object[] { expression12.VariableName }), manager));
                 }
             }
             else if (((left is CodeThisReferenceExpression) || (left is CodeBaseReferenceExpression)) && (className != null))
             {
                 AddStatement(table, className, statement6);
             }
         }
     }
 }
コード例 #19
0
 protected CodeExpression SerializeToExpression(IDesignerSerializationManager manager, object value)
 {
     CodeExpression legacyExpression = null;
     using (TraceScope("SerializeToExpression"))
     {
         if (value != null)
         {
             if (this.IsSerialized(manager, value))
             {
                 legacyExpression = this.GetExpression(manager, value);
             }
             else
             {
                 legacyExpression = this.GetLegacyExpression(manager, value);
                 if (legacyExpression != null)
                 {
                     this.SetExpression(manager, value, legacyExpression);
                 }
             }
         }
         if (legacyExpression != null)
         {
             return legacyExpression;
         }
         CodeDomSerializer serializer = this.GetSerializer(manager, value);
         if (serializer != null)
         {
             CodeStatementCollection statements = null;
             if (value != null)
             {
                 this.SetLegacyExpression(manager, value);
                 StatementContext context = manager.Context[typeof(StatementContext)] as StatementContext;
                 if (context != null)
                 {
                     statements = context.StatementCollection[value];
                 }
                 if (statements != null)
                 {
                     manager.Context.Push(statements);
                 }
             }
             object obj2 = null;
             try
             {
                 obj2 = serializer.Serialize(manager, value);
             }
             finally
             {
                 if (statements != null)
                 {
                     manager.Context.Pop();
                 }
             }
             legacyExpression = obj2 as CodeExpression;
             if ((legacyExpression == null) && (value != null))
             {
                 legacyExpression = this.GetExpression(manager, value);
             }
             CodeStatementCollection statements2 = obj2 as CodeStatementCollection;
             if (statements2 == null)
             {
                 CodeStatement statement = obj2 as CodeStatement;
                 if (statement != null)
                 {
                     statements2 = new CodeStatementCollection();
                     statements2.Add(statement);
                 }
             }
             if (statements2 != null)
             {
                 if (statements == null)
                 {
                     statements = manager.Context[typeof(CodeStatementCollection)] as CodeStatementCollection;
                 }
                 if (statements != null)
                 {
                     statements.AddRange(statements2);
                     return legacyExpression;
                 }
                 string name = "(null)";
                 if (value != null)
                 {
                     name = manager.GetName(value);
                     if (name == null)
                     {
                         name = value.GetType().Name;
                     }
                 }
                 manager.ReportError(System.Design.SR.GetString("SerializerLostStatements", new object[] { name }));
             }
             return legacyExpression;
         }
         manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { value.GetType().FullName }));
     }
     return legacyExpression;
 }
コード例 #20
0
 protected void DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
 {
     using (TraceScope("CodeDomSerializerBase::DeserializeStatement"))
     {
         manager.Context.Push(statement);
         try
         {
             CodeAssignStatement statement2 = statement as CodeAssignStatement;
             if (statement2 != null)
             {
                 this.DeserializeAssignStatement(manager, statement2);
             }
             else
             {
                 CodeVariableDeclarationStatement statement3 = statement as CodeVariableDeclarationStatement;
                 if (statement3 != null)
                 {
                     this.DeserializeVariableDeclarationStatement(manager, statement3);
                 }
                 else if (!(statement is CodeCommentStatement))
                 {
                     CodeExpressionStatement statement4 = statement as CodeExpressionStatement;
                     if (statement4 != null)
                     {
                         this.DeserializeExpression(manager, null, statement4.Expression);
                     }
                     else if (statement is CodeMethodReturnStatement)
                     {
                         this.DeserializeExpression(manager, null, statement4.Expression);
                     }
                     else
                     {
                         CodeAttachEventStatement statement6 = statement as CodeAttachEventStatement;
                         if (statement6 != null)
                         {
                             this.DeserializeAttachEventStatement(manager, statement6);
                         }
                         else
                         {
                             CodeRemoveEventStatement statement7 = statement as CodeRemoveEventStatement;
                             if (statement7 != null)
                             {
                                 this.DeserializeDetachEventStatement(manager, statement7);
                             }
                             else
                             {
                                 CodeLabeledStatement statement8 = statement as CodeLabeledStatement;
                                 if (statement8 != null)
                                 {
                                     this.DeserializeStatement(manager, statement8.Statement);
                                 }
                             }
                         }
                     }
                 }
             }
         }
         catch (CheckoutException)
         {
             throw;
         }
         catch (Exception innerException)
         {
             if (innerException is TargetInvocationException)
             {
                 innerException = innerException.InnerException;
             }
             if (!(innerException is CodeDomSerializerException) && (statement.LinePragma != null))
             {
                 innerException = new CodeDomSerializerException(innerException, statement.LinePragma);
             }
             manager.ReportError(innerException);
         }
         finally
         {
             manager.Context.Pop();
         }
     }
 }
コード例 #21
0
 protected void DeserializePropertiesFromResources(IDesignerSerializationManager manager, object value, Attribute[] filter)
 {
     using (TraceScope("ComponentCodeDomSerializerBase::DeserializePropertiesFromResources"))
     {
         IDictionaryEnumerator metadataEnumerator = ResourceCodeDomSerializer.Default.GetMetadataEnumerator(manager);
         if (metadataEnumerator == null)
         {
             metadataEnumerator = ResourceCodeDomSerializer.Default.GetEnumerator(manager, CultureInfo.InvariantCulture);
         }
         if (metadataEnumerator != null)
         {
             string name;
             RootContext context = manager.Context[typeof(RootContext)] as RootContext;
             if ((context != null) && (context.Value == value))
             {
                 name = "$this";
             }
             else
             {
                 name = manager.GetName(value);
             }
             PropertyDescriptorCollection descriptors = GetPropertiesHelper(manager, value, null);
             while (metadataEnumerator.MoveNext())
             {
                 string key = metadataEnumerator.Key as string;
                 int index = key.IndexOf('.');
                 if ((index != -1) && key.Substring(0, index).Equals(name))
                 {
                     string str4 = key.Substring(index + 1);
                     PropertyDescriptor descriptor = descriptors[str4];
                     if (descriptor != null)
                     {
                         bool flag = true;
                         if (filter != null)
                         {
                             AttributeCollection attributes = descriptor.Attributes;
                             foreach (Attribute attribute in filter)
                             {
                                 if (!attributes.Contains(attribute))
                                 {
                                     flag = false;
                                     break;
                                 }
                             }
                         }
                         if (flag)
                         {
                             object obj2 = metadataEnumerator.Value;
                             try
                             {
                                 descriptor.SetValue(value, obj2);
                                 continue;
                             }
                             catch (Exception exception)
                             {
                                 manager.ReportError(exception);
                                 continue;
                             }
                         }
                     }
                 }
             }
         }
     }
 }
 private void SerializeContentProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, bool isExtender, CodeStatementCollection statements)
 {
     bool flag;
     object presetValue = this.GetPropertyValue(manager, property, value, out flag);
     CodeDomSerializer serializer = null;
     if (presetValue == null)
     {
         string name = manager.GetName(value);
         if (name == null)
         {
             name = value.GetType().FullName;
         }
         manager.ReportError(System.Design.SR.GetString("SerializerNullNestedProperty", new object[] { name, property.Name }));
     }
     else
     {
         serializer = (CodeDomSerializer) manager.GetSerializer(presetValue.GetType(), typeof(CodeDomSerializer));
         if (serializer != null)
         {
             CodeExpression targetObject = base.SerializeToExpression(manager, value);
             if (targetObject != null)
             {
                 CodeExpression expression = null;
                 if (isExtender)
                 {
                     ExtenderProvidedPropertyAttribute attribute = (ExtenderProvidedPropertyAttribute) property.Attributes[typeof(ExtenderProvidedPropertyAttribute)];
                     CodeExpression expression3 = base.SerializeToExpression(manager, attribute.Provider);
                     CodeExpression expression4 = base.SerializeToExpression(manager, value);
                     if ((expression3 != null) && (expression4 != null))
                     {
                         CodeMethodReferenceExpression expression5 = new CodeMethodReferenceExpression(expression3, "Get" + property.Name);
                         CodeMethodInvokeExpression expression6 = new CodeMethodInvokeExpression {
                             Method = expression5
                         };
                         expression6.Parameters.Add(expression4);
                         expression = expression6;
                     }
                 }
                 else
                 {
                     expression = new CodePropertyReferenceExpression(targetObject, property.Name);
                 }
                 if (expression != null)
                 {
                     ExpressionContext context = new ExpressionContext(expression, property.PropertyType, value, presetValue);
                     manager.Context.Push(context);
                     object obj3 = null;
                     try
                     {
                         SerializeAbsoluteContext context2 = (SerializeAbsoluteContext) manager.Context[typeof(SerializeAbsoluteContext)];
                         if (base.IsSerialized(manager, presetValue, context2 != null))
                         {
                             obj3 = base.GetExpression(manager, presetValue);
                         }
                         else
                         {
                             obj3 = serializer.Serialize(manager, presetValue);
                         }
                     }
                     finally
                     {
                         manager.Context.Pop();
                     }
                     CodeStatementCollection statements2 = obj3 as CodeStatementCollection;
                     if (statements2 == null)
                     {
                         CodeStatement statement2 = obj3 as CodeStatement;
                         if (statement2 != null)
                         {
                             statements.Add(statement2);
                         }
                     }
                     else
                     {
                         foreach (CodeStatement statement in statements2)
                         {
                             statements.Add(statement);
                         }
                     }
                 }
             }
         }
         else
         {
             manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { property.PropertyType.FullName }));
         }
     }
 }
コード例 #23
0
		internal void ReportError (IDesignerSerializationManager manager, string message, string details)
		{
			try {
				throw new Exception (message);
			} catch (Exception e) {
				e.Data["Details"] = message + Environment.NewLine + Environment.NewLine + details;
				manager.ReportError (e);
			}
		}
 private CodeArrayCreateExpression SerializeArray(IDesignerSerializationManager manager, Type targetType, ICollection array, ICollection valuesToSerialize)
 {
     CodeArrayCreateExpression expression = null;
     using (CodeDomSerializerBase.TraceScope("CollectionCodeDomSerializer::SerializeArray"))
     {
         if (((Array) array).Rank != 1)
         {
             manager.ReportError(System.Design.SR.GetString("SerializerInvalidArrayRank", new object[] { ((Array) array).Rank.ToString(CultureInfo.InvariantCulture) }));
             return expression;
         }
         Type elementType = targetType.GetElementType();
         CodeTypeReference reference = new CodeTypeReference(elementType);
         CodeArrayCreateExpression expression2 = new CodeArrayCreateExpression {
             CreateType = reference
         };
         bool flag = true;
         foreach (object obj2 in valuesToSerialize)
         {
             if ((obj2 is IComponent) && TypeDescriptor.GetAttributes(obj2).Contains(InheritanceAttribute.InheritedReadOnly))
             {
                 flag = false;
                 break;
             }
             CodeExpression expression3 = null;
             ExpressionContext context = null;
             ExpressionContext context2 = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
             if (context2 != null)
             {
                 context = new ExpressionContext(context2.Expression, elementType, context2.Owner);
                 manager.Context.Push(context);
             }
             try
             {
                 expression3 = base.SerializeToExpression(manager, obj2);
             }
             finally
             {
                 if (context != null)
                 {
                     manager.Context.Pop();
                 }
             }
             if (expression3 != null)
             {
                 if ((obj2 != null) && (obj2.GetType() != elementType))
                 {
                     expression3 = new CodeCastExpression(elementType, expression3);
                 }
                 expression2.Initializers.Add(expression3);
             }
             else
             {
                 flag = false;
                 break;
             }
         }
         if (flag)
         {
             expression = expression2;
         }
     }
     return expression;
 }
コード例 #25
0
        private object DeserializeName(IDesignerSerializationManager manager, string name)
        {
            string typeName   = null;
            Type   objectType = null;
            object obj2       = this.nameTable[name];

            using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::DeserializeName"))
            {
                CodeMemberField field = null;
                CodeObject      obj3  = obj2 as CodeObject;
                if (obj3 != null)
                {
                    obj2 = null;
                    this.nameTable[name] = null;
                    if (obj3 is CodeVariableDeclarationStatement)
                    {
                        CodeVariableDeclarationStatement statement = (CodeVariableDeclarationStatement)obj3;
                        typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, statement.Type);
                    }
                    else if (obj3 is CodeMemberField)
                    {
                        field    = (CodeMemberField)obj3;
                        typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type);
                    }
                }
                else
                {
                    if (obj2 != null)
                    {
                        return(obj2);
                    }
                    IContainer service = (IContainer)manager.GetService(typeof(IContainer));
                    if (service != null)
                    {
                        IComponent component = service.Components[name];
                        if (component != null)
                        {
                            typeName             = component.GetType().FullName;
                            this.nameTable[name] = component;
                        }
                    }
                }
                if (name.Equals(this.ContainerName))
                {
                    IContainer container2 = (IContainer)manager.GetService(typeof(IContainer));
                    if (container2 != null)
                    {
                        obj2 = container2;
                    }
                }
                else if (typeName != null)
                {
                    objectType = manager.GetType(typeName);
                    if (objectType == null)
                    {
                        manager.ReportError(new SerializationException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeName })));
                    }
                    else
                    {
                        CodeStatementCollection codeObject = (CodeStatementCollection)this.statementTable[name];
                        if ((codeObject != null) && (codeObject.Count > 0))
                        {
                            CodeDomSerializer serializer = (CodeDomSerializer)manager.GetSerializer(objectType, typeof(CodeDomSerializer));
                            if (serializer == null)
                            {
                                manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { objectType.FullName }));
                            }
                            else
                            {
                                try
                                {
                                    obj2 = serializer.Deserialize(manager, codeObject);
                                    if ((obj2 != null) && (field != null))
                                    {
                                        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj2)["Modifiers"];
                                        if ((descriptor != null) && (descriptor.PropertyType == typeof(MemberAttributes)))
                                        {
                                            MemberAttributes attributes = field.Attributes & MemberAttributes.AccessMask;
                                            descriptor.SetValue(obj2, attributes);
                                        }
                                    }
                                }
                                catch (Exception exception)
                                {
                                    manager.ReportError(exception);
                                }
                            }
                        }
                    }
                }
                this.nameTable[name] = obj2;
            }
            return(obj2);
        }
コード例 #26
0
        /// <summary>
        ///  This retrieves the value of this property.  If the property returns false
        ///  from ShouldSerializeValue (indicating the ambient value for this property)
        ///  This will look for an AmbientValueAttribute and use it if it can.
        /// </summary>
        private object GetPropertyValue(IDesignerSerializationManager manager, PropertyDescriptor property, object value, out bool validValue)
        {
            object propertyValue = null;

            validValue = true;
            try
            {
                if (!property.ShouldSerializeValue(value))
                {
                    // We aren't supposed to be serializing this property, but we decided to do
                    // it anyway.  Check the property for an AmbientValue attribute and if we
                    // find one, use it's value to serialize.
                    AmbientValueAttribute attr = (AmbientValueAttribute)property.Attributes[typeof(AmbientValueAttribute)];

                    if (attr != null)
                    {
                        return(attr.Value);
                    }
                    else
                    {
                        DefaultValueAttribute defAttr = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];

                        if (defAttr != null)
                        {
                            return(defAttr.Value);
                        }
                        else
                        {
                            // nope, we're not valid...
                            //
                            validValue = false;
                        }
                    }
                }

                propertyValue = property.GetValue(value);
            }
            catch (Exception e)
            {
                // something failed -- we don't have a valid value
                validValue = false;

                manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, property.Name, e.Message), manager));
            }

            if ((propertyValue != null) && (!propertyValue.GetType().IsValueType) && !(propertyValue is Type))
            {
                // DevDiv2 (Dev11) bug 187766 : property whose type implements ISupportInitialize is not
                // serialized with Begin/EndInit.
                Type type = TypeDescriptor.GetProvider(propertyValue).GetReflectionType(typeof(object));
                if (!type.IsDefined(typeof(ProjectTargetFrameworkAttribute), false))
                {
                    // TargetFrameworkProvider is not attached
                    TypeDescriptionProvider typeProvider = CodeDomSerializerBase.GetTargetFrameworkProvider(manager, propertyValue);
                    if (typeProvider != null)
                    {
                        TypeDescriptor.AddProvider(typeProvider, propertyValue);
                    }
                }
            }

            return(propertyValue);
        }
コード例 #27
0
        /// <include file='doc\ComponentCodeDomSerializer.uex' path='docs/doc[@for="ComponentCodeDomSerializer.Serialize"]/*' />
        /// <devdoc>
        ///     Serializes the given object into a CodeDom object.
        /// </devdoc>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            Debug.WriteLineIf(traceSerialization.TraceVerbose, "ComponentCodeDomSerializer::Serialize");
            Debug.Indent();
            try {
                Debug.WriteLineIf(traceSerialization.TraceVerbose, "Value: " + value.ToString());
            }
            catch {
                // in case the ToString throws...
            }


            if (manager == null || value == null)
            {
                throw new ArgumentNullException(manager == null ? "manager" : "value");
            }

            CodeStatementCollection statements           = new CodeStatementCollection();
            CodeExpression          instanceDescrExpr    = null;
            InheritanceAttribute    inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)];
            InheritanceLevel        inheritanceLevel     = InheritanceLevel.NotInherited;

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

            // Get the name for this object.  Components can only be serialized if they have
            // a name.
            //
            string name = manager.GetName(value);
            bool   generateDeclaration = (name != null);

            if (name == null)
            {
                IReferenceService referenceService = (IReferenceService)manager.GetService(typeof(IReferenceService));
                if (referenceService != null)
                {
                    name = referenceService.GetName(value);
                }
            }
            Debug.WriteLineIf(traceSerialization.TraceWarning && name == null, "WARNING: object has no name so we cannot serialize.");
            if (name != null)
            {
                Debug.WriteLineIf(traceSerialization.TraceVerbose, "Name: " + name);

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

                try {
                    try {
                        // If the object is not inherited ensure that is has a component declaration.
                        //
                        if (generateDeclaration && inheritanceLevel == InheritanceLevel.NotInherited)
                        {
                            // Check to make sure this isn't our base component.  If it is, there is
                            // no need to serialize its declaration.
                            //
                            IDesignerHost host = (IDesignerHost)manager.GetService(typeof(IDesignerHost));
                            if ((host == null || host.RootComponent != value))
                            {
                                SerializeDeclaration(manager, statements, value);
                            }
                        }
                        else
                        {
                            Debug.WriteLineIf(traceSerialization.TraceVerbose, "Skipping declaration of inherited or namespace component.");
                        }

                        // Next, if the object is not being privately inherited, serialize the
                        // rest of its state.
                        //
                        if (inheritanceLevel != InheritanceLevel.InheritedReadOnly)
                        {
                            bool supportInitialize = (value is ISupportInitialize);

                            if (supportInitialize)
                            {
                                Debug.WriteLineIf(traceSerialization.TraceVerbose, "Object implements ISupportInitialize.");
                                SerializeSupportInitialize(manager, statements, value, "BeginInit");
                            }

                            // Add a nice comment that declares we're about to serialize this component
                            //
                            int insertLoc = statements.Count;
                            SerializePropertiesToResources(manager, statements, value, designTimeProperties);
                            SerializeProperties(manager, statements, value, runTimeProperties);
                            SerializeEvents(manager, statements, value, null);

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

                            if (supportInitialize)
                            {
                                SerializeSupportInitialize(manager, statements, value, "EndInit");
                            }
                        }
                        else
                        {
                            Debug.WriteLineIf(traceSerialization.TraceVerbose, "Skipping serialization of read-only inherited component");
                        }
                    }
                    catch (Exception ex) {
                        manager.ReportError(ex);
                    }
                }
                finally {
                    Debug.Assert(manager.Context.Current == value, "Context stack corrupted");
                    manager.Context.Pop();
                }
            }
            else
            {
                Debug.WriteLineIf(traceSerialization.TraceWarning, "Attempting instance descriptor serialization.");
                Debug.Indent();
                // Last resort, lets see if if can serialize itself to an instance descriptor.
                //
                if (TypeDescriptor.GetConverter(value).CanConvertTo(typeof(InstanceDescriptor)))
                {
                    Debug.WriteLineIf(traceSerialization.TraceWarning, "Type supports instance descriptor.");
                    // Got an instance descriptor.  Ask it to serialize
                    //
                    object o = InstanceDescriptorCodeDomSerializer.Default.Serialize(manager, value);
                    if (o is CodeExpression)
                    {
                        Debug.WriteLineIf(traceSerialization.TraceWarning, "Serialized successfully.");
                        instanceDescrExpr = (CodeExpression)o;
                    }
                }
                Debug.Unindent();
            }

            if (instanceDescrExpr != null)
            {
                Debug.WriteLineIf(traceSerialization.TraceVerbose, "Object serialized into a single InstanceDescriptor expression.");
                Debug.Unindent();
                return(instanceDescrExpr);
            }
            else
            {
                Debug.WriteLineIf(traceSerialization.TraceVerbose, "Object serialized into " + statements.Count.ToString() + " statements.");
                Debug.Unindent();
                return(statements);
            }
        }
コード例 #28
0
        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);
        }
コード例 #29
0
 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;
 }
コード例 #30
0
		protected CodeExpression SerializeToExpression (IDesignerSerializationManager manager, object instance)
		{
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (instance == null)
				throw new ArgumentNullException ("instance");

			CodeExpression expression = this.GetExpression (manager, instance); // 1 - IDesignerSerializationManager.GetExpression
			if (expression == null) {
				CodeDomSerializer serializer = this.GetSerializer (manager, instance); // 2 - manager.GetSerializer().Serialize()
				if (serializer != null) {
					object serialized = serializer.Serialize (manager, instance);
					expression = serialized as CodeExpression; // 3 - CodeStatement or CodeStatementCollection
					if (expression == null) {
						CodeStatement statement = serialized as CodeStatement;
						CodeStatementCollection statements = serialized as CodeStatementCollection;

						if (statement != null || statements != null) {
							CodeStatementCollection contextStatements = null;

							StatementContext context = manager.Context[typeof (StatementContext)] as StatementContext;
							if (context != null)
								contextStatements = context.StatementCollection[instance];

							if (contextStatements == null)
								contextStatements = manager.Context[typeof (CodeStatementCollection)] as CodeStatementCollection;

							if (contextStatements != null) {
								if (statements != null)
									contextStatements.AddRange (statements);
								else
									contextStatements.Add (statement);
							}
						}
					}
					if (expression == null)
						expression = this.GetExpression (manager, instance); // 4

					if (expression == null)
						manager.ReportError ("SerializeToExpression: " + instance.GetType ().AssemblyQualifiedName + " failed.");
				}
			}
			return expression;
		}
 private object GetPropertyValue(IDesignerSerializationManager manager, PropertyDescriptor property, object value, out bool validValue)
 {
     object instance = null;
     validValue = true;
     try
     {
         if (!property.ShouldSerializeValue(value))
         {
             AmbientValueAttribute attribute = (AmbientValueAttribute) property.Attributes[typeof(AmbientValueAttribute)];
             if (attribute != null)
             {
                 return attribute.Value;
             }
             DefaultValueAttribute attribute2 = (DefaultValueAttribute) property.Attributes[typeof(DefaultValueAttribute)];
             if (attribute2 != null)
             {
                 return attribute2.Value;
             }
             validValue = false;
         }
         instance = property.GetValue(value);
     }
     catch (Exception exception)
     {
         validValue = false;
         manager.ReportError(System.Design.SR.GetString("SerializerPropertyGenFailed", new object[] { property.Name, exception.Message }));
     }
     if (((instance != null) && !instance.GetType().IsValueType) && !TypeDescriptor.GetProvider(instance).GetReflectionType(typeof(object)).IsDefined(typeof(ProjectTargetFrameworkAttribute), false))
     {
         TypeDescriptionProvider targetFrameworkProvider = CodeDomSerializerBase.GetTargetFrameworkProvider(manager, instance);
         if (targetFrameworkProvider != null)
         {
             TypeDescriptor.AddProvider(targetFrameworkProvider, instance);
         }
     }
     return instance;
 }
コード例 #32
0
        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);
        }
コード例 #33
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeDomSerializer serial = GetBaseComponentSerializer(manager);

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

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

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

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

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

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

            #region Mapping property serialization

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

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

            #endregion

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

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

            return(statements);
        }
コード例 #34
0
 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;
 }
コード例 #35
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 == null || value == null)
                {
                    throw new ArgumentNullException(manager == 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         rootCxt   = 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 == 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 expCxt) || expCxt.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 (rootCxt == 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 modifersProp = props["Modifiers"];
                                    MemberAttributes   fieldAttrs;

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

                                    if (modifersProp != null && modifersProp.PropertyType == typeof(MemberAttributes))
                                    {
                                        fieldAttrs = (MemberAttributes)modifersProp.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(rootCxt.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 == null, "No RHS code assign for object {0}", value);
                            if (assignRhs != null)
                            {
                                if (assignLhs == 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 == 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 == 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 == 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 depedency 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 seriallization 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);
                                }
                            }

                            // Regarless, 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");
                            }
                        }
                    }
                    catch (CheckoutException)
                    {
                        throw;
                    }
                    catch (Exception ex)
                    {
                        manager.ReportError(ex);
                    }
                    finally
                    {
                        Debug.Assert(manager.Context.Current == statements, "Context stack corrupted");
                        manager.Context.Pop();
                        manager.Context.Pop();
                    }
                }
            }

            return(statements);
        }