Ejemplo n.º 1
0
        public void SetUpFixture()
        {
            using (DesignSurface designSurface = new DesignSurface(typeof(Form))) {
                IDesignerHost        host = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
                IEventBindingService eventBindingService = new MockEventBindingService(host);
                Form form = (Form)host.RootComponent;
                form.ClientSize = new Size(200, 300);

                PropertyDescriptorCollection descriptors            = TypeDescriptor.GetProperties(form);
                PropertyDescriptor           namePropertyDescriptor = descriptors.Find("Name", false);
                namePropertyDescriptor.SetValue(form, "MainForm");

                // Add list view.
                ListView listView = (ListView)host.CreateComponent(typeof(ListView), "listView1");
                listView.TabIndex   = 0;
                listView.Location   = new Point(0, 0);
                listView.ClientSize = new Size(200, 100);
                descriptors         = TypeDescriptor.GetProperties(listView);
                PropertyDescriptor descriptor = descriptors.Find("UseCompatibleStateImageBehavior", false);
                descriptor.SetValue(listView, true);
                descriptor = descriptors.Find("View", false);
                descriptor.SetValue(listView, View.Details);
                form.Controls.Add(listView);

                // Add ImageList.
                Icon      icon      = new Icon(typeof(GenerateFormResourceTestFixture), "App.ico");
                ImageList imageList = (ImageList)host.CreateComponent(typeof(ImageList), "imageList1");
                imageList.Images.Add("App.ico", icon);
                imageList.Images.Add("b.ico", icon);
                imageList.Images.Add("c.ico", icon);

                DesignerSerializationManager  designerSerializationManager = new DesignerSerializationManager(host);
                IDesignerSerializationManager serializationManager         = (IDesignerSerializationManager)designerSerializationManager;
                using (designerSerializationManager.CreateSession()) {
                    // Add list view items.
                    ListViewItem item = (ListViewItem)serializationManager.CreateInstance(typeof(ListViewItem), new object[] { "aaa" }, "listViewItem1", false);
                    item.ImageIndex = 1;
                    listView.Items.Add(item);

                    ListViewItem item2 = (ListViewItem)serializationManager.CreateInstance(typeof(ListViewItem), new object[] { "bbb" }, "listViewItem2", false);
                    item2.ImageKey = "App.ico";
                    listView.Items.Add(item2);

                    ListViewItem item3 = (ListViewItem)serializationManager.CreateInstance(typeof(ListViewItem), new object[0], "listViewItem3", false);
                    item3.ImageIndex = 2;
                    listView.Items.Add(item3);

                    ListViewItem item4 = (ListViewItem)serializationManager.CreateInstance(typeof(ListViewItem), new object[0], "listViewItem4", false);
                    item4.ImageKey = "b.ico";
                    listView.Items.Add(item4);

                    RubyCodeDomSerializer serializer = new RubyCodeDomSerializer("    ");
                    generatedRubyCode = serializer.GenerateInitializeComponentMethodBody(host, serializationManager);
                }
            }
        }
Ejemplo n.º 2
0
        public void SetUpFixture()
        {
            using (DesignSurface designSurface = new DesignSurface(typeof(Form))) {
                IDesignerHost        host = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
                IEventBindingService eventBindingService = new MockEventBindingService(host);
                Form form = (Form)host.RootComponent;
                form.ClientSize = new Size(200, 300);

                PropertyDescriptorCollection descriptors            = TypeDescriptor.GetProperties(form);
                PropertyDescriptor           namePropertyDescriptor = descriptors.Find("Name", false);
                namePropertyDescriptor.SetValue(form, "MainForm");

                // Add list view.
                ListView listView = (ListView)host.CreateComponent(typeof(ListView), "listView1");
                listView.TabIndex   = 0;
                listView.Location   = new Point(0, 0);
                listView.ClientSize = new Size(200, 100);
                descriptors         = TypeDescriptor.GetProperties(listView);
                PropertyDescriptor descriptor = descriptors.Find("UseCompatibleStateImageBehavior", false);
                descriptor.SetValue(listView, true);
                descriptor = descriptors.Find("View", false);
                descriptor.SetValue(listView, View.Details);
                form.Controls.Add(listView);

                // Add column headers.
                columnHeader1 = (ColumnHeader)host.CreateComponent(typeof(ColumnHeader), "columnHeader1");
                descriptors   = TypeDescriptor.GetProperties(columnHeader1);
                descriptor    = descriptors.Find("Text", false);
                descriptor.SetValue(columnHeader1, "columnHeader1");
                listView.Columns.Add(columnHeader1);

                columnHeader2 = (ColumnHeader)host.CreateComponent(typeof(ColumnHeader), "columnHeader2");
                descriptors   = TypeDescriptor.GetProperties(columnHeader2);
                descriptor    = descriptors.Find("Text", false);
                descriptor.SetValue(columnHeader2, "columnHeader2");
                listView.Columns.Add(columnHeader2);

                // Add list view items.
                DesignerSerializationManager  designerSerializationManager = new DesignerSerializationManager(host);
                IDesignerSerializationManager serializationManager         = (IDesignerSerializationManager)designerSerializationManager;
                using (designerSerializationManager.CreateSession()) {
                    ListViewItem item = (ListViewItem)serializationManager.CreateInstance(typeof(ListViewItem), new object[] { "aaa" }, "listViewItem1", false);
                    item.ToolTipText = "tooltip";
                    listView.Items.Add(item);

                    item = (ListViewItem)serializationManager.CreateInstance(typeof(ListViewItem), new object[] { "bbb" }, "listViewItem2", false);
                    listView.Items.Add(item);

                    item = (ListViewItem)serializationManager.CreateInstance(typeof(ListViewItem), new object[0], "listViewItem3", false);
                    listView.Items.Add(item);

                    RubyCodeDomSerializer serializer = new RubyCodeDomSerializer("    ");
                    generatedRubyCode = serializer.GenerateInitializeComponentMethodBody(host, serializationManager, 1);
                }
            }
        }
Ejemplo n.º 3
0
        public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
        {
            CodeTypeDeclaration declaration = (CodeTypeDeclaration)codeObject;
            Type   rootType = manager.GetType(declaration.BaseTypes[0].BaseType);
            object root     = manager.CreateInstance(rootType, null, declaration.Name, true);

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

            manager.Context.Push(rootContext);

            CodeMemberMethod initComponentMethod = GetInitializeMethod(declaration);

            if (initComponentMethod == null)
            {
                throw new InvalidOperationException("InitializeComponent method is missing in: " + declaration.Name);
            }

            foreach (CodeStatement statement in initComponentMethod.Statements)
            {
                base.DeserializeStatement(manager, statement);
            }

            manager.Context.Pop();
            return(root);
        }
Ejemplo n.º 4
0
        public void SetUpFixture()
        {
            using (DesignSurface designSurface = new DesignSurface(typeof(Form))) {
                IDesignerHost        host = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
                IEventBindingService eventBindingService = new MockEventBindingService(host);
                Form form = (Form)host.RootComponent;
                form.ClientSize = new Size(200, 300);

                PropertyDescriptorCollection descriptors            = TypeDescriptor.GetProperties(form);
                PropertyDescriptor           namePropertyDescriptor = descriptors.Find("Name", false);
                namePropertyDescriptor.SetValue(form, "MainForm");

                // Add list view.
                ListView listView = (ListView)host.CreateComponent(typeof(ListView), "listView1");
                listView.TabIndex   = 0;
                listView.Location   = new Point(0, 0);
                listView.ClientSize = new Size(200, 100);
                descriptors         = TypeDescriptor.GetProperties(listView);
                PropertyDescriptor descriptor = descriptors.Find("UseCompatibleStateImageBehavior", false);
                descriptor.SetValue(listView, true);
                descriptor = descriptors.Find("View", false);
                descriptor.SetValue(listView, View.Details);
                form.Controls.Add(listView);

                DesignerSerializationManager  designerSerializationManager = new DesignerSerializationManager(host);
                IDesignerSerializationManager serializationManager         = (IDesignerSerializationManager)designerSerializationManager;
                using (designerSerializationManager.CreateSession()) {
                    // Add groups.
                    ListViewGroup group1 = (ListViewGroup)serializationManager.CreateInstance(typeof(ListViewGroup), new object[0], "listViewGroup1", false);
                    group1.Header          = "ListViewGroup";
                    group1.HeaderAlignment = HorizontalAlignment.Right;
                    group1.Name            = "defaultGroup";
                    group1.Tag             = "tag1";
                    listView.Groups.Add(group1);

                    ListViewGroup group2 = (ListViewGroup)serializationManager.CreateInstance(typeof(ListViewGroup), new object[0], "listViewGroup2", false);
                    group2.Header          = "ListViewGroup";
                    group2.HeaderAlignment = HorizontalAlignment.Center;
                    group2.Name            = "listViewGroup2";
                    listView.Groups.Add(group2);

                    PythonCodeDomSerializer serializer = new PythonCodeDomSerializer("    ");
                    generatedPythonCode = serializer.GenerateInitializeComponentMethodBody(host, designerSerializationManager, String.Empty, 1);
                }
            }
        }
Ejemplo n.º 5
0
        public void SetUpFixture()
        {
            using (DesignSurface designSurface = new DesignSurface(typeof(Form))) {
                IDesignerHost        host = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
                IEventBindingService eventBindingService = new MockEventBindingService(host);
                Form form = (Form)host.RootComponent;
                form.ClientSize = new Size(200, 300);

                PropertyDescriptorCollection descriptors            = TypeDescriptor.GetProperties(form);
                PropertyDescriptor           namePropertyDescriptor = descriptors.Find("Name", false);
                namePropertyDescriptor.SetValue(form, "MainForm");

                // Add tree view.
                TreeView treeView = (TreeView)host.CreateComponent(typeof(TreeView), "treeView1");
                treeView.LineColor = Color.Black;
                treeView.Location  = new Point(0, 0);
                treeView.Size      = new Size(100, 100);

                DesignerSerializationManager  designerSerializationManager = new DesignerSerializationManager(host);
                IDesignerSerializationManager serializationManager         = (IDesignerSerializationManager)designerSerializationManager;
                using (designerSerializationManager.CreateSession()) {
                    // Add first root node.
                    TreeNode firstRootNode = (TreeNode)serializationManager.CreateInstance(typeof(TreeNode), new object[0], "treeNode3", false);
                    firstRootNode.Name = "RootNode0";
                    firstRootNode.Text = "RootNode0.Text";
                    treeView.Nodes.Add(firstRootNode);

                    // Add first child node.
                    TreeNode firstChildNode = (TreeNode)serializationManager.CreateInstance(typeof(TreeNode), new object[0], "treeNode2", false);
                    firstChildNode.Name = "ChildNode0";
                    firstChildNode.Text = "ChildNode0.Text";
                    firstRootNode.Nodes.Add(firstChildNode);

                    // Add second child node.
                    TreeNode secondChildNode = (TreeNode)serializationManager.CreateInstance(typeof(TreeNode), new object[0], "treeNode1", false);
                    secondChildNode.Name = "ChildNode1";
                    secondChildNode.Text = "ChildNode1.Text";
                    firstChildNode.Nodes.Add(secondChildNode);

                    form.Controls.Add(treeView);

                    RubyCodeDomSerializer serializer = new RubyCodeDomSerializer("    ");
                    generatedRubyCode = serializer.GenerateInitializeComponentMethodBody(host, designerSerializationManager, String.Empty, 1);
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Extends CreateInstance so that methods that return a specific type object given a Type parameter can be
        /// used as generic method and casting is not required.
        /// <example>
        /// idesignerserializationmanager.CreateInstance&lt;int&gt;(arguments, name, addToContainer);
        /// </example>
        /// </summary>
        public static T CreateInstance <T>(this IDesignerSerializationManager idesignerserializationmanager, System.Collections.ICollection arguments, String name, Boolean addToContainer)
        {
            if (idesignerserializationmanager == null)
            {
                throw new ArgumentNullException("idesignerserializationmanager");
            }

            return((T)idesignerserializationmanager.CreateInstance(typeof(T), arguments, name, addToContainer));
        }
        protected virtual object DeserializeInstance(IDesignerSerializationManager manager, Type type,
                                                     object[] parameters, string name, bool addToContainer)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            return(manager.CreateInstance(type, parameters, name, addToContainer));
        }
        public void SetUpFixture()
        {
            using (DesignSurface designSurface = new DesignSurface(typeof(Form))) {
                IDesignerHost        host = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
                IEventBindingService eventBindingService = new MockEventBindingService(host);
                Form form = (Form)host.RootComponent;
                form.ClientSize = new Size(200, 300);

                PropertyDescriptorCollection descriptors            = TypeDescriptor.GetProperties(form);
                PropertyDescriptor           namePropertyDescriptor = descriptors.Find("Name", false);
                namePropertyDescriptor.SetValue(form, "MainForm");

                // Add custom control
                CustomUserControl userControl = (CustomUserControl)host.CreateComponent(typeof(CustomUserControl), "userControl1");
                userControl.Location   = new Point(0, 0);
                userControl.ClientSize = new Size(200, 100);

                DesignerSerializationManager  designerSerializationManager = new DesignerSerializationManager(host);
                IDesignerSerializationManager serializationManager         = (IDesignerSerializationManager)designerSerializationManager;
                using (designerSerializationManager.CreateSession()) {
                    FooItem fooItem = (FooItem)serializationManager.CreateInstance(typeof(FooItem), new object[] { "aa" }, "fooItem1", false);
                    userControl.FooItems.Add(fooItem);
                    fooItem = (FooItem)serializationManager.CreateInstance(typeof(FooItem), new object[] { "bb" }, "fooItem2", false);
                    userControl.FooItems.Add(fooItem);

                    BarItem barItem = (BarItem)serializationManager.CreateInstance(typeof(BarItem), new object[] { "cc" }, "barItem1", false);
                    userControl.ParentComponent.ParentBarItems.Add(barItem);
                    barItem = (BarItem)serializationManager.CreateInstance(typeof(BarItem), new object[] { "dd" }, "barItem2", false);
                    userControl.ParentComponent.ParentBarItems.Add(barItem);
                    form.Controls.Add(userControl);

                    PythonCodeDomSerializer serializer = new PythonCodeDomSerializer("    ");
                    generatedPythonCode = serializer.GenerateInitializeComponentMethodBody(host, serializationManager, String.Empty, 1);
                }
            }
        }
 protected override object DeserializeInstance(IDesignerSerializationManager manager, System.Type type, object[] parameters, string name, bool addToContainer)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (type == null)
     {
         throw new ArgumentNullException("type");
     }
     if (((name != null) && name.Equals(this.ResourceManagerName)) && typeof(ResourceManager).IsAssignableFrom(type))
     {
         return(this.CreateResourceManager(manager));
     }
     return(manager.CreateInstance(type, parameters, name, addToContainer));
 }
Ejemplo n.º 10
0
        public object CreateInstance(Type type, ICollection arguments, string name, bool addToContainer)
        {
            CreatedInstance createdInstance = new CreatedInstance(type, arguments, name, addToContainer);

            createdInstances.Add(createdInstance);

            object[] argumentsArray = new object[arguments.Count];
            arguments.CopyTo(argumentsArray, 0);

            object o = null;
            DesignerSerializationManager designerSerializationManager = new DesignerSerializationManager();

            using (designerSerializationManager.CreateSession()) {
                IDesignerSerializationManager manager = designerSerializationManager as IDesignerSerializationManager;
                o = manager.CreateInstance(type, arguments, name, addToContainer);
            }
            createdInstance.Object = o;
            return(o);
        }
        public virtual object Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (declaration == null)
            {
                throw new ArgumentNullException("declaration");
            }
            object obj2 = null;

            using (CodeDomSerializerBase.TraceScope("TypeCodeDomSerializer::Deserialize"))
            {
                bool            caseInsensitive = false;
                CodeDomProvider service         = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
                if (service != null)
                {
                    caseInsensitive = (service.LanguageOptions & LanguageOptions.CaseInsensitive) != LanguageOptions.None;
                }
                Type   type = null;
                string name = declaration.Name;
                foreach (CodeTypeReference reference in declaration.BaseTypes)
                {
                    Type type2 = manager.GetType(CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, reference));
                    name = reference.BaseType;
                    if ((type2 != null) && !type2.IsInterface)
                    {
                        type = type2;
                        break;
                    }
                }
                if (type == null)
                {
                    CodeDomSerializerBase.Error(manager, System.Design.SR.GetString("SerializerTypeNotFound", new object[] { name }), "SerializerTypeNotFound");
                }
                if (CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, type).IsAbstract)
                {
                    CodeDomSerializerBase.Error(manager, System.Design.SR.GetString("SerializerTypeAbstract", new object[] { type.FullName }), "SerializerTypeAbstract");
                }
                ResolveNameEventHandler handler = new ResolveNameEventHandler(this.OnResolveName);
                manager.ResolveName += handler;
                obj2 = manager.CreateInstance(type, null, declaration.Name, true);
                int count = declaration.Members.Count;
                this._nameTable      = new HybridDictionary(count, caseInsensitive);
                this._statementTable = new Dictionary <string, CodeDomSerializerBase.OrderedCodeStatementCollection>(count);
                Dictionary <string, string> names = new Dictionary <string, string>(count);
                RootContext context = new RootContext(new CodeThisReferenceExpression(), obj2);
                manager.Context.Push(context);
                try
                {
                    StringComparison comparisonType = caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
                    foreach (CodeTypeMember member in declaration.Members)
                    {
                        CodeMemberField field = member as CodeMemberField;
                        if ((field != null) && !string.Equals(field.Name, declaration.Name, comparisonType))
                        {
                            this._nameTable[field.Name] = field;
                            if ((field.Type != null) && !string.IsNullOrEmpty(field.Type.BaseType))
                            {
                                names[field.Name] = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type);
                            }
                        }
                    }
                    CodeMemberMethod[] initializeMethods = this.GetInitializeMethods(manager, declaration);
                    if (initializeMethods == null)
                    {
                        throw new InvalidOperationException();
                    }
                    foreach (CodeMemberMethod method in initializeMethods)
                    {
                        foreach (CodeStatement statement in method.Statements)
                        {
                            CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement;
                            if (statement2 != null)
                            {
                                this._nameTable[statement2.Name] = statement;
                            }
                        }
                    }
                    this._nameTable[declaration.Name] = context.Expression;
                    foreach (CodeMemberMethod method2 in initializeMethods)
                    {
                        CodeDomSerializerBase.FillStatementTable(manager, this._statementTable, names, method2.Statements, declaration.Name);
                    }
                    PropertyDescriptor descriptor = manager.Properties["SupportsStatementGeneration"];
                    if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool)descriptor.GetValue(manager)))
                    {
                        foreach (string str2 in this._nameTable.Keys)
                        {
                            if (!this._statementTable.ContainsKey(str2))
                            {
                                continue;
                            }
                            CodeStatementCollection statements = this._statementTable[str2];
                            bool flag2 = false;
                            foreach (CodeStatement statement3 in statements)
                            {
                                object obj3 = statement3.UserData["GeneratedStatement"];
                                if (((obj3 == null) || !(obj3 is bool)) || !((bool)obj3))
                                {
                                    flag2 = true;
                                    break;
                                }
                            }
                            if (!flag2)
                            {
                                this._statementTable.Remove(str2);
                            }
                        }
                    }
                    base.DeserializePropertiesFromResources(manager, obj2, _designTimeFilter);
                    CodeDomSerializerBase.OrderedCodeStatementCollection[] array = new CodeDomSerializerBase.OrderedCodeStatementCollection[this._statementTable.Count];
                    this._statementTable.Values.CopyTo(array, 0);
                    Array.Sort(array, StatementOrderComparer.Default);
                    CodeDomSerializerBase.OrderedCodeStatementCollection statements2 = null;
                    foreach (CodeDomSerializerBase.OrderedCodeStatementCollection statements3 in array)
                    {
                        if (statements3.Name.Equals(declaration.Name))
                        {
                            statements2 = statements3;
                        }
                        else
                        {
                            this.DeserializeName(manager, statements3.Name, statements3);
                        }
                    }
                    if (statements2 != null)
                    {
                        this.DeserializeName(manager, statements2.Name, statements2);
                    }
                }
                finally
                {
                    this._nameTable      = null;
                    this._statementTable = null;
                    manager.ResolveName -= handler;
                    manager.Context.Pop();
                }
            }
            return(obj2);
        }
 protected override object DeserializeInstance(IDesignerSerializationManager manager, System.Type type, object[] parameters, string name, bool addToContainer)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (type == null)
     {
         throw new ArgumentNullException("type");
     }
     if (((name != null) && name.Equals(this.ResourceManagerName)) && typeof(ResourceManager).IsAssignableFrom(type))
     {
         return this.CreateResourceManager(manager);
     }
     return manager.CreateInstance(type, parameters, name, addToContainer);
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Creates a new instance of the specified type.
 /// </summary>
 public object CreateInstance(Type type, ICollection arguments, string name, bool addToContainer)
 {
     return(serializationManager.CreateInstance(type, arguments, name, addToContainer));
 }
 public virtual object Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (declaration == null)
     {
         throw new ArgumentNullException("declaration");
     }
     object obj2 = null;
     using (CodeDomSerializerBase.TraceScope("TypeCodeDomSerializer::Deserialize"))
     {
         bool caseInsensitive = false;
         CodeDomProvider service = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
         if (service != null)
         {
             caseInsensitive = (service.LanguageOptions & LanguageOptions.CaseInsensitive) != LanguageOptions.None;
         }
         Type type = null;
         string name = declaration.Name;
         foreach (CodeTypeReference reference in declaration.BaseTypes)
         {
             Type type2 = manager.GetType(CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, reference));
             name = reference.BaseType;
             if ((type2 != null) && !type2.IsInterface)
             {
                 type = type2;
                 break;
             }
         }
         if (type == null)
         {
             CodeDomSerializerBase.Error(manager, System.Design.SR.GetString("SerializerTypeNotFound", new object[] { name }), "SerializerTypeNotFound");
         }
         if (CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, type).IsAbstract)
         {
             CodeDomSerializerBase.Error(manager, System.Design.SR.GetString("SerializerTypeAbstract", new object[] { type.FullName }), "SerializerTypeAbstract");
         }
         ResolveNameEventHandler handler = new ResolveNameEventHandler(this.OnResolveName);
         manager.ResolveName += handler;
         obj2 = manager.CreateInstance(type, null, declaration.Name, true);
         int count = declaration.Members.Count;
         this._nameTable = new HybridDictionary(count, caseInsensitive);
         this._statementTable = new Dictionary<string, CodeDomSerializerBase.OrderedCodeStatementCollection>(count);
         Dictionary<string, string> names = new Dictionary<string, string>(count);
         RootContext context = new RootContext(new CodeThisReferenceExpression(), obj2);
         manager.Context.Push(context);
         try
         {
             StringComparison comparisonType = caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
             foreach (CodeTypeMember member in declaration.Members)
             {
                 CodeMemberField field = member as CodeMemberField;
                 if ((field != null) && !string.Equals(field.Name, declaration.Name, comparisonType))
                 {
                     this._nameTable[field.Name] = field;
                     if ((field.Type != null) && !string.IsNullOrEmpty(field.Type.BaseType))
                     {
                         names[field.Name] = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type);
                     }
                 }
             }
             CodeMemberMethod[] initializeMethods = this.GetInitializeMethods(manager, declaration);
             if (initializeMethods == null)
             {
                 throw new InvalidOperationException();
             }
             foreach (CodeMemberMethod method in initializeMethods)
             {
                 foreach (CodeStatement statement in method.Statements)
                 {
                     CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement;
                     if (statement2 != null)
                     {
                         this._nameTable[statement2.Name] = statement;
                     }
                 }
             }
             this._nameTable[declaration.Name] = context.Expression;
             foreach (CodeMemberMethod method2 in initializeMethods)
             {
                 CodeDomSerializerBase.FillStatementTable(manager, this._statementTable, names, method2.Statements, declaration.Name);
             }
             PropertyDescriptor descriptor = manager.Properties["SupportsStatementGeneration"];
             if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool) descriptor.GetValue(manager)))
             {
                 foreach (string str2 in this._nameTable.Keys)
                 {
                     if (str2.Equals(declaration.Name) || !this._statementTable.ContainsKey(str2))
                     {
                         continue;
                     }
                     CodeStatementCollection statements = this._statementTable[str2];
                     bool flag2 = false;
                     foreach (CodeStatement statement3 in statements)
                     {
                         object obj3 = statement3.UserData["GeneratedStatement"];
                         if (((obj3 == null) || !(obj3 is bool)) || !((bool) obj3))
                         {
                             flag2 = true;
                             break;
                         }
                     }
                     if (!flag2)
                     {
                         this._statementTable.Remove(str2);
                     }
                 }
             }
             base.DeserializePropertiesFromResources(manager, obj2, _designTimeFilter);
             CodeDomSerializerBase.OrderedCodeStatementCollection[] array = new CodeDomSerializerBase.OrderedCodeStatementCollection[this._statementTable.Count];
             this._statementTable.Values.CopyTo(array, 0);
             Array.Sort(array, StatementOrderComparer.Default);
             CodeDomSerializerBase.OrderedCodeStatementCollection statements2 = null;
             foreach (CodeDomSerializerBase.OrderedCodeStatementCollection statements3 in array)
             {
                 if (statements3.Name.Equals(declaration.Name))
                 {
                     statements2 = statements3;
                 }
                 else
                 {
                     this.DeserializeName(manager, statements3.Name, statements3);
                 }
             }
             if (statements2 != null)
             {
                 this.DeserializeName(manager, statements2.Name, statements2);
             }
         }
         finally
         {
             this._nameTable = null;
             this._statementTable = null;
             manager.ResolveName -= handler;
             manager.Context.Pop();
         }
     }
     return obj2;
 }
 public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
 {
     if ((manager == null) || (codeObject == null))
     {
         throw new ArgumentNullException((manager == null) ? "manager" : "codeObject");
     }
     object obj2 = null;
     using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::Deserialize"))
     {
         if (!(codeObject is CodeTypeDeclaration))
         {
             throw new ArgumentException(System.Design.SR.GetString("SerializerBadElementType", new object[] { typeof(CodeTypeDeclaration).FullName }));
         }
         bool caseInsensitive = false;
         CodeDomProvider service = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
         if (service != null)
         {
             caseInsensitive = (service.LanguageOptions & LanguageOptions.CaseInsensitive) != LanguageOptions.None;
         }
         CodeTypeDeclaration declaration = (CodeTypeDeclaration) codeObject;
         CodeTypeReference reference = null;
         Type type = null;
         foreach (CodeTypeReference reference2 in declaration.BaseTypes)
         {
             Type type2 = manager.GetType(CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, reference2));
             if ((type2 != null) && !type2.IsInterface)
             {
                 reference = reference2;
                 type = type2;
                 break;
             }
         }
         if (type == null)
         {
             Exception exception = new SerializationException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { reference.BaseType })) {
                 HelpLink = "SerializerTypeNotFound"
             };
             throw exception;
         }
         if (type.IsAbstract)
         {
             Exception exception2 = new SerializationException(System.Design.SR.GetString("SerializerTypeAbstract", new object[] { type.FullName })) {
                 HelpLink = "SerializerTypeAbstract"
             };
             throw exception2;
         }
         ResolveNameEventHandler handler = new ResolveNameEventHandler(this.OnResolveName);
         manager.ResolveName += handler;
         if (!(manager is DesignerSerializationManager))
         {
             manager.AddSerializationProvider(new CodeDomSerializationProvider());
         }
         obj2 = manager.CreateInstance(type, null, declaration.Name, true);
         this.nameTable = new HybridDictionary(declaration.Members.Count, caseInsensitive);
         this.statementTable = new HybridDictionary(declaration.Members.Count, caseInsensitive);
         this.initMethod = null;
         RootContext context = new RootContext(new CodeThisReferenceExpression(), obj2);
         manager.Context.Push(context);
         try
         {
             foreach (CodeTypeMember member in declaration.Members)
             {
                 if (member is CodeMemberField)
                 {
                     if (string.Compare(member.Name, declaration.Name, caseInsensitive, CultureInfo.InvariantCulture) != 0)
                     {
                         this.nameTable[member.Name] = member;
                     }
                 }
                 else if ((this.initMethod == null) && (member is CodeMemberMethod))
                 {
                     CodeMemberMethod method = (CodeMemberMethod) member;
                     if ((string.Compare(method.Name, this.InitMethodName, caseInsensitive, CultureInfo.InvariantCulture) == 0) && (method.Parameters.Count == 0))
                     {
                         this.initMethod = method;
                     }
                 }
             }
             if (this.initMethod != null)
             {
                 foreach (CodeStatement statement in this.initMethod.Statements)
                 {
                     CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement;
                     if (statement2 != null)
                     {
                         this.nameTable[statement2.Name] = statement;
                     }
                 }
             }
             if (this.nameTable[declaration.Name] != null)
             {
                 this.nameTable[declaration.Name] = obj2;
             }
             if (this.initMethod != null)
             {
                 this.FillStatementTable(this.initMethod, declaration.Name);
             }
             PropertyDescriptor descriptor = manager.Properties["SupportsStatementGeneration"];
             if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool) descriptor.GetValue(manager)))
             {
                 foreach (string str in this.nameTable.Keys)
                 {
                     CodeDomSerializerBase.OrderedCodeStatementCollection statements = (CodeDomSerializerBase.OrderedCodeStatementCollection) this.statementTable[str];
                     if (statements != null)
                     {
                         bool flag2 = false;
                         foreach (CodeStatement statement3 in statements)
                         {
                             object obj3 = statement3.UserData["GeneratedStatement"];
                             if (((obj3 == null) || !(obj3 is bool)) || !((bool) obj3))
                             {
                                 flag2 = true;
                                 break;
                             }
                         }
                         if (!flag2)
                         {
                             this.statementTable.Remove(str);
                         }
                     }
                 }
             }
             IContainer container = (IContainer) manager.GetService(typeof(IContainer));
             if (container != null)
             {
                 foreach (object obj4 in container.Components)
                 {
                     base.DeserializePropertiesFromResources(manager, obj4, designTimeProperties);
                 }
             }
             object[] array = new object[this.statementTable.Values.Count];
             this.statementTable.Values.CopyTo(array, 0);
             Array.Sort(array, StatementOrderComparer.Default);
             foreach (CodeDomSerializerBase.OrderedCodeStatementCollection statements2 in array)
             {
                 string name = statements2.Name;
                 if ((name != null) && !name.Equals(declaration.Name))
                 {
                     this.DeserializeName(manager, name);
                 }
             }
             CodeStatementCollection statements3 = (CodeStatementCollection) this.statementTable[declaration.Name];
             if ((statements3 != null) && (statements3.Count > 0))
             {
                 foreach (CodeStatement statement4 in statements3)
                 {
                     base.DeserializeStatement(manager, statement4);
                 }
             }
             return obj2;
         }
         finally
         {
             manager.ResolveName -= handler;
             this.initMethod = null;
             this.nameTable = null;
             this.statementTable = null;
             manager.Context.Pop();
         }
     }
     return obj2;
 }
		protected virtual object DeserializeInstance (IDesignerSerializationManager manager, Type type, 
							      object[] parameters, string name, bool addToContainer)
		{
			if (type == null)
				throw new ArgumentNullException ("type");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			return manager.CreateInstance (type, parameters, name, addToContainer);
		}
        public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
        {
            if ((manager == null) || (codeObject == null))
            {
                throw new ArgumentNullException((manager == null) ? "manager" : "codeObject");
            }
            object obj2 = null;

            using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::Deserialize"))
            {
                if (!(codeObject is CodeTypeDeclaration))
                {
                    throw new ArgumentException(System.Design.SR.GetString("SerializerBadElementType", new object[] { typeof(CodeTypeDeclaration).FullName }));
                }
                bool            caseInsensitive = false;
                CodeDomProvider service         = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
                if (service != null)
                {
                    caseInsensitive = (service.LanguageOptions & LanguageOptions.CaseInsensitive) != LanguageOptions.None;
                }
                CodeTypeDeclaration declaration = (CodeTypeDeclaration)codeObject;
                CodeTypeReference   reference   = null;
                Type type = null;
                foreach (CodeTypeReference reference2 in declaration.BaseTypes)
                {
                    Type type2 = manager.GetType(CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, reference2));
                    if ((type2 != null) && !type2.IsInterface)
                    {
                        reference = reference2;
                        type      = type2;
                        break;
                    }
                }
                if (type == null)
                {
                    Exception exception = new SerializationException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { reference.BaseType }))
                    {
                        HelpLink = "SerializerTypeNotFound"
                    };
                    throw exception;
                }
                if (type.IsAbstract)
                {
                    Exception exception2 = new SerializationException(System.Design.SR.GetString("SerializerTypeAbstract", new object[] { type.FullName }))
                    {
                        HelpLink = "SerializerTypeAbstract"
                    };
                    throw exception2;
                }
                ResolveNameEventHandler handler = new ResolveNameEventHandler(this.OnResolveName);
                manager.ResolveName += handler;
                if (!(manager is DesignerSerializationManager))
                {
                    manager.AddSerializationProvider(new CodeDomSerializationProvider());
                }
                obj2                = manager.CreateInstance(type, null, declaration.Name, true);
                this.nameTable      = new HybridDictionary(declaration.Members.Count, caseInsensitive);
                this.statementTable = new HybridDictionary(declaration.Members.Count, caseInsensitive);
                this.initMethod     = null;
                RootContext context = new RootContext(new CodeThisReferenceExpression(), obj2);
                manager.Context.Push(context);
                try
                {
                    foreach (CodeTypeMember member in declaration.Members)
                    {
                        if (member is CodeMemberField)
                        {
                            if (string.Compare(member.Name, declaration.Name, caseInsensitive, CultureInfo.InvariantCulture) != 0)
                            {
                                this.nameTable[member.Name] = member;
                            }
                        }
                        else if ((this.initMethod == null) && (member is CodeMemberMethod))
                        {
                            CodeMemberMethod method = (CodeMemberMethod)member;
                            if ((string.Compare(method.Name, this.InitMethodName, caseInsensitive, CultureInfo.InvariantCulture) == 0) && (method.Parameters.Count == 0))
                            {
                                this.initMethod = method;
                            }
                        }
                    }
                    if (this.initMethod != null)
                    {
                        foreach (CodeStatement statement in this.initMethod.Statements)
                        {
                            CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement;
                            if (statement2 != null)
                            {
                                this.nameTable[statement2.Name] = statement;
                            }
                        }
                    }
                    if (this.nameTable[declaration.Name] != null)
                    {
                        this.nameTable[declaration.Name] = obj2;
                    }
                    if (this.initMethod != null)
                    {
                        this.FillStatementTable(this.initMethod, declaration.Name);
                    }
                    PropertyDescriptor descriptor = manager.Properties["SupportsStatementGeneration"];
                    if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool)descriptor.GetValue(manager)))
                    {
                        foreach (string str in this.nameTable.Keys)
                        {
                            CodeDomSerializerBase.OrderedCodeStatementCollection statements = (CodeDomSerializerBase.OrderedCodeStatementCollection) this.statementTable[str];
                            if (statements != null)
                            {
                                bool flag2 = false;
                                foreach (CodeStatement statement3 in statements)
                                {
                                    object obj3 = statement3.UserData["GeneratedStatement"];
                                    if (((obj3 == null) || !(obj3 is bool)) || !((bool)obj3))
                                    {
                                        flag2 = true;
                                        break;
                                    }
                                }
                                if (!flag2)
                                {
                                    this.statementTable.Remove(str);
                                }
                            }
                        }
                    }
                    IContainer container = (IContainer)manager.GetService(typeof(IContainer));
                    if (container != null)
                    {
                        foreach (object obj4 in container.Components)
                        {
                            base.DeserializePropertiesFromResources(manager, obj4, designTimeProperties);
                        }
                    }
                    object[] array = new object[this.statementTable.Values.Count];
                    this.statementTable.Values.CopyTo(array, 0);
                    Array.Sort(array, StatementOrderComparer.Default);
                    foreach (CodeDomSerializerBase.OrderedCodeStatementCollection statements2 in array)
                    {
                        string name = statements2.Name;
                        if ((name != null) && !name.Equals(declaration.Name))
                        {
                            this.DeserializeName(manager, name);
                        }
                    }
                    CodeStatementCollection statements3 = (CodeStatementCollection)this.statementTable[declaration.Name];
                    if ((statements3 != null) && (statements3.Count > 0))
                    {
                        foreach (CodeStatement statement4 in statements3)
                        {
                            base.DeserializeStatement(manager, statement4);
                        }
                    }
                    return(obj2);
                }
                finally
                {
                    manager.ResolveName -= handler;
                    this.initMethod      = null;
                    this.nameTable       = null;
                    this.statementTable  = null;
                    manager.Context.Pop();
                }
            }
            return(obj2);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// This method deserializes a previously serialized code type declaration. The default implementation performs the following tasks:
        /// • Case Sensitivity Checks: It looks for a CodeDomProvider service to decide if it should treat members as case sensitive or case insensitive.
        /// • Statement Sorting:  All member variables and local variables from init methods are stored in a table. Then each statement in an init method is added to a statement collection grouped according to its left hand side. So all statements assigning or operating on a particular variable are grouped under that variable.  Variables that have no statements are discarded.
        /// • Deserialization: Finally, the statement collections for each variable are deserialized according to the variable. Deserialize returns an instance of the root object.
        /// </summary>
        public virtual object Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

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

            object rootObject = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    // Design time properties must be resolved before runtime properties to make sure that properties like "language" get established before we need to read values out the resource bundle
                    Trace("--------------------------------------------------------------------");
                    Trace("     Beginning deserialization of {0} (design time)", declaration.Name);
                    Trace("--------------------------------------------------------------------");
                    // Deserialize design time properties for the root component.
                    DeserializePropertiesFromResources(manager, rootObject, s_designTimeFilter);
                    // sort by the order so we deserialize in the same order the objects were decleared in.
                    OrderedCodeStatementCollection[] statementArray = new OrderedCodeStatementCollection[_statementTable.Count];
                    _statementTable.Values.CopyTo(statementArray, 0);
                    Array.Sort(statementArray, StatementOrderComparer.s_default);
                    // make sure we have fully deserialized everything that is referenced in the statement table. Skip the root object for last
                    OrderedCodeStatementCollection rootStatements = null;
                    foreach (OrderedCodeStatementCollection statements in statementArray)
                    {
                        if (statements.Name.Equals(declaration.Name))
                        {
                            rootStatements = statements;
                        }
                        else
                        {
                            DeserializeName(manager, statements.Name, statements);
                        }
                    }
                    if (rootStatements != null)
                    {
                        DeserializeName(manager, rootStatements.Name, rootStatements);
                    }
                }
                finally
                {
                    _nameTable      = null;
                    _statementTable = null;
                    Debug.Assert(manager.Context.Current == rootCxt, "Context stack corrupted");
                    manager.ResolveName -= onResolveName;
                    manager.Context.Pop();
                }
            }
            return(rootObject);
        }
		public override object Deserialize (IDesignerSerializationManager manager, object codeObject)
		{
			CodeTypeDeclaration declaration = (CodeTypeDeclaration) codeObject;
			Type rootType = manager.GetType (declaration.BaseTypes[0].BaseType);
			object root = manager.CreateInstance (rootType, null, declaration.Name, true);

			CodeMemberMethod initComponentMethod = GetInitializeMethod (declaration);
			if (initComponentMethod == null)
				throw new InvalidOperationException ("InitializeComponent method is missing in: " + declaration.Name);

			foreach (CodeStatement statement in initComponentMethod.Statements)
				base.DeserializeStatement (manager, statement);

			return root;
		}