public virtual object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			bool isComplete = true;
			CodeStatementCollection statements = new CodeStatementCollection ();
			ExpressionContext context = manager.Context[typeof (ExpressionContext)] as ExpressionContext;
			object serialized = null;

			if (context != null && context.PresetValue == value) {
				string varName = base.GetUniqueName (manager, value);
				CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement (value.GetType (), varName); // declare
				statement.InitExpression = base.SerializeCreationExpression (manager, value, out isComplete); // initialize
				base.SetExpression (manager, value, statement.InitExpression);
				statements.Add (statement);
				serialized = statement;
			} else {
				string name = manager.GetName (value);
				if (name == null)
					name = base.GetUniqueName (manager, value);
				serialized = GetFieldReference (manager, name);
			}

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

			return serialized;
		}
        public override object Serialize(IDesignerSerializationManager manager, object obj)
        {
            if (manager == null)
                throw new ArgumentNullException("manager");
            if (obj == null)
                throw new ArgumentNullException("obj");

            CodeExpression retVal = null;
            CodeStatementCollection statements = manager.Context[typeof(CodeStatementCollection)] as CodeStatementCollection;
            System.Diagnostics.Debug.Assert(statements != null);
            if (statements != null)
            {
                Activity activity = (Activity)manager.Context[typeof(Activity)];
                CodeExpression objectExpression = SerializeToExpression(manager, activity);
                ICollection<String> handles = obj as ICollection<String>;
                if (handles == null)
                    throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(StringCollection).FullName), "obj");

                string variableName = GetUniqueName(manager, new StringCollection());
                statements.Add(new CodeVariableDeclarationStatement(obj.GetType(), variableName, new CodeObjectCreateExpression(obj.GetType())));

                foreach (string handle in handles)
                    statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(variableName), "Add"), new CodeExpression[] { new CodePrimitiveExpression(handle) }));

                retVal = new CodeVariableReferenceExpression(variableName);
            }
            return retVal;
        }
        public override object Serialize(IDesignerSerializationManager manager, object obj)
        {
            if (manager == null)
                throw new ArgumentNullException("manager");
            if (obj == null)
                throw new ArgumentNullException("obj");

            Activity activity = obj as Activity;
            if (activity == null)
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(Activity).FullName), "obj");

            if (Helpers.IsActivityLocked(activity))
                return null;

            CodeStatementCollection retVal = base.Serialize(manager, activity) as CodeStatementCollection;
            if (retVal != null)
            {
                Activity rootActivity = Helpers.GetRootActivity(activity);
                if (rootActivity != null && rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty) != null &&
                    (int)activity.GetValue(ActivityMarkupSerializer.StartLineProperty) != -1)
                {
                    foreach (CodeStatement statement in retVal)
                    {
                        if (!(statement is CodeCommentStatement))
                            statement.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)activity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
                    }
                }
            }
            return retVal;
        }
 private bool CanCacheComponent(IDesignerSerializationManager manager, object value, PropertyDescriptorCollection props)
 {
     IComponent component = value as IComponent;
     if (component != null)
     {
         if (component.Site != null)
         {
             INestedSite site = component.Site as INestedSite;
             if ((site != null) && !string.IsNullOrEmpty(site.FullName))
             {
                 return false;
             }
         }
         if (props == null)
         {
             props = TypeDescriptor.GetProperties(component);
         }
         foreach (PropertyDescriptor descriptor in props)
         {
             if (typeof(IComponent).IsAssignableFrom(descriptor.PropertyType) && !descriptor.Attributes.Contains(DesignerSerializationVisibilityAttribute.Hidden))
             {
                 MemberCodeDomSerializer serializer = (MemberCodeDomSerializer) manager.GetSerializer(descriptor.GetType(), typeof(MemberCodeDomSerializer));
                 if ((serializer != null) && serializer.ShouldSerialize(manager, value, descriptor))
                 {
                     return false;
                 }
             }
         }
     }
     return true;
 }
		public override object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			object serialized = null;
			string name = manager.GetName (value);

			ExpressionContext exprContext = manager.Context[typeof (ExpressionContext)] as ExpressionContext;
			if (exprContext != null && exprContext.PresetValue == value) {
				CodeStatementCollection statements = new CodeStatementCollection ();
				bool isComplete = true;

				statements.Add (new CodeCommentStatement (String.Empty));
				statements.Add (new CodeCommentStatement (name));
				statements.Add (new CodeCommentStatement (String.Empty));
				statements.Add (new CodeAssignStatement (GetFieldReference (manager, name), 
														 base.SerializeCreationExpression (manager, value, out isComplete)));
				base.SerializeProperties (manager, statements, value, new Attribute[0]);
				base.SerializeEvents (manager, statements, value);
				serialized = statements;
			} else {
				serialized = base.Serialize (manager, value);
			}

			return serialized;
		}
 protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl, object value)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (typeDecl == null)
     {
         throw new ArgumentNullException("typeDecl");
     }
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     CodeMemberMethod method = typeDecl.UserData[_initMethodKey] as CodeMemberMethod;
     if (method == null)
     {
         method = new CodeMemberMethod {
             Name = "InitializeComponent",
             Attributes = MemberAttributes.Private
         };
         typeDecl.UserData[_initMethodKey] = method;
         CodeConstructor constructor = new CodeConstructor {
             Attributes = MemberAttributes.Public
         };
         constructor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "InitializeComponent", new CodeExpression[0]));
         typeDecl.Members.Add(constructor);
     }
     return method;
 }
Esempio n. 7
0
		public override object Serialize(
			IDesignerSerializationManager manager, object value)
		{
			CodeDomSerializer baseSerializer = manager.GetSerializer(
				typeof(FlowChart).BaseType, typeof(CodeDomSerializer)) as CodeDomSerializer;

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

			if (codeObject is CodeStatementCollection)
			{
				CodeStatementCollection code =
					codeObject as CodeStatementCollection;
				FlowChart chart = value as FlowChart;

				// Brushes
				SerializeBrush(code, "BackBrush", chart, chart.BackBrush);
				SerializeBrush(code, "BoxBrush", chart, chart.BoxBrush);
				SerializeBrush(code, "TableBrush", chart, chart.TableBrush);
				SerializeBrush(code, "ArrowBrush", chart, chart.ArrowBrush);

				// Pens
				SerializePen(code, "BoxPen", chart, chart.BoxPen);
				SerializePen(code, "TablePen", chart, chart.TablePen);
				SerializePen(code, "ArrowPen", chart, chart.ArrowPen);

				// Text alignment
				SerializeTextFormat(code, "TextFormat", chart, chart.TextFormat);
			}

			return codeObject;
		}
        object SerializeCell(IDesignerSerializationManager manager, CodeExpression target, Cell cell)
        {
            object codeObject = null;
            ExpressionContext context = null;
            ExpressionContext context2 = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
            if (context2 != null)
            {
                CodeMethodInvokeExpression codeIndexer = new CodeMethodInvokeExpression(target, "GetAt", new CodePrimitiveExpression(cell.Column.Index));
                context = new ExpressionContext(codeIndexer, typeof(RowCollection), context2.PresetValue, cell);
                manager.Context.Push(context);
            }
            try
            {
                CodeDomSerializer rowSerialzier = (CodeDomSerializer)manager.GetSerializer(cell.GetType(), typeof(CodeDomSerializer));

                //codeObject = rowSerialzier.Serialize(manager, row);
                codeObject = rowSerialzier.SerializeAbsolute(manager, cell);
            }
            finally
            {
                if (context != null)
                {
                    manager.Context.Pop();
                }
            }

            return codeObject;
        }
Esempio n. 9
0
		public override object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (value == null)
				throw new ArgumentNullException ("value");

			Enum[] enums = null;
			TypeConverter converter = TypeDescriptor.GetConverter (value);
			if (converter.CanConvertTo (typeof (Enum[])))
				enums = (Enum[]) converter.ConvertTo (value, typeof (Enum[]));
			else
				enums = new Enum[] { (Enum) value };
			CodeExpression left = null;
			CodeExpression right = null;
			foreach (Enum e in enums) {
				right = GetEnumExpression (e);
				if (left == null) // just the first time
					left = right;
				else
					left = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.BitwiseOr, right);
			}

			return left;
		}
Esempio n. 10
0
		public override object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			ICollection originalCollection = value as ICollection;
			if (originalCollection == null)
				throw new ArgumentException ("originalCollection is not an ICollection");

			CodeExpression targetExpression = null;

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

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

			ArrayList valuesToSerialize = new ArrayList ();
			foreach (object o in originalCollection)
				valuesToSerialize.Add (o);

			return this.SerializeCollection (manager, targetExpression, value.GetType (), originalCollection, valuesToSerialize);
		}
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            object codeObject = base.Serialize(manager, value);

            if (codeObject is CodeStatementCollection)
            {
                CodeStatementCollection statements = codeObject as CodeStatementCollection;

                CodeExpression target = base.SerializeToExpression(manager, value);

                RowCollection rows = value as RowCollection;

                if (rows != null)
                {
                    foreach (Row item in rows)
                    {
                        object rowCode = SerializeRow(manager, target, item);

                        if (rowCode is CodeStatementCollection)
                        {
                            statements.AddRange(rowCode as CodeStatementCollection);
                        }
                    }
                }

                foreach (CodeObject item in statements)
                {
                    item.UserData["statement-ordering"] = "end";
                }
            }

            return codeObject;
        }
 internal ComponentCache(IDesignerSerializationManager manager)
 {
     this.serManager = manager;
     IComponentChangeService service = (IComponentChangeService) manager.GetService(typeof(IComponentChangeService));
     if (service != null)
     {
         service.ComponentChanging += new ComponentChangingEventHandler(this.OnComponentChanging);
         service.ComponentChanged += new ComponentChangedEventHandler(this.OnComponentChanged);
         service.ComponentRemoving += new ComponentEventHandler(this.OnComponentRemove);
         service.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemove);
         service.ComponentRename += new ComponentRenameEventHandler(this.OnComponentRename);
     }
     DesignerOptionService service2 = manager.GetService(typeof(DesignerOptionService)) as DesignerOptionService;
     object obj2 = null;
     if (service2 != null)
     {
         PropertyDescriptor descriptor = service2.Options.Properties["UseOptimizedCodeGeneration"];
         if (descriptor != null)
         {
             obj2 = descriptor.GetValue(null);
         }
         if ((obj2 != null) && (obj2 is bool))
         {
             this.enabled = (bool) obj2;
         }
     }
 }
		public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
		{
			if (manager == null)
				throw new ArgumentNullException("manager");
			if (codeObject == null)
				throw new ArgumentNullException("codeObject");
			
			object instance = null;
			
			CodeStatementCollection statements = codeObject as CodeStatementCollection;
			if (statements != null) {
				foreach (CodeStatement statement in statements) {
					
					if (!this.DeserializeProjectResourceStatement(manager, statement)) {
						object result = this.baseSerializer.Deserialize(manager, new CodeStatementCollection(new [] {statement}));
						if (instance == null) {
							instance = result;
						}
					}
					
				}
				return instance;
			}
			
			return this.baseSerializer.Deserialize(manager, codeObject);
		}
		public object GetSerializer (IDesignerSerializationManager manager, object currentSerializer, 
									 Type objectType, Type serializerType) 
		{
			CodeDomSerializerBase serializer = null;

			if (serializerType == typeof(CodeDomSerializer)) { // CodeDomSerializer
				if (objectType == null) // means that value to serialize is null CodePrimitiveExpression (null)
					serializer = _primitiveSerializer;
				else if (typeof(IComponent).IsAssignableFrom (objectType))
					serializer = _componentSerializer;
				else if (objectType.IsEnum || typeof (Enum).IsAssignableFrom (objectType))
					serializer = _enumSerializer;
				else if (objectType.IsPrimitive || objectType == typeof (String))
					serializer = _primitiveSerializer;
				else if (typeof(ICollection).IsAssignableFrom (objectType)) 
					serializer = _collectionSerializer;
				else
					serializer = _othersSerializer;
			} else if (serializerType == typeof(MemberCodeDomSerializer)) { // MemberCodeDomSerializer
				if (typeof (PropertyDescriptor).IsAssignableFrom (objectType))
					serializer = _propertySerializer;
				else if (typeof (EventDescriptor).IsAssignableFrom (objectType))
					serializer = _eventSerializer;
			} else if (serializerType == typeof (RootCodeDomSerializer)) {
				serializer = _rootSerializer;
			}

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

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

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

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

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

			return declaration;
		}
Esempio n. 16
0
		public override bool ShouldSerialize (IDesignerSerializationManager manager, object value, MemberDescriptor descriptor)
		{
			IEventBindingService service = manager.GetService (typeof (IEventBindingService)) as IEventBindingService;
			if (service != null) // serialize only if there is an event to serialize
				return service.GetEventProperty ((EventDescriptor)descriptor).GetValue (value) != null;
			return false;
		}
Esempio n. 17
0
        public override object Serialize(IDesignerSerializationManager manager, object value) {
            var baseSerializer = (CodeDomSerializer)manager
                .GetSerializer(typeof(ResourceManagerSetter).BaseType, typeof(CodeDomSerializer));
            object codeObject = baseSerializer.Serialize(manager, value);

            var statements = codeObject as CodeStatementCollection;
            if (statements != null) {
                CodeExpression leftCodeExpression = new CodeVariableReferenceExpression("resources");
                var classTypeDeclaration = (CodeTypeDeclaration)manager.GetService(typeof(CodeTypeDeclaration));
                CodeExpression typeofExpression = new CodeTypeOfExpression(classTypeDeclaration.Name);
                CodeExpression rightCodeExpression =
                    new CodeObjectCreateExpression(typeof(XafComponentResourceManager),
                                                                  new[] { typeofExpression });
                //CodeExpression rightCodeExpression =
                //    new CodeTypeReferenceExpression(
                //        "new DevExpress.ExpressApp.Win.Templates"),
                //        "XafComponentResourceManager", new[] { typeofExpression });

                statements.Insert(0, new CodeAssignStatement(leftCodeExpression, rightCodeExpression));
            }

            return codeObject;


        }
 public override object Serialize(IDesignerSerializationManager manager, object obj)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (obj == null)
     {
         throw new ArgumentNullException("obj");
     }
     CodeExpression expression = null;
     CodeStatementCollection statements = manager.Context[typeof(CodeStatementCollection)] as CodeStatementCollection;
     if (statements == null)
     {
         return expression;
     }
     Activity activity = (Activity) manager.Context[typeof(Activity)];
     base.SerializeToExpression(manager, activity);
     ICollection<string> is2 = obj as ICollection<string>;
     if (is2 == null)
     {
         throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(StringCollection).FullName }), "obj");
     }
     string uniqueName = base.GetUniqueName(manager, new StringCollection());
     statements.Add(new CodeVariableDeclarationStatement(obj.GetType(), uniqueName, new CodeObjectCreateExpression(obj.GetType(), new CodeExpression[0])));
     foreach (string str2 in is2)
     {
         statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(uniqueName), "Add"), new CodeExpression[] { new CodePrimitiveExpression(str2) }));
     }
     return new CodeVariableReferenceExpression(uniqueName);
 }
Esempio n. 19
0
		public override void Serialize (IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, 
						CodeStatementCollection statements)
		{
			if (statements == null)
				throw new ArgumentNullException ("statements");
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (value == null)
				throw new ArgumentNullException ("value");
			if (descriptor == null)
				throw new ArgumentNullException ("descriptor");

			IEventBindingService service = manager.GetService (typeof (IEventBindingService)) as IEventBindingService;
			if (service != null) {
				EventDescriptor eventDescriptor = (EventDescriptor) descriptor;
				string methodName = (string) service.GetEventProperty (eventDescriptor).GetValue (value);

				if (methodName != null) {
					CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression (new CodeTypeReference (eventDescriptor.EventType),
																							   _thisReference, methodName);
					CodeExpression targetObject = base.SerializeToExpression (manager, value);
					CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression (targetObject, eventDescriptor.Name);
					statements.Add (new CodeAttachEventStatement (eventRef, listener));
				}
			}
		}
		public override void Serialize (IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
		{
			if (statements == null)
				throw new ArgumentNullException ("statements");
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (value == null)
				throw new ArgumentNullException ("value");
			if (descriptor == null)
				throw new ArgumentNullException ("descriptor");

			IEventBindingService service = manager.GetService (typeof (IEventBindingService)) as IEventBindingService;
			if (service != null) {
				// In the propertygrid the events are represented by PropertyDescriptors and the value is a string
				// which contains the method name to bind to. The propertydescriptors are managed and created by the 
				// IEventBindingService
				// 
				EventDescriptor ev = (EventDescriptor) descriptor;
				string methodName = (string) service.GetEventProperty (ev).GetValue (value);
				CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression (new CodeTypeReference (ev.EventType), _thisReference, methodName);
				CodeExpression targetObject = base.SerializeToExpression (manager, value);
				CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression (targetObject, ev.Name);
				statements.Add (new CodeAttachEventStatement (eventRef, listener));
			}
		}
 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;
 }
 protected object DeserializeStatementToInstance(IDesignerSerializationManager manager, CodeStatement statement)
 {
     object obj2 = null;
     CodeVariableDeclarationStatement statement3;
     CodeAssignStatement statement2 = statement as CodeAssignStatement;
     if (statement2 != null)
     {
         CodeFieldReferenceExpression left = statement2.Left as CodeFieldReferenceExpression;
         if (left != null)
         {
             return base.DeserializeExpression(manager, left.FieldName, statement2.Right);
         }
         CodeVariableReferenceExpression expression2 = statement2.Left as CodeVariableReferenceExpression;
         if (expression2 != null)
         {
             return base.DeserializeExpression(manager, expression2.VariableName, statement2.Right);
         }
         base.DeserializeStatement(manager, statement2);
         return obj2;
     }
     if (((statement3 = statement as CodeVariableDeclarationStatement) != null) && (statement3.InitExpression != null))
     {
         return base.DeserializeExpression(manager, statement3.Name, statement3.InitExpression);
     }
     base.DeserializeStatement(manager, statement);
     return obj2;
 }
Esempio n. 23
0
		public override object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			if (!(value is Control))
				throw new InvalidOperationException ("value is not a Control");

			object serialized = base.Serialize (manager, value);
			CodeStatementCollection statements = serialized as CodeStatementCollection;
			if (statements != null) { // the root control is serialized to CodeExpression
				ICollection childControls = TypeDescriptor.GetProperties (value)["Controls"].GetValue (value) as ICollection;
				if (childControls.Count > 0) {
					CodeExpression componentRef = base.GetExpression (manager, value);

					CodeStatement statement = new CodeExpressionStatement (
						new CodeMethodInvokeExpression (componentRef, "SuspendLayout"));
					statement.UserData["statement-order"] = "begin";
					statements.Add (statement);
					statement = new CodeExpressionStatement (
						new CodeMethodInvokeExpression (componentRef, "ResumeLayout", 
										new CodeExpression[] { 
											new CodePrimitiveExpression (false) }));
					statement.UserData["statement-order"] = "end";
					statements.Add (statement);
					serialized = statements;
				}
			}
			return serialized;
		}
Esempio n. 24
0
 public object GetSerializer(IDesignerSerializationManager manager, object currentSerializer, Type objectType, Type serializerType)
 {
     if (objectType == typeof(Stack))
         return this;
     else
         return currentSerializer;
 }
 internal void ApplyCacheEntry(IDesignerSerializationManager manager, ComponentCache.Entry entry)
 {
     SerializationResourceManager resourceManager = this.GetResourceManager(manager);
     if (entry.Metadata != null)
     {
         foreach (ComponentCache.ResourceEntry entry2 in entry.Metadata)
         {
             resourceManager.SetMetadata(manager, entry2.Name, entry2.Value, entry2.ShouldSerializeValue, true);
         }
     }
     if (entry.Resources != null)
     {
         foreach (ComponentCache.ResourceEntry entry3 in entry.Resources)
         {
             manager.Context.Push(entry3.PropertyDescriptor);
             manager.Context.Push(entry3.ExpressionContext);
             try
             {
                 resourceManager.SetValue(manager, entry3.Name, entry3.Value, entry3.ForceInvariant, entry3.ShouldSerializeValue, entry3.EnsureInvariant, true);
             }
             finally
             {
                 manager.Context.Pop();
                 manager.Context.Pop();
             }
         }
     }
 }
 private void FillLinePragmaFromContext(IDesignerSerializationManager manager)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
 }
        protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl, object value)
        {
            if (manager == null)
                throw new ArgumentNullException("manager");
            if (typeDecl == null)
                throw new ArgumentNullException("typeDecl");
            if (value == null)
                throw new ArgumentNullException("value");

            CodeMemberMethod method = typeDecl.UserData[_initMethodKey] as CodeMemberMethod;
            if (method == null)
            {
                method = new CodeMemberMethod();
                method.Name = _initMethodName;
                method.Attributes = MemberAttributes.Private;
                typeDecl.UserData[_initMethodKey] = method;

                // Now create a ctor that calls this method.
                CodeConstructor ctor = new CodeConstructor();
                ctor.Attributes = MemberAttributes.Public;
                ctor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), _initMethodName));
                typeDecl.Members.Add(ctor);
            }
            return method;
        }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     object obj2 = ((CodeDomSerializer) manager.GetSerializer(typeof(ImageList).BaseType, typeof(CodeDomSerializer))).Serialize(manager, value);
     ImageList list = value as ImageList;
     if (list != null)
     {
         StringCollection keys = list.Images.Keys;
         if (!(obj2 is CodeStatementCollection))
         {
             return obj2;
         }
         CodeExpression targetObject = base.GetExpression(manager, value);
         if (targetObject == null)
         {
             return obj2;
         }
         CodeExpression expression2 = new CodePropertyReferenceExpression(targetObject, "Images");
         if (expression2 == null)
         {
             return obj2;
         }
         for (int i = 0; i < keys.Count; i++)
         {
             if ((keys[i] != null) || (keys[i].Length != 0))
             {
                 CodeMethodInvokeExpression expression3 = new CodeMethodInvokeExpression(expression2, "SetKeyName", new CodeExpression[] { new CodePrimitiveExpression(i), new CodePrimitiveExpression(keys[i]) });
                 ((CodeStatementCollection) obj2).Add(expression3);
             }
         }
     }
     return obj2;
 }
		public virtual object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			object serialized = null;
			bool isComplete = false;
			CodeExpression createExpr = base.SerializeCreationExpression (manager, value, out isComplete);
			if (isComplete) {
				serialized = createExpr;
				base.SetExpression (manager, value, createExpr);
			} else {
				ExpressionContext context = manager.Context[typeof (ExpressionContext)] as ExpressionContext;
				if (context != null && context.PresetValue == value) {
					CodeStatementCollection statements = new CodeStatementCollection ();
					statements.Add (new CodeAssignStatement (context.Expression, createExpr));
					base.SerializeProperties (manager, statements, value, new Attribute[0]);
					base.SerializeEvents (manager, statements, value, new Attribute[0]);
				} else {
					CodeExpression expression = base.GetExpression (manager, value);
					if (expression == null) {
						serialized = expression = createExpr;
						base.SetExpression (manager, value, expression);
					}
				}
			}
			return serialized;
		}
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     CodeExpression expression;
     CodeTypeDeclaration declaration = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
     RootContext context = manager.Context[typeof(RootContext)] as RootContext;
     CodeStatementCollection statements = new CodeStatementCollection();
     if ((declaration != null) && (context != null))
     {
         CodeMemberField field = new CodeMemberField(typeof(IContainer), "components") {
             Attributes = MemberAttributes.Private
         };
         declaration.Members.Add(field);
         expression = new CodeFieldReferenceExpression(context.Expression, "components");
     }
     else
     {
         CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(typeof(IContainer), "components");
         statements.Add(statement);
         expression = new CodeVariableReferenceExpression("components");
     }
     base.SetExpression(manager, value, expression);
     CodeObjectCreateExpression right = new CodeObjectCreateExpression(typeof(Container), new CodeExpression[0]);
     CodeAssignStatement statement2 = new CodeAssignStatement(expression, right);
     statement2.UserData["IContainer"] = "IContainer";
     statements.Add(statement2);
     return statements;
 }
        public virtual object Serialize(IDesignerSerializationManager manager, object value)
        {
            object obj2 = null;

            if ((manager == null) || (value == null))
            {
                throw new ArgumentNullException((manager == null) ? "manager" : "value");
            }
            using (CodeDomSerializerBase.TraceScope("CodeDomSerializer::Serialize"))
            {
                bool flag2;
                bool flag3;
                if (value is Type)
                {
                    return(new CodeTypeOfExpression((Type)value));
                }
                bool           flag       = false;
                CodeExpression expression = base.SerializeCreationExpression(manager, value, out flag2);
                if (!(value is IComponent))
                {
                    flag = flag2;
                }
                ExpressionContext context = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
                if ((context != null) && object.ReferenceEquals(context.PresetValue, value))
                {
                    flag3 = true;
                }
                else
                {
                    flag3 = false;
                }
                if (expression == null)
                {
                    return(obj2);
                }
                if (flag)
                {
                    return(expression);
                }
                CodeStatementCollection statements = new CodeStatementCollection();
                if (flag3)
                {
                    base.SetExpression(manager, value, expression, true);
                }
                else
                {
                    string uniqueName = base.GetUniqueName(manager, value);
                    CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(TypeDescriptor.GetClassName(value), uniqueName)
                    {
                        InitExpression = expression
                    };
                    statements.Add(statement);
                    CodeExpression expression2 = new CodeVariableReferenceExpression(uniqueName);
                    base.SetExpression(manager, value, expression2);
                }
                base.SerializePropertiesToResources(manager, statements, value, _designTimeFilter);
                base.SerializeProperties(manager, statements, value, _runTimeFilter);
                base.SerializeEvents(manager, statements, value, _runTimeFilter);
                return(statements);
            }
        }
 private void SerializeSuspendLayout(IDesignerSerializationManager manager, CodeStatementCollection statements, object control)
 {
     this.SerializeMethodInvocation(manager, statements, control, "SuspendLayout", null, new Type[0], ControlCodeDomSerializer.StatementOrdering.Prepend);
 }
        private void SerializeControlHierarchy(IDesignerSerializationManager manager, IDesignerHost host, object value)
        {
            Control control = value as Control;

            if (control != null)
            {
                IMultitargetHelperService multitargetHelperService = host.GetService(typeof(IMultitargetHelperService)) as IMultitargetHelperService;
                string text;
                if (control == host.RootComponent)
                {
                    text = "$this";
                    IEnumerator enumerator = host.Container.Components.GetEnumerator();
                    {
                        while (enumerator.MoveNext())
                        {
                            IComponent component = (IComponent)enumerator.Current;
                            if (!(component is Control) && !TypeDescriptor.GetAttributes(component).Contains(InheritanceAttribute.InheritedReadOnly))
                            {
                                string name   = manager.GetName(component);
                                string value2 = (multitargetHelperService == null) ? component.GetType().AssemblyQualifiedName : multitargetHelperService.GetAssemblyQualifiedName(component.GetType());
                                if (name != null)
                                {
                                    base.SerializeResourceInvariant(manager, ">>" + name + ".Name", name);
                                    base.SerializeResourceInvariant(manager, ">>" + name + ".Type", value2);
                                }
                            }
                        }
                        goto IL_107;
                    }
                }
                text = manager.GetName(value);
                if (text == null)
                {
                    return;
                }
IL_107:
                base.SerializeResourceInvariant(manager, ">>" + text + ".Name", manager.GetName(value));
                base.SerializeResourceInvariant(manager, ">>" + text + ".Type", (multitargetHelperService == null) ? control.GetType().AssemblyQualifiedName : multitargetHelperService.GetAssemblyQualifiedName(control.GetType()));
                Control parent = control.Parent;
                if (parent != null && parent.Site != null)
                {
                    string text2;
                    if (parent == host.RootComponent)
                    {
                        text2 = "$this";
                    }
                    else
                    {
                        text2 = manager.GetName(parent);
                    }
                    if (text2 != null)
                    {
                        base.SerializeResourceInvariant(manager, ">>" + text + ".Parent", text2);
                    }
                    for (int i = 0; i < parent.Controls.Count; i++)
                    {
                        if (parent.Controls[i] == control)
                        {
                            base.SerializeResourceInvariant(manager, ">>" + text + ".ZOrder", i.ToString(CultureInfo.InvariantCulture));
                            return;
                        }
                    }
                }
            }
        }
 public string CustomGetUniqueName(IDesignerSerializationManager manager, object value)
 {
     return(base.GetUniqueName(manager, value));
 }
Esempio n. 35
0
        /// <summary>
        /// This method deserializes a previously serialized code type declaration. The default implementation performs the following tasks:
        /// • Case Sensitivity Checks: It looks for a CodeDomProvider service to decide if it should treat members as case sensitive or case insensitive.
        /// • Statement Sorting:  All member variables and local variables from init methods are stored in a table. Then each statement in an init method is added to a statement collection grouped according to its left hand side. So all statements assigning or operating on a particular variable are grouped under that variable.  Variables that have no statements are discarded.
        /// • Deserialization: Finally, the statement collections for each variable are deserialized according to the variable. Deserialize returns an instance of the root object.
        /// </summary>
        public virtual object Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

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

            object rootObject = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            using (TraceScope("EnumCodeDomSerializer::" + nameof(Serialize)))
            {
                Trace("Type: {0}", (value == null ? "(null)" : value.GetType().Name));
                if (value is Enum)
                {
                    bool          needCast = false;
                    Enum[]        values;
                    TypeConverter converter = TypeDescriptor.GetConverter(value);
                    if (converter != null && converter.CanConvertTo(typeof(Enum[])))
                    {
                        values   = (Enum[])converter.ConvertTo(value, typeof(Enum[]));
                        needCast = (values.Length > 1);
                    }
                    else
                    {
                        values   = new Enum[] { (Enum)value };
                        needCast = true;
                    }

                    // EnumConverter (and anything that is overridden to support enums)
                    // should be providing us a conversion to Enum[] for flag styles.
                    // If it doesn't, we will emit a warning and just do a cast from the enum value.

                    CodeTypeReferenceExpression enumType = new CodeTypeReferenceExpression(value.GetType());

                    // If names is of length 1, then this is a simple field reference. Otherwise,
                    // it is an or-d combination of expressions.
                    //
                    TraceIf(values.Length == 1, "Single field entity.");
                    TraceIf(values.Length > 1, "Multi field entity.");

                    // We now need to serialize the enum terms as fields. We new up an EnumConverter to do
                    // that. We cannot use the type's own converter since it might have a different string
                    // representation for its values. Hardcoding is okay in this case, since all we want is
                    // the enum's field name. Simply doing ToString() will not give us any validation.
                    TypeConverter enumConverter = new EnumConverter(value.GetType());
                    foreach (Enum term in values)
                    {
                        string         termString    = enumConverter?.ConvertToString(term);
                        CodeExpression newExpression = !String.IsNullOrEmpty(termString) ? new CodeFieldReferenceExpression(enumType, termString) : null;

                        if (newExpression != null)
                        {
                            if (expression == null)
                            {
                                expression = newExpression;
                            }
                            else
                            {
                                expression = new CodeBinaryOperatorExpression(expression, CodeBinaryOperatorType.BitwiseOr, newExpression);
                            }
                        }
                    }

                    // If we had to combine multiple names, wrap the result in an appropriate cast.
                    //
                    if (expression != null && needCast)
                    {
                        expression = new CodeCastExpression(value.GetType(), expression);
                    }
                }
                else
                {
                    Debug.Fail("Enum serializer called for non-enum object.");
                    TraceError("Enum serializer called for non-enum object {0}", (value == null ? "(null)" : value.GetType().Name));
                }
            }

            return(expression);
        }
        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);
        }
        /// <summary>
        ///     This serializes the given property on this object.
        /// </summary>
        private void SerializeExtenderProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, CodeStatementCollection statements)
        {
            AttributeCollection attributes = property.Attributes;

            using (CodeDomSerializer.TraceScope("PropertyMemberCodeDomSerializer::" + nameof(SerializeExtenderProperty)))
            {
                ExtenderProvidedPropertyAttribute exAttr = (ExtenderProvidedPropertyAttribute)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 == null, "Extender object {0} could not be serialized.", manager.GetName(exAttr.Provider));
                CodeDomSerializer.TraceWarningIf(extended == null, "Extended object {0} could not be serialized.", manager.GetName(value));
                if (extender != null && extended != null)
                {
                    CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression(extender, "Set" + property.Name);
                    bool           validValue;
                    object         propValue = GetPropertyValue(manager, property, value, out validValue);
                    CodeExpression serializedPropertyValue = null;

                    // Serialize the value of this property into a code expression.  If we can't get one,
                    // then we won't serialize the property.
                    if (validValue)
                    {
                        ExpressionContext tree = null;

                        if (propValue != value)
                        {
                            // make sure the value isn't the object or we'll end up printing
                            // this property instead of the value.
                            tree = new ExpressionContext(methodRef, property.PropertyType, value);
                            manager.Context.Push(tree);
                        }

                        try
                        {
                            serializedPropertyValue = SerializeToExpression(manager, propValue);
                        }
                        finally
                        {
                            if (tree != null)
                            {
                                Debug.Assert(manager.Context.Current == tree, "Context stack corrupted.");
                                manager.Context.Pop();
                            }
                        }
                    }

                    if (serializedPropertyValue != null)
                    {
                        CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression();

                        methodInvoke.Method = methodRef;
                        methodInvoke.Parameters.Add(extended);
                        methodInvoke.Parameters.Add(serializedPropertyValue);
                        statements.Add(methodInvoke);
                    }
                }
            }
        }
        /// <summary>
        ///    This method returns true if the given member descriptor should be serialized,
        ///    or false if there is no need to serialize the member.
        /// </summary>
        public override bool ShouldSerialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor)
        {
            PropertyDescriptor propertyToSerialize = descriptor as PropertyDescriptor;

            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (propertyToSerialize == null)
            {
                throw new ArgumentNullException(nameof(descriptor));
            }

            bool shouldSerializeProperty = propertyToSerialize.ShouldSerializeValue(value);

            if (!shouldSerializeProperty)
            {
                SerializeAbsoluteContext absolute = (SerializeAbsoluteContext)manager.Context[typeof(SerializeAbsoluteContext)];

                if (absolute != null && absolute.ShouldSerialize(propertyToSerialize))
                {
                    // For ReadOnly properties, we only want to override the value returned from
                    // ShouldSerializeValue() if the property is marked with DesignerSerializationVisibilityAttribute(Content).
                    // Consider the case of a property with just a getter - we only want to serialize those
                    // if they're marked in this way (see ReflectPropertyDescriptor::ShouldSerializeValue())
                    if (!propertyToSerialize.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content))
                    {
                        shouldSerializeProperty = false; // it's already false at this point, but this is clearer.
                    }
                    else
                    {
                        shouldSerializeProperty = true; // Always serialize difference properties
                    }
                }
            }

            if (shouldSerializeProperty)
            {
                bool isDesignTime = propertyToSerialize.Attributes.Contains(DesignOnlyAttribute.Yes);
                if (!isDesignTime)
                {
                    return(true);
                }
            }

            // If we don't have to serialize, we need to make sure there isn't a member
            // relationship with this property.  If there is, we still need to serialize.

            MemberRelationshipService relationships = manager.GetService(typeof(MemberRelationshipService)) as MemberRelationshipService;

            if (relationships != null)
            {
                MemberRelationship relationship = relationships[value, descriptor];

                if (relationship != MemberRelationship.Empty)
                {
                    return(true);
                }
            }


            return(false);
        }
        public void CodeDomSerializerException_Ctor_Exception_IDesignerSerializationManager(Exception innerException, IDesignerSerializationManager manager)
        {
            var exception = new CodeDomSerializerException(innerException, manager);

            Assert.NotEmpty(exception.Message);
            Assert.Same(innerException, exception.InnerException);
            Assert.Null(exception.LinePragma);
        }
        /// <summary>
        ///     This serializes the given property on this object.
        /// </summary>
        private void SerializeNormalProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, CodeStatementCollection statements)
        {
            using (CodeDomSerializer.TraceScope("CodeDomSerializer::" + nameof(SerializeProperty)))
            {
                CodeExpression target = SerializeToExpression(manager, value);

                CodeDomSerializer.TraceWarningIf(target == null, "Unable to serialize target for property {0}", property.Name);
                if (target != null)
                {
                    CodeExpression propertyRef = new CodePropertyReferenceExpression(target, property.Name);

                    CodeExpression serializedPropertyValue = null;

                    // First check for a member relationship service to see if this property
                    // is related to another member.  If it is, then we will use that
                    // relationship to construct the property assign statement.  if
                    // it isn't, then we're serialize ourselves.
                    MemberRelationshipService relationships = manager.GetService(typeof(MemberRelationshipService)) as MemberRelationshipService;

                    if (relationships != null)
                    {
                        MemberRelationship relationship = relationships[value, property];

                        if (relationship != MemberRelationship.Empty)
                        {
                            CodeExpression rhsTarget = SerializeToExpression(manager, relationship.Owner);

                            if (rhsTarget != null)
                            {
                                serializedPropertyValue = new CodePropertyReferenceExpression(rhsTarget, relationship.Member.Name);
                            }
                        }
                    }

                    if (serializedPropertyValue == null)
                    {
                        // Serialize the value of this property into a code expression.  If we can't get one,
                        // then we won't serialize the property.
                        //
                        bool   validValue;
                        object propValue = GetPropertyValue(manager, property, value, out validValue);

                        if (validValue)
                        {
                            ExpressionContext tree = null;

                            if (propValue != value)
                            {
                                // make sure the value isn't the object or we'll end up printing
                                // this property instead of the value.
                                tree = new ExpressionContext(propertyRef, property.PropertyType, value);
                                manager.Context.Push(tree);
                            }

                            try
                            {
                                serializedPropertyValue = SerializeToExpression(manager, propValue);
                            }
                            finally
                            {
                                if (tree != null)
                                {
                                    Debug.Assert(manager.Context.Current == tree, "Context stack corrupted.");
                                    manager.Context.Pop();
                                }
                            }
                        }
                    }

                    if (serializedPropertyValue != null)
                    {
                        CodeAssignStatement assign = new CodeAssignStatement(propertyRef, serializedPropertyValue);
                        statements.Add(assign);
                    }
                }
            }
        }
Esempio n. 43
0
 /// <summary>
 /// This is a small helper method that returns the serializer for base Class
 /// </summary>
 private CodeDomSerializer GetBaseSerializer(IDesignerSerializationManager manager)
 {
     return((CodeDomSerializer)manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer)));
 }
        /// <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.");

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

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

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

                string name = manager.GetName(value);

                if (name == 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 == 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 == null, "Extender object {0} could not be serialized.", manager.GetName(exAttr.Provider));
                            CodeDomSerializer.TraceWarningIf(extended == 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();
                                methodInvoke.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();
                            }

                            CodeStatementCollection csc = result as CodeStatementCollection;

                            if (csc != null)
                            {
                                foreach (CodeStatement statement in csc)
                                {
                                    statements.Add(statement);
                                }
                            }
                            else
                            {
                                CodeStatement cs = result as CodeStatement;

                                if (cs != null)
                                {
                                    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));
                }
            }
        }
 public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
 {
     return(null);
 }
        public void CodeDomSerializerException_Ctor_String_IDesignerSerializationManager(string message, IDesignerSerializationManager manager)
        {
            var exception = new CodeDomSerializerException(message, manager);

            Assert.NotEmpty(exception.Message);
            Assert.Null(exception.InnerException);
            Assert.Null(exception.LinePragma);
        }
Esempio n. 47
0
        public override object Deserialize(IDesignerSerializationManager manager, object codeDomObject)
        {
            var baseSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(ResourceManagerSetter).BaseType, typeof(CodeDomSerializer));

            return(baseSerializer.Deserialize(manager, codeDomObject));
        }
Esempio n. 48
0
 /// <summary>
 /// We implement this for the abstract method on CodeDomSerializer.
 /// </summary>
 public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
 {
     return(GetBaseSerializer(manager).Deserialize(manager, codeObject));
 }
Esempio n. 49
0
 protected CodeExpression SerializeToReferenceExpression(IDesignerSerializationManager manager, object value)
 {
     return(base.SerializeToExpression(manager, value));
 }
 protected override void PerformFlush(IDesignerSerializationManager designerSerializationManager)
 {
     System.Diagnostics.Trace.WriteLine("ReportDesignerLoader:PerformFlush");
     generator.MergeFormChanges((System.CodeDom.CodeCompileUnit)null);
 }
 /// <summary>
 ///  This method returns true if the given member descriptor should be serialized,
 ///  or false if there is no need to serialize the member.
 /// </summary>
 public override bool ShouldSerialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor) => true;
Esempio n. 52
0
        /// <summary>
        ///  Serializes the given object into a CodeDom object.
        /// </summary>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeStatementCollection      statements = null;
            PropertyDescriptorCollection props      = TypeDescriptor.GetProperties(value);

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

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

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

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

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

                    statements = new CodeStatementCollection();
                    CodeTypeDeclaration typeDecl  = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
                    RootContext         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 is null)
                        {
                            // We were in a serialize content
                            // property and would still serialize it.  This code reverses what the
                            // outer if block does for this specific case.  We also need this
                            // for Everett / 1.0 backwards compat.
                            if (!(manager.Context[typeof(ExpressionContext)] is ExpressionContext 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 is null)
                        {
                            generateLocal = true;
                            generateField = false;
                        }
                    }

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

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

                        string typeName = TypeDescriptor.GetClassName(value);

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

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

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

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

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

                            bool persistSettings = (value is IPersistComponentSettings) && ((IPersistComponentSettings)value).SaveSettings;
                            if (persistSettings)
                            {
                                string fullName = typeof(IPersistComponentSettings).FullName;
                                persistSettings = manager.GetType(fullName) != null;
                            }
                            if (persistSettings)
                            {
                                reflectionType  = reflectionType ?? GetReflectionTypeHelper(manager, value);
                                persistSettings = GetReflectionTypeFromTypeHelper(manager, typeof(IPersistComponentSettings)).IsAssignableFrom(reflectionType);
                            }
                            // We implement statement caching only for the main code generation phase.  We don't implement it for other
                            // serialization managers.  How do we tell the difference?  The main serialization manager exists as a service.
                            IDesignerSerializationManager mainManager = manager.GetService(typeof(IDesignerSerializationManager)) as IDesignerSerializationManager;

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

                            SerializePropertiesToResources(manager, statements, value, _designTimeFilter);

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

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

                                    // We cache components even if they're not valid so dependencies are
                                    // still tracked correctly (see comment below).  The problem is, we will create a
                                    // new entry object even if there is still an existing one that is just invalid, and it
                                    // might have dependencies that will be lost.
                                    // we need to make sure we copy over any dependencies that are also tracked.
                                    ComponentCache.Entry oldEntry = cache?.GetEntryAll(value);
                                    if (oldEntry != null && oldEntry.Dependencies != null && oldEntry.Dependencies.Count > 0)
                                    {
                                        foreach (object dependency in oldEntry.Dependencies)
                                        {
                                            entry.AddDependency(dependency);
                                        }
                                    }
                                }
                                entry.Component = value;
                                // we need to link the cached entry with its corresponding component right away, before it's put in the context
                                // see CodeDomSerializerBase.cs::GetExpression for usage

                                // This entry will only be used if the valid bit is set.
                                // This is useful because we still need to setup 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");
                            }
                        }
                    }
Esempio n. 53
0
        // Called by the host when we load a document.
        protected override void PerformLoad(IDesignerSerializationManager designerSerializationManager)
        {
            this.host = this.LoaderHost;

            if (host == null)
            {
                throw new ArgumentNullException("BasicHostLoader.BeginLoad: Invalid designerLoaderHost.");
            }

            // The loader will put error messages in here.
            ArrayList errors     = new ArrayList();
            bool      successful = true;
            string    baseClassName;

            // If no filename was passed in, just create a form and be done with it.  If a file name
            // was passed, read it.
            if (fileName == null)
            {
                baseClassName = name;
                if (rootComponentType == typeof(Form))
                {
                    host.CreateComponent(typeof(Form));
                }
                else if (rootComponentType == typeof(UserControl))
                {
                    host.CreateComponent(typeof(UserControl));
                }
                else if (rootComponentType == typeof(Component))
                {
                    host.CreateComponent(typeof(Component));
                }
                else
                {
                    throw new Exception("Undefined Host Type: " + rootComponentType.ToString());
                }
            }
            else
            {
                baseClassName = ReadFile(fileName, errors, out xmlDocument);
            }

            // Now that we are done with the load work, we need to begin to listen to events.
            // Listening to event notifications is how a designer "Loader" can also be used
            // to save data.  If we wanted to integrate this loader with source code control,
            // we would listen to the "ing" events as well as the "ed" events.
            IComponentChangeService cs = host.GetService(typeof(IComponentChangeService)) as IComponentChangeService;

            if (cs != null)
            {
                cs.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged);
                cs.ComponentAdded   += new ComponentEventHandler(OnComponentAddedRemoved);
                cs.ComponentRemoved += new ComponentEventHandler(OnComponentAddedRemoved);
            }

            // Let the host know we are done loading.
            host.EndLoad(baseClassName, successful, errors);

            // We've just loaded a document, so you can bet we need to flush changes.
            dirty   = true;
            unsaved = false;
        }
        /// <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 == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (!(descriptor is EventDescriptor eventToSerialize))
            {
                throw new ArgumentNullException(nameof(descriptor));
            }
            if (statements == null)
            {
                throw new ArgumentNullException(nameof(statements));
            }

            try
            {
                IEventBindingService eventBindings = (IEventBindingService)manager.GetService(typeof(IEventBindingService));

                // If the IEventBindingService is not available, we don't throw - we just don't do anything.
                if (eventBindings != null)
                {
                    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 == 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));
            }
        }
 public CodeDomSerializerException(Exception ex, IDesignerSerializationManager manager) : base(ex.Message, ex)
 {
     this.FillLinePragmaFromContext(manager);
 }
        public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
        {
            var baseSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(SharedImageCollection), typeof(CodeDomSerializer));

            return(baseSerializer.Deserialize(manager, codeObject));
        }
        /// <include file='doc\ComponentCodeDomSerializer.uex' path='docs/doc[@for="ComponentCodeDomSerializer.SerializeDeclaration"]/*' />
        /// <devdoc>
        ///     This ensures that the declaration for the component exists in the code class.  In
        ///     addition, it will wire up the creation of the object in the init method.
        /// </devdoc>
        private void SerializeDeclaration(IDesignerSerializationManager manager, CodeStatementCollection statements, object value)
        {
            Debug.WriteLineIf(traceSerialization.TraceVerbose, "ComponentCodeDomSerializer::SerializeDeclaration");
            Debug.Indent();

            // Attempt to get the type declaration in the context.
            //
            CodeTypeDeclaration docType = (CodeTypeDeclaration)manager.Context[typeof(CodeTypeDeclaration)];
            string name = manager.GetName(value);

            Debug.Assert(name != null, "Cannot serialize declaration of unnamed component.");

            if (name != null)
            {
                CodeTypeReference type = new CodeTypeReference(value.GetType());

                // Add the declaration to the code type, if we found one.
                //
                if (docType != null)
                {
                    MemberAttributes   modifiers    = MemberAttributes.Private;
                    PropertyDescriptor modifierProp = TypeDescriptor.GetProperties(value)["Modifiers"];
                    if (modifierProp != null && modifierProp.PropertyType == typeof(MemberAttributes))
                    {
                        modifiers = (MemberAttributes)modifierProp.GetValue(value);
                    }
                    else
                    {
                        Debug.WriteLineIf(traceSerialization.TraceWarning, "WARNING: No Modifiers property on component " + name + "; assuming private.");
                    }

                    // Create a field on the class that represents this component.
                    //
                    CodeMemberField field = new CodeMemberField(type, name);
                    field.Attributes = modifiers;

                    docType.Members.Add(field);
                }

                // Next, add the instance creation to our statement list.  We check to see if there is an instance
                // descriptor attached to this compnent type that knows how to emit, which allows components to
                // init themselves from static method calls or public static fields, rather than always creating
                // an instance.
                //
                CodeFieldReferenceExpression fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), name);
                CodeExpression createExpression       = null;

                if (TypeDescriptor.GetConverter(value).CanConvertTo(typeof(InstanceDescriptor)))
                {
                    // Got an instance descriptor.  Ask it to serialize
                    //
                    object o = InstanceDescriptorCodeDomSerializer.Default.Serialize(manager, value);
                    if (o is CodeExpression)
                    {
                        createExpression = (CodeExpression)o;
                    }
                }

                if (createExpression == null)
                {
                    // Standard object create
                    //
                    CodeObjectCreateExpression objectCreate = new CodeObjectCreateExpression();
                    objectCreate.CreateType = type;

                    // Check to see if this component has a constructor that takes an IContainer.  If it does,
                    // then add the container reference to the creation parameters.
                    //
                    ConstructorInfo ctr = value.GetType().GetConstructor(BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
                                                                         null, containerConstructor, null);

                    if (ctr != null)
                    {
                        Debug.WriteLineIf(traceSerialization.TraceVerbose, "Object requires an IContainer constructor.");
                        RootCodeDomSerializer rootSerializer = (RootCodeDomSerializer)manager.Context[typeof(RootCodeDomSerializer)];
                        Debug.WriteLineIf(traceSerialization.TraceWarning && rootSerializer == null, "WARNING : Context stack does not have a root serializer on it so we cannot emit a required container constructor.");
                        if (rootSerializer != null)
                        {
                            CodeFieldReferenceExpression container = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), rootSerializer.ContainerName);
                            objectCreate.Parameters.Add(container);
                            rootSerializer.ContainerRequired = true;
                        }
                    }

                    createExpression = objectCreate;
                }


                statements.Add(new CodeAssignStatement(fieldRef, createExpression));
            }

            Debug.Unindent();
        }
 public CodeDomSerializerException(string message, IDesignerSerializationManager manager) : base(message)
 {
     this.FillLinePragmaFromContext(manager);
 }
 public void CustomSerializeResource(IDesignerSerializationManager manager, string resourceName, object value)
 {
     base.SerializeResource(manager, resourceName, value);
 }
        /// <include file='doc\ComponentCodeDomSerializer.uex' path='docs/doc[@for="ComponentCodeDomSerializer.Deserialize"]/*' />
        /// <devdoc>
        ///     Deserilizes the given CodeDom object into a real object.  This
        ///     will use the serialization manager to create objects and resolve
        ///     data types.  The root of the object graph is returned.
        /// </devdoc>
        public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
        {
            if (manager == null || codeObject == null)
            {
                throw new ArgumentNullException(manager == null ? "manager" : "codeObject");
            }

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

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

            object instance = null;

            if (manager.Context[typeof(CodeExpression)] != null)
            {
                Debug.WriteLineIf(traceSerialization.TraceVerbose, "Retrieving instance from context stack");
                instance = DeserializeExpression(manager, null, (CodeExpression)manager.Context[typeof(CodeExpression)]);
                Debug.WriteLineIf(traceSerialization.TraceWarning && instance == null, "WARNING: CodeExpression on stack did not return an instance.");
                if (instance != null)
                {
                    DeserializePropertiesFromResources(manager, instance, designTimeProperties);
                }
            }


            // Now look for things we understand.
            //
            foreach (CodeStatement element in (CodeStatementCollection)codeObject)
            {
                if (element is CodeAssignStatement)
                {
                    CodeAssignStatement statement = (CodeAssignStatement)element;

                    // If this is an assign statement to a field, that field is our object.  Let DeserializeExpression
                    // do the work, but supply the field name as the name of the object.
                    //
                    if (statement.Left is CodeFieldReferenceExpression)
                    {
                        CodeFieldReferenceExpression fieldRef = (CodeFieldReferenceExpression)statement.Left;
                        Debug.WriteLineIf(traceSerialization.TraceVerbose, "Creating instance of object: " + fieldRef.FieldName);
                        Debug.WriteLineIf(traceSerialization.TraceWarning && instance != null, "WARNING: Instance has already been established.");
                        instance = DeserializeExpression(manager, fieldRef.FieldName, statement.Right);

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

            Debug.Unindent();
            return(instance);
        }