Monday, February 12, 2007

Design time rendering and run time rendering.

I was doing some work on the GMap.Control over the weekend. On thing I found is that whenever I drop the control on the form, it always gives me an error on rendering, error to create control, error to render a control.

The problem is , when the visual studio render a control on the form, it will look for the DesignerAttribute, if it's not available, it will look for the default ControlDesigner. The ControlDesigner has a default method called GetDesignTimeHtml() , It will render the view on the form.

Use the reflector, here is what GetDesignTimeHtml() will do by default:

public virtual string GetDesignTimeHtml()
{
StringWriter writer1 = new StringWriter(CultureInfo.InvariantCulture);
DesignTimeHtmlTextWriter writer2 = new DesignTimeHtmlTextWriter(writer1);
string text1 = null;
bool flag1 = false;
bool flag2 = true;
Control control1 = null;
try
{
control1 = this.ViewControl;
flag2 = control1.Visible;
if (!flag2)
{
control1.Visible = true;
flag1 = !this.UsePreviewControl;
}
control1.RenderControl(writer2);
text1 = writer1.ToString();
}
catch (Exception exception1)
{
text1 = this.GetErrorDesignTimeHtml(exception1);
}
finally
{
if (flag1)
{
control1.Visible = flag2;
}
}
if ((text1 != null) && (text1.Length != 0))
{
return text1;
}
return this.GetEmptyDesignTimeHtml();
}
Actaully, at the design time, a lot of objects are not initialized properly, so it will cause an exception.
So, I made an easy approach, I override the GetDesignTimeHtml() method to let it simply draw a string. Of course, there are a lot of more interesting stuff you can do here.
 



public override string GetDesignTimeHtml()
{
try
{
StringBuilder sb
= new System.Text.StringBuilder();
sb.Append(
"GMap2 Server Control");
return sb.ToString();
}
catch (Exception ex)
{
return GetErrorDesignTimeHtml(ex);
}
}



It at lease won't give me any error anymore.

No comments: