ASPX, Calculator, WebApp

How To Create a Four Function Web Calculator using ASPX

 


Overview

It is assumed that the reader hasBrowser_Server some knowledge of HTML (HyperText Markup Language) and programming logic.  Access to reference materials is recommended!

The four-function calculator ASPX (Active Server Page Extended using Microsoft ASP.NET framework) uses HTML, CSS and JQuery for web page presentation and VBScript  (Visual Basic Scripting) programming logic for ease of reading.

This application utilizes a client-server architecture where the client (Web Browser) initiates a request by POSTing to the web server using HTTP (Hypertext Transfer Protocol).  In turn, the web server reciprocates with a web page to the client (Web Browser) as a response.

The following sections exhibit and explain the code snippets for web presentation and page processing logic including installation instructions onto a Windows operating system.

This logic is the same of ASP, but, the placement of variables and subroutines are declared within SCRIPT tags including new page directives.

This web calculator is hosted at this link:   ASPX_Calculator

 


Web Page Presentation

<body>

<!-- Calculator FORM -->
<form method="POST" action="<%=myScriptName%>" name="CalculateIT">
<!-- Place border on FORM and border title accordingly -->
<fieldset style="border-color:green; background-color:beige">
<legend style="color:blue; font-size: 18pt; background-color:lightsteelblue"><%=myTitle%></legend>
<!-- Audit Trail and Intermediate Result textboxes -->
<table align="center">
<tr>
<td align="center">Audit Trail</td>
<td align="center">Intermediate Results</td>
</tr>
<tr>
<td><textarea id="t1" rows="15" name="AuditTape" cols="30"  readonly="readonly"><%=frm_AuditTape%></textarea></td>
<td><textarea id="t2" rows="15" name="AccumTape" cols="40" readonly="readonly"><%=frm_AccumTape%></textarea></td>
</tr>
</table>

<!-- Script to scroll both result windows simultanously -->
<script type="text/javascript">
function Scroll_to_Bottom() 
{
document.getElementById('t1').scrollTop=document.getElementById('t1').scrollHeight;
document.getElementById('t2').scrollTop=document.getElementById('t2').scrollHeight;
}
//call the function
Scroll_to_Bottom ();
    </script>

<!-- Audit Trail and Intermediate Result textboxes -->
<br/> 
<table border="1" cellpadding="10" cellspacing="0" align="center" style="border-collapse: collapse ; background-color:DarkSeaGreen">
<tr>
<td>
<!-- Place border on keyboard and display components -->
<fieldset style="border-color:green; background-color:lightsteelblue">
<!-- Calculator Display Title -->
<%=MaxInput%> Digit Display
<br/>
<!-- Calculator Display -->
	<input name="NumIn" size="15" value="<%=frm_NumIn%>" style="text-align:right; font-size: 10pt" readonly="readonly">
<!-- Calculator Error Message area -->
<br/>
<font color=red size="2"><%=ErrMsg%></font>
<!-- Calculator Keypad -->
<br/>
      <input id="btn" type="submit" value="C"   name="Fclear" >&nbsp;
      <input id="btn" type="submit" value="CE"  name="Fcleare" >&nbsp;
      <input id="btn" type="submit" value="off" name="Poff" style="background-color: red; ">&nbsp;
      <input id="btn" type="submit" value="on"  name="Pon" style="background-color: green; color:lawngreen; ">&nbsp;
<br/>
      <input id="btn" type="submit" value="7"   name="B7" >&nbsp;
      <input id="btn" type="submit" value="8"   name="B8" >&nbsp;
      <input id="btn" type="submit" value="9"   name="B9" >&nbsp;
      <input id="btn" type="submit" value="/"   name="Fdiv" >&nbsp;
<br/>
      <input id="btn" type="submit" value="4"   name="B4" >&nbsp;
      <input id="btn" type="submit" value="5"   name="B5" >&nbsp;
      <input id="btn" type="submit" value="6"   name="B6" >&nbsp;
      <input id="btn" type="submit" value="x"   name="Fmult" >&nbsp;
<br/>
      <input id="btn" type="submit" value="1"   name="B1" >&nbsp;
      <input id="btn" type="submit" value="2"   name="B2" >&nbsp;
      <input id="btn" type="submit" value="3"   name="B3" >&nbsp;
      <input id="btn" type="submit" value="-"   name="Fminus" >&nbsp;
<br/>
      <input id="btn" type="submit" value="0"   name="B0" >&nbsp;
      <input id="btn" type="submit" value="."   name="Bdot" >&nbsp;
      <input id="btn" type="submit" value="="   name="Fequal" >&nbsp;
      <input id="btn" type="submit" value="+"   name="Fplus" >&nbsp;
</fieldset>
</td>
</tr>
</table>
</fieldset>
</form>
<u><i>myCalc</i></u> is for illustrative and educational purposes and does not represent a fully robust and tested calculator product.<br>
Copyright &copy; 2015 Larry Belmontes, Jr.
</body>

The above snippet represents the HTML BODY section.  The FORM, which is within the BODY, contains three components (keypad, audit trail and results) used to interact with the web browser and web server.  Below is a description of HTML used in this web page.

Line Description
4 FORM declaration containing all interactive components contained within the <FORM> and </FORM> HTML tags.
When form is submitted (any keypad button is pressed), form data is POST-ed to the web server by invoking ASPX script calc_42.aspx.
6-7 Declare a green border with the title of myWeb Calculator.  The border surrounds all calculator components.  A beige background is applied within the green boarder.
9-18 Declare a one-row, two-column table containing two text boxes (AuditTape, AccumTape) centered horizontally within the FORM.
21-29 Javascript to scroll down both text boxes (AuditTape, AccumTape) simultaneously keeping current activity visible.
33 Declares a one-row, one-column table to contain the display and keypad components centered horizontally within the FORM.  A DarkSeaGreen background is applied to the this table.
37 Declare a green border with a lightsteelblue background for keypad components (display, error message, keypad).
39 Display title (e.g. 12 Digit Display) on the calculator keypad.
42 Numeric entry text box on the calculator keypad.
45 Error message area to display errors in red.
48-71 The buttons representing the calculator keypad.  When any keypad button is pressed, the FORM contents are POSTed to the web server for processing.
   
   

 


Application Processing Logic

<!-- directives -->
<%@ Page Language="VB" Explicit="True"%>

<!-- code section executed after server script -->
<%
'
'********************************************************
' My first web calculator
'
' Author     : Elario Belmontes, Jr.
' Description: Four function calculator simulator for
'              educational purposes to illustrate the 
'              use of a web page on a personal web
'              server
' Languanges : VBSCRIPT, JAVASCRIPT, JQUERY, HTML, CSS
' File Name  : calc_42.aspx
' Disclaimer: This software is intended for educational learning
'             purposes.
'
'             This software is provided "AS IS" and without any
'             expressed or implied warranties, including, without
'             limitation, the implied warranties of merchantability
'             and fitness for a particular purpose.
'
'             No guarantee; No warranty; Install / Use at your own risk.
'
'
' Copyright (C) 2015 Larry Belmontes, Jr. 
'
'
'
'********************************************************
'
'
'********************************************************
' Get my script file name
'********************************************************
'
myScriptName = Request.ServerVariables("SCRIPT_NAME")
If Instr(myScriptName, "/") > 0 Then 
  myScriptName = Right(myScriptName, Len(myScriptName) - instrRev(myScriptName, "/")) 
End If 
'
ErrMsg = "&nbsp;"
MaxInput = 12
'
'********************************************************
' Process FORM post (i.e. calculator button pressed)
'********************************************************
'
If UCase(Request.ServerVariables("REQUEST_METHOD")) = "POST" Then
    '
    '********************************************************
    ' Obtain data from FORM controls 
    '   and initialize variables
    '********************************************************
    '
    myTitle = "myWeb Calculator"
    frm_AuditTape = Trim(Request.Form("AuditTape"))
    frm_NumIn = Trim(Request.Form("NumIn"))
    frm_AccumTape = Trim(Request.Form("AccumTape"))
    '
    '********************************************************
    ' Button on FORM pressed -
    '   Process number, function or housekeep button on form
    '
    '   Loop through each FORM field and take appropriate
    '     action from POST data
    '       (i.e.  AuditTape=&AccumTape=&NumIn=&B8=8)
    '********************************************************
    '
    'Response.Write (Request.Form & "<br/>")
    '
    For each frm_Control in Request.Form
        Select Case frm_Control
            '
            '********************************************************
            ' Math functions: add, subtract, multiply, divide
            '********************************************************
            Case "Fplus", "Fminus", "Fmult", "Fdiv"
                Call Do_Math
            '
            '********************************************************
            ' Terminate Math function: equals
            '********************************************************
            Case "Fequal"
                Call Finalize_Math
            '
            '********************************************************
            ' Housekeep: Clear all
            '********************************************************
            Case "Fclear"
                Call Clear_key
            '
            '********************************************************
            ' Housekeep: Power Off
            '********************************************************
            Case "Poff"
                Call Power_Off_key
                Response.End
            '
            '********************************************************
            ' Housekeep: Power On
            '********************************************************
            Case "Pon"
                Call Power_On_key
            '
            '********************************************************
            ' Housekeep: Clear entry
            '********************************************************
            Case "Fcleare"
                Call Clear_Entry_key
            '
            '********************************************************
            ' Numeric entry
            ' Limit to 16 digits entry excluding decimal point
            '********************************************************
            Case "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9"
                Call Numeric_key
            '
            '********************************************************
            ' Decimal point entry
            '********************************************************
            Case "Bdot"
                Call Decimal_key
        End Select				
    Next
Else
    '
    '********************************************************
    ' NOT a POST, initialize session variables 
    '  Assume first time invoked
    '********************************************************
    Session("NumberIn") = ""
    Session("NumberInFunction") = ""
    myTitle = "Welcome to myCalculator and happy calculating!"
    frm_AuditTape = ""
    frm_NumIn = ""
    frm_AccumTape = ""

End If
%>

<!-- code section executed first -->
<script runat="server" language="vb">
'
'********************************************************
' Declare variables
'********************************************************
Dim myScriptName As String
Dim myTitle As String
Dim frm_AuditTape As String
Dim frm_NumIn As String
Dim frm_Control As String
Dim frm_AccumTape As String
Dim ErrMsg As String, MaxInput As Integer
'
'
'
'********************************************************
' Subroutines Section
'********************************************************



'
'********************************************************
' Subroutine: Do_Math
' Math functions: add, subtract, multiply, divide
'********************************************************
Sub Do_Math
    '
    If frm_NumIn > "" Then
        frm_AccumTape = frm_AccumTape & Session("NumberIn") & Session("NumberInFunction")
        Call ComputeIT
        frm_AuditTape = frm_AuditTape & frm_NumIN & " " & Request.Form(frm_Control) & " " & vbCrLf
        frm_AccumTape = frm_AccumTape & frm_NumIn & "=" & Session("NumberIn") & " " & vbCrLf
        Session("NumberInFunction") = Request.Form(frm_Control)
        frm_NumIn = ""
    Else
        ErrMsg = "No data entered..."
    End If

End Sub

 

The code snippet does not include all subroutines.  Although in the same ASPX file, subroutines are in a different SCRIPT declaration that runs on the server.

The execution order for this ASPX file is as follows:

  • Resolve and apply directives (line 2)
  • Execute all <SCRIPT RUNAT=SERVER> content (line 145)
  • Execute all <% … %> script elements for the page (line 5)

On initial calculator submission, the client PC web browser sends a calc_42.aspx URL request to the web server (IIS) via HTTP.  The calc_42.aspx code starts execution on IIS at line 1 with the declarative.

Next, <SCRIPT RUNAT=SERVER..> tags are executed which includes declaration of variables and subroutines.  

Lastly, <% … %> element tags are executed starting from the top of the page to the bottom which will include the HTML page content rendered to the browser.

Starting with the setting of variable myScriptname (lines 39-41), and followed by first time action logic (lines 134-139).  An HTML response is constructed from code between the <HTML> and </HTML> tags that includes STYLE, JavaScript and FORM code.  The HTML response is sent via HTTP to the client PC and rendered by the web browser as an initial calculator page.

On subsequent calculation submission, the client PC web browser posts a calc_42.aspx request to the web server (IIS) via HTTP when a calculator key is pressed (keypad 8 key, clear key, addition key, etc).  The calc_42.aspx code starts executions on IIS at line 1 followed by declaration of variables (lines 150-156), setting variables (lines 39-45), and POST action logic (lines 51-128) processing the appropriate button via the associated subroutine (e.g. Call Numeric_key when key 0-9 is clicked) including the updating of FORM fields.  An HTML response is constructed from code between the <HTML> and </HTML> tags that includes STYLE, JavaScript and FORM code.  The HTML response is sent via HTTP to the client PC and rendered by the web browser as an updated calculator page.  Below is a description of VBScript logic for the above snippet.

Line Description
150-156 Declare variables.
44 Set error message (ErrMsg) to blanks
45 Set maximum number of digits (MaxInput) to 12
74-127 Logic to execute when post method = POST (keypad button has been pressed)
Line Description
58 Set myTitle to “myWeb Calculator”
59-61 Fetch form variables from textboxes (AuditTape, AccumTape) and current display value (NumIn)
74
Loop
Loop through each form variable testing for buttons
80-81 When buttons –  or  are detected, call subroutine Do_Math to process math function of add, subtract, multiply or divide updating result windows
86-87   When button  =  is detected, call subroutine Finalize_Math to complete current math operation updating result windows
92-93   When button  C  is detected, call subroutine Clear_key to clear result windows and calculator display
105-106   When button  on  is detected, call subroutine Power_On_key to clear web page and present hyperlink to power on calculator
98-99   When button  off  power is detected, call subroutine Power_Off_key to post error message “Power already ON…”
111-112   When button  CE   is detected, call subroutine Clear_Entry_key to clear numeric entry display
108-109   When buttons  0 1 2 3 4 5 6 7 8 or 9   are detected, call subroutine Numeric_key to enter digit into numeric entry display
124-125   When button  .  is detected, call subroutine Decimal_key to enter decimal into numeric entry display
End Loop  
129-141 Logic to execute when post method does not = POST (first time action)
Line Description
134-135 Declare session variables to store data between calculator interactions
136 Set myTitle to “Welcome to myCalculator and happy calculating!”
137-139 Reinitialize form fields
   

 


Download and Installing ASPX VBScript Web Calculator

This application was successfully installed and tested on:

  • Windows Home Server (part of MS Server 2003), IIS 6, IE10, Chrome v41

 

1. The web server, IIS (Information Internet Services), must be installed with support of ASPX (Active Server Pages Extended) on your desktop or laptop computer before attempting to run this web application.

2. Download the ZIP file and extract to a temporary directory.

Download calc_42_aspx

3. Open the ZIP file and copy the file, calc_42.aspx,  to the IIS webroot directory.
Typically, the default directory name is c:\Inetpub\wwwroot\

4. Open a brower window (e.g. Internet Explorer or Chrome)

5. Type http://localhost/calc_42.aspx in the address bar and press ENTER.

6. The calculator web page should display.

7. On the calculator keyboard –
Click 3.  Click +.  Click 7.  Click /.  Click 2.   Click =.  The result should be 5.

8. Happy calculating!!

 


Next Learning Experience

Extend the calculator exercise into Python client-server application.  Python is another prevalent web application language used for personal, small business and corporate business web applications.

Also, developing the calculator logic in Python illustrates the use of similar function when compared to ASPX, PHP and ASP.

Take a look at related posts below!

 

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image

This site uses Akismet to reduce spam. Learn how your comment data is processed.