Inline (Single File) vs. CodeBehind - asp.net

In ASP.NET if the code and the asp.net markup is in one ascx file for example for a user control,would it perform poorly compared to a User control with Code Behind using a cs file and a designer.cs file?

The difference is in the initial compilation time; when your app first starts up.
With a code-behind file you can pre-compile things and deliver a dll to the server that's ready to go. With inline code, the framework will have to compile your code into an assembly when the app starts. But after this point compiled code is compiled code, and it just doesn't matter.

for performance it will not make any difference, although for maintainability reasons, you should keep your code behind separated from your markup.

An interesting fact - Microsoft sometimes suggests you create a code-behind assemblies for your ASP.net pages for maintainability and presentation/business logics separation.
However, when you take a look at how SharePoint is built, its pages (for instance, /_layouts/workflow.aspx) are full of inline code.
They actually do reveal that the speed of inline code is the same as code-behind:
Another myth is that codebehind is
faster than inline, which is
absolutely false. It doesn't matter
where your code for your ASP.NET
application lives, whether in a
codebehind file or inline with the
ASP.NET page.
This makes me think that performance and maintainability is not always the main reason why you choose inline code over code-behind.

Related

Vb aspx project, I need help to understand the logic behind

I'm a java programmer and for the first time I need to face a VB and ASP.NET web project.
I found some very basic tutorials on how ASP.NET works but I didn't understand very well how the logic behind works.
This project consist of lot of coupled files, the main pattern I found is:
file.ascx
file.ascx.designer.vb
file.ascx.vb
file2.aspx
file2.aspx.designer.vb
file2.aspx.vb
How do these file work and interact? I'm trying to understand it in a MVC logic but I can't seem to get it.
Drop the MVC logic in your head. ASPX doesn't use the MVC (at least by default).
The code files you see are grouped in two:
ascx: markup file. On the fly converted to VB.NET > MSIL;
ascx.vb: the code behind file. This one is merged with the generated code from the markup file (thanks to the partial keyword in the class declaration).
The ascx file is a control file, the aspx file is a page file. A page file can consist of zero or more controls, defined by the ASP.NET team, third party developers or you. If you want a custom control, you can create an own control by creating an ascx and ascx.vb file (or let Visual Studio do it for you).
aspx files usually will have the UI and will which is usually HTML tags, some ASP.NET server control embed code. aspx.vb file (codebehind) will have server-side coding in VB.NET.
In the MVC logic, you can relate aspx page to View and aspx.vb to Controller action methods.

New runat="server" div element on aspx, does it require compiling?

A new div element with a runat="server" property added to an ASP.NET presentation control does not require compilation, but can anyone explain why this works without a rebuild? If you were to perform a rebuild would the assemblies contain any new information?
I am trying to understand how the .NET framework treats these changes and why runat="server" controls can be added without rebuilding the related assemblies.
When adding new runat="server" controls the related designer files are updated to include additional references, therefore the compiled output differs.
Does anyone know what tools I could use to examine assemblies in this level of detail and perform side-by-side comparisons to identify minor alterations in their content?
It will work without a rebuild, so why do I care?
I have a fix for a current project which involves the addition of a new runat="server" div element and I need to know if I can deploy this fix without new assemblies.
I know it will work, but I need to know the technical differences (if any) between deploying just the aspx files and deploying the aspx files with a rebuilt dll.
This question was raised to help write a deployment process for a production environment I had no direct access to. The client was particularly hot on tracking changes and maintaining a clear audit trail.
Deployment packages for hotfixes would have to be small for rapid production and deployment, but must ensure environments match.
It works because you only changed the markup so the new HTML div will be rendered in the page and nothing is going to break because the code behind is not aware of the new control so does not even try to use it.
All html controls like div, tr-s, td-s and etc. are located in aspx file and adding runat="server" will not require rebuild. This will basically convert them into server-side controls, and they will be processed with full asp.net lifecycle.
But you need to remember, as soon as you will use it for example: Div1.Visible = false; it will require rebuild.
Looking back through unanswered questions, providing updates where possible.
This question was raised in an attempt to understand the inner workings of the .NET framework in regards to runat="server" controls.
When adding a new control I can see the designer files changing which would suggest that on build the related dll would differ.
However, you could make the change to the aspx element and deploy this without a new dll and it would work fine, there would be no error thrown saying the aspx included a runat="server" control that the assembly did not know about.
It was this relaxed handling of runat="server" controls I was trying to understand.
Useful tools
For anyone interested in understanding compilation output, assemblies can be decompiled to view their content using tools such as:
https://www.jetbrains.com/decompiler/
http://ilspy.net/
FYI: Using a decompiler I can see that the reference is included in the dll, meaning adding a runat="server" control will change your assemblies. If environments must be identical, then assemblies must be deployed.

Does ASP.NET use reflection to check for existance of event handlers?

I create an asp.net page e.g. default.aspx.
I then define a button...
<asp:Button ID="btnNew" runat="server" Text="New" OnClick="btnNew_OnClick" />
... however I do not define the handler for btnNew_OnClick in code.
ASP.Net will tell me this when I start the page and throw an exception.
Therefore, does it use reflection to check if the class that implements my page has this method ?
Is this efficient if it has to do this each time it parses a page's markup?
Not specifically. This happens when ASP.NET compiles your ASPX markup. ASPX markup is compiled the first time the page is hit on the fly, and stored somewhere in C:\WINDOWS\Microsoft.NET\Framework\vX\Temporary ASP.NET Files.
The exception to that is if you precompile your pages using aspnet_compiler.exe. However, if you were to pre-compile it you'd see there error there, not when you hit the site.
Is this efficient if it has to do this each time it parses a page's markup?
ASP.NET isn't parsing the markup on every page view and post back; it's only parsing it once when it's compiled. It stored a hash of the page (usually called hash.web somewhere in Temporary ASP.NET Files) and compares the hashes. If the hash is different (the page changed) then it recompiles it. Here is an example of what that compiled code may look like:
#line 58 "C:\X\UserControls\FilterControl.ascx"
#__ctrl.Click -= new System.EventHandler(this.btnApply_Click);
#line default
#line hidden
#line 58 "C:\X\UserControls\FilterControl.ascx"
#__ctrl.Click += new System.EventHandler(this.btnApply_Click);
This of course gets compiled into an executable assembly. Effectively, what the ASPX compiler is doing is compiling the server side markup into C# code, then compiler that into an assembly.
ASP.NET actually generates a class descending from your page using the ASPX markup as a template of sorts. You can find the generated classes source code in the folders under %WINDIR%\Microsoft.NET\v[FRAMEWORK VERSION]\Temporary ASP.NET File.
My understanding is it generates a class which instantiates the control and wires the event handlers to whatever method applies. This is why things break badly when you, say, make your event handler private -- the descendant class can't access it.
The code generation is pretty expensive up-front; it is partially responsible for that lengthy asp.net warm-up most of us asp.net developers suffer through. But it is very, very efficient once the app gets warmed up as everything is rendering via compiled code.
No it does not use reflection. As #Wyatt Barnett said, the compiler generates code for this. The generated code is the same as if you would register the event yourself.
btnNew.Click += new EventHandler(btnNew_Click);
As the code for the markup is generated it is the same regarding performance, maybe except for the first call.

ServerControl versus UserControl

I'd like to hear some reasons for using a ServerControl opposed to a UserControl. I've found that I probably overuse UserControls.
My list looks something like this:
Pro UserControl
Easily modified. Need to add a class attribute to an element, hack it out in html.
Quick and easy to create initial view. Everyone can write simple html right?
Pro ServerControl
Performance. No html parsing.
Flexibility. Control rendering down to a gnat's behind.
Reusability. Compile it and stick it in the GAC for later use. Or, sell it.
Anything that I'm missing?
The following two advantages of server controls come to mind:
support for inheritance (because the actual user control at runtime inherits from your code behind, you can't inherit from it anymore)
detailed control over the tag's parsing (should nested tags be treated as child controls or properties, etc.)
support for control adapters (declarative, e.g. in a .browsers file)
support for tag mapping (if you're making your own controls that's often very useful though)
However, user controls do have an additional edge because they're templated:
support for databinding expressions
One other consideration is whether you want visual studio designer support at the time you're building the control or at the time you're using the control on the page. It really irks me that you only get one or the other, but not both.
Performance. No html parsing
I wouldn't expect that to be much of a runtime difference - the .ascx should get compiled on first use as well. Perhaps there's some slight overhead saved by not checking the file for modifications - but I can't think of much else.

Best way to share ASP.NET .ascx controls across different website applications?

Suppose you have 2 different ASP.NET applications in IIS. Also, you have some ASCX controls that you want to share across these 2 applications.
What's the best way to create a "user control library", so that you can use the same control implementation in the 2 applications, withuot having to duplicate code?
Controls have ASCX with HTML + code behind.
Composite controls will be difficult, because we work with designers who use the HTML syntax in the ASCX files to style the controls.
Tundey, we use SVN here. Do you have an example on how to implement your suggestion? How can SVN share the ASP.NET controls?
Thanks!
Scott Guthrie gives some great advice here on how to set up a User Control Library project, then use pre-build events to copy the user controls into multiple projects. It works really well.
http://webproject.scottgu.com/CSharp/usercontrols/usercontrols.aspx
You would need to create composite controls instead of .ASCX controls if you wanted to be able to use them in separate projects.
In addition to what Tundey said, NTFS Link shell extension is helpful when it comes to sharing a large chunk of content (e.g.: a folder with .ascx/.aspx) between otherwise independent projects. In case of code, i think making another working copy from VCS is preferable.
Have a look at this: http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx?msg=1782921
An alternative is to use your source control tool to "share" the ASCX controls between your webapps. This will allow you to make changes to the controls in either application and have the source control ensure the changes are reflected in the our webapps.
The biggest problem I've noticed with controls in ASP.Net is that you can't easily get designer support for both building the control and using the control in a site once you built it. The only way I've been able to do that is create an .ascx control with no code-behind (ie: all the server-side code is in a script tag in the .ascx file with the runat="server" attribute).
But even then, you still have to copy the .ascx file around, so if you ever need to make a change that means updating the file at every location where you've used it. So yeah, make sure it's in source control.
I managed to do this by sacrificing some of the ease of building the controls in the first place.
You can create a Control Library project that will generate a control library DLL for you. The drawback is that you have to create the controls with code only. In my last project, this was fine. In more complicated controls, this may be a problem.
Here's an example:
<DefaultProperty("Text"), ToolboxData("<{0}:BreadCrumb runat=server />")> _
Public Class BreadCrumb
WebControl
<Bindable(True)> _
Property Text() As String
'...'
End Property
Protected Overrides Sub RenderContents(output as HtmlTextWriter)
output.write(Text)
End Sub
Private Sub Page_Load(...) Handles MyBase.Load
' Setup your breadcrumb and store the HTML output '
' in the Text property '
End Sub
End Class
Anything you put in that Text property will be rendered.
Then, any controls you put in here can function just like any other control you use. Just import it into your Toolbox, make your registration reference, then plop it onto the ASP page.
I use StarTeam here and it allows you to "share" objects (files, change requests, requirements etc) across multiple folders. Not sure if Subversion (SVN) has that feature. If it doesn't, here's another trick you can use: create a junction from the primary location of the controls to a location in the other projects. A junction is just like a Unix symbolic link. You can download the tool for creating junctions in Windows from here
I have a suggestion.WE can use user control across multiples application by creating user control inside website project as normally.Then change the website property Use fixed naming and single page assemblies.Then we can use the user control dll into multiple applications.
I recently did a web application that just referenced the files (about 90 in total) from one web application (aspx, master and ascx) without too much of an issue. That said I was using a heavily modified version of the MVP pattern, a lot of interfaces and conventions to keep the complexity down, the same middle tier and one site was a subset of the other.
Big issues:
Master pages (and in turn designers and html view formatting) don’t work on a referenced file so you lose a lot of functionality. A pre-build step and a lot of svn:ignore entries was my hack around this. It was also a pain to get CruiseControl.NET to get the pre-build task to execute in the right folders.
Shared pages/controls need to be extremely aware of what they touch and reference as to avoid bringing in extra dependencies.
Both sites are locked together for deployment.
I now have to pray that the maintainer reads my pokey little document about the mess I made. It’s so far outside of what I’ve seen in ASP.NET projects.
I was under a massive time pressure to get it to work, it does and now both apps are in production. I wouldn’t recommend it but if you’re interested start at:
Add Existing Item, select some files, click on the Add button’s arrow and say Add as a Link.

Resources