ASP to ASP.NET Helper Functions - c#

I'm looking at converting a web site from classic ASP to ASP.NET. I'm thinking of doing an agile style approach and providing deliverables as quickly as possible and so am thinking of doing a line by line conversion and creating "bad" ASP.NET and have it all in the ASPX file for phase 1 and get that working. That, I figure, will be the fastest and safest (i.e. preserving identical functionality). The next phase would be to split the code out into codebehind and multi-tiers.
I plan on replacing the VBScript in the ASP files with C# in the ASPX files.
So apart from general comments about what I'm planning on doing (which I welcome) the specific question that I have is: Are there any helper functions out there that wrap the VBScript functions from ASP to a C# equivalent that someone's already done?
So I'd be looking for a C# file (library) that has wrappers like:
string Mid(string txt,int start,int length)
{
return txt.SubString(start, length); // or is it start - 1?
}
double Abs(double num)
{
return Math.Abs(num);
}

Look in the Microsoft.VisualBasic namespace to get access to the old VBScript/VB6 functions. You can use them directly from C#.
Additionally, you're in for a shock. ASP.Net uses a different compiler model, and so some of the things you did in Classic ASP aren't allowed at all in ASP.Net. Include files is the big one that comes to mind-- all of your supporting code (code outside of the *.asp file for the page itself) must be re-thought to support the new model.

I don't think a line-by-line approach is a good idea - you'll just end up with a bunch of bad code that you'll still have to refactor. That doesn't sound very Agile to me either.
I'd try breaking the site up logically into modules, and then try rewriting specific pages or modules as ASPX. For example, if the site has an admin section, maybe you could just rewrite the admin portion. Then repeat for the next section. This could be done iteratively for each section until you're done.

I agree with the comment by Jason, and would like to also point out a higher level issue that you'd have to address, if you haven't thought about it already.
Does your classic ASP site make use of session variables to manage state between pages? If so, have you thought about how you're going to share session state between ASP and ASP.NET? Classic ASP and ASP.NET implement session state in different ways, so you will need methods to transfer between the two.
Smaller applications may be easier to "convert", but if you've got a large app that makes heavy use of session variables, you may want to think about other options.

If using ASP.NET MVC is an option for you, I'd take a look at that first. I would think it would be a much easier translation than trying to go from a scripting language to WebForms.

I don't think you gain anything by redoing the site as-is in .Net. Implementing it properly will be so radically different than what you'll start with in .Net that it just seems like wasted effort. Furthermore, it will be very difficult to write unit tests if you implement everything in .aspx pages without even code-behind.
I would aim for an MVC conversion. If you do port it over as-is, at least investigate master pages, that should save you some headaches.

Related

What is the equivalent approach of ASP.Net's Page Load method in JSP

While working on an ASP.NET project, I really liked the concept of a class for each page or webform, where I could write all the method and actions I want, and more importantly, the Page Load method.
Everyone says that we should avoid using scriplets, either in ASP or JSP.
And I suppose that the Page Load existed for us so that we don't use scriplets anymore.
Because I heard and read many times that we can't know when these scriplets will run, but in the Page Load method, we know exactly how the codes will run and how the page will be rendered.
But in JSP, as far as I know, we don't have this type of server-side class for each page.
Instead we have something called servelts, which everyone encourages to use.
But technically servlets are independent from the normal JSP pages.
So still, I'm using scriplets in my JSP pages, even though I'm trying to make them less as much as I could, but I still use some scriplets to check the Session and some URL parameters.
Isn't there a similar idea or approach to the Page Load (ASP) in JSP?
BalusC was right in saying you are comparing apples to oranges. JSF was created in response to asp.net. (source # 47 minutes) It has grown independently and you might do well to look into all the different frameworks and paradigms out there. While JSF will work similar to asp.net there are plenty of alternatives worth exploring. In .NET you might want to look into MVC4. In Java there is Tapestry, Spring MVC, Seams, etc.
I would start with wiki comparison and go from there. At your stage in the game I would pick one and try to get familiar with it, than try 2 more to do that same thing.
http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#Java_2

When to choose Javascript injection from code-behind over external js file

I'm working on a C# web app and I've to handle some javascript code.
I can do it both using javascript injection from my .cs file, which I'm doing now or choose to include my code into an external js file.
I would like to know when you would prefer to choose one way over the other.
According to me, it can be more clear to put code in external .js file and it can ease debugging.
Code injection from code-behind would however keep together all the necessary code for my component.
Can I please have your ideas ?
Thanks.
Pat.
Question #1: Do you need to dynamically generate JS?
Yes - inject from codebehind
No - external file
Question #2: Is the usage in a user control that may be used in several projects?
Yes - MAYBE inject, more likely either markup or an external file with a known relative path or a shared absolute path.
No - definitely external code.
If the dynamic generation is basically dynamically generating identifiers or numbers in the code, you can inline some ASP tags to get the job done in the markup. In short, dynamic JS should happen when you need it to happen because you can't do it any other way. Making sure dynamic JS works is a two-layer process; make sure the ASP.NET code creates the JS you expect, then make sure the JS you expect actually works as you expect.
You nailed it Pat, look at it the same way that you can choose to have a code behind file or not. ASP.NET is flexible enough to allow you to choose where you want to write your code, but ultimately do whats best FOR YOU.
Generally speaking, best practice is to have separation of code from the UI, separating into more manageable components. Isolating your JS into a separate file affords you other benefits as well. For example, local js files can be pulled into your page load via CompositeScript references in a ClientScriptManager, or even file compression via third party projects found on CodePlex and other websites.
If you can, separate the files, you'll be happy you did in the future.

ASP.NET User-based Templates

Is there anyway to let users write their own aspx templates with my defined dynamic variables? Note that I don't want to use Web Forms (so there are no tags like <asp:button> etc).
In addition, I'd need a security solution so users can't change the system or do dangerous things like this.
Thanks.
Personally I would avoid using the ASPX engine for this. I would probably use either a really simple custom formatting solution (such as just a text file with %%VAR_NAME%% allowed for dynamic values), or I would look at a templating language such as Markdown (used by StackOverflow and others). BBCode is another option in a similar vein.
Allowing people to create ASPX templated pages on the fly seems like to much of a security issue to me. It would be hard to make sure you have closed all the possible attack vectors once they have direct access to the ASP.NET engine.
Since you didn't specify, I'm just guessing at your needs, so depending on the exact problem this may or may not be your best bet. If you include more details about the problem you are solving it would be easier to make suggestions.

Is it a Good Practice to Write HTML Using a StringBuilder in my ASP.NET Codebehind?

I'm interested to hear from other developers their opinion on an approach that I typically take. I have a web application, asp.net 2.0, c#.
What I usually do to write out drop downs, tables, input controls, etc. is in the code behind use StringBuilder and write out something like sb.Append("
I don't find myself using to many .net controls as I typically write out the html in the code behind. When I want to use jQuery or call JavaScript I just put that function call in my sb.Append tag like sb.Append("td...onblur='fnCallJS()'.
I've gotten pretty comfortable with this approach. For data access I use EntitySpaces.
I'm just kind of curious if this sort of approach is horribly wrong, ok depending on the context, good, time to learn 3.0, etc. I'm interested in learning and was just looking for some input.
Edit
After reading the comments here it sounds like I should take a look at MVC. I've not done that yet. The only hesitancy in doing so is that the existing project is just that, existing. There is a lot of code already done the way I explained and it is hard to imagine what would be involved in changing it, advantages of doing so, and just learning what that would take.
The other thing I'm taking away from the comments is that my code behind should really not include much of the sb.Append code, whereas now it is filled with it in numerous functions. To me it is not messy but that is because I know what each function does and can look at it and see, oh that writes out x, y, and z.
It's not uncommon for me to just have a div on the .aspx part and then build up the .innerHtml of that with the StringBuilder in the code behind.
Thanks again for the comments. I'm thinking as I'm reading them.
I typically write out the html in the code behind.
That part is a little odd, and not something I recommend for webforms. If you want to do that, consider an asp.net mvc project instead.
In webforms, you really want the meat of your html to live with the markup rather than the code. The two should remain separate. You also don't want a huge stringbuilder that encompasses your entire page. This will force you to keep the entire page in memory twice (once for the stringbuilder bytes and once for the built string at the end) rather than writing the page to the response stream as it's built. That means more memory per request, which can really kill scalability.
To those ends, I would abstract distinct portions of your stringbuilder code into custom/user controls that you can use in the aspx markup. These controls can use a stringbuilder to create their output. This means you only need to keep enough html markup in memory to render one control at a time. It also allows you to more easily re-use common markup across pages or even sites.
There are times when you need to generate some HTML in your code behind, but in general, you want to leave the HTML where it belongs, and that's seperated from your code. The VS IDE is a pretty good HTML editor. Use it.
I'm going to go out on a limb and guess you may have come from a "Classic" ASP (vbScript) or PHP background.
My back ground is "Classic ASP" and my first attempts at the Webforms Model were pretty much the same as yours, once I started usnig them and understanding them I've never looked back. There is a disctinct learning curve though in understanding how the page life cycle interacts with the various WebForm controls.
Look up the various threads on ASP.net WebForms vs MCV to see which suits your projects needs the best. MVC Isn't a magic cure-all but in many respects may be more familiar if you're from a "Classic ASP" or PHP backgound.
From a practical perspective, assuming you're sticking with WebForms, if there is the possibility of other developers becoming involved in the project you aim towards using more of the inbuilt controls where you can as that is more than likely what they will be familiar with. Stating the obvious, the more you use the controls the more you will become familiar with what they can and can't do and before to long you will find yourself writing your own controls to fill the gaps or finding existing 3rd party controls.
A big problem you have with that it can get pretty messy... having to escape all the " or messing with carriage returns. Sure YOU can program around that, but what if you want to copy/paste code? sounds like a nightmare and WAY more work than it's worth.
It sounds like you should be writing a custom control and using HtmlTextWriter to write the markup.
Or perhaps more appropriate would be a user control, with markup in the aspx page and anything else in the code behind.
If you're using this approach, you should migrate your development efforts to ASP.Net MVC. Whereas ASP.Net actively tries to abstract the HTML, CSS, JavaScript, etc. away by using web controls, ASP.Net MVC is built around a paradigm of directly controlling the markup itself (though that may arguably be the least of the differences between the two - you should definitely read up on it to at least know the alternatives, even if you stick with ASP.Net in the long run).
Otherwise, what you're doing works if done properly (though you'll be fighting the framework the whole way), though I'd recommend using a StringWriter instead. It uses a StringBuilder internally so the performance characteristics are the same between the two, but the semantics are more consistent with the rest of the .Net framework (e.g., Write vs. Append).
I think this approach kind of defeats the purpose of what webforms was trying to accomplish (separating markup and code).
I know this thread is kind of old and has been answered really well, I just thought I would "append" (pun intended) my answer since I am working with code that was mentioned in the question.
ALL the markup is in the C# classes and they created a StringBuilder object to append all the html and JavaScript strings. This has made it very difficult to read the code and see what's going on, and what if they want to change the markup/design of the front-end? Now, I've got a heck of job on my hands having to go in and refactor all that markup in the classes, when it would be so much easier to change the .aspx pages and connect the data model to those pages.
In my humble opinion, I can't find a good reason to put any markup in your classes/code behind. They are for logic only. Plus, it makes it difficult to test and debug Javascript. That's my two cents. K.

Rewriting Existing Functionality in the .NET Base Class Library

Relating to another question I asked yesterday with regards to logging I was introduced to TraceListeners which I'd never come across before and sorely wish I had. I can't count the amount of times I've written loggers needlessly to do this and nobody had ever pointed this out or asked my why I didn't use the built in tools. This leads me to wonder what other features I've overlooked and written into my applications needlessly because of features of .NET that I'm unaware of.
Does anyone else have features of .NET that would've completely changed the way they wrote applications or components of their applications had they only known that .NET already had a built in means of supporting it?
It would be handy if other developers posted scenarios where they frequently come across components or blocks of code that are completely needless in hindsight had the original developer only known of a built in .NET component - such as the TraceListeners that I previously noted.
This doesn't necessarily include newly added features of 3.5 per se, but could if pertinent to the scenario.
Edit - As per previous comments, I'm not really interested in the "Hidden Features" of the language which I agree have been documented before - I'm looking for often overlooked framework components that through my own (or the original developer's) ignorance have written/rewritten their own components/classes/methods needlessly.
The yield keyword changed the way I wrote code. It is an AMAZING little keyword that has a ton of implications for writing really great code.
Yield creates "differed invoke" with the data that allows you to string together several operations, but only ever traverse the list once. In the following example, with yield, you would only ever create one list, and traverse the data set once.
FindAllData().Filter("keyword").Transform(MyTransform).ToList()
The yield keyword is what the majority of LINQ extensions were built off of that gives you the performance that LINQ has.
Also:
Hidden Features of ASP.NET
Hidden Features of VB.NET?
Hidden Features of F#
The most frequently overlooked feature I came across is the ASP.net Health Monitoring system. A decent overview is here: https://web.archive.org/web/20210305134220/https://aspnet.4guysfromrolla.com/articles/031407-1.aspx
I know I personally recreated it on several apps before I actually saw anything in a book or on the web about it.
I spoke to someone at a conference one time and asked about it. They told me the developer at MS had bad communication skills so it was largely left undocumented :)
I re-wrote the System.Net.WebClient class a while back. I was doing some web scraping and started my own class to wrap HttpWebRequest/HttpWebReponse. Then I discovered WebClient part way through. I finished it anyway because I needed functionality that WebClient does not provide (control of cookies and user agent).
Something I'm thinking about re-writing is the String.Format() method. I want to reflect the code used to parse the input string and mimic it to build my own "CompiledFormat" class that you can use in a loop without having to re-parse your format string with each iteration. The result will allow efficient code like this:
var PhoneFormat = new CompiledFormat("({0}){1}-{2}x{3}");
foreach (PhoneNumber item in MyPhoneList)
{
Console.WriteLine(PhoneFormat.Apply(PhoneNumber.AreaCode, PhoneNumber.Prefix, PhoneNumber.Number, PhoneNumber.Extension));
}
Update:
This prompted me to finally go do it. See the results here: Performance issue: comparing to String.Format

Categories

Resources