Click here to Skip to main content
15,881,882 members
Articles / Web Development / HTML
Article

Repurpose ASP code in ASP.NET using Lightweight JavaScript

Rate me:
Please Sign up or sign in to vote.
1.33/5 (2 votes)
9 May 20055 min read 43.4K   179   20   9
How to reuse existing ASP rendering logic with an ASP.NET page by packaging the HTML as JavaScript and writing it to the client at render time.

Introduction

When migrating from an existing ASP 3.0 application to ASP.NET, a number of factors can complicate the situation. These may include how to make use of existing COM objects for the middle layer, how to restructure existing UI code as user controls, etc. Sometimes, a full transition to ASP.NET is not possible in one fell swoop. Instead, the existing ASP application may be required to live along side of the new ASP.NET application for quite some time while the site is ported on a phase-by-phase basis.

If you don't care about a fictitious business-case scenario, feel free to jump right to the code in "Solution Alternatives".

Case Study: International Staffing Company's Web Based Career Services Center

The fictitious company International Staffing Company (ICS) has an existing ASP 3.0 application. It is comprised of a backend database of Oracle, a middle tier of COM Objects, and front-end written in ASP with VBScript on the server and JavaScript for the web browser. Their site template consists of a left side menu, header section, and footer section. The appearance of these areas is constructed through complicated logic that examines the roles and responsibilities of the logged in user to determine which parts are accessible and appropriate for rendering.

ICS has decided to implement some new features of their web site using ASP.NET because they don't want to fall behind the times and lose their programmers to other companies. But, ICS expects that after the new development, only 5% of the application's UI will be done in ASP.NET, while the rest of the application will remain ASP.

ICS hardly sees the justification of rewriting their entire application using ASP.NET just to implement 5% of the application. As a result, ICS would like to make use of as much existing code for the time being and do as little refactoring as possible until the time is ready.

Problem Statement

How can we migrate existing UI rendering logic from our ASP application to an ASP.NET application? And, how can we do it such that the two applications can live side by side and that changes made to the ASP application's UI rendering logic are inherited by the ASP.NET application?

Complicating Factors

Here are some complicating factors:

  1. ICS has chosen to use as a base for their new efforts a freely available portal system upon which they can build new parts or modify existing parts. This will eliminate the need to build all the needed code from the ground up.
  2. The portal system must live in its own virtual directory.
  3. As mentioned above, there are thousands of different users for this application, and based upon their roles, the user interface changes for each login.
  4. Changes to the ASP 3.0 application are expected to continue concurrently.

Solution Alternatives

Some ideas come to mind in this situation:

  1. Rewrite the application UI logic so that it is done as Custom User Control in ASP.NET.
  2. Use the System.Net.WebClient class to call the existing application to extract the user interface code and place it into the HTTP response.
  3. Store the HTML code for the interface into a JavaScript and use the document.write method in the browser to construct the page GUI at render time.

Problems With 1 and 2

Options 1 and 2 sound attractive at first glance, but they suffer from a couple of fatal pitfalls:

In option 1, ICS has made it clear that they do not want to redesign everything right now as it would take too much time and they do not want to maintain two code bases while changes continue to happen in the ASP 3.0 application.

In option 2, the flaw is that since the user interface changes for each user logged in, the WebClient class, which executes on the server, would have to mimic the logged in user. While this is possible, it may not be possible in all situations, such as when digital certificates are required for authentication for log in.

Solution Chosen: Use JavaScript to Write out the HTML

Option 3 is the most pragmatic and easiest approach. Here's why:

  1. The user must authenticate through the existing ASP application before any of the ASP.NET content can be accessed.
  2. Modifying the ASP application to send chunks of HTML embedded into JavaScript scripts is very easy to do.
  3. Future changes to the ASP application's interface will automatically be inherited by the ASP.NET application.

Solution Outline

The solution will have three parts:

  1. A header portion of the existing ASP application that contains functions that will render all three template areas as discrete chunks of HTML.
  2. A page area of the existing ASP application that uses the functions to render these three chunks as JavaScript variables.
  3. An ASP.NET page that includes a reference to the ASP page in a JavaScript SCRIPT tag and then writes these chunks to the client page during render time.

Code for Original ASP Page

VB
<%
Dim userRole

userRole = "PUBLIC"

If Len(Request.QueryString("userRole")) > 0 Then
    userRole = Request.QueryString("userRole")
End If

Dim strMenuLeft, strMenuTop, strMenuBottom

Dim scriptUrl

scriptUrl = Request.ServerVariables("SCRIPT_NAME") & "?userRole=" & userRole

strMenuLeft = _
        "<div id='pnlMenu'>" & vblf & _
        "    <b>User Role:" & userRole & "</b>" & vblf & _
        "    <div class='mnuOptions'>" & vblf & _
        "        <div class='mnuTitle'>View</div>" & vblf & _
        "        <div class='mnuItem'><a href='" & scriptUrl & _
        "&cmd=ViewServices'>Services</a></div>" & vblf & _
        "        <div class='mnuItem'><a href='" & scriptUrl & _
        "&cmd=ViewProducts'>Products</a></div>" & vblf & _
        "    </div>" & vblf
If userRole = "EDITOR" Or userRole = "STAFF" Then
    strMenuLeft = strMenuLeft & _
        "    <div class='mnuOptions'>" & vblf & _
        "        <div class='mnuTitle'>Edit</div>" & vblf & _
        "        <div class='mnuItem'><a href='" & scriptUrl & _
        "&cmd=ModifyServices'>Modify Services</a></div>" & vblf & _
        "        <div class='mnuItem'><a href='" & scriptUrl & _
        "&cmd=ModifyProducts'>Modify Products</a></div>" & vblf & _
        "    </div>" & vblf
End If
If userRole = "STAFF" Then
    strMenuLeft = strMenuLeft & _
        "    <div class='mnuOptions'>" & vblf & _
        "        <div class='mnuTitle'>Manage</div>" & vblf & _
        "        <div class='mnuItem'><a href='" & scriptUrl & _
        "&cmd=ManageUsers'>Manage Users</a></div>" & vblf & _
        "        <div class='mnuItem'><a href='" & scriptUrl & _
        "&cmd=ManageSite'>Manage Site</a></div>" & vblf & _
        "    </div>" & vblf
End If
strMenuLeft = strMenuLeft & "</div>"


strMenuTop = "Home | Products | Services | Search | Feedback"
strMenuBottom = "Home | Privacy | Copyright"

%>
<html>
<head>
<title>International Staffing Company</title>

<link rel="stylesheet" type="text/css" href="style.css"></link>

</head>

<body>
    <img src="images/isclogo.gif"><br />
    <table border="0" cellpadding="2" cellspacing="6">
        <tr valign="top">
            <td><%=strMenuLeft%></td>
            <td>
                <table border="0" cellpadding="0" cellspacing="0>
                    <tr valign="top">
                        <td><%=strMenuTop%></td>
                    </tr>
                    <tr valign="top">
                        <td><br /><br /><br />[Content Area]
                           <br /><br /><br /></td>
                    </tr>
                    <tr valign="bottom">
                        <td><%=strMenuBottom%></td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>

Code to add to Original ASP Page VBScript to Render Values as JavaScript

VB
strMenuTop = "Home | Products | Services | Search | Feedback"
strMenuBottom = "Home | Privacy | Copyright"

Dim renderType
renderType = Request.QueryString("renderType")

If renderType = "js" Then
    Response.Write PackageAsJS(strMenuLeft, "strMenuLeft") & vblf
    Response.Write PackageAsJS(strMenuTop, "strMenuTop") & vblf
    Response.Write PackageAsJS(strMenuBottom, "strMenuBottom") & vblf
    Response.End
End If

Function PackageAsJS(str, name)
    str = Replace(str, vblf, "\n")
    str = Replace(str, """", "\""")
    str = Replace(str, vbtab, "\t")
    PackageAsJs = name + " = """ + str + """;"
End Function

Code for ASP.NET Page that Reuses the ASP Content

HTML
<html>
<head>
<title>International Staffing Company</title>

<link rel="stylesheet" type="text/css" href="style.css"></link>
<script type="text/javascript"   src=
  "http://localhost/ASPapp/Menu.asp?userRole=STAFF&cmd=ViewProducts&renderType=js">
  </script>

</head>

<body>
    <img src="images/isclogo.gif"><br />
    <table border="0" cellpadding="2" cellspacing="6">
        <tr valign="top">
            <td>
                <script type="text/javascript">
                <!--
                    document.write(strMenuLeft);
                //-->
                </script>
            </td>
            <td>
                <table border="0" cellpadding="0" cellspacing="0>
                    <tr valign="top">
                        <td>
                            <script type="text/javascript">
                            <!--
                                document.write(strMenuTop);
                            //-->
                            </script>                        
                        </td>
                    </tr>
                    <tr valign="top">
                        <td><br /><br /><br />
                          <form runat="server">
                          <input type="text" runat="server" 
                          value="[Content Area]" />
                          </form><br /><br /><br /></td>
                    </tr>
                    <tr valign="bottom">
                        <td>
                            <script type="text/javascript">
                            <!--
                                document.write(strMenuBottom);
                            //-->
                            </script>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>

</html>

How it Works

The code at the top of the .asp page checks the user's role and then renders the menu items as appropriate for that user. Later on, those dynamic values are written to the client. The new code is used to intercept the "renderType" parameter, and if it equals "js", then the HTML is escaped as JavaScript strings for the .NET client to apply to the client during render time. Of course, the link is hard-coded, but the idea is illustrated.

Summary

While it is nice to start projects fresh with the latest and greatest technology, sometimes this is not possible due to time constraints or current investment. Instead, a phased approach can mitigate concerns of technical obsolescence, while ushering in new functionality in a way that preserves the end-user experience. I hope you found this simple technique useful.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralA better way... Pin
piers712-Jun-05 3:40
piers712-Jun-05 3:40 
GeneralRe: A better way... Pin
UV200312-Jun-05 5:19
UV200312-Jun-05 5:19 
Thanks for the response. This gives me some good ideas. Your suggestion is better for certain situations. But, depending on how much logic is behind the current ASP portion, you may get into problems of sharing application state. If it is just a few variables that can easily be recreated in .NET, I definitely prefer your suggestion to make a COM/.NET component to render the HTML. I'm going to look into doing that, because I don't have too many variables or functions in the mix.
There could be one stored-procedure in the DB that both ASP and ASP.NET execute to get any database-specific info. This would not be difficult and would remove the need for client-side script.

I'll want to look into the implications of setting ASPCompat though, if I make a COM object. But, maybe I could make a .NET object that is called from ASP. Do you know how reliable either of this approaches is? I have not tried the latter at all.

Regarding the javascript approach, if there are a lot of vbscript functions instead of COM that are used to render HTML though, with the javascript approach, the user is already authenticated by the ASP application, so there is no need for any variables and functions that exist in the ASP application to have to be mirrored by the .NET application.

The only reliance on client-side script is three document.write calls. I don't see how that is a maintenance nightmare at all. It is a simple way to get some small dynamic portions of the UI from an already-authenticated session without having to reinvent everything immediately in new code. It also allows the ASP interface to continue to change without having to maintain multiple branches. Just write the center portion of the page in .NET and let the rest come from ASP. But, as someone else suggested it may not be compliant with turning off scripting.

Maybe to get around that, you could use WebClient on the server to simulate the user session and extract the HTML on the server side. The problem I had on that was that our users have to have a digital certificate to authenticate with first. I can think of one way to circumvent this now though, after having figured out how to attach a digital certificate to the HttpWebRequest:

1. On the web server, have a page called UIcode.asp, and this page will allow you to pass a UserId in the query string, which will then set the ID of the user and render the UI code as seen by that user. To make sure that this page can only be called from the server, check the remote address off the client and make sure it's the local machine.
2. In the new .NET application, use WebClient and attach a Digital Certificate to the request (Search on CAPICOM dll and user certificate store for this info)
3. Issue the request to UIcode.asp?userid=UserNumberHere.
4. The response from that page will be just like the packaged javascript objects, but it will all be server side, so the user will not even have to have Javascript turned on.

This would work for me without having to introduce new COM or .NET logic for the UI and not require the user to have JavaScript. But there is one other problem:

In our environment, when a user tries to request a web page on an HTTPS machine, there is a gateway Netgrity SiteMinder Agent that runs on all IIS boxes which intercepts the request. It then redirects the user to a central gateway authentication server. That server reads their digital certificate and asks them to specify a challenge phrase. They type that in then the gateway machine sets a browser cookie into their agent and redirects them to the requested URL. The SiteMinder agent then recognizes that they have already been authenticated and passes them through to the local IIS resource.

So, before I could get into the site, I'd have to issue a challenge phrase through a web form. I may be able to do it with a GET or POST request to the URL, but I still want to find out whether something similar to the PERL library HTML::Form exists for .NET? HTML::Form lets you parse an HTML document and generate a Form object which you can execute methods against. See http://aspn.activestate.com/ASPN/CodeDoc/libwww-perl/HTML/Form.html

After all that though, I agree that doing the whole thing in .NET is the most elegant and fun way, but sometimes people, often managers, can be skeptical that ASP.NET and ASP 3.0 can exist together. They say this because they fear that it's going to take a "big rewrite" to get them to live together and that you're going to have reinvent all of the logic that they already had you do in ASP.

In my case, since our site currently requires JavaScript and does a lot of dynamic document.write statements for showing form-validation feedback or selectively showing/hiding elements that we have not had any problems with for several years, showing that we could use this simple method without rewriting any code or introduce RCWs or CCWs at all and without maintaining multiple branches was a big help. We also are thinking about doing the .NET portion on the intranet-only for now as a way to make application management easier, so that is a factor as well.

Josh
GeneralDDA Pin
SoftADR19-May-05 3:47
SoftADR19-May-05 3:47 
GeneralWhy not run side by side Pin
paul heap9-May-05 20:21
paul heap9-May-05 20:21 
GeneralRe: Why not run side by side Pin
UV200310-May-05 1:40
UV200310-May-05 1:40 
GeneralRe: Why not run side by side Pin
paul heap10-May-05 5:53
paul heap10-May-05 5:53 
GeneralRe: Why not run side by side Pin
UV200310-May-05 14:00
UV200310-May-05 14:00 
GeneralRe: Why not run side by side Pin
justinsb18-May-05 0:22
justinsb18-May-05 0:22 
GeneralRe: Why not run side by side Pin
UV200319-May-05 17:00
UV200319-May-05 17:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.