Want to know one simple requirement that makes Windows Forms designer useles?
Here it is:
Application should use one instance of Dataset (or other component) in all windows and user controls.
Simple enough, right. So let's see it on some simple example: application that have two forms - list and the details of concrete record.
So first the list form. I've dragged the dataset table from the datasource window (in VS 2008) and it creates automagically Dataset object, datasource and gridview with apropriate databindings. Pretty amazing, huh.
Now lets go to the details form. The same way I've dragged the table but choosed that I want to see details. The same story: Dataset object, datasource and fields.
Now it seems that because we have two separate datasets in each form, the Microsoft way to fill this datasets is to fill them twice from the database (which cost bandwith), or once from the database - on the list form - and on the details form just copy it (which costs your developement time needed for code you must write). The situation is worse if each line on the list (let say customers) have many related tables that are also needed (for example are aggregated and shown in Dataset expression columns) - you must reload/copy them all.
Another stupid effect of this default behaviour of designer is that you must first call InitilizeComponent() which binds all controls to the created empty dataset and only then you can fill/copy data making great cascade of unnecesary events that will refresh the controls and which could be avoided if we will have ability to provide already filled Dataset and then the code could databind.
The simplest solution to this problem would be to force the designer in some way to use only one instance of Dataset in all windows.
Three years ago, when I for the first time spot this problem, the only solution that came to my mind was to abandon the designer...
OK I'm joking
The only solution that I've found then was to create a method that goes through all components and rebinds all components to the new Dataset (just after InitilizeComponent()). It was ugly hack that had similiar performance like copying all needed data to the new already binded Dataset, but doesn't duplicated the data in memory.
This way I used it for three years and it somehow works.
During this time I've found that InstanceDescriptor (object that defines what code to produce in InitilizeComponent() to create your component) allows to use static methods. My happines was cooled down so fast when I saw that code generates correctly, but it makes designer to crash. I cannot find the reason for two days and I droped this path.
In the beggining of this year I owned Visual Studio 2008 and tried to write one application using WPF. I saw that it allows to use DynamicResource which behave exactly like my rebinding in windows forms. I've tried also to force it to use static method to create object, but again failed and I must say that WPF for me seems less extensive than windows forms (read - more sealed and interal, or better - even runtime control tree has Sealed flag - lol).
I'm not convinced to WPF. Comparing to Windows Forms you must assume that you will have no designer. Nor Expression Blend, nor VS 2008 designer works for me. It ends for me that I designed only in XAML and the only preview was runtime, because designer didn't worked. For my luck this project was skipped for some time.
Right now I'm sitting on a new project back in Windows Forms and it's so much easier :-). But this time I had some free time and enough patience to sit down and find the reason why InstanceDescriptor generating static method blows away designer (of course this bug was not fixed in VS 2008 :-( ).
So in short time I've created typed Dataset called DB and my class called Data that will inherit from it to use InstanceDescriptor
[TypeConverter(typeof(OneInstanceTypeConverter<Data>))]
[FactoryMethod(typeof(Data), "Instance")]
public class Data : DB
{
static readonly Data instance = new Data();
public static Data Instance()
{
return instance;
}
}
public class OneInstanceTypeConverter<T> : TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor))
return true;
TypeConverter converter =
(TypeConverter) typeof (T).BaseType.GetCustomAttributes(typeof (TypeConverter), false)[0];
return converter.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof (InstanceDescriptor) && value is T)
{
object[] attributes = typeof (T).GetCustomAttributes(typeof (FactoryMethodAttribute), false);
if (attributes.Length == 0)
return new InstanceDescriptor(typeof (T).GetConstructor(new Type[0]), null);
return new InstanceDescriptor(((FactoryMethodAttribute)attributes[0]).Method, null, true);
}
TypeConverter converter =
(TypeConverter)typeof(T).BaseType.GetCustomAttributes(typeof(TypeConverter), false)[0];
return converter.ConvertTo(context, culture, value, destinationType);
}
}
[AttributeUsage(AttributeTargets.Class)]
public class FactoryMethodAttribute : Attribute
{
private readonly MethodInfo method;
public FactoryMethodAttribute(Type type, string method)
{
this.method = type.GetMethod(method, BindingFlags.Public | BindingFlags.Static);
}
public MethodInfo Method
{
get { return method; }
}
}
This code produces following line in InitilizeComponent():
this.data = Data.Instance();
Sweet, but when you close the form and try to open it again it will show you few exceptions that happens somwhere in CodeDomSerializer.Deserialize and says that field 'data' does not exists.
So serialization to static method works, but deserialization can't create object from it, and this is the reason I've abandoned it earlier.
Right now after two nights with Reflector and VS Debugger (of course for some reason VS 2008 didn't wanted to cooperate and load System.Design source code to debugger) I finally spot the place that have problem. But first... some theory.
When you drag some object onto form, it's created in memory and added to the designer list of objects which should be serialized to code. Later when designer is opening the file it deserializes it and calls appropriate methods to create it. usually it's a constructor, but we are trying here to call static method. What we see here is that VS can create object from constructor, but have some problem when it must call the static method. So coming this path I've checked if static method is called at all. To my lucky it was. Her is the stack trace:
HRDB.exe!Data.Instance() Line 23 C#
[Native to Managed Transition]
[Managed to Native Transition]
System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, string name, System.CodeDom.CodeExpression expression) + 0xc25 bytes
System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializer.DeserializeStatementToInstance(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, System.CodeDom.CodeStatement statement) + 0x6b bytes
System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializer.Deserialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, object codeObject) + 0x114 bytes
System.Design.dll!System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.DeserializeName(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, string name = "data", System.CodeDom.CodeStatementCollection statements) + 0x300 bytes
System.Design.dll!System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Deserialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, System.CodeDom.CodeTypeDeclaration declaration = {System.CodeDom.CodeTypeDeclaration}) + 0xe00 bytes
System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager) + 0x56 bytes
Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(System.ComponentModel.Design.Serialization.IDesignerSerializationManager serializationManager) + 0x2c4 bytes
Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(int fReload) + 0x48 bytes
[Native to Managed Transition]
I tried to find the bug somwhere in the code near the one stack trace shows me, but without success. And as a one of my ideas, I tried to comapre it to normal constructor.
HRDB.exe!HRDB.Data.Data() Line 18 C#
[Native to Managed Transition]
[Managed to Native Transition]
System.dll!System.SecurityUtils.SecureConstructorInvoke(System.Type type, System.Type[] argTypes, object[] args, bool allowNonPublic, System.Reflection.BindingFlags extraFlags) Line 153 + 0xc bytes C#
System.dll!System.ComponentModel.ReflectTypeDescriptionProvider.CreateInstance(System.IServiceProvider provider, System.Type objectType = {Name = "Data" FullName = "HRDB.Data"}, System.Type[] argTypes, object[] args = {object[0]}) Line 198 + 0x11 bytes C#
System.dll!System.ComponentModel.TypeDescriptor.TypeDescriptionNode.CreateInstance(System.IServiceProvider provider, System.Type objectType, System.Type[] argTypes, object[] args) Line 3751 + 0x10 bytes C#
System.dll!System.ComponentModel.TypeDescriptionProvider.CreateInstance(System.IServiceProvider provider, System.Type objectType, System.Type[] argTypes, object[] args) Line 70 + 0xfffffff1 bytes C#
System.dll!System.ComponentModel.TypeDescriptor.TypeDescriptionNode.CreateInstance(System.IServiceProvider provider, System.Type objectType, System.Type[] argTypes, object[] args) Line 3751 + 0x10 bytes C#
System.dll!System.ComponentModel.TypeDescriptor.CreateInstance(System.IServiceProvider provider, System.Type objectType, System.Type[] argTypes, object[] args) Line 600 + 0x18 bytes C#
System.Design.dll!System.ComponentModel.Design.DesignSurface.CreateInstance(System.Type type = {Name = "Data" FullName = "HRDB.Data"}) + 0x60 bytes
Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.VSDesignSurface.CreateInstance(System.Type type) + 0x20 bytes
System.Design.dll!System.ComponentModel.Design.DesignerHost.System.ComponentModel.Design.IDesignerHost.CreateComponent(System.Type componentType = {Name = "Data" FullName = "HRDB.Data"}, string name = "data") + 0xcf bytes
System.Design.dll!System.ComponentModel.Design.Serialization.DesignerSerializationManager.CreateInstance(System.Type type = {Name = "Data" FullName = "HRDB.Data"}, System.Collections.ICollection arguments, string name = "data", bool addToContainer = true) + 0x1fb bytes
System.Design.dll!System.ComponentModel.Design.Serialization.DesignerSerializationManager.System.ComponentModel.Design.Serialization.IDesignerSerializationManager.CreateInstance(System.Type type, System.Collections.ICollection arguments, string name = "data", bool addToContainer) + 0x94 bytes
System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeInstance(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, System.Type type, object[] parameters, string name, bool addToContainer) + 0x24 bytes
System.Design.dll!System.ComponentModel.Design.Serialization.ComponentCodeDomSerializer.DeserializeInstance(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, System.Type type, object[] parameters, string name, bool addToContainer) + 0x23 bytes
System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, string name, System.CodeDom.CodeExpression expression) + 0x550 bytes
System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializer.DeserializeStatementToInstance(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, System.CodeDom.CodeStatement statement) + 0x6b bytes
System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializer.Deserialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, object codeObject) + 0x114 bytes
System.Design.dll!System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.DeserializeName(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, string name = "data", System.CodeDom.CodeStatementCollection statements) + 0x300 bytes
System.Design.dll!System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Deserialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, System.CodeDom.CodeTypeDeclaration declaration = {System.CodeDom.CodeTypeDeclaration}) + 0xe00 bytes
System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager) + 0x56 bytes
Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(System.ComponentModel.Design.Serialization.IDesignerSerializationManager serializationManager) + 0x2c4 bytes
Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(int fReload) + 0x48 bytes
[Native to Managed Transition]
This one is a longer one but it shows that for normal contructor there is much more done than for static method. The paths seems to break in CodeDomSerializerBase.DeserializeExpression() method. For static method it calls the metod, but for constructor it calls ComponentCodeDomSerializer.DeserializeInstance().
Another night and I knew everything.
CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, string name, CodeExpression expression);
For static method expression parameter is CodeMethodInvokeExpression which results in just one call to System.Type.InvokeMember().
For constructor, expresion parameter is CodeObjectCreateExpression which results in call to ComponentCodeDomSerializer.DeserializeInstance() which is calling IDesignerSerializationManager.CreateInstance which apart from calling constructor is also adding created object to the list of components so it can be later used when it's refrenced in other CodeStatement.
So I've found a bug, but how to overcome it. It takes me a little time to find a way to do it without using Reflection. I was forced to create my own serializer which will exchange the CodeMethodInvokeExpression to CodeObjectCreateExpression just before deserialization. Below you have the full code:
[DesignerSerializer(typeof(OneInstanceSerializer<Data>), typeof(CodeDomSerializer))]
[TypeConverter(typeof(OneInstanceTypeConverter<Data>))]
[FactoryMethod(typeof(Data), "Instance")]
public class Data : DB
{
static readonly Data instance = new Data();
public static Data Instance()
{
return instance;
}
}
public class OneInstanceTypeConverter<T> : TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor))
return true;
TypeConverter converter =
(TypeConverter) typeof (T).BaseType.GetCustomAttributes(typeof (TypeConverter), false)[0];
return converter.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof (InstanceDescriptor) && value is T)
{
object[] attributes = typeof (T).GetCustomAttributes(typeof (FactoryMethodAttribute), false);
if (attributes.Length == 0)
return new InstanceDescriptor(typeof (T).GetConstructor(new Type[0]), null);
return new InstanceDescriptor(((FactoryMethodAttribute)attributes[0]).Method, null, true);
}
TypeConverter converter =
(TypeConverter)typeof(T).BaseType.GetCustomAttributes(typeof(TypeConverter), false)[0];
return converter.ConvertTo(context, culture, value, destinationType);
}
}
[AttributeUsage(AttributeTargets.Class)]
public class FactoryMethodAttribute : Attribute
{
private readonly MethodInfo method;
public FactoryMethodAttribute(Type type, string method)
{
this.method = type.GetMethod(method, BindingFlags.Public | BindingFlags.Static);
}
public MethodInfo Method
{
get { return method; }
}
}
public class OneInstanceSerializer<T> : CodeDomSerializer
{
public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
{
CodeDomSerializer serializer = GetSerializer(manager, typeof (T).BaseType);
CodeStatementCollection statements = codeObject as CodeStatementCollection;
if (statements != null)
{
for (int i = 0; i < statements.Count; i++)
{
object value = DeserializeStatementToInstance(manager, statements[i]);
if (value != null)
{
CodeAssignStatement statement = statements[i] as CodeAssignStatement;
if(statement != null)
statement.Right = new CodeObjectCreateExpression(typeof (T));
break;
}
}
return serializer.Deserialize(manager, statements);
}
return serializer.Deserialize(manager, codeObject);
}
public override object Serialize(IDesignerSerializationManager manager, object value)
{
return GetSerializer(manager, typeof(T).BaseType).Serialize(manager, value);
}
}
It's written in a way that you can just copy it and use in your project to any component you want. Just remember that you must use all 3 attributes.
I hope that it will help someone to write more performant code and still use designer to design the window in an elegant way.
I must say that - in my opinion - it's sad that windows forms style of designing will be abandon in favour of WPF and XAML. Just try to do such thing in WPF.
Wait I have better one, try to inherit from BaseForm class in WPF.
And my favourite - try to write equivalent of following generated code in WPF:
this.components = new MyContainer(this);
The key here is keyword this. I don't know how to pass Form reference in XAML. In Windows Forms it was not easy to do it, but it's possible (I'll show you later how). BTW I needed it to inject my IServiceProvider into each Form and its controls/components.