HTML Code to C# StringBuilder Tool?

Danpe picture Danpe · Apr 21, 2011 · Viewed 11.3k times · Source

I used to use a tool that you type in an HTML Code lik this one:

        <div id="pnlLoggedIn" style="width:480px;">
            <label for="txtUsername">Username</label>:
            <input name="txtUsername" type="text" id="txtUsername" class="input_small" tabindex="1"> 
            &nbsp;&nbsp;&nbsp;
            <label for="txtPassword">Password</label>:
            <input name="txtPassword" type="password" id="txtPassword" class="input_small" tabindex="2"> 
            &nbsp;&nbsp;
            <input type="submit" name="cmdLogin" value="Login" id="cmdLogin" class="red-button" tabindex="3" runat="server">
        </div>

And it gives you this as output:

StringBuilder sb = new StringBuilder();
sb.AppendLine("            <div id=\"pnlLoggedIn\" style=\"width:480px;\">");
sb.AppendLine("                <label for=\"txtUsername\">Username</label>:");
sb.AppendLine("                <input name=\"txtUsername\" type=\"text\" id=\"txtUsername\" class=\"input_small\" tabindex=\"1\"> ");
sb.AppendLine("                &nbsp;&nbsp;&nbsp;");
sb.AppendLine("                <label for=\"txtPassword\">Password</label>:");
sb.AppendLine("                <input name=\"txtPassword\" type=\"password\" id=\"txtPassword\" class=\"input_small\" tabindex=\"2\"> ");
sb.AppendLine("                &nbsp;&nbsp;");
sb.AppendLine("                <input type=\"submit\" name=\"cmdLogin\" value=\"Login\" id=\"cmdLogin\" class=\"red-button\" tabindex=\"3\" runat=\"server\">");
sb.AppendLine("            </div>");
return sb.ToString();

I cant remember the name of the tool, i remember it was an online tool.

If someone knows a tool that does that can please write it here.


--UPDATE--

Here is the tool i created: C# HTML Builder

Answer

Mike Hofer picture Mike Hofer · Apr 21, 2011

At the risk of providing an anti-answer, this strikes me as a bad solution. The code sample provided looks like a static resource to me. As such, it likely doesn't belong in the source code. Rather, it belongs somewhere else: either as an embedded resource, or as a page that's loaded on demand.

This sort of code tends to be a nightmare to maintain. Further, depending on how much code of this sort you have in your system, it can become a major performance sink due to all the string allocations and the eventual pressure on the garbage collector. (StringBuilder won't save you from this. Monitor your application with a tool like .NET Performance Monitor and view the data type you allocate most frequently. You might be surprised.)

The point of this response (I won't deign to call it an answer), is this: think outside the box. Your solution may not be the right one. Is there a better way to tackle this problem? If so, consider it.