예제 #1
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeDomSerializer serializer1 = (CodeDomSerializer)manager.GetSerializer(this.GetPropType().BaseType, typeof(CodeDomSerializer));
            object            obj1        = serializer1.Serialize(manager, value);

            if (this.ShouldSerialize(value) && (obj1 is CodeStatementCollection))
            {
                string text1 = manager.GetName(value);
                if ((text1 != null) && (text1 != string.Empty))
                {
                    CodeStatementCollection collection1 = (CodeStatementCollection)obj1;
                    CodeExpression          expression1 = base.SerializeToExpression(manager, value);
                    IDesignerHost           host1       = ((Component)value).Container as IDesignerHost;
                    if (host1.RootComponent != null)
                    {
                        string text2 = manager.GetName(host1.RootComponent);
                        if ((text2 != null) && (text2 != string.Empty))
                        {
                            CodePropertyReferenceExpression expression2 = new CodePropertyReferenceExpression(expression1, this.GetPropName());
                            CodeExpression[] expressionArray1           = new CodeExpression[1] {
                                new CodeTypeOfExpression(text2)
                            };
                            expressionArray1 = new CodeExpression[1] {
                                new CodePrimitiveExpression(text1 + ".XmlScheme")
                            };
                            CodeMethodInvokeExpression expression3 = new CodeMethodInvokeExpression(new CodeObjectCreateExpression(typeof(ResourceManager), expressionArray1), "GetObject", expressionArray1);
                            CodeCastExpression         expression4 = new CodeCastExpression("System.String", expression3);
                            CodeAssignStatement        statement1  = new CodeAssignStatement(expression2, expression4);
                            collection1.Add(statement1);
                        }
                    }
                }
            }
            return(obj1);
        }
예제 #2
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeDomSerializer baseClassSerializer = (CodeDomSerializer)manager.
                                                    GetSerializer(typeof(MyComponent).BaseType, typeof(CodeDomSerializer));

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

            if (codeObject is CodeStatementCollection)
            {
                CodeStatementCollection statements = (CodeStatementCollection)codeObject;
                // Initial MyList
                // Generate "myComponent1.MyList = new System.Collections.Generic.List<string>();"
                CodeObjectCreateExpression objectCreate1;
                objectCreate1 = new CodeObjectCreateExpression("System.Collections.Generic.List<string>", new CodeExpression[] { });
                CodeAssignStatement as2 =
                    new CodeAssignStatement(new CodeVariableReferenceExpression(manager.GetName(value) + ".MyList"),
                                            objectCreate1);
                statements.Insert(0, as2);

                // Add my generated code comment
                string commentText           = "MyList generation code";
                CodeCommentStatement comment = new CodeCommentStatement(commentText);
                statements.Insert(1, comment);

                // Add items to MyList
                // Generate the following code
                // this.myComponent1.MyList.Add("string5");
                // this.myComponent1.MyList.Add("string4");
                // this.myComponent1.MyList.Add("string3");
                // this.myComponent1.MyList.Add("string2");
                // this.myComponent1.MyList.Add("string1");
                MyComponent myCom = (MyComponent)manager.GetInstance(manager.GetName(value));
                for (int i = 0; i < myCom.MyList.Count; i++)
                {
                    CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(
                        // targetObject that contains the method to invoke.
                        new CodeThisReferenceExpression(),
                        // methodName indicates the method to invoke.
                        manager.GetName(value) + ".MyList.Add",
                        // parameters array contains the parameters for the method.
                        new CodeExpression[] { new CodePrimitiveExpression(myCom.MyList[i]) });
                    CodeExpressionStatement expressionStatement;
                    expressionStatement = new CodeExpressionStatement(methodInvoke);
                    statements.Insert(2, expressionStatement);
                }
                // Remove system generated code
                statements.RemoveAt(statements.Count - 1);
            }
            return(codeObject);
        }
        /// <devdoc>
        ///     Serializes a SuspendLayout / ResumeLayout.
        /// </devdoc>
        private void SerializeSuspendResume(IDesignerSerializationManager manager, CodeStatementCollection statements, object value, string methodName)
        {
            Debug.WriteLineIf(traceSerialization.TraceVerbose, "ControlCodeDomSerializer::SerializeSuspendResume(" + methodName + ")");
            Debug.Indent();

            string name = manager.GetName(value);

            Debug.WriteLineIf(traceSerialization.TraceVerbose, name + "." + methodName);

            // Assemble a cast to ISupportInitialize, and then invoke the method.
            //
            CodeExpression field = SerializeToReferenceExpression(manager, value);
            CodeMethodReferenceExpression method       = new CodeMethodReferenceExpression(field, methodName);
            CodeMethodInvokeExpression    methodInvoke = new CodeMethodInvokeExpression();

            methodInvoke.Method = method;
            CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke);

            if (methodName == "SuspendLayout")
            {
                statement.UserData["statement-ordering"] = "begin";
            }
            else
            {
                methodInvoke.Parameters.Add(new CodePrimitiveExpression(false));
                statement.UserData["statement-ordering"] = "end";
            }

            statements.Add(statement);
            Debug.Unindent();
        }
        /// <summary>
        ///  We don't actually want to serialize any code here, so we just delegate that to the base type's
        ///  serializer. All we want to do is if we are in a localizable form, we want to push a
        ///  'LayoutSettings' entry into the resx.
        /// </summary>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            // First call the base serializer to serialize the object.
            object codeObject = GetBaseSerializer(manager).Serialize(manager, value);

            // Now push our layout settings stuff into the resx if we are not inherited read only and
            // are in a localizable Form.
            TableLayoutPanel tlp = value as TableLayoutPanel;

            Debug.Assert(tlp != null, "Huh? We were expecting to be serializing a TableLayoutPanel here.");

            if (tlp != null)
            {
                InheritanceAttribute ia = (InheritanceAttribute)TypeDescriptor.GetAttributes(tlp)[typeof(InheritanceAttribute)];

                if (ia is null || ia.InheritanceLevel != InheritanceLevel.InheritedReadOnly)
                {
                    IDesignerHost host = (IDesignerHost)manager.GetService(typeof(IDesignerHost));

                    if (IsLocalizable(host))
                    {
                        PropertyDescriptor lsProp = TypeDescriptor.GetProperties(tlp)[LayoutSettingsPropName];
                        object             val    = (lsProp != null) ? lsProp.GetValue(tlp) : null;

                        if (val != null)
                        {
                            string key = manager.GetName(tlp) + "." + LayoutSettingsPropName;
                            SerializeResourceInvariant(manager, key, val);
                        }
                    }
                }
            }

            return(codeObject);
        }
예제 #5
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            object           obj2      = this.GetBaseSerializer(manager).Serialize(manager, value);
            TableLayoutPanel component = value as TableLayoutPanel;

            if (component != null)
            {
                InheritanceAttribute attribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(component)[typeof(InheritanceAttribute)];
                if ((attribute == null) || (attribute.InheritanceLevel != InheritanceLevel.InheritedReadOnly))
                {
                    IDesignerHost service = (IDesignerHost)manager.GetService(typeof(IDesignerHost));
                    if (this.IsLocalizable(service))
                    {
                        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(component)[LayoutSettingsPropName];
                        object             obj3       = (descriptor != null) ? descriptor.GetValue(component) : null;
                        if (obj3 != null)
                        {
                            string resourceName = manager.GetName(component) + "." + LayoutSettingsPropName;
                            base.SerializeResourceInvariant(manager, resourceName, obj3);
                        }
                    }
                }
            }
            return(obj2);
        }
 private void SerializeMethodInvocation(IDesignerSerializationManager manager, CodeStatementCollection statements, object control, string methodName, CodeExpressionCollection parameters, Type[] paramTypes, bool preorder)
 {
     manager.GetName(control);
     paramTypes = ToTargetTypes(control, paramTypes);
     if (TypeDescriptor.GetReflectionType(control).GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance, null, paramTypes, null) != null)
     {
         CodeMethodReferenceExpression expression2 = new CodeMethodReferenceExpression(base.SerializeToExpression(manager, control), methodName);
         CodeMethodInvokeExpression    expression  = new CodeMethodInvokeExpression();
         expression.Method = expression2;
         if (parameters != null)
         {
             expression.Parameters.AddRange(parameters);
         }
         CodeExpressionStatement statement = new CodeExpressionStatement(expression);
         if (preorder)
         {
             statement.UserData["statement-ordering"] = "begin";
         }
         else
         {
             statement.UserData["statement-ordering"] = "end";
         }
         statements.Add(statement);
     }
 }
        protected string GetUniqueName(IDesignerSerializationManager manager, object instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            string name = manager.GetName(instance);

            if (name == null)
            {
                INameCreationService service = manager.GetService(typeof(INameCreationService)) as INameCreationService;
                name = service.CreateName(null, instance.GetType());
                if (name == null)
                {
                    name = instance.GetType().Name.ToLower();
                }
                manager.SetName(instance, name);
            }
            return(name);
        }
        public override CodeTypeDeclaration Serialize(IDesignerSerializationManager manager, object root, ICollection members)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (root == null)
            {
                throw new ArgumentNullException("root");
            }
            Activity activity = root as Activity;

            if (activity == null)
            {
                throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(Activity).FullName }), "root");
            }
            CodeTypeDeclaration declaration = base.Serialize(manager, root, members);
            CodeMemberMethod    method      = declaration.UserData[_initMethodKey] as CodeMemberMethod;

            if ((method != null) && (activity is CompositeActivity))
            {
                CodeStatement[] array = new CodeStatement[method.Statements.Count];
                method.Statements.CopyTo(array, 0);
                method.Statements.Clear();
                CodeAssignStatement statement = new CodeAssignStatement {
                    Left  = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "CanModifyActivities"),
                    Right = new CodePrimitiveExpression(true)
                };
                method.Statements.Add(statement);
                foreach (CodeStatement statement2 in array)
                {
                    method.Statements.Add(statement2);
                }
                CodeAssignStatement statement3 = new CodeAssignStatement {
                    Left  = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "CanModifyActivities"),
                    Right = new CodePrimitiveExpression(false)
                };
                method.Statements.Add(statement3);
            }
            foreach (CodeTypeMember member in declaration.Members)
            {
                CodeMemberField field = member as CodeMemberField;
                if (field != null)
                {
                    foreach (object obj2 in members)
                    {
                        if (!(obj2 is Activity))
                        {
                            throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(Activity).FullName }), "members");
                        }
                        Activity activity2 = obj2 as Activity;
                        if (((field.Name == manager.GetName(activity2)) && (((int)activity2.GetValue(ActivityMarkupSerializer.StartLineProperty)) != -1)) && (activity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty) != null))
                        {
                            field.LinePragma = new CodeLinePragma((string)activity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)activity2.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
                        }
                    }
                }
            }
            return(declaration);
        }
 private void SerializeMethodInvocation(IDesignerSerializationManager manager, CodeStatementCollection statements, object control, string methodName, CodeExpressionCollection parameters, Type[] paramTypes, ControlCodeDomSerializer.StatementOrdering ordering)
 {
     {
         string name = manager.GetName(control);
         paramTypes = ControlCodeDomSerializer.ToTargetTypes(control, paramTypes);
         MethodInfo method = TypeDescriptor.GetReflectionType(control).GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public, null, paramTypes, null);
         if (method != null)
         {
             CodeExpression targetObject           = base.SerializeToExpression(manager, control);
             CodeMethodReferenceExpression method2 = new CodeMethodReferenceExpression(targetObject, methodName);
             CodeMethodInvokeExpression    codeMethodInvokeExpression = new CodeMethodInvokeExpression();
             codeMethodInvokeExpression.Method = method2;
             if (parameters != null)
             {
                 codeMethodInvokeExpression.Parameters.AddRange(parameters);
             }
             CodeExpressionStatement codeExpressionStatement = new CodeExpressionStatement(codeMethodInvokeExpression);
             if (ordering != ControlCodeDomSerializer.StatementOrdering.Prepend)
             {
                 if (ordering == ControlCodeDomSerializer.StatementOrdering.Append)
                 {
                     codeExpressionStatement.UserData["statement-ordering"] = "end";
                 }
             }
             else
             {
                 codeExpressionStatement.UserData["statement-ordering"] = "begin";
             }
             statements.Add(codeExpressionStatement);
         }
     }
 }
		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;
		}
예제 #11
0
            private object DeserializeEntry(IDesignerSerializationManager manager, ObjectEntry objectEntry)
            {
                object deserialized = null;

                if (objectEntry.IsEntireObject)
                {
                    CodeDomSerializer serializer = (CodeDomSerializer)manager.GetSerializer(objectEntry.Type,
                                                                                            typeof(CodeDomSerializer));
                    if (serializer != null)
                    {
                        deserialized = serializer.Deserialize(manager, objectEntry.Serialized);
                        // check if the name of the object has changed
                        // (if it e.g clashes with another name)
                        string newName = manager.GetName(deserialized);
                        if (newName != objectEntry.Name)
                        {
                            objectEntry.Name = newName;
                        }
                    }
                }
                else
                {
                    foreach (MemberEntry memberEntry in objectEntry.Members.Values)
                    {
                        CodeDomSerializer serializer = (CodeDomSerializer)manager.GetSerializer(objectEntry.Type,
                                                                                                typeof(CodeDomSerializer));
                        if (serializer != null)
                        {
                            serializer.Deserialize(manager, memberEntry.Serialized);
                        }
                    }
                }

                return(deserialized);
            }
		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;
		}
예제 #13
0
        private void SerializeMethodInvocation(IDesignerSerializationManager manager, CodeStatementCollection statements, object control, string methodName, CodeExpressionCollection parameters, System.Type[] paramTypes, StatementOrdering ordering)
        {
            using (CodeDomSerializerBase.TraceScope("ControlCodeDomSerializer::SerializeMethodInvocation(" + methodName + ")"))
            {
                manager.GetName(control);
                paramTypes = ToTargetTypes(control, paramTypes);
                if (TypeDescriptor.GetReflectionType(control).GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance, null, paramTypes, null) != null)
                {
                    CodeMethodReferenceExpression expression2 = new CodeMethodReferenceExpression(base.SerializeToExpression(manager, control), methodName);
                    CodeMethodInvokeExpression    expression  = new CodeMethodInvokeExpression {
                        Method = expression2
                    };
                    if (parameters != null)
                    {
                        expression.Parameters.AddRange(parameters);
                    }
                    CodeExpressionStatement statement = new CodeExpressionStatement(expression);
                    switch (ordering)
                    {
                    case StatementOrdering.Prepend:
                        statement.UserData["statement-ordering"] = "begin";
                        break;

                    case StatementOrdering.Append:
                        statement.UserData["statement-ordering"] = "end";
                        break;
                    }
                    statements.Add(statement);
                }
            }
        }
예제 #14
0
		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;
		}
        protected CodeExpression GetExpression(IDesignerSerializationManager manager, object instance)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            CodeExpression expression = null;

            ExpressionTable expressions = manager.Context[typeof(ExpressionTable)] as ExpressionTable;

            if (expressions != null)             // 1st try: ExpressionTable
            {
                expression = expressions [instance] as CodeExpression;
            }

            if (expression == null)               // 2nd try: RootContext
            {
                RootContext context = manager.Context[typeof(RootContext)] as RootContext;
                if (context != null && context.Value == instance)
                {
                    expression = context.Expression;
                }
            }

            if (expression == null)               // 3rd try: IReferenceService (instnace.property.property.property
            {
                string name = manager.GetName(instance);
                if (name == null || name.IndexOf(".") == -1)
                {
                    IReferenceService service = manager.GetService(typeof(IReferenceService)) as IReferenceService;
                    if (service != null)
                    {
                        name = service.GetName(instance);
                        if (name != null && name.IndexOf(".") != -1)
                        {
                            string[] parts = name.Split(new char[] { ',' });
                            instance = manager.GetInstance(parts[0]);
                            if (instance != null)
                            {
                                expression = SerializeToExpression(manager, instance);
                                if (expression != null)
                                {
                                    for (int i = 1; i < parts.Length; i++)
                                    {
                                        expression = new CodePropertyReferenceExpression(expression, parts[i]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(expression);
        }
예제 #16
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            PropertyDescriptor descriptor = (PropertyDescriptor)manager.Context[typeof(PropertyDescriptor)];
            ExpressionContext  context    = (ExpressionContext)manager.Context[typeof(ExpressionContext)];
            bool flag  = (value != null) ? CodeDomSerializerBase.GetReflectionTypeHelper(manager, value).IsSerializable : true;
            bool flag2 = !flag;
            bool flag3 = (descriptor != null) && descriptor.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content);

            if (!flag2)
            {
                flag2 = ((context != null) && (context.PresetValue != null)) && (context.PresetValue == value);
            }
            if (((this._model == CodeDomLocalizationModel.PropertyReflection) && !flag3) && !flag2)
            {
                CodeStatementCollection statements = (CodeStatementCollection)manager.Context[typeof(CodeStatementCollection)];
                bool flag4 = false;
                ExtenderProvidedPropertyAttribute attribute = null;
                if (descriptor != null)
                {
                    attribute = descriptor.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute;
                    if ((attribute != null) && (attribute.ExtenderProperty != null))
                    {
                        flag4 = true;
                    }
                }
                if ((!flag4 && (context != null)) && (statements != null))
                {
                    string         name       = manager.GetName(context.Owner);
                    CodeExpression expression = base.SerializeToExpression(manager, context.Owner);
                    if ((name != null) && (expression != null))
                    {
                        RootContext context2 = manager.Context[typeof(RootContext)] as RootContext;
                        if ((context2 != null) && (context2.Value == context.Owner))
                        {
                            name = "$this";
                        }
                        base.SerializeToResourceExpression(manager, value, false);
                        if (this.EmitApplyMethod(manager, context.Owner))
                        {
                            ResourceManager manager2 = manager.Context[typeof(ResourceManager)] as ResourceManager;
                            CodeMethodReferenceExpression expression3 = new CodeMethodReferenceExpression(base.GetExpression(manager, manager2), "ApplyResources");
                            CodeMethodInvokeExpression    expression4 = new CodeMethodInvokeExpression {
                                Method = expression3
                            };
                            expression4.Parameters.Add(expression);
                            expression4.Parameters.Add(new CodePrimitiveExpression(name));
                            statements.Add(expression4);
                        }
                        return(null);
                    }
                }
            }
            if (flag2)
            {
                return(this._currentSerializer.Serialize(manager, value));
            }
            return(base.SerializeToResourceExpression(manager, value));
        }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     PropertyDescriptor descriptor = (PropertyDescriptor) manager.Context[typeof(PropertyDescriptor)];
     ExpressionContext context = (ExpressionContext) manager.Context[typeof(ExpressionContext)];
     bool flag = (value != null) ? CodeDomSerializerBase.GetReflectionTypeHelper(manager, value).IsSerializable : true;
     bool flag2 = !flag;
     bool flag3 = (descriptor != null) && descriptor.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content);
     if (!flag2)
     {
         flag2 = ((context != null) && (context.PresetValue != null)) && (context.PresetValue == value);
     }
     if (((this._model == CodeDomLocalizationModel.PropertyReflection) && !flag3) && !flag2)
     {
         CodeStatementCollection statements = (CodeStatementCollection) manager.Context[typeof(CodeStatementCollection)];
         bool flag4 = false;
         ExtenderProvidedPropertyAttribute attribute = null;
         if (descriptor != null)
         {
             attribute = descriptor.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute;
             if ((attribute != null) && (attribute.ExtenderProperty != null))
             {
                 flag4 = true;
             }
         }
         if ((!flag4 && (context != null)) && (statements != null))
         {
             string name = manager.GetName(context.Owner);
             CodeExpression expression = base.SerializeToExpression(manager, context.Owner);
             if ((name != null) && (expression != null))
             {
                 RootContext context2 = manager.Context[typeof(RootContext)] as RootContext;
                 if ((context2 != null) && (context2.Value == context.Owner))
                 {
                     name = "$this";
                 }
                 base.SerializeToResourceExpression(manager, value, false);
                 if (this.EmitApplyMethod(manager, context.Owner))
                 {
                     ResourceManager manager2 = manager.Context[typeof(ResourceManager)] as ResourceManager;
                     CodeMethodReferenceExpression expression3 = new CodeMethodReferenceExpression(base.GetExpression(manager, manager2), "ApplyResources");
                     CodeMethodInvokeExpression expression4 = new CodeMethodInvokeExpression {
                         Method = expression3
                     };
                     expression4.Parameters.Add(expression);
                     expression4.Parameters.Add(new CodePrimitiveExpression(name));
                     statements.Add(expression4);
                 }
                 return null;
             }
         }
     }
     if (flag2)
     {
         return this._currentSerializer.Serialize(manager, value);
     }
     return base.SerializeToResourceExpression(manager, value);
 }
예제 #18
0
 protected CodeStatement AttachToEvent(IDesignerSerializationManager manager,
                                       string eventName, Type delegateType, object connectingComponent, string componentMethod)
 {
     return(new CodeAttachEventStatement(
                new CodeThisReferenceExpression(), eventName,
                new CodeDelegateCreateExpression(
                    new CodeTypeReference(delegateType),
                    new CodeVariableReferenceExpression(manager.GetName(connectingComponent)),
                    componentMethod)));
 }
        /// <include file='doc\ComponentCodeDomSerializer.uex' path='docs/doc[@for="ComponentCodeDomSerializer.SerializeSupportInitialize"]/*' />
        /// <devdoc>
        ///     This emits a method invoke to ISupportInitialize.
        /// </devdoc>
        private void SerializeSupportInitialize(IDesignerSerializationManager manager, CodeStatementCollection statements, object value, string methodName)
        {
            Debug.WriteLineIf(traceSerialization.TraceVerbose, "ComponentCodeDomSerializer::SerializeSupportInitialize");
            Debug.Indent();

            string name = manager.GetName(value);

            if (name == null)
            {
                IReferenceService referenceService = (IReferenceService)manager.GetService(typeof(IReferenceService));
                if (referenceService != null)
                {
                    name = referenceService.GetName(value);
                }
            }

            Debug.WriteLineIf(traceSerialization.TraceVerbose, name + "." + methodName);

            // Assemble a cast to ISupportInitialize, and then invoke the method.
            //
            CodeExpression targetExpr = null;

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

            if (host != null && host.RootComponent == value)
            {
                targetExpr = new CodeThisReferenceExpression();
            }
            else
            {
                targetExpr = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), name);
            }

            CodeTypeReference             type         = new CodeTypeReference(typeof(ISupportInitialize));
            CodeCastExpression            castExp      = new CodeCastExpression(type, targetExpr);
            CodeMethodReferenceExpression method       = new CodeMethodReferenceExpression(castExp, methodName);
            CodeMethodInvokeExpression    methodInvoke = new CodeMethodInvokeExpression();

            methodInvoke.Method = method;
            CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke);

            if (methodName == "BeginInit")
            {
                statement.UserData["statement-ordering"] = "begin";
            }
            else
            {
                statement.UserData["statement-ordering"] = "end";
            }

            statements.Add(statement);
            Debug.Unindent();
        }
예제 #20
0
        /// <summary>
        ///  This method is invoked during deserialization to obtain an instance of an object.  When this is called, an instance
        ///  of the requested type should be returned.  This implementation calls base and then tries to deserialize design
        ///  time properties for the component.
        /// </summary>
        protected override object DeserializeInstance(IDesignerSerializationManager manager, Type type, object[] parameters, string name, bool addToContainer)
        {
            object instance = base.DeserializeInstance(manager, type, parameters, name, addToContainer);

            if (instance != null)
            {
                Trace("Deserializing design time properties for {0}", manager.GetName(instance));
                DeserializePropertiesFromResources(manager, instance, _designTimeFilter);
            }

            return(instance);
        }
예제 #21
0
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

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

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

            manager.Context.Push(rootContext);

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

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

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

            manager.Context.Pop();
            return(_codeMap.GenerateClass());
        }
        public virtual CodeTypeDeclaration Serialize(IDesignerSerializationManager manager, object root, ICollection members)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (root == null)
            {
                throw new ArgumentNullException("root");
            }
            CodeTypeDeclaration         declaration = new CodeTypeDeclaration(manager.GetName(root));
            CodeThisReferenceExpression expression  = new CodeThisReferenceExpression();
            RootContext      context  = new RootContext(expression, root);
            StatementContext context2 = new StatementContext();

            context2.StatementCollection.Populate(root);
            if (members != null)
            {
                context2.StatementCollection.Populate(members);
            }
            declaration.BaseTypes.Add(root.GetType());
            manager.Context.Push(declaration);
            manager.Context.Push(context);
            manager.Context.Push(context2);
            try
            {
                if (members != null)
                {
                    foreach (object obj2 in members)
                    {
                        if (obj2 != root)
                        {
                            base.SerializeToExpression(manager, obj2);
                        }
                    }
                }
                base.SerializeToExpression(manager, root);
                this.IntegrateStatements(manager, root, members, context2, declaration);
            }
            finally
            {
                manager.Context.Pop();
                manager.Context.Pop();
                manager.Context.Pop();
            }
            return(declaration);
        }
예제 #23
0
        public virtual CodeStatementCollection SerializeMember(IDesignerSerializationManager manager,
                                                               object owningobject, MemberDescriptor member)
        {
            if (member == null)
            {
                throw new ArgumentNullException("member");
            }
            if (owningobject == null)
            {
                throw new ArgumentNullException("owningobject");
            }
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            CodeStatementCollection statements = new CodeStatementCollection();

            CodeExpression expression = base.GetExpression(manager, owningobject);

            if (expression == null)
            {
                string name = manager.GetName(owningobject);
                if (name == null)
                {
                    name = base.GetUniqueName(manager, owningobject);
                }
                expression = new CodeVariableReferenceExpression(name);
                base.SetExpression(manager, owningobject, expression);
            }

            manager.Context.Push(new ExpressionContext(expression, expression.GetType(), null, owningobject));

            if (member is PropertyDescriptor)
            {
                base.SerializeProperty(manager, statements, owningobject, (PropertyDescriptor)member);
            }
            if (member is EventDescriptor)
            {
                base.SerializeEvent(manager, statements, owningobject, (EventDescriptor)member);
            }

            manager.Context.Pop();

            return(statements);
        }
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeDomSerializer serial = GetConfiguredSerializer(manager, value);

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

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

            PropertyDescriptor prop = TypeDescriptor.GetProperties(value)["WebMapping"];
            MapperInfo         info = (MapperInfo)prop.GetValue(value);

            DataUIMapper dm = (DataUIMapper)
                              DesignUtils.ProviderProperty.GetValue(prop, new object[0]);

            //Attach the view mappings to the control attributes.
            if (info.ControlProperty != String.Empty && info.DataProperty != String.Empty)
            {
                CodeExpression     ctlref = SerializeToExpression(manager, value);
                CodeCastExpression cast   = new CodeCastExpression(typeof(IAttributeAccessor), ctlref);

                statements.Add(new CodeMethodInvokeExpression(
                                   cast, "SetAttribute", new CodeExpression[] {
                    new CodePrimitiveExpression("DIM_Mapper"),
                    new CodePrimitiveExpression(manager.GetName(dm))
                }));
                statements.Add(new CodeMethodInvokeExpression(
                                   cast, "SetAttribute", new CodeExpression[] {
                    new CodePrimitiveExpression("DIM_Format"),
                    new CodePrimitiveExpression(info.Format)
                }));
                statements.Add(new CodeMethodInvokeExpression(
                                   cast, "SetAttribute", new CodeExpression[] {
                    new CodePrimitiveExpression("DIM_DataProperty"),
                    new CodePrimitiveExpression(info.DataProperty)
                }));
                statements.Add(new CodeMethodInvokeExpression(
                                   cast, "SetAttribute", new CodeExpression[] {
                    new CodePrimitiveExpression("DIM_ControlProperty"),
                    new CodePrimitiveExpression(info.ControlProperty)
                }));
            }
            return(statements);
        }
        private void SerializeComponent(IDesignerSerializationManager manager, IComponent component)
        {
            CodeDomSerializer serializer = base.GetSerializer(manager, component) as CodeDomSerializer;              // ComponentCodeDomSerializer

            if (serializer != null)
            {
                this.Code.AddField(new CodeMemberField(component.GetType(), manager.GetName(component)));

                CodeStatementCollection statements = (CodeStatementCollection)serializer.Serialize(manager, component);

                CodeStatement ctorStatement = ExtractCtorStatement(manager, statements, component);
                if (ctorStatement != null)
                {
                    Code.AddPreInitStatement(ctorStatement);
                }
                Code.AddInitStatements(statements);
            }
        }
예제 #26
0
        /// <summary>
        ///  Serializes a method invocation on the control being serialized.  Used to serialize Suspend/ResumeLayout pairs, etc.
        /// </summary>
        private void SerializeMethodInvocation(IDesignerSerializationManager manager, CodeStatementCollection statements, object control, string methodName, CodeExpressionCollection parameters, Type[] paramTypes, StatementOrdering ordering)
        {
            using (TraceScope("ControlCodeDomSerializer::SerializeMethodInvocation(" + methodName + ")"))
            {
                string name = manager.GetName(control);
                Trace(name + "." + methodName);

                // Use IReflect to see if this method name exists on the control.
                paramTypes = ToTargetTypes(control, paramTypes);
                MethodInfo mi = TypeDescriptor.GetReflectionType(control).GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance, null, paramTypes, null);

                if (mi != null)
                {
                    CodeExpression field = SerializeToExpression(manager, control);
                    CodeMethodReferenceExpression method       = new CodeMethodReferenceExpression(field, methodName);
                    CodeMethodInvokeExpression    methodInvoke = new CodeMethodInvokeExpression();
                    methodInvoke.Method = method;

                    if (parameters != null)
                    {
                        methodInvoke.Parameters.AddRange(parameters);
                    }

                    CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke);

                    switch (ordering)
                    {
                    case StatementOrdering.Prepend:
                        statement.UserData["statement-ordering"] = "begin";
                        break;

                    case StatementOrdering.Append:
                        statement.UserData["statement-ordering"] = "end";
                        break;

                    default:
                        Debug.Fail("Unsupported statement ordering: " + ordering);
                        break;
                    }

                    statements.Add(statement);
                }
            }
        }
예제 #27
0
            private static void GenerateWorkItemCode(IDesignerSerializationManager manager, object value, CodeStatementCollection statements)
            {
                // See if there's a smartpart assigned at designtime.
                string smartPart = (string)TypeDescriptor.GetProperties(value)["SmartPart"].GetValue(value);

                if (smartPart != null)
                {
                    // Add the registration information to it.
                    CodeMethodInvokeExpression registerSP = new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(
                            new CodeBaseReferenceExpression(),
                            "RegisterSmartPartInfo"),
                        new CodeFieldReferenceExpression(
                            new CodeThisReferenceExpression(),
                            smartPart),
                        new CodeFieldReferenceExpression(
                            new CodeThisReferenceExpression(),
                            manager.GetName(value)));
                    statements.Add(registerSP);
                }
            }
예제 #28
0
        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);
        }
예제 #29
0
        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);
        }
        private Hashtable SerializeDesignTimeProperties(IDesignerSerializationManager manager, ICollection objectList)
        {
            Hashtable t = new Hashtable();

            Attribute[] dtAttrs = new Attribute[] { DesignOnlyAttribute.Yes };
            foreach (object o in objectList)
            {
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(o, dtAttrs);
                string name = manager.GetName(o);
                foreach (PropertyDescriptor prop in props)
                {
                    string propName = name + "." + prop.Name;
                    object value    = prop.GetValue(o);

                    if (prop.ShouldSerializeValue(o) && (value == null || value.GetType().IsSerializable))
                    {
                        t[propName] = value;
                    }
                }
            }
            return(t);
        }
        protected CodeExpression SerializeToReferenceExpression(IDesignerSerializationManager manager, object value)
        {
            CodeExpression expression = null;

            using (CodeDomSerializerBase.TraceScope("CodeDomSerializer::SerializeToReferenceExpression"))
            {
                expression = base.GetExpression(manager, value);
                if ((expression != null) || !(value is IComponent))
                {
                    return(expression);
                }
                string name = manager.GetName(value);
                bool   flag = false;
                if (name == null)
                {
                    IReferenceService service = (IReferenceService)manager.GetService(typeof(IReferenceService));
                    if (service != null)
                    {
                        name = service.GetName(value);
                        flag = name != null;
                    }
                }
                if (name == null)
                {
                    return(expression);
                }
                RootContext context = (RootContext)manager.Context[typeof(RootContext)];
                if ((context != null) && (context.Value == value))
                {
                    return(context.Expression);
                }
                if (flag && (name.IndexOf('.') != -1))
                {
                    int index = name.IndexOf('.');
                    return(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(_thisRef, name.Substring(0, index)), name.Substring(index + 1)));
                }
                return(new CodeFieldReferenceExpression(_thisRef, name));
            }
        }
예제 #32
0
        private void SerializeComponent(IDesignerSerializationManager manager, IComponent component)
        {
            CodeDomSerializer serializer = base.GetSerializer(manager, component) as CodeDomSerializer; // ComponentCodeDomSerializer

            if (serializer != null)
            {
                this._codeMap.AddField(new CodeMemberField(component.GetType(), manager.GetName(component)));
                // statements can be a CodeExpression if the full serialization has been completed prior
                // to this serialization call (e.g when it is requested during the serialization of another
                // component.
                //
                CodeStatementCollection statements = serializer.Serialize(manager, component) as CodeStatementCollection;
                if (statements != null)
                {
                    _codeMap.Add(statements);
                }
                CodeStatement statement = serializer.Serialize(manager, component) as CodeStatement;
                if (statement != null)
                {
                    _codeMap.Add(statement);
                }
            }
        }
예제 #33
0
        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);
        }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     object obj2 = this.GetBaseSerializer(manager).Serialize(manager, value);
     TableLayoutPanel component = value as TableLayoutPanel;
     if (component != null)
     {
         InheritanceAttribute attribute = (InheritanceAttribute) TypeDescriptor.GetAttributes(component)[typeof(InheritanceAttribute)];
         if ((attribute == null) || (attribute.InheritanceLevel != InheritanceLevel.InheritedReadOnly))
         {
             IDesignerHost service = (IDesignerHost) manager.GetService(typeof(IDesignerHost));
             if (this.IsLocalizable(service))
             {
                 PropertyDescriptor descriptor = TypeDescriptor.GetProperties(component)[LayoutSettingsPropName];
                 object obj3 = (descriptor != null) ? descriptor.GetValue(component) : null;
                 if (obj3 != null)
                 {
                     string resourceName = manager.GetName(component) + "." + LayoutSettingsPropName;
                     base.SerializeResourceInvariant(manager, resourceName, obj3);
                 }
             }
         }
     }
     return obj2;
 }
 public override CodeTypeDeclaration Serialize(IDesignerSerializationManager manager, object root, ICollection members)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (root == null)
     {
         throw new ArgumentNullException("root");
     }
     Activity activity = root as Activity;
     if (activity == null)
     {
         throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(Activity).FullName }), "root");
     }
     CodeTypeDeclaration declaration = base.Serialize(manager, root, members);
     CodeMemberMethod method = declaration.UserData[_initMethodKey] as CodeMemberMethod;
     if ((method != null) && (activity is CompositeActivity))
     {
         CodeStatement[] array = new CodeStatement[method.Statements.Count];
         method.Statements.CopyTo(array, 0);
         method.Statements.Clear();
         CodeAssignStatement statement = new CodeAssignStatement {
             Left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "CanModifyActivities"),
             Right = new CodePrimitiveExpression(true)
         };
         method.Statements.Add(statement);
         foreach (CodeStatement statement2 in array)
         {
             method.Statements.Add(statement2);
         }
         CodeAssignStatement statement3 = new CodeAssignStatement {
             Left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "CanModifyActivities"),
             Right = new CodePrimitiveExpression(false)
         };
         method.Statements.Add(statement3);
     }
     foreach (CodeTypeMember member in declaration.Members)
     {
         CodeMemberField field = member as CodeMemberField;
         if (field != null)
         {
             foreach (object obj2 in members)
             {
                 if (!(obj2 is Activity))
                 {
                     throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(Activity).FullName }), "members");
                 }
                 Activity activity2 = obj2 as Activity;
                 if (((field.Name == manager.GetName(activity2)) && (((int) activity2.GetValue(ActivityMarkupSerializer.StartLineProperty)) != -1)) && (activity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty) != null))
                 {
                     field.LinePragma = new CodeLinePragma((string) activity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int) activity2.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
                 }
             }
         }
     }
     return declaration;
 }
		private void DeserializeAssignmentStatement (IDesignerSerializationManager manager, CodeAssignStatement statement)
		{
			CodeExpression leftExpr = statement.Left;
			
			// Assign to a Property
			//
			CodePropertyReferenceExpression propRef = leftExpr as CodePropertyReferenceExpression;
			if (propRef != null) {
				object propertyHolder = DeserializeExpression (manager, null, propRef.TargetObject);
				object value = null;
				if (propertyHolder != null && propertyHolder != _errorMarker)
					value = DeserializeExpression (manager, null, statement.Right);

				if (value != null && value != _errorMarker && propertyHolder != null) {
					PropertyDescriptor property = TypeDescriptor.GetProperties (propertyHolder)[propRef.PropertyName];
					if (property != null) {
						property.SetValue (propertyHolder, value);
					} else {
						ReportError (manager, 
							     "Missing property '" + propRef.PropertyName + 
							     "' in type '" + propertyHolder.GetType ().Name + "'");
					}
				}
			}
			
			// Assign to a Field
			// 
			CodeFieldReferenceExpression fieldRef = leftExpr as CodeFieldReferenceExpression;
			if (fieldRef != null && fieldRef.FieldName != null) {
				// Note that if the Right expression is a CodeCreationExpression the component will be created in this call
				//
				object fieldHolder = DeserializeExpression (manager, null, fieldRef.TargetObject);
				object value = null;
				if (fieldHolder != null && fieldHolder != _errorMarker)
					value = DeserializeExpression (manager, fieldRef.FieldName, statement.Right);
				FieldInfo field = null;

				RootContext context = manager.Context[typeof (RootContext)] as RootContext;
				if (fieldHolder != null && fieldHolder != _errorMarker && value != _errorMarker) {
					if (fieldRef.TargetObject is CodeThisReferenceExpression && context != null && context.Value == fieldHolder) {
						// Do not deserialize the fields of the root component, because the root component type 
						// is actually an instance of the its parent type, e.g: CustomControl : _UserControl_
						// and thus it doesn't contain the fields. The trick is that once DeserializeExpression 
						// is called on a CodeObjectCreateExpression the component is created and is added to the name-instance
						// table.
						// 
					} else {
						if (fieldHolder is Type) // static field
							field = ((Type)fieldHolder).GetField (fieldRef.FieldName, 
											      BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
						else // instance field
							field = fieldHolder.GetType().GetField (fieldRef.FieldName, 
												BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance);
						if (field != null)
							field.SetValue (fieldHolder, value);
						else {
							ReportError (manager, "Field '" + fieldRef.FieldName + "' missing in type '" +
								     fieldHolder.GetType ().Name + "'",
								     "Field Name: " + fieldRef.FieldName + System.Environment.NewLine +
								     "Field is: " + (fieldHolder is Type ? "static" : "instance") + System.Environment.NewLine +
								     "Field Value: " + (value == null ? "null" : value.ToString()) + System.Environment.NewLine +
								     "Field Holder Type: " + fieldHolder.GetType ().Name + System.Environment.NewLine +
								     "Field Holder Expression Type: " + fieldRef.TargetObject.GetType ().Name);
						}
					}
				}
			}

			// Assign to a Variable
			// 
			CodeVariableReferenceExpression varRef = leftExpr as CodeVariableReferenceExpression;
			if (varRef != null && varRef.VariableName != null) {
				object value = DeserializeExpression (manager, varRef.VariableName, statement.Right);
				// If .Right is not CodeObjectCreateExpression the instance won't be assigned a name, 
				// so do it ourselves
				if (value != _errorMarker && manager.GetName (value) == null)
					manager.SetName (value, varRef.VariableName);
			}
		}
예제 #37
0
		private void SerializeComponent (IDesignerSerializationManager manager, IComponent component)
		{
			CodeDomSerializer serializer = base.GetSerializer (manager, component) as CodeDomSerializer; // ComponentCodeDomSerializer
			if (serializer != null) {
				this._codeMap.AddField (new CodeMemberField (component.GetType (), manager.GetName (component)));
				// statements can be a CodeExpression if the full serialization has been completed prior 
				// to this serialization call (e.g when it is requested during the serialization of another 
				// component.
				// 
				CodeStatementCollection statements = serializer.Serialize (manager, component) as CodeStatementCollection;
				if (statements != null)
					_codeMap.Add (statements);
				CodeStatement statement = serializer.Serialize (manager, component) as CodeStatement;
				if (statement != null)
					_codeMap.Add (statement);
			}
		}
예제 #38
0
        /// <summary>
        ///  Serializes the given object into a CodeDom object.  This uses the stock
        ///  resource serialization scheme and retains the expression it provides.
        /// </summary>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            PropertyDescriptor desc = (PropertyDescriptor)manager.Context[typeof(PropertyDescriptor)];
            ExpressionContext  tree = (ExpressionContext)manager.Context[typeof(ExpressionContext)];
            bool isSerializable     = (value is not null) ? GetReflectionTypeHelper(manager, value).IsSerializable : true;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return(SerializeToResourceExpression(manager, value));
        }
 private object Serialize(IDesignerSerializationManager manager, object value, bool forceInvariant, bool shouldSerializeInvariant, bool ensureInvariant)
 {
     using (CodeDomSerializerBase.TraceScope("ResourceCodeDomSerializer::Serialize"))
     {
         bool flag;
         string str3;
         SerializationResourceManager resourceManager = this.GetResourceManager(manager);
         CodeStatementCollection statements = (CodeStatementCollection) manager.Context[typeof(CodeStatementCollection)];
         if (!forceInvariant)
         {
             if (!resourceManager.DeclarationAdded)
             {
                 resourceManager.DeclarationAdded = true;
                 RootContext context = manager.Context[typeof(RootContext)] as RootContext;
                 if (statements != null)
                 {
                     CodeExpression[] expressionArray;
                     if (context != null)
                     {
                         string name = manager.GetName(context.Value);
                         expressionArray = new CodeExpression[] { new CodeTypeOfExpression(name) };
                     }
                     else
                     {
                         expressionArray = new CodeExpression[] { new CodePrimitiveExpression(this.ResourceManagerName) };
                     }
                     CodeExpression initExpression = new CodeObjectCreateExpression(typeof(ComponentResourceManager), expressionArray);
                     statements.Add(new CodeVariableDeclarationStatement(typeof(ComponentResourceManager), this.ResourceManagerName, initExpression));
                     base.SetExpression(manager, resourceManager, new CodeVariableReferenceExpression(this.ResourceManagerName));
                     resourceManager.ExpressionAdded = true;
                 }
             }
             else if (!resourceManager.ExpressionAdded)
             {
                 if (base.GetExpression(manager, resourceManager) == null)
                 {
                     base.SetExpression(manager, resourceManager, new CodeVariableReferenceExpression(this.ResourceManagerName));
                 }
                 resourceManager.ExpressionAdded = true;
             }
         }
         ExpressionContext tree = (ExpressionContext) manager.Context[typeof(ExpressionContext)];
         string str2 = resourceManager.SetValue(manager, tree, value, forceInvariant, shouldSerializeInvariant, ensureInvariant, false);
         if ((value is string) || ((tree != null) && (tree.ExpressionType == typeof(string))))
         {
             flag = false;
             str3 = "GetString";
         }
         else
         {
             flag = true;
             str3 = "GetObject";
         }
         CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression {
             Method = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(this.ResourceManagerName), str3)
         };
         expression.Parameters.Add(new CodePrimitiveExpression(str2));
         if (flag)
         {
             System.Type castType = this.GetCastType(manager, value);
             if (castType != null)
             {
                 return new CodeCastExpression(castType, expression);
             }
             return expression;
         }
         return expression;
     }
 }
		public override object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (value == null)
				throw new ArgumentNullException ("value");

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

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

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

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

			manager.Context.Pop ();
			return _codeMap.GenerateClass ();
		}
			private object DeserializeEntry (IDesignerSerializationManager manager, ObjectEntry objectEntry)
			{
				object deserialized = null;

				if (objectEntry.IsEntireObject) {
					CodeDomSerializer serializer = (CodeDomSerializer) manager.GetSerializer (objectEntry.Type, 
														  typeof (CodeDomSerializer));
					if (serializer != null) {
						deserialized = serializer.Deserialize (manager, objectEntry.Serialized);
						// check if the name of the object has changed
						// (if it e.g clashes with another name)
						string newName = manager.GetName (deserialized);
						if (newName != objectEntry.Name)
							objectEntry.Name = newName;
					}
				} else {
					foreach (MemberEntry memberEntry in objectEntry.Members.Values) {
						CodeDomSerializer serializer = (CodeDomSerializer) manager.GetSerializer (objectEntry.Type, 
															  typeof (CodeDomSerializer));
						if (serializer != null) 
							serializer.Deserialize (manager, memberEntry.Serialized);
					}
				}

				return deserialized;
			}
 private CodeExpression GetLegacyExpression(IDesignerSerializationManager manager, object value)
 {
     LegacyExpressionTable table = manager.Context[typeof(LegacyExpressionTable)] as LegacyExpressionTable;
     CodeExpression expression = null;
     if (table != null)
     {
         object obj2 = table[value];
         if (obj2 != value)
         {
             return (obj2 as CodeExpression);
         }
         string name = manager.GetName(value);
         bool flag = false;
         if (name == null)
         {
             IReferenceService service = (IReferenceService) manager.GetService(typeof(IReferenceService));
             if (service != null)
             {
                 name = service.GetName(value);
                 flag = name != null;
             }
         }
         if (name != null)
         {
             RootContext context = (RootContext) manager.Context[typeof(RootContext)];
             if (context != null)
             {
                 if (context.Value == value)
                 {
                     expression = context.Expression;
                 }
                 else if (flag && (name.IndexOf('.') != -1))
                 {
                     int index = name.IndexOf('.');
                     expression = new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(context.Expression, name.Substring(0, index)), name.Substring(index + 1));
                 }
                 else
                 {
                     expression = new CodeFieldReferenceExpression(context.Expression, name);
                 }
             }
             else if (flag && (name.IndexOf('.') != -1))
             {
                 int length = name.IndexOf('.');
                 expression = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(name.Substring(0, length)), name.Substring(length + 1));
             }
             else
             {
                 expression = new CodeVariableReferenceExpression(name);
             }
         }
         table[value] = expression;
     }
     return expression;
 }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     if ((manager == null) || (value == null))
     {
         throw new ArgumentNullException((manager == null) ? "manager" : "value");
     }
     CodeTypeDeclaration declaration = new CodeTypeDeclaration(manager.GetName(value));
     RootContext context = new RootContext(new CodeThisReferenceExpression(), value);
     using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::Serialize"))
     {
         declaration.BaseTypes.Add(value.GetType());
         this.containerRequired = false;
         manager.Context.Push(context);
         manager.Context.Push(this);
         manager.Context.Push(declaration);
         if (!(manager is DesignerSerializationManager))
         {
             manager.AddSerializationProvider(new CodeDomSerializationProvider());
         }
         try
         {
             if (value is IComponent)
             {
                 ISite site = ((IComponent) value).Site;
                 if (site == null)
                 {
                     return declaration;
                 }
                 ICollection components = site.Container.Components;
                 StatementContext context2 = new StatementContext();
                 context2.StatementCollection.Populate(components);
                 manager.Context.Push(context2);
                 try
                 {
                     foreach (IComponent component in components)
                     {
                         if ((component != value) && !base.IsSerialized(manager, component))
                         {
                             if (base.GetSerializer(manager, component) != null)
                             {
                                 base.SerializeToExpression(manager, component);
                             }
                             else
                             {
                                 manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { component.GetType().FullName }));
                             }
                         }
                     }
                     manager.Context.Push(value);
                     try
                     {
                         if ((base.GetSerializer(manager, value) != null) && !base.IsSerialized(manager, value))
                         {
                             base.SerializeToExpression(manager, value);
                         }
                         else
                         {
                             manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { value.GetType().FullName }));
                         }
                     }
                     finally
                     {
                         manager.Context.Pop();
                     }
                 }
                 finally
                 {
                     manager.Context.Pop();
                 }
                 CodeMemberMethod method = new CodeMemberMethod {
                     Name = this.InitMethodName,
                     Attributes = MemberAttributes.Private
                 };
                 declaration.Members.Add(method);
                 ArrayList elements = new ArrayList();
                 foreach (object obj2 in components)
                 {
                     if (obj2 != value)
                     {
                         elements.Add(context2.StatementCollection[obj2]);
                     }
                 }
                 if (context2.StatementCollection[value] != null)
                 {
                     elements.Add(context2.StatementCollection[value]);
                 }
                 if (this.ContainerRequired)
                 {
                     this.SerializeContainerDeclaration(manager, method.Statements);
                 }
                 this.SerializeElementsToStatements(elements, method.Statements);
             }
             return declaration;
         }
         finally
         {
             manager.Context.Pop();
             manager.Context.Pop();
             manager.Context.Pop();
         }
     }
     return declaration;
 }
 protected void SerializePropertiesToResources(IDesignerSerializationManager manager, CodeStatementCollection statements, object value, Attribute[] filter)
 {
     using (TraceScope("ComponentCodeDomSerializerBase::SerializePropertiesToResources"))
     {
         PropertyDescriptorCollection descriptors = GetPropertiesHelper(manager, value, filter);
         manager.Context.Push(statements);
         try
         {
             CodeExpression targetObject = this.SerializeToExpression(manager, value);
             if (targetObject != null)
             {
                 CodePropertyReferenceExpression expression = new CodePropertyReferenceExpression(targetObject, string.Empty);
                 foreach (PropertyDescriptor descriptor in descriptors)
                 {
                     ExpressionContext context = new ExpressionContext(expression, descriptor.PropertyType, value);
                     manager.Context.Push(context);
                     try
                     {
                         if (descriptor.Attributes.Contains(DesignerSerializationVisibilityAttribute.Visible))
                         {
                             string name;
                             expression.PropertyName = descriptor.Name;
                             if (targetObject is CodeThisReferenceExpression)
                             {
                                 name = "$this";
                             }
                             else
                             {
                                 name = manager.GetName(value);
                             }
                             name = string.Format(CultureInfo.CurrentCulture, "{0}.{1}", new object[] { name, descriptor.Name });
                             ResourceCodeDomSerializer.Default.SerializeMetadata(manager, name, descriptor.GetValue(value), descriptor.ShouldSerializeValue(value));
                         }
                     }
                     finally
                     {
                         manager.Context.Pop();
                     }
                 }
             }
         }
         finally
         {
             manager.Context.Pop();
         }
     }
 }
		public override object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			// Check if we are serializing the root component. Happens, because GetSerializer does not 
			// check for a RootCodeDomSerializer so reference-to type of an expression is delivered
			// by the CodeDomSerializer
			RootContext rootContext = manager.Context[typeof (RootContext)] as RootContext;
			if (rootContext != null && rootContext.Value == value)
				return rootContext.Expression;

			if (((IComponent)value).Site == null) {
				Console.WriteLine ("ComponentCodeDomSerializer: Not sited : " + value);
				return null;
			}

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

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

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

				// Do not serialize a creation expression for Nested components
				//
				if (! (((IComponent)value).Site is INestedSite))
					statements.Add (new CodeAssignStatement (componentRef, 
															 base.SerializeCreationExpression (manager, value, out isComplete)));

				manager.Context.Push (new ExpressionContext (componentRef, componentRef.GetType (), null, value));
				base.SerializeProperties (manager, statements, value, new Attribute[0]);
				base.SerializeEvents (manager, statements, value);
				manager.Context.Pop ();

				serialized = statements;
			} else {
				serialized = base.GetExpression (manager, value);
				if (serialized == null) {
					base.SetExpression (manager, value, componentRef);
					serialized = componentRef;
				}
			}

			return serialized;
		}
예제 #46
0
		public virtual CodeStatementCollection SerializeMember (IDesignerSerializationManager manager, 
									object owningobject, MemberDescriptor member)
		{
			if (member == null)
				throw new ArgumentNullException ("member");
			if (owningobject == null)
				throw new ArgumentNullException ("owningobject");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			CodeStatementCollection statements = new CodeStatementCollection ();

			CodeExpression expression = base.GetExpression (manager, owningobject);
			if (expression == null) {
				string name = manager.GetName (owningobject);
				if (name == null)
					name = base.GetUniqueName (manager, owningobject);
				expression = new CodeVariableReferenceExpression (name);
				base.SetExpression (manager, owningobject, expression);
			}

			if (member is PropertyDescriptor)
				base.SerializeProperty (manager, statements, owningobject, (PropertyDescriptor) member);
			if (member is EventDescriptor)
				base.SerializeEvent (manager, statements, owningobject, (EventDescriptor) member);

			return statements;
		}
		private void SerializeComponent (IDesignerSerializationManager manager, IComponent component)
		{
			CodeDomSerializer serializer = base.GetSerializer (manager, component) as CodeDomSerializer; // ComponentCodeDomSerializer
			if (serializer != null) {
				this.Code.AddField (new CodeMemberField (component.GetType (), manager.GetName (component)));

				CodeStatementCollection statements = (CodeStatementCollection) serializer.Serialize (manager, component);

				CodeStatement ctorStatement = ExtractCtorStatement (manager, statements, component);
				if (ctorStatement != null)
					Code.AddPreInitStatement (ctorStatement);
				Code.AddInitStatements (statements);
			}
		}
 public virtual CodeTypeDeclaration Serialize(IDesignerSerializationManager manager, object root, ICollection members)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (root == null)
     {
         throw new ArgumentNullException("root");
     }
     CodeTypeDeclaration declaration = new CodeTypeDeclaration(manager.GetName(root));
     CodeThisReferenceExpression expression = new CodeThisReferenceExpression();
     RootContext context = new RootContext(expression, root);
     StatementContext context2 = new StatementContext();
     context2.StatementCollection.Populate(root);
     if (members != null)
     {
         context2.StatementCollection.Populate(members);
     }
     declaration.BaseTypes.Add(root.GetType());
     manager.Context.Push(declaration);
     manager.Context.Push(context);
     manager.Context.Push(context2);
     try
     {
         if (members != null)
         {
             foreach (object obj2 in members)
             {
                 if (obj2 != root)
                 {
                     base.SerializeToExpression(manager, obj2);
                 }
             }
         }
         base.SerializeToExpression(manager, root);
         this.IntegrateStatements(manager, root, members, context2, declaration);
     }
     finally
     {
         manager.Context.Pop();
         manager.Context.Pop();
         manager.Context.Pop();
     }
     return declaration;
 }
예제 #49
0
		public override object Serialize(IDesignerSerializationManager manager, object value) 
		{
			/* Associate the component with the serializer in the same manner as with
				Deserialize */
			CodeDomSerializer baseClassSerializer = (CodeDomSerializer)manager.
				GetSerializer(typeof(RoundGauge).BaseType, typeof(CodeDomSerializer));
 
			object codeObject = baseClassSerializer.Serialize(manager, value);

			CodeStatementCollection newCode = new CodeStatementCollection();
 
			if (codeObject is CodeStatementCollection) 
			{
				CodeMethodInvokeExpression invokeExpr;
				
				CodeStatementCollection statements = (CodeStatementCollection)codeObject;
 
				// The code statement collection is valid, so add our Begin/EndUpdate calls.
				CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression();
				CodeFieldReferenceExpression gaugeRef = new CodeFieldReferenceExpression(thisRef, manager.GetName(value));

				// move the comments and the "new" call
				for(int i = 0 ; i < 4 ; i++)
				{
					newCode.Add(statements[0]);
					statements.RemoveAt(0);
				}
				
				// add BeginInvoke
				invokeExpr = new CodeMethodInvokeExpression(gaugeRef, "BeginUpdate");
				newCode.Add(invokeExpr);

				// add the designer-generated code
				newCode.AddRange(statements);

				// add EndUpdate
				invokeExpr = new CodeMethodInvokeExpression(gaugeRef, "EndUpdate");
				newCode.Add(invokeExpr);
			}
			return newCode;
		}
 private void SerializeContentProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, bool isExtender, CodeStatementCollection statements)
 {
     bool flag;
     object presetValue = this.GetPropertyValue(manager, property, value, out flag);
     CodeDomSerializer serializer = null;
     if (presetValue == null)
     {
         string name = manager.GetName(value);
         if (name == null)
         {
             name = value.GetType().FullName;
         }
         manager.ReportError(System.Design.SR.GetString("SerializerNullNestedProperty", new object[] { name, property.Name }));
     }
     else
     {
         serializer = (CodeDomSerializer) manager.GetSerializer(presetValue.GetType(), typeof(CodeDomSerializer));
         if (serializer != null)
         {
             CodeExpression targetObject = base.SerializeToExpression(manager, value);
             if (targetObject != null)
             {
                 CodeExpression expression = null;
                 if (isExtender)
                 {
                     ExtenderProvidedPropertyAttribute attribute = (ExtenderProvidedPropertyAttribute) property.Attributes[typeof(ExtenderProvidedPropertyAttribute)];
                     CodeExpression expression3 = base.SerializeToExpression(manager, attribute.Provider);
                     CodeExpression expression4 = base.SerializeToExpression(manager, value);
                     if ((expression3 != null) && (expression4 != null))
                     {
                         CodeMethodReferenceExpression expression5 = new CodeMethodReferenceExpression(expression3, "Get" + property.Name);
                         CodeMethodInvokeExpression expression6 = new CodeMethodInvokeExpression {
                             Method = expression5
                         };
                         expression6.Parameters.Add(expression4);
                         expression = expression6;
                     }
                 }
                 else
                 {
                     expression = new CodePropertyReferenceExpression(targetObject, property.Name);
                 }
                 if (expression != null)
                 {
                     ExpressionContext context = new ExpressionContext(expression, property.PropertyType, value, presetValue);
                     manager.Context.Push(context);
                     object obj3 = null;
                     try
                     {
                         SerializeAbsoluteContext context2 = (SerializeAbsoluteContext) manager.Context[typeof(SerializeAbsoluteContext)];
                         if (base.IsSerialized(manager, presetValue, context2 != null))
                         {
                             obj3 = base.GetExpression(manager, presetValue);
                         }
                         else
                         {
                             obj3 = serializer.Serialize(manager, presetValue);
                         }
                     }
                     finally
                     {
                         manager.Context.Pop();
                     }
                     CodeStatementCollection statements2 = obj3 as CodeStatementCollection;
                     if (statements2 == null)
                     {
                         CodeStatement statement2 = obj3 as CodeStatement;
                         if (statement2 != null)
                         {
                             statements.Add(statement2);
                         }
                     }
                     else
                     {
                         foreach (CodeStatement statement in statements2)
                         {
                             statements.Add(statement);
                         }
                     }
                 }
             }
         }
         else
         {
             manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { property.PropertyType.FullName }));
         }
     }
 }
        public override CodeTypeDeclaration Serialize(IDesignerSerializationManager manager, object root, ICollection members)
        {
            if (manager == null)
                throw new ArgumentNullException("manager");
            if (root == null)
                throw new ArgumentNullException("root");

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

            CodeTypeDeclaration codeTypeDeclaration = base.Serialize(manager, root, members);

            // Emit CanModifyActivities properties
            CodeMemberMethod method = codeTypeDeclaration.UserData[_initMethodKey] as CodeMemberMethod;
            if (method != null && rootActivity is CompositeActivity)
            {
                CodeStatement[] codeStatements = new CodeStatement[method.Statements.Count];
                method.Statements.CopyTo(codeStatements, 0);
                method.Statements.Clear();

                CodeAssignStatement beginInit = new CodeAssignStatement();
                beginInit.Left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "CanModifyActivities");
                beginInit.Right = new CodePrimitiveExpression(true);
                method.Statements.Add(beginInit);

                foreach (CodeStatement s in codeStatements)
                    method.Statements.Add(s);

                CodeAssignStatement endInit = new CodeAssignStatement();
                endInit.Left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "CanModifyActivities");
                endInit.Right = new CodePrimitiveExpression(false);
                method.Statements.Add(endInit);
            }

            foreach (CodeTypeMember member in codeTypeDeclaration.Members)
            {
                CodeMemberField field = member as CodeMemberField;
                if (field != null)
                {
                    foreach (object objectActivity in members)
                    {
                        if (!(objectActivity is Activity))
                            throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(Activity).FullName), "members");

                        Activity activity = objectActivity as Activity;
                        if (field.Name == manager.GetName(activity) &&
                            (int)activity.GetValue(ActivityMarkupSerializer.StartLineProperty) != -1 &&
                            rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty) != null)
                        {
                            // generate line pragma for fields
                            field.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)activity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
                        }
                    }
                }
            }
            return codeTypeDeclaration;
        }
 protected CodeExpression SerializeToReferenceExpression(IDesignerSerializationManager manager, object value)
 {
     CodeExpression expression = null;
     using (CodeDomSerializerBase.TraceScope("CodeDomSerializer::SerializeToReferenceExpression"))
     {
         expression = base.GetExpression(manager, value);
         if ((expression != null) || !(value is IComponent))
         {
             return expression;
         }
         string name = manager.GetName(value);
         bool flag = false;
         if (name == null)
         {
             IReferenceService service = (IReferenceService) manager.GetService(typeof(IReferenceService));
             if (service != null)
             {
                 name = service.GetName(value);
                 flag = name != null;
             }
         }
         if (name == null)
         {
             return expression;
         }
         RootContext context = (RootContext) manager.Context[typeof(RootContext)];
         if ((context != null) && (context.Value == value))
         {
             return context.Expression;
         }
         if (flag && (name.IndexOf('.') != -1))
         {
             int index = name.IndexOf('.');
             return new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(_thisRef, name.Substring(0, index)), name.Substring(index + 1));
         }
         return new CodeFieldReferenceExpression(_thisRef, name);
     }
 }
 public string SetValue(IDesignerSerializationManager manager, ExpressionContext tree, object value, bool forceInvariant, bool shouldSerializeInvariant, bool ensureInvariant, bool applyingCachedResources)
 {
     string name = null;
     bool flag = false;
     if (tree != null)
     {
         string propertyName;
         if (tree.Owner == this.RootComponent)
         {
             name = "$this";
         }
         else
         {
             name = manager.GetName(tree.Owner);
             if (name == null)
             {
                 IReferenceService service = (IReferenceService) manager.GetService(typeof(IReferenceService));
                 if (service != null)
                 {
                     name = service.GetName(tree.Owner);
                 }
             }
         }
         CodeExpression expression = tree.Expression;
         if (expression is CodePropertyReferenceExpression)
         {
             propertyName = ((CodePropertyReferenceExpression) expression).PropertyName;
         }
         else if (expression is CodeFieldReferenceExpression)
         {
             propertyName = ((CodeFieldReferenceExpression) expression).FieldName;
         }
         else if (expression is CodeMethodReferenceExpression)
         {
             propertyName = ((CodeMethodReferenceExpression) expression).MethodName;
             if (propertyName.StartsWith("Set"))
             {
                 propertyName = propertyName.Substring(3);
             }
         }
         else
         {
             propertyName = null;
         }
         if (name == null)
         {
             name = "resource";
         }
         if (propertyName != null)
         {
             name = name + "." + propertyName;
         }
     }
     else
     {
         name = "resource";
         flag = true;
     }
     string key = name;
     int num = 1;
     do
     {
         if (flag)
         {
             key = name + num.ToString(CultureInfo.InvariantCulture);
             num++;
         }
         else
         {
             flag = true;
         }
     }
     while (this.nameTable.ContainsKey(key));
     this.SetValue(manager, key, value, forceInvariant, shouldSerializeInvariant, ensureInvariant, applyingCachedResources);
     this.nameTable[key] = key;
     return key;
 }
 private void SerializeControlHierarchy(IDesignerSerializationManager manager, IDesignerHost host, object value)
 {
     Control control = value as Control;
     if (control != null)
     {
         string str;
         IMultitargetHelperService service = host.GetService(typeof(IMultitargetHelperService)) as IMultitargetHelperService;
         if (control == host.RootComponent)
         {
             str = "$this";
             foreach (IComponent component in host.Container.Components)
             {
                 if (!(component is Control) && !TypeDescriptor.GetAttributes(component).Contains(InheritanceAttribute.InheritedReadOnly))
                 {
                     string name = manager.GetName(component);
                     string str3 = (service == null) ? component.GetType().AssemblyQualifiedName : service.GetAssemblyQualifiedName(component.GetType());
                     if (name != null)
                     {
                         base.SerializeResourceInvariant(manager, ">>" + name + ".Name", name);
                         base.SerializeResourceInvariant(manager, ">>" + name + ".Type", str3);
                     }
                 }
             }
         }
         else
         {
             str = manager.GetName(value);
             if (str == null)
             {
                 return;
             }
         }
         base.SerializeResourceInvariant(manager, ">>" + str + ".Name", manager.GetName(value));
         base.SerializeResourceInvariant(manager, ">>" + str + ".Type", (service == null) ? control.GetType().AssemblyQualifiedName : service.GetAssemblyQualifiedName(control.GetType()));
         Control parent = control.Parent;
         if ((parent != null) && (parent.Site != null))
         {
             string str4;
             if (parent == host.RootComponent)
             {
                 str4 = "$this";
             }
             else
             {
                 str4 = manager.GetName(parent);
             }
             if (str4 != null)
             {
                 base.SerializeResourceInvariant(manager, ">>" + str + ".Parent", str4);
             }
             for (int i = 0; i < parent.Controls.Count; i++)
             {
                 if (parent.Controls[i] == control)
                 {
                     base.SerializeResourceInvariant(manager, ">>" + str + ".ZOrder", i.ToString(CultureInfo.InvariantCulture));
                     return;
                 }
             }
         }
     }
 }
        private void SerializeMethodInvocation(IDesignerSerializationManager manager, CodeStatementCollection statements, object control, string methodName, CodeExpressionCollection parameters, System.Type[] paramTypes, StatementOrdering ordering)
        {
            using (CodeDomSerializerBase.TraceScope("ControlCodeDomSerializer::SerializeMethodInvocation(" + methodName + ")"))
            {
                manager.GetName(control);
                paramTypes = ToTargetTypes(control, paramTypes);
                if (TypeDescriptor.GetReflectionType(control).GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance, null, paramTypes, null) != null)
                {
                    CodeMethodReferenceExpression expression2 = new CodeMethodReferenceExpression(base.SerializeToExpression(manager, control), methodName);
                    CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression {
                        Method = expression2
                    };
                    if (parameters != null)
                    {
                        expression.Parameters.AddRange(parameters);
                    }
                    CodeExpressionStatement statement = new CodeExpressionStatement(expression);
                    switch (ordering)
                    {
                        case StatementOrdering.Prepend:
                            statement.UserData["statement-ordering"] = "begin";
                            break;

                        case StatementOrdering.Append:
                            statement.UserData["statement-ordering"] = "end";
                            break;
                    }
                    statements.Add(statement);
                }
            }
        }
		protected CodeExpression GetExpression (IDesignerSerializationManager manager, object instance)
		{
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (instance == null)
				throw new ArgumentNullException ("instance");

			CodeExpression expression = null;

			ExpressionTable expressions = manager.Context[typeof (ExpressionTable)] as ExpressionTable;
			if (expressions != null) // 1st try: ExpressionTable
				expression = expressions [instance] as CodeExpression;

			if (expression == null) { // 2nd try: RootContext
				RootContext context = manager.Context[typeof (RootContext)] as RootContext;
				if (context != null && context.Value == instance)
					expression = context.Expression;
			}

			if (expression == null) { // 3rd try: IReferenceService (instance.property.property.property
				string name = manager.GetName (instance);
				if (name == null || name.IndexOf (".") == -1) {
					IReferenceService service = manager.GetService (typeof (IReferenceService)) as IReferenceService;
					if (service != null) {
						name = service.GetName (instance);
						if (name != null && name.IndexOf (".") != -1) {
							string[] parts = name.Split (new char[] { ',' });
							instance = manager.GetInstance (parts[0]);
							if (instance != null) {
								expression = SerializeToExpression (manager, instance);
								if (expression != null) {
									for (int i=1; i < parts.Length; i++)
										expression = new CodePropertyReferenceExpression (expression, parts[i]);
								}
							}
						}
					}
				}
			}
			return expression;
		}
		public override object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (value == null)
				throw new ArgumentNullException ("value");

			// Add the provider to supply the ComponentCodeSerializer, Primitives..., etc
			manager.AddSerializationProvider (_provider);
			RootContext rootContext = new RootContext (new CodeThisReferenceExpression (), value);
			manager.Context.Push (rootContext);

			// Initialize code map
			if (_codeMap != null)
				_codeMap = new CodeMap (value.GetType (), manager.GetName (value));
			_codeMap.Clear ();
			CodeStatementCollection statements = null;
			CodeDomSerializer serializer = null;

			foreach (object component in ((IComponent) value).Site.Container.Components) {
				if (!Object.ReferenceEquals (component, value)) {
					serializer = base.GetSerializer (manager, component) as CodeDomSerializer; // ComponentCodeDomSerializer
					if (serializer != null) {
						// add an expressioncontext to inform the component that we want it fully serialized (it is in context)
						ExpressionContext context = new ExpressionContext (null, null, null, component);
						manager.Context.Push (context);

						_codeMap.AddField (new CodeMemberField (value.GetType (), manager.GetName (value)));
						statements = (CodeStatementCollection) serializer.Serialize (manager, component);

						manager.Context.Pop ();
						// XXX: what if there are more than one objects constructed by the serializer?
						// this will only add the first one on the statements list.
						CodeStatement ctorStatement = ExtractCtorStatement (statements);
						if (ctorStatement != null)
							_codeMap.AddPreInitStatement (ctorStatement);
						_codeMap.AddInitStatements (statements);
					}
				}
			}

			// Serializer root component
			// 
			statements = new CodeStatementCollection ();
			base.SerializeProperties (manager, statements, value, new Attribute[0]);
			base.SerializeEvents (manager, statements, value, new Attribute[0]);
			_codeMap.AddInitStatements (statements);

			manager.Context.Pop ();
			return _codeMap.GenerateClass ();
		}
		protected string GetUniqueName (IDesignerSerializationManager manager, object instance)
		{
			if (instance == null)
				throw new ArgumentNullException ("instance");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			string name = manager.GetName (instance);
			if (name == null) {
				INameCreationService service = manager.GetService (typeof (INameCreationService)) as INameCreationService;
				name = service.CreateName (null, instance.GetType ());
				if (name == null)
					name = instance.GetType ().Name.ToLower ();
				manager.SetName (instance, name);
			}
			return name;
		}
예제 #59
0
		public override object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			RootContext rootContext = manager.Context[typeof (RootContext)] as RootContext;
			if (rootContext != null && rootContext.Value == value)
				return rootContext.Expression;

			CodeStatementCollection statements = new CodeStatementCollection ();

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

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

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

			base.SetExpression (manager, value, componentRef);

			ExpressionContext context = manager.Context[typeof (ExpressionContext)] as ExpressionContext;
			// Perform some heuristics here. 
			// 
			// If there is an ExpressionContext of PropertyReference where PresetValue == this
			// partial serialization doesn't make sense, so perform full. E.g in the case of:
			// 
			// PropertyCodeDomSerializer.SerializeContentProperty and splitContainer1.*Panel1* 
			//
			if (context == null || context.PresetValue != value ||
			    (context.PresetValue == value && (context.Expression is CodeFieldReferenceExpression ||
							      context.Expression is CodePropertyReferenceExpression))) {
				bool isComplete = true;
				statements.Add (new CodeCommentStatement (String.Empty));
				statements.Add (new CodeCommentStatement (name));
				statements.Add (new CodeCommentStatement (String.Empty));
	
				// Do not serialize a creation expression for Nested components
				//
				if (! (((IComponent)value).Site is INestedSite)) {
					CodeStatement assignment = new CodeAssignStatement (componentRef, 
									base.SerializeCreationExpression (manager, value, 
													  out isComplete));
					assignment.UserData["statement-order"] = "initializer";
					statements.Add (assignment);
				}
	
				base.SerializeProperties (manager, statements, value, new Attribute[0]);
				base.SerializeEvents (manager, statements, value);
			}

			return statements;
		}
 protected CodeExpression SerializeToExpression(IDesignerSerializationManager manager, object value)
 {
     CodeExpression legacyExpression = null;
     using (TraceScope("SerializeToExpression"))
     {
         if (value != null)
         {
             if (this.IsSerialized(manager, value))
             {
                 legacyExpression = this.GetExpression(manager, value);
             }
             else
             {
                 legacyExpression = this.GetLegacyExpression(manager, value);
                 if (legacyExpression != null)
                 {
                     this.SetExpression(manager, value, legacyExpression);
                 }
             }
         }
         if (legacyExpression != null)
         {
             return legacyExpression;
         }
         CodeDomSerializer serializer = this.GetSerializer(manager, value);
         if (serializer != null)
         {
             CodeStatementCollection statements = null;
             if (value != null)
             {
                 this.SetLegacyExpression(manager, value);
                 StatementContext context = manager.Context[typeof(StatementContext)] as StatementContext;
                 if (context != null)
                 {
                     statements = context.StatementCollection[value];
                 }
                 if (statements != null)
                 {
                     manager.Context.Push(statements);
                 }
             }
             object obj2 = null;
             try
             {
                 obj2 = serializer.Serialize(manager, value);
             }
             finally
             {
                 if (statements != null)
                 {
                     manager.Context.Pop();
                 }
             }
             legacyExpression = obj2 as CodeExpression;
             if ((legacyExpression == null) && (value != null))
             {
                 legacyExpression = this.GetExpression(manager, value);
             }
             CodeStatementCollection statements2 = obj2 as CodeStatementCollection;
             if (statements2 == null)
             {
                 CodeStatement statement = obj2 as CodeStatement;
                 if (statement != null)
                 {
                     statements2 = new CodeStatementCollection();
                     statements2.Add(statement);
                 }
             }
             if (statements2 != null)
             {
                 if (statements == null)
                 {
                     statements = manager.Context[typeof(CodeStatementCollection)] as CodeStatementCollection;
                 }
                 if (statements != null)
                 {
                     statements.AddRange(statements2);
                     return legacyExpression;
                 }
                 string name = "(null)";
                 if (value != null)
                 {
                     name = manager.GetName(value);
                     if (name == null)
                     {
                         name = value.GetType().Name;
                     }
                 }
                 manager.ReportError(System.Design.SR.GetString("SerializerLostStatements", new object[] { name }));
             }
             return legacyExpression;
         }
         manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { value.GetType().FullName }));
     }
     return legacyExpression;
 }