ASP Web Application

Snoops

   

 
Migrating to .NET: A Pragmatic Path to Visual Basic .NET, Visual C++ .NET, and ASP.NET
By Dhananjay  Katre, Prashant  Halari, Narayana  Rao  Surapaneni, Manu  Gupta, Meghana  Deshpande

Table of Contents
Chapter 13.   Case Study: ASP to ASP.NET


Architecture

Figure 13-1 shows the architecture of the ASP Web application. The Web client sends requests, which are received by IIS. IIS then directs the requests to the ASP application. The application refers to COM components for communicating with the database, in this case SQL Server.

Figure 13-1. Architecture of ASP application.

graphics/13fig01.gif

The best practice for any Web application using COM is to carry out database-related activities across the application through COM. In this application, though, we have made use of ADO in certain pages to demonstrate its use and to resolve related issues arising during migration. In some pages we have also called stored procedures directly, without using the available COM.

The Web application consists of two modules: Customer and Admin. A customer has rights only to buy or sell stocks and view his or her portfolio report. The Administrator can add a user and approve or cancel orders created during a buy/sell transaction by a customer and can also view reports on stock performance. The coding styles for the two modules are distinctly different. In the Customer module, coding is in a modular manner (i.e., most of the functionality is written in methods and functions across the pages). The appropriate functions are called on some event such as a page submit event with an associated query string value. The Admin module is coded without resorting to functions. This will help us select an appropriate migration approach for each of the modules. There are two include files used in the application, adovbs.inc and header.inc . In the Web application the home page, home.asp , provides links to both the modules as shown in Figure 13-2.

Figure 13-2. Home page for ASP Web application.

graphics/13fig02.gif

Customer Module

After clicking on the customer link, the user is taken to the login page for Customer. See Figure 13-3. The user has to enter a user ID and password and can enter the site only after the user ID-password combination is validated . The user can also change the password at logon.

Figure 13-3. Login page for Customer in ASP Web application.

graphics/13fig03.gif

The user authentication is carried out by the method Login in the COM component VBLoginCOM , which in turn calls the stored procedure sp_Login . The following code written in the ASP page login_customer.asp shows a function for calling the COM method:

 graphics/icon01.gif function validateUser()          dim objLogin          dim usrName          dim usrPwd          dim strMessage          dim intLogin          usrName = trim(Request.Form("txtID"))          if trim(Request.Form("txtNewPWD")) <> "" then                usrPwd = trim(Request.Form("txtNewPWD"))          else                usrPwd = trim(Request.Form("txtPWD"))          end if          strMessage=""          set objLogin = _  server.CreateObject("VBLoginCOM.cLogin")          intLogin = objLogin.Login(cstr(usrName), _          cstr(usrPwd), strMessage)          set objLogin = nothing          if intLogin <> 0 then                validateUser = strMessage          else                validateUser = ""          end if    end function 

Users can change their password during logon; the method changePassword in login_customer.asp calls the COM method ChangePassword, which in turn calls the stored procedure sp_Change_Password . The stored procedure validates the new password and updates the database table Customer accordingly .

In the login page, login_customer.asp , we have provided client-side validations written in JavaScript to prevent null values from being sent across. The validation function is shown in the following code. The function is called when the onClick event of either the Login or Change Password button is fired . Because the same function is called on the click of two buttons , a check is kept within the function to find out which button has been clicked.

 graphics/icon01.gif function validate(str)      {            if(document.frmLogin.txtID.value=="")            {                  alert("Please enter login id")                  document.frmLogin.txtID.focus();                  return false;            }            if(document.frmLogin.txtPWD.value=="")            {                  alert("Please enter password")                  document.frmLogin.txtPWD.focus();                  return false;            }            //If Change Password is clicked.            if(str=='change')            {                  if (document.frmLogin.txtNewPWD.value=="")                  {                        alert("Please enter New Password")                        document.frmLogin.txtNewPWD.focus();                        return false;                  }                  document.frmLogin.action=_                 'login_customer.asp?change=1';                  document.frmLogin.submit();            }            // If Login is clicked  else            {                  document.frmLogin.action=_                 'login_customer.asp?usrlogged=1';                  document.frmLogin.submit();            }      } 

On successful login, the menu on page welcome.asp is displayed as shown Figure 13-4. Users buy and sell stocks and view their portfolio in the form of a report. These options along with an option to log out from the site appear in the menu as shown.

Figure 13-4. Menu for user Customer.

graphics/13fig04.gif

After clicking on the hyperlink Buy Stocks, the user is taken to a page stock_service.asp , which displays a list of stocks along with current prices. This page makes use of ADO to retrieve records for stocks. The following code in the page stock_service.asp shows a connection object being opened:

 graphics/icon01.gif dim con  set con = server.CreateObject("ADODB.connection")  con.CursorLocation = 3  con.Open "Stock_System","sa","" 

Following this, a recordset object is created and an SQL query is fired to retrieve records for stocks and their latest prices into the recordset. The page appears with two buttons for buy and cancel, as shown in Figure 13-5.

Figure 13-5. Stocks listed for buying.

graphics/13fig05.gif

The user can select only one stock at a time for buying, and on a click of the Buy button the page is submitted to itself with a certain query string. Based on the value of the query string, the COM method PlaceOrder is called with appropriate parameters indicating that it is a buy transaction. Before the actual COM method is called, a function createParameter is called. This function creates and returns all the parameters required to call the method PlaceOrder :

 graphics/icon01.gif createParameters()  'To call the COM method  set objTrade = server.CreateObject("VBBuySellCOM.cBuySell")  intTrade = objTrade.PlaceOrder(cstr(custID), cstr(stockID),_  cdbl(stockprice), cint(qty), "B", strMessage) 

The COM method PlaceOrder calls a stored procedure sp_Order , which contains the logic for checking the customer's margin amount and updating the database accordingly.

The same page stock_services.asp is called by a click of the Sell Stocks button. This time a different query string value is passed, and as a result the database query returns with records of stocks owned by the user. The page then looks like that shown in Figure 13-6.

Figure 13-6. Stocks listed for selling.

graphics/13fig06.gif

When the Sell Stocks button is clicked, the page is submitted onto itself, this time with a different query string that identifies the transaction as a sell transaction. The COM method PlaceOrder is called again, with appropriate parameters.

The page contains client-side validation routines written in JavaScript to check that a radio button is selected and that the quantity of stocks is mentioned against the selected stock. Any order placed for buying or selling stocks has to be approved by the administrator before the transaction reflects in the customer's margin amount. This process will be covered in the Admin module.

To view a portfolio report, the user has to click on View Report. The page show_report.asp gives details of the customer portfolio, including the names and quantity of stocks owned, the value of each stock, and the total value of the customer's assets. The report, as shown in Figure 13-7, also displays current prices of stocks and margin amount for the customer.

Figure 13-7. Customer Portfolio Report.

graphics/13fig07.gif

To prevent caching, the following code is included in all the pages across the Customer module:

 graphics/icon01.gif Response.Expires = 60  Response.Expiresabsolute = Now() - 1  Response.AddHeader "pragma","no-cache"  Response.AddHeader "cache-control","private"  Response.CacheControl = "no-cache" 

The first line sets the page expiration time to 60 seconds. The second line says that this page should expire 24 hours before the current time. This ensures that the page expires immediately after it is served so that even if a user hits the back button and tries to view the page, it will not be made visible. Also, it provides for time differences rather than specifying a static date. The rest of the lines use properties of the Response object to prevent caching.

The following line is added to each page to enable buffering. When an ASP page is buffered, none of the page contents are output until all the contents are rendered. As a result, in the case of very large HTML pages, a buffered page might create some delay.

 graphics/icon01.gif Response.Buffer = true 

When Logout is clicked, the function userLogout is called on the page login_customer.asp . This function calls the COM method Logout, which refers to the stored procedure sp_Logout , which updates the database table Customer on successful logout. When Cancel is clicked on the login_customer.asp page, the user is taken back to the home page home.asp .

Admin Module

When the administrator clicks the hyperlink Admin on home.asp , the login page for the administrator, login_admin.asp , is shown. This is similar to the customer login page, the only difference being that the method Login of VBAdminCOM is called for validating the administrator. An administrator has rights to approve or cancel any order created by a customer during a transaction and can add and edit customer information. It is assumed here that the customer information is passed on to the administrator in some manner out of the scope of the application. The administrator can also view a report of the performance of a particular stock over a week. These options along with a Logout option are presented to the Admin user on successful login on the page welcome.asp , as shown in Figure 13-8.

Figure 13-8. Menus for Admin user.

graphics/13fig08.gif

After clicking Approve Orders, the administrator is taken to the page orderapprove.asp to select orders awaiting approval. The selection can be made on customer name and type of order, whether it is a buy or a sell. The screen is as shown in Figure 13-9. This page uses ADO to populate the dropdown list box from database table Customer. A connection is opened and records are fetched into a recordset. The recordset is then moved in a while loop to display its contents in the dropdown list box. The following code shows how the list box is populated from the recordset RCustomers :

Figure 13-9. Selecting orders for approval.

graphics/13fig09.gif

 graphics/icon01.gif <%While Not RCustomers.EOF%>        <option value="<%=RCustomers("CustomerID")%>">           <%=RCustomers("CustomerName")%>        </option>  <%  RCustomers.MoveNext  Wend  RCustomers.close  %> 

When the customer name and order type is selected, pending orders for that customer are displayed on the page approveorder.asp as shown in Figure 13-10. This page uses a stored procedure sp_Get_Unapproved_Orders to retrieve the unapproved orders based on the selection criteria. The following code shows the stored procedure being called within the page:

Figure 13-10. Approving orders.

graphics/13fig10.gif

 graphics/icon01.gif Dim Con, MyCommand, RS  Dim Customer, buy_sell, order_id  Customer = TRIM(Request("lstCustomer"))  buy_sell = TRIM(Request("lstType"))  Set Con = Server.CreateObject("ADODB.Connection")  Con.Open "PROVIDER=SQLOLEDB;DATA SOURCE=pc- p3793;UID=sa;PWD=;DATABASE=Stock_System"  Set MyCommand = Server.CreateObject ("ADODB.Command")  MyCommand.ActiveConnection = Con  MyCommand.CommandType = adCmdStoredProc  MyCommand.CommandText = "sp_Get_Unapproved_Orders"  MyCommand.Parameters.Append MyCommand.CreateParameter  ("ReturnCode", adInteger, adParamReturnValue, 4)  MyCommand.Parameters.Append MyCommand.CreateParameter  ("CustomerID", adVarChar, adParamInput, 8, Customer)  MyCommand.Parameters.Append MyCommand.CreateParameter  ("Buy_Sell", adChar, adParamInput, 1, buy_sell)  MyCommand.Parameters.Append MyCommand.CreateParameter  ("Status", adInteger, adParamOutput, 4)  MyCommand.Parameters.Append MyCommand.CreateParameter  ("Message", adVarChar, adParamOutput, 1000)  Set RS = Mycommand.Execute () 

The administrator user can select only one order at a time to approve or cancel. The page approve.asp calls the COM method ApproveOrder if the order is to be approved and CancelOrder if it is to be cancelled. On successful transaction, an appropriate message is displayed on the page.

The menu Add Customer takes the user to the page addcustomer.asp where details about a customer can be added. The page is shown in Figure 13-11. The form validation on this page is on the server side, when the page submits to custadd.asp . This page includes a file validateForm.asp , which contains a method validateForm to validate the form fields. If the form is validated successfully, the page custadd.asp calls a COM method AddUser , which in turn calls the stored procedure sp_Customer for adding new customer details to the database table Customer.

Figure 13-11. Adding a new Customer.

graphics/13fig11.gif

On clicking Update Customer, the administrator can update information about a particular customer. A method UpdateUser called on the page update.asp calls a stored procedure sp_Update_customer , which reconciles the changes made to customer information with the database.

The administrator can view a report based on the performance of a selected stock over a period of a week. To retrieve the information regarding the particular stock, a stored procedure sp_Get_Prices_For_Week is called in the page stockperfrpt.asp .

Because only one administrator is assumed to be present in the system, there is no check during logout.


Snoops

   
Top


Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
ISBN: 131009621
EAN: N/A
Year: 2001
Pages: 149

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net