Is there any reason to put code in the code behind rather than in the aspx file? - asp.net

Any time I need to write code I almost always put it in the code behind file. For some reason this has always seemed like the "right" way to write code.
Based on most of the examples I see online, a lot of other people choose to write code this way too, but it seems like putting your code in the aspx file allows you to do all the same stuff as well as offering a few advantages.
Top of the list being:
Easier to make changes since no
recompile.
You have access to all code if
you can't find the project in source
control (this recently happened to
me).
Is there any benefit to having code in a code behind file? Is there any disadvantage to putting code in your aspx file?

Separating the code from the markup results in much cleaner structure, especially for non-trivial pages.
This is one of the major benefits to ASP.Net over ASP Classic.

Easier to make changes since no
recompile.
Depends in what context, you can upload normal ASPX + ASPX.CS to the server and it will compile it for you on IIS.
I use this for my personal web site, I hate having to 'publish' the web site and then upload the files, sometimes on the server I need to make quick edits in Notepad, hence this approach is perfect.
I personally like the setup of keeping them separate.
PS. I use 'Web Sites' not 'Web Projects' which I believe has to be compiled before uploading to the server.

Maintainability. It allows the HTML part to be edited independently of the code, by and large.

When you have a very small project it is just a bad practice. They just tell you it's wrong, but it feels perfectly right.
You will hit the wall when you start working on big projects and especially when you will need to maintain them.
When your project gets big -the GUI part(the form) becomes smaller: one component here, this color there... not too complicated.
On the other hand, the logic part becomes a real pain... if I use a function in 20 pages will I change each replication of the function in each form? If they are almost identical, yet a bit different... how will I implement the solution?
OOP offers many design patterns so that your code will be as clean and efficient as possible... but you have to work with objects rather than a form.
A form is an object, yet it doesn't meet the OOP design patterns rules. And those rules are there to make your life easier.
I once had to maintain a huge system... and every change required changing many forms and testing many forms. After rebuilding the system it became a SMALL system and easy to maintain. It is easy to just build a form from scratch ignoring the entire system... but it's really hard to maintain this form.
Never think of the year you build the project, think of the 20 years you are going to maintain it.
Good luck
Asaf

Stumbled upon this link now searching for the real advantages of putting code in cb files, and to confirm SLaks' answer, see this link for those who still wondered. Really thought processing and speed could've been an advantage as well, but alas...

Related

converting Legacy ASP app to ASP.NET: best approach

I've taken over support of a legacy web app written predominantly in classic ASP. One page has a form for doing a job estimate, and consists of about 2500 lines of javascript and ASP code to achieve a "transparent edit" - i.e., the form is always in edit mode, and changes are instantly updated into the DOM.
There is also a "Print To Word Doc" button that, when clicked, goes to an entirely separate ASP file that produces (supposedly) the same view in HTML sent downloaded to a Word document.
The problem is that we have discovered inconsistencies and bugs in the two versions that are produced. My first response, applying the DRY principle, was This needs to be re-written in ASP.NET with a single code-behind file outputting the view for both the web page and the word document, so that we have one place to maintain the source.
However, upon getting into it, I'm questioning the wisdom of that approach, and I'm soliciting advice.
The problem is that, because of the integration of the view with the editing on the web page, as opposed to simply presentation on the work document, the two functions really do have two different purposes. Also, the ASP code, while ugly and hard to maintain, produces a reasonably nice-looking document. Doing the same thing in ASP.NET, at least using ASP.NET controls like FormView, is proving challenging. (One of the rewrite requirements is that the new page must function like the old page, minus bugs, of course.) The integration of the javascript to accomplish the editing functions on the client side makes for a good UX (assuming they work correctly). I can probably accomplish that same thing with AJAX and/or jQuery, but I'm wondering if I'm really gaining anything here.
How would you handle this?
You also have to take into consideration a couple of other issues:
How critical are the defects?
How
much time to do you have to get this
thing fixed?
How long will it take
you to correct the defects in classic
ASP?
How long will it take you to
convert the entire thing to ASP.NET?
At the end of the whole thing, will
anyone care which platform it's
implemented in? That is, will they
still be able to get their work done?
Because, at the end of the day,
that's all that really matters.
ASP.NET, while a wonderful thing, is not a silver bullet. If you're spinning your wheels, you're not being productive, and no one's getting a fixed product in a reasonable timeframe. It's like refactoring code just for the sake of refactoring it. It doesn't fix any defects, but darn does the code look pretty.
My advice to you: stick with classic ASP until you get the bugs out. THEN port it to ASP.NET. I'd much rather port a fixed product than a broken one.
That's a really complex question you're posing. The main issue is right there at the end:
I'm wondering if I'm really gaining
anything here.
Is the modification you need to make a small mod? or is it large? How much will you have to maintain this in the future?
You'll only realize dividends on your effort with future modifications. If you're never touching this system again, re-writing won't realize any benefits.
I have worked in projects in which we "converted" a classic ASP application into a .NET application. This is what we did:
Made a copy of the classic ASP files and then used the automated conversion feature from Visual Studio to convert this new copy into a .NET application.
Listed the .NET features we wanted to take advantage of in this new application and then found the correct places in the application to implement them.
Re-wrote code where needed to take full advantage of such features.
Refactored existing classic ASP code to avoid re-inventing the wheel where it was not needed.
Tested everything and then ran both applications in parallel until we felt comfortable that the new .NET application was running as expected.

Cleaning up a complex WebForms project

I'm currently working on a high-traffic online search site.
They have various changes they want to implement over time, and they've indicated that ultimately they want the site re-done in ASP.NET MVC.
Currently the site is an ASP.NET WebForms project; however true ASP.NET controls are rarely used. Instead there are lots of server-side tags - i.e. <% ... %>. The code in these tags will usually be a call to a static method in a static class or a fragment of C# code that generates HTML.
Many of the static methods generate HTML by appending text to a string-builder and returning it as a string.
I understand the concept of a 'Helper' method, but I don't like the idea of the HTML being rendered by concatenating it to a string variable. I think they'd be better off using 'Partials'.
The thing that concerns me is that it's a pretty complex site, and I'm not sure if a complete rebuild of the site in ASP.NET MVC is a good idea.
In spite of the bad structure, it's not really that hard to add the new features that are being requested. (Perhaps because I've had past experience working with difficult code).
However I think there's a risk that at some time in the future, a requirement will come along that will be very difficult to implement unless we do a complete clean-up of the code-base.
I want to put this question out there and see if anyone's faced a similar issue, and how you dealt with it.
Also what are your thoughts on doing the re-build as a 20%-time side-project? Are there any downsides to doing it this way?
Wow, this is some project.
Personally I think any site written in ASP.Net will need to be totally re-done as far as the UI is concerned. MVC does it a whole lot differently.
Your business logic on the other hand should be ok though me thinks so long as you have seperation of concerns and it's not bound to the UI.
Data access should be ok and probably needs minimal touching. But that again depends on how tightly bound your web site is.
I think the best approach is to spend some time looking at how MVC does business and do a critical analysis of what it would take to convert and then begin converting all the layers above the UI in preperation.
Get your foundation in place and maybe even, if possible, use the MVC framework already. Again, only if you can and only if viable.
Doing this as a side project would work I think because you can take some of your libraries and begin converting them in preperation for the mvc conversion.
But be mindful that once you have converted a project/layer that you (do) implement it else it runs the risk of being forgotten or changes get made to the other layer that then need to be coded into the new etc. You know the traps.
As for the UI, that's going to be the big one especially if you use a lot of asp controls. You maight want to spend a lot of time evaluating the UI and come up with a list of controls that you either need to replace or write. Then you can begin to see a pattern and get some consistency going.
If you have a lot of code in your code behind, you may want to begin moving this to another layer as this will help later on when you create controllers etc. They can then instantiate your new layer and all should be good.
That's all I can think of from the top of my head. I'll edit or comment as I think of things.
Hope this helps.
If I have that project and I was asked to redo it from scratch, I will not use MVC to render the UI, I will use Web API/OData to host all the backend, and will use any good Front End to draw the UI, Angular will be a very good option.
Having it as a side project is good only if the pace of changes and new features in the old project is less than the progrress done in the new project, you don't want to end up with doing duplicate effort and at some point you will have to code freeze the old one.
Also, you have to consider any data migration if you will have to change the data storage option.

Refactoring "include file hell"

One thing that's really been making life difficult in getting up to speed on the codebase on an ASP classic project is that the include file situation is kind of a mess. I sometimes find the function I was looking for being included in an include file that is totally unrelated. Does anyone have any advice on how to refactor this such that one can more easily tell where a function is if they need to find it?
EDIT: One thing I forgot to ask: does vbscript have any kind of mechanism for preventing a file from being included twice? Sorta like #ifndef's from C?
There are a few basic things you can do when taking over a classic ASP application, but you will probably end up regretting doing them.
Eliminate duplicate include files. Every classic ASP app I've ever seen has had 5 "login.asp" pages and 7 "datepicker.js" files and so forth. Hunt down and remove all the duplicates, and then change references in the rest of the app as necessary. Be careful to do a diff check on each file as you remove it - often the duplicated files have slight differences because the original author copied it and then changed just the copy. This is a great thing for Evolution, but not so much for code.
Create a rational folder structure and move all the files into it. This one is obvious, but it's the one you will most regret doing. Whether the links in the application are relative or absolute, you'll have to change most of them.
Combine all of your include files into one big file. You can then re-order all the functions logically and break them up into separate, sensibly-named files. You'll then have to go through the app page by page and figure out what the include statements on each page need to be (or stick with the one file, and just include it on every page - I can't remember whether or not that's a good idea in ASP). I can't comprehend the pain level involved here, and that's assuming that the existing include files don't make heavy use of same-named globals.
I wouldn't do any of this. To paraphrase Steve Yegge (I think), "there's nothing wrong with a classic ASP application that can't be fixed with a total rewrite". I'm very serious about this - I don't think there's a bigger waste of a programmer's time in this world than maintaining an ASP app, and the problem just gets worse as ASP gets more and more out of date.
#MusiGenisis bullet point list is good advice to follow but I'd disagree with -
"I wouldn't do any of this. To paraphrase Steve Yegge (I think), "there's nothing wrong with a classic ASP application that can't be fixed with a total rewrite". I'm very serious about this - I don't think there's a bigger waste of a programmer's time in this world than maintaining an ASP app, and the problem just gets worse as ASP gets more and more out of date."
All very well, but if it's a sizable legacy app doing complete re-writes is often not possible due to a lack of developer time/resource.
We have a fairly large classic ASP app which has grown arms and legs over the years, it's not pretty but it does serve the business needs. We have no time to spend the next six months doing a complete re-write, it would be nice, but just not possible. Our approach is -
Where there's new functionality required, it's implemented in ASP.NET. This happens 95% of the time. The 5% edge cases usually being that there are a large number of points where the new app code touches the old app requiring us to do a lot of classic ASP re-work potentially making the app more fragile.
Where there's a change in functionality we assess whether we can refactor to ASP.NET with minimal impact. If this isn't possible then we'll implement the change in classic ASP and tidy up existing code as we go along e.g. simplifying include file nesting, replacing javascript with more cross browser friendly code, that kinda thing.
In answer to your question about #ifndef's, there isn't an equivalent I'm afraid.
Use one file to global headings and includes (lets name it t-head.asp). This file is included in all asp files.
Use one file to make the site visual global header (logos, menus, etc) and include it right behind . Let call it t-begin.asp
Use one file to make the site visual global footer (copyright, google analytics, etc.) and closing all divs or tables opened in t-begin.asp. Lets call this file t-end.asp
Use one folder to put the business logic files, called BUS. The files in this folder can not have includes. Every function inside the file must be preceded by the name of the logic unit (IE: all function in products.asp must begin with product_*)
Use one folder to put some reused UI code called UI. The files in this folder can not have includes.
Example:
<%# Language=VBScript %>
<% Option Explicit %>
<% Response.Buffer = true%>
<html>
<head>
<!--#include file="../general/t-head.asp"-->
<!--#include file="../bus/product.asp"-->
<title>Products page</title>
</head>
<body>
<!--#include file="../general/t-begin.asp"-->
<% 'all your code %>
<!--#include file="../general/t-end.asp"-->
</body>
</html>
Wow. It constantly surprises me how many people have a hate for ASP. In decent hands it's a perfectly capable language for designing web applications.
However, I will concede that the way include files are managed in ASP can be a bit of a brainache -- because (depending on how you use them) they have to be loaded and parsed even if you're not using half the functions contained within.
I tend to have one include file (initialise.asp or some such) that itself includes links to several functions libraries (lib_http.asp, lib_mssql.asp or similar) and all library functions are self-contained so there is no worry about crossing variables. Any global vars are declared and set in the master file. This means I can use a function anywhere, any time and not worry about where it was defined, it's just there for use. And IDEs such as Visual Studio and Primalscript have the ability to "jump to definition" when you find a call to a function that you don't recognise.
Then, any script-specific includes are included in the script after the call to this master include file.
I concede that this is a memory-hungry approach as all the functions in all the libraries are compiled for every script call, so the method needs refining for each site you develop -- decide what to call via the master include and what is more page-specific. It would be nice to be able to only load what you need -- but that's the DLL approach and is not available for the majority of real-world developments, and also you'd have to weigh up the processor cost of compiling small scripts vs loading components.
A concise directory structure is requisite and easily developed, but it can be a chore to wade through all the code in an existing site and change any links or mappath calls. Also, be aware that some IIS administrators disallow the '..\' method of traversing directories via VBScript, so then all file references have to be absolute paths.
i think you should consider moving your code from ASP VBScript to Visual Basic COM DLLs. that'll ease on you having too much includes.
I don't know of a way to prevent a double inclusion, other than getting an error message that is. Are you seeing includes placed throughout the page, which is making them difficult to spot?
Just as an aside, are you working with a copy of the code and the database on a development server? From my experience, the first thing to do is separate yourself from the live site ASAP. While a hassle initially, it'll give you the freedom to make changes without messing up the live site. It's easy to make that one tiny change in an include and BAM! the whole site goes down.
I've worked through a few projects like you've described and used the following strategies:
Complete rewrite - perfect when there's time/money, but usually I get the call when something has gone wrong and results are needed ASAP.
Smaller projects - I open up everything in the IDE and just start searching all the project files for the functions/sub, in order to build a knowledge of the include logic. Pretty much each time, everything is spread out everywhere, so I start rebuilding the includes organized by business logic. I've also run across inline code (raw code, not subs or functions) thrown into an include, so I'll usually just pull the code back into the page for refactoring later.
Larger projects - I'll use some code I have laying around to parse the includes for lines with sub/function headers and dump those to a text file to build up a list of what routines are where and refer to that. This comes in handy when you've got a ton of includes on each page and can't get your head around the codebase.

Tips for avoiding big ball of mud with ASP.NET WebForms

Although ASP.NET MVC seems to have all the hype these days, WebForms are still quite pervasive. How do you keep your project sane? Let's collect some tips here.
I generally try to stay clear of it... but when i do use WebForms, i follow these precepts:
Keep the resulting HTML clean: Just because you're not hand-coding every <div> doesn't mean the generated code has to become an unreadable nightmare. Avoiding controls that produce ugly code can pay off in reduced debugging time later on, by making problems easier to see.
Minimize external dependencies: You're not being paid to debug other people's code. If you do choose to rely on 3rd-party components then get the source so you don't have to waste unusually large amounts of time fixing their bugs.
Avoid doing too much on one page: If you find yourself implementing complex "modes" for a given page, consider breaking it into multiple, single-mode pages, perhaps using master pages to factor out common aspects.
Avoid postback: This was always a terrible idea, and hasn't gotten any less terrible. The headaches you'll save by not using controls that depend on postback are a nice bonus.
Avoid VIEWSTATE: See comments for #4.
With large projects the best suggestion that I can give you is to follow a common design pattern that all your developers are well trained in and well aware of. If you're dealing with ASP.NET then the best two options for me are:
o Model View Presenter (though this is now Supervisor Controller and Passive View).
This is a solid model pushing seperation between your user interface and business model that all of your developers can follow without too much trouble. The resulting code is far more testable and maintainable. The problem is that it isn't enforced and you are required to write lots of supporting code to implement the model.
o ASP.NET MVC
The problem with this one is that it's in preview. I spoke with Tatham Oddie and be mentioned that it is very stable and usable. I like it, it enforces the seperation of concerns and does so with minimal extra code for the developer.
I think that whatever model you choose, the most important thing is to have a model and to ensure that all of your developers are able to stick to that model.
Create web user controls for anything that will be shown on more than one page that isn't a part of masterpage type content. Example: If your application displays product information on 10 pages, it's best to have a user control that is used on 10 pages rather than cut'n'pasting the display code 10 times.
Put as little business logic in the code behind as possible. The code behind should defer to your business layer to perform the work that isn't directly related to putting things on the page and sending data back and forth from the business layer.
Do not reinvent the wheel. A lot of sloppy codebehinds that I've seen are made up of code that is doing things that the framework already provides.
In general, avoid script blocks in the html.
Do not have one page do too many things. Something I have seen time and time again is a page that say has add and edit modes. That's fine. However if you have many sub modes to add and edit, you are better off having multiple pages for each sub mode with reuse through user controls. You really need to avoid going a bunch of nested IFs to determine what your user is trying to do and then showing the correct things depending on that. Things get out of control quickly if your page has many possible states.
Learn/Grok the page lifecycle and use it to your advantage. Many ugly codebehind pages that I've seen could be cleaner if the coder understood the page lifecycle better.
Start with Master Pages on day #1 - its a pain coming back to retrofit.
Following what Odd said, I am trying out a version of the MVP called Model Presentation which is working well for me so far. I am still getting an understanding of it and adapting it to my own use but it is refreshing from the code I used to write.
Check it out here: Presentation Model
Use version control and a folder structure to prevent too many files from all being in the same folder. There is nothing more painful than waiting for Windows Explorer to load something because there are 1,000+ files in a folder and it has to load all of them when the folder is opened. A convention on naming variables and methods is also good to have upfront if possible so that there isn't this mish-mash of code where different developers all put their unique touches and it painfully shows.
Using design patterns can be helpful in organizing code and having it scale nicely, e.g. a strategy pattern can lead to an easier time when one has to add a new type of product or device that has to be supported. Similar for using some adapter or facade patterns.
Lastly, know what standards your forms are going to uphold: Is it just for IE users or should any of IE, Firefox, or Safari easily load the form and look good?

Is inline code in your aspx pages a good practice?

If I use the following code I lose the ability to right click on variables in the code behind and refactor (rename in this case) them
<a href='<%# "/Admin/Content/EditResource.aspx?ResourceId=" + Eval("Id").ToString() %>'>Edit</a>
I see this practice everywhere but it seems weird to me as I no longer am able to get compile time errors if I change the property name.
My preferred approach is to do something like this
<a runat="server" id="MyLink">Edit</a>
and then in the code behind
MyLink.Href= "/Admin/Content/EditResource.aspx?ResourceId=" + myObject.Id;
I'm really interested to hear if people think the above approach is better since that's what I always see on popular coding sites and blogs (e.g. Scott Guthrie) and it's smaller code, but I tend to use ASP.NET because it is compiled and prefer to know if something is broken at compile time, not run time.
I wouldnt call it bad practice (some would disagree, but why did they give us that option in the first place?), but I would say that you'll improve overall readability and maintainability if you do not submit to this practice. You already conveyed out a good point, and that is IDE feature limitation (i.e., design time inspection, compile time warning, etc.).
I could go on and on about how many principles it violates (code reuse, separation of concerns, etc.), but I can think of many applications out there that break nearly every principle, but still work after several years. I for one, prefer to make my code as modular and maintainable as possible.
It's known as spaghetti code and many programmers find it objectionable... then again, if you and the other developers at your company find it readable and maintainable, who am I to tell you what to do.
For sure though, use includes to reduce redundancy (DRY - don't repeat yourself)
I use it only occasionally, and generally for some particular reason. I will always be a happier developer with my code separated entirely from my HTML markup. It's somewhat a personal preference, but I would say this is a better practice.
It's up to you. Sometimes "spagehetti" code is easier to maintain than building/using a full on templating system for something simple, but once you get fairly complicated pages, or more specifically, once you start including a lot of logic into the page itself, it can get dirty really quickly.
I think it is interesting that more asp.net is requiring code in the aspx pages. The listview in 3.5, and even the ASP.NET MVC. The MVC has basically no code behind, but code in the pages to render information.
If you think of it in terms of template development, then it is wise to keep it in the view, and not in the code behind. What if if needs to change from a anchor to a list item with unobtrusive JS to handle a click? Yes, this is not the best example, rather just that, and example.
I always try to think in terms of if I had a designer (HTML, CSS, anything), what would I have him doing and what would I be doing in the code behind, and how do we not step on each other's toes.
Its only a bad practice, if you cannot encapsulate it well.
Like everything else, you can create nasty, unreadable spaghetti code, except now you have tags to content with, which by design aren't the most readable things in the world.
I try and keep tons of if's out of hte template, but excessive encapsulation, leads to having to look in 13 diferent places to see why div x isn't firing to the client, so its a trade off.
It's not, but sometimes it's a necessary evil.
Take your case for an example, although code behind seems to have a better separation of concern, but the problem with it is that it may not separate out the concerns as clearly as you wish. Usually when we do the code behind stuff we are not building the apps in MVC framework. The code behind code is also not easy to maintain and test anyway, at least when compare to MVC.
If you are building ASP.NET MVC apps then I think you are surely stuck with inline code. But building in MVC pattern is the best way to go about in terms of maintainability and testability.
To sum: inline code is not a good practice, but it's a necessary evil.
My 2cents.
Normally I use like this way.
<a href='<%# DataBinder.Eval(Container.DataItem,"Id",""/Admin/Content/EditResource.aspx?ResourceId={0}") %'>

Resources