1

There are numerous examples on the web that show how to use the CodeDomSerializer. Most of them show how to override the Serialize and Deserialize methods of that class. The problem is that this Serialize method takes a manager argument of type IDesignerSerializationManager. I cannot figure out how to create an instance of that type...

Here's what I tried:

var root = new Form();
root.Controls.Add(new TextBox()
{
   Text = "hello"
});

Type rootSerializerType = Type.GetType("System.ComponentModel.Design.Serialization.RootCodeDomSerializer, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true);

var rootSerializer = Activator.CreateInstance(
   rootSerializerType,
   BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance,
   null,
   null,
   null) as CodeDomSerializer;

IDesignerSerializationManager manager = new DesignerSerializationManager();
var serializationResult = (CodeTypeDeclaration)rootSerializer.Serialize(manager, root);

Because my manager object is not properly initialized, when I call the Serialize method as shown above, this exception is thrown:

[System.InvalidOperationException] "This method cannot be invoked because the serialization manager does not have an active serialization session."

I have googled and checked StackOverflow and I can't find any help on how to properly initialize the manager object ahead of my .Serialize invokation.

Any ideas?

1

1 Answer 1

2

You need to create the section. Change last two lines to:

DesignerSerializationManager manager = new DesignerSerializationManager();
using (var session = manager.CreateSession())
{
    var serializationResult = (CodeTypeDeclaration)rootSerializer.Serialize(manager, root);
    // handle the result here
}

Use either the concrete class DesignerSerializationManager or var, because the IDesignerSerializationManager interface does not have the CreateSession method.

Sign up to request clarification or add additional context in comments.

8 Comments

That makes sense. But when I follow your instructions I get a "Object reference not set to an instance of an object." exception at the call to the .Serialize(manager, root) method. Any ideas?
Yeah. The root (second parameter) should be initialized before the call
Yes, the root in fact contains a fully-baked object of type System.Windows.Forms.Form. I checked in the debugger and manager and rootSerializer also are set to instances of an object.
Strange. When I test with "object root = new object();" it runs just fine. Could you try it please?
Cast the the result to CodeTypeDeclaration. I updated my answer to reflect this change
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.