.Net UserControl: I don't think this should work, but it does-- and that worries me

  •  Overview: One UserControl (bar.ascx) is used in two projects. Both projects are on the same IIS. I want to avoid copy/paste.

    Proposed "solution": Create a virtual directory such that ProjB\VirtualDirectory points to ProjA\PhysicalDirectory

    ProjA => PhysicalDirectory=> bar.ascx

    ProjB => VirtualDirectory => [bar.ascx]

    Now open up ProjB\foo.aspx, and add a reference to the user control:

    <%@ Register src="~/ProjB/VirtualDirectory/bar.ascx" TagPrefix="uc1" TagName="bar" />

    <uc1:bar runat="server" id="wtf" />

    Visual Studios rightly throws an error saying the file ~/ProjB/VirtualDirectory/bar.ascx  cannot be found.

    [b]BUT[/b], it works.  bar.PublicProperty = 1 happens.  If you go to http://example.com/ProjB/foo.aspx, the content of bar.ascx appears.

    I'm confused and worried.  When something shouldn't work, and when the compiler throws actual errors about it not working, and it works-- that means either something else is wrong, or something else is going to go wrong a year down the road once this is rolled out everywhere.  But I can't figure out what.

    So,  am I being overly cautious (friggin compiler errors!), or is this a cromulent solution?

    (Sidenote: Even if this does work, how is this kludge better than, say, a UserControl Library?)

  • Nothing to worry about, this is how it should be working. When you reference a User Control, Master Page, etc., ASP.NET Hosting Runtime uses an overridable VirtualPathProvider to resolve the resource. In IIS, the VirtualPathProvider is smart enough to understand Virtual directories and what not. You could write your own VirtualPathProvider that resolves ~/My/Path.ascx to return something from the database, and it will be used/compiled by ASP.NET just fine. That being said, VS.Net doesn't host your files and thus isn't smart enough to resolve these. So, a compiler warning is to be expected.

    I tried tihs pattern a long while ago (one Resource folder with UCs, MasterPages, etc., shared amongst multiple websites), but have since avoided it because it's complicated to configure.

Log in to reply

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.