Home

Posts Tagged ‘C#’

ASPX: Don’t put UserControls inside of code blocks

Sunday, November 30th, 2008

I was trying to figure out why an ASPX page was taking so long to render. I put time markers all through my code, but the slowdown was happening between the end of the Page_Load execution, and the beginning of the page render. There were no exceptions or anything.

Finally, by a painful process of elimination, it turned out to be a block of code like this in the ASPX file. At render, it was deciding whether to include a custom UserControl. While the code executed properly, the only hint of a problem was iistrace showing “IISISAPI: ISAPI_END – IIS ends processing an ISAPI Request” taking a long time.

<% if( IsSomething ) { %>

    <%@ Register src="~/Sidebar.ascx" tagname="SiteSidebar" tagprefix="MySite" %>
    <MySite:SiteSidebar runat="server" />

<% } %>

If you want to save yourself hours of grief, don’t do this :D I wonder if this is the problem with a certain video player ;)

C#: Returning an array via webservice with derived classes

Thursday, November 20th, 2008

Here’s a neat little thing I learned today. I was writing a WebMethod for a WebService I’m working on for ScribbleLive. The return type is an array of Post objects.

[WebMethod]
public Post[] GetPostsSince( int ThreadId, DateTime Since )
{ ... }

But sometimes the array actually has objects of the type Comment, that is a derived class of Post. When I tried tried it out, it threw this exception:

System.InvalidOperationException: There was an error generating the XML document. —> System.InvalidOperationException: The type Comment was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

The problem is that the Serializer doesn’t know about the Comment class until runtime, and it throws a tantrum. Luckily, the fix is just to put a directive in there to make sure it knows that the Comment class may be used.

In my case, I just added the XmlInclude directive right about my Post class declaration like this:

[Serializable()]
[XmlInclude( typeof( Comment ) )]
public class Post
{ ... }

And that did the trick! I hope this is helpful for someone else :)