Using custom DesignerSerializer to generate class declaration -
05-23-2005
, 02:38 PM
I am trying to use a custom DesignerSerializer to generate a class
declaration based on the properties of a custom control which is used by the
container class (a windows form or a web page) . The idea is that whenever
the user changes the values of the control properties, the class declaration
is modified accordingly (like a simplified code generation wizard).
However, I have been having problems to make it work. The issue is that I
can not make the Serialize method of the custom DesignerSerializer to
incorporate the class declaration.
First I tried to add the class declaration to the same namespace block of
the container class. But whenever I make this call:
public override object Serialize(IDesignerSerializationManager manager,
object value)
{
CodeNamespace namespaceBlock = (CodeNamespace)
manager.Context[typeof(CodeNamespace)];
/* Code that tries to use the namespaceBlock */
}
the variable namespaceBlock returns "null". So it seems that you can not
generate code outside the container class in the design-time.
As a result, I changed my strategy to generate a nested class inside the
container class. However, that did not work either. The strange thing is that
I am able to add method declaration to the container class. However, any
attempt to a add a nested class is ignored by the design-time framework.
Here is the code:
public override object Serialize(IDesignerSerializationManager manager,
object value)
{
CodeDomSerializer baseSerializer = (CodeDomSerializer)
manager.GetSerializer(typeof(MyCustomControl).Base Type,
typeof(CodeDomSerializer));
object codeObject = baseSerializer.Serialize(manager, value);
// Get reference to the container Class code
CodeTypeDeclaration containerClassCode = (CodeTypeDeclaration)
manager.Context[typeof(CodeTypeDeclaration)];
// Generating the method declaration.
CodeMemberMethod myMethod = new CodeMemberMethod();
myMethod.Name = "MyMethod";
myMethod.Attributes = MemberAttributes.Family | MemberAttributes.Final;
myMethod.ReturnType = new CodeTypeReference(typeof(void));
// Generating the class declaration.
CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass");
myClass.Attributes = MemberAttributes.Family | MemberAttributes.Final;
myClass.TypeAttributes = TypeAttributes.Class |
TypeAttributes.NestedFamily;
// This works beautifully. :-)
// Method declaration is added to the container class code.
containerClassCode.Members.Add(myMethod);
// This does not work. :-(
// No nested class declaration is added to the container class code.
containerClassCode.Members.Add(myClass);
return codeObject;
}
Thanks in advance for any help in this issue.
Marcos |