More Advanced ASP.NET 3.5 Functions and Subroutines

If you read the first part of this two-part series, you know that functions and subroutines can help make coding programs with ASP.NET 3.5 simpler in certain ways. In this article, you will be presented with a slightly more complex web application that uses functions and subroutines in ASP.NET.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 8
March 18, 2010
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

In the first part, we used the subroutines and functions independently in each of the short examples presented. In this tutorial you will learn how to integrate the two together in a single web application.

If you still have not read the first part, I suggest that you read it now, as it contains very important details and theory regarding subroutines and functions.

Project Case Study: Stock Investment Planner

One of the most important investment decisions, especially for someone investing in the stock market, is to have a stock investment planner. In ASP.NET 3.5, you can build a web application that will plan the investment and estimate the following:

1. The percentage (compounded annually) that the investment needs to earn annually in order to double its present worth in a required number of years.

2. The estimated future worth of the capital given the optimal percentage (determined in the first objective) and required number of years.

To get the above expected results from the planner, the web form needs to ask for the following three inputs:

1. The investor's first and last name for identification.

2. The capital that needs to be invested (present worth) in stocks.

3. The number of years within which the investor wants to double his present worth (original investment).

A web form needs to be created using Visual Web Developer Express that should look exactly like the screen shot below:

Create the Web Form

To create a web form like the one shown in the screen shot on the previous page, you need to follow the steps below:

1. Launch Visual Web Developer Express 2008.

2. In the dashboard, click “Create” -> “Website”

3. Under Visual Studio's Installed templates, select “ASP.NET Web Site.”

4. Under “Location,” choose “File System” and select the path where you need to save your project in your Windows hard drive, for example E:aspprojectsfinancialplanner

5. Under Language, select “Visual Basic.”

6. Click OK.

Visual Web Developer Express automatically creates three important files: Default.aspx, Default.aspx.vb and web.config. In the “Source” view of Default.aspx, delete all of the source code and replace it with the code below:

 

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

<style type="text/css">

.style1

{

font-family: Verdana;

}

</style>

</head>

<body>

<h3 class="style1">Stock Investment Planner</h3>

<br class="style1" />

<span class="style1">Note: This tool can approximate what %annual return (compounded annually) you need to double your capital invested in stocks.

</span>

<br class="style1" />

<span class="style1">It also shows the estimated future worth of the capital assuming your stock portfolio performs at that estimated % annual return.</span>

<form id="form1" runat="server">

<div style="margin-top: 37px; font-family: Verdana;">

Enter your first name and last name in the box:

<asp:TextBox ID="name" runat="server"></asp:TextBox>

<br /><br />

Enter the capital you need to invest in stocks(in dollars):

<asp:TextBox ID="capital" runat="server"></asp:TextBox>

<br /><br />

Enter the number of years you wish to double your capital:

<asp:TextBox ID="yearsinvested" runat="server"></asp:TextBox>

<br /><br />

<asp:Button ID="planmystocks" runat="server"

Text="Give me financial projections now!"

style="font-family: Verdana; font-size: medium" />

</div>

</form>

<br /><br />

<asp:Label ID="displayresults" runat="server" Text=""

style="font-family: Verdana; color: #0000FF"></asp:Label>

<br />

<asp:Label ID="displaypercentage" runat="server" Text=""

style="font-family: Verdana; color: #0000FF"></asp:Label>

<br />

<asp:Label ID="displayfutureworth" runat="server" Text=""

style="font-family: Verdana; color: #0000FF"></asp:Label>

</body>

</html>

 

After pasting in the code above, click the “Save all” button. The most important thing in the above source code is the ID used with each of the text boxes. This is because these IDs will be used to identify the variables in the Visual Basic server side script, which will be discussed later in this tutorial. If you are not familiar with ASP.NET web forms, it is recommended that you read this tutorial

Create Click Event Handlers

Now that you have created the form, it is time to start creating the server side script to process those form inputs and output the desired results (e.g. financial projections).

You need to create a click event handler, so that when the user clicks the submit button that says “Give me financial projections now!” ASP.NET will execute the script associated with that click event -- which will compute those financial projections and return the results back to the browser.

To create a click event, go to the Design view in Visual Web Developer Express and then double click the “Give me financial projections now!” button. See screen shot below:

After double clicking the button, Visual Web Developer Express will then show the Visual Basic file editor (Default.aspx.vb). This is where you will place your Visual Basic scripts and the definitions of your functions and subroutines.

Create Subroutine to display name

Based on the information in the previous, introductory article about subroutine and functions, you can let:

Showmyname = the subroutine name to display name

username = the function variable to hold the user name

With this; the complete subroutine is as follows:

 

Sub Showmyname(ByVal username As String)

displayresults.Text = "Hey " & username & ", your financial projections according to your inputted values are as follows:"

End Sub

 

The ID displayresults will display the name back to the web browser.

Create Function to Compute the Percentage Required for Doubling Capital

The good thing about the use of subroutines and functions in the server side Visual Basic script is that they modularize applications, which makes them easy to develop, troubleshoot and understand. To create the function to compute the percentage, you will use the rule of 72.

 

Function ComputePercentage(ByVal years As Decimal) As Decimal

Dim Annualpercentage As Decimal

Annualpercentage = (72) / (years)

Return Annualpercentage

End Function

 

Create Function to Compute Future Worth

To compute the future worth of the investment using compounding interest, you will use the formula discussed here: http://en.wikipedia.org/wiki/Future_value , which is:

 

F= P(1+i)^n

 

In Visual Basic, it can be written as:

 

Function Computefutureworth(ByVal years As Decimal, ByVal Annualpercentage As Decimal, ByVal Presentworth As Decimal) As Decimal

Dim Futureworth As Decimal

Dim Convertedtodecimal As Decimal

'Implementing the formula for Future worth of the capital compounded annually.

Convertedtodecimal = Annualpercentage / 100

Futureworth = Presentworth * ((1 + Convertedtodecimal) ^ years)

Return Futureworth

End Function

 

In the above function, you have used three important parameters as input, which are:

1. Years

2. Annualpercentage

3. Presentworth (or the original capital invested)

The two parameters (years and presentworth) are inputted by the user via the web form. The annualpercentage is computed from the function earlier. One tricky thing is that annualpercentage is not in decimal form after computation, so it is converted to percentage using the following formula:

Convertedtodecimal = Annualpercentage / 100

Call the functions and subroutines in the main script

As discussed in the first tutorial on functions and subroutines, they are virtually useless unless called to action. The following will call the functions and subroutines formulated earlier in this article:

 

Protected Sub planmystocks_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles planmystocks.Click

Dim years As Decimal = yearsinvested.Text

Dim Presentworth As Decimal = capital.Text

Dim inputname As String = name.Text

Dim Annualpercentage As Decimal = ComputePercentage(years)

Showmyname(inputname)

displaypercentage.Text = "The percentage (compounded annually) that your stock needs to earn in order to double your present worth is: " & Fix(ComputePercentage(years)) & "%"

displayfutureworth.Text = "The future worth compounded annually at the percentage mentioned above is:" & "$" & Fix(Computefutureworth(years, Annualpercentage, Presentworth))

End Sub

 

First the values from the web form are assigned to a Visual Basic variable, which is then used by the functions and subroutines. The fix function is used to truncate decimal values and give a user-friendly result to the user.

So where will all these functions, subroutines and main scripts be placed in the overall Default.aspx.vb script? When the click event handler is activated and you are presented with the Visual Basic editor for Default.aspx.vb, below is the script structure for all functions, subroutines and calling script:

Complete Default.aspx.vb script

Below is the working script for Default.aspx.vb:

 

Partial Class _Default

Inherits System.Web.UI.Page

'Use Subroutine to display the name

Sub Showmyname(ByVal username As String)

displayresults.Text = "Hey " & username & ", your financial projections according to your inputted values are as follows:"

End Sub

'Use Function to compute the %annual interest needed to double the capital invested in stocks

Function ComputePercentage(ByVal years As Decimal) As Decimal

Dim Annualpercentage As Decimal

'Implementing Rule of 72 to compute the percentage it takes to double the capital present worth.

Annualpercentage = (72) / (years)

Return Annualpercentage

End Function

'Use Function to compute the estimated future worth of the invested capital in stocks using the annual percentage

Function Computefutureworth(ByVal years As Decimal, ByVal Annualpercentage As Decimal, ByVal Presentworth As Decimal) As Decimal

Dim Futureworth As Decimal

Dim Convertedtodecimal As Decimal

'Implementing the formula for Future worth of the capital compounded annually.

Convertedtodecimal = Annualpercentage / 100

Futureworth = Presentworth * ((1 + Convertedtodecimal) ^ years)

Return Futureworth

End Function

Protected Sub planmystocks_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles planmystocks.Click

'Create variables to get values entered by the user from the webform

Dim years As Decimal = yearsinvested.Text

Dim Presentworth As Decimal = capital.Text

Dim inputname As String = name.Text

Dim Annualpercentage As Decimal = ComputePercentage(years)

Showmyname(inputname)

displaypercentage.Text = "The percentage (compounded annually) that your stock needs to earn in order to double your present worth is: " & Fix(ComputePercentage(years)) & "%"

displayfutureworth.Text = "The future worth compounded annually at the percentage mentioned above is:" & "$" & Fix(Computefutureworth(years, Annualpercentage, Presentworth))

End Sub

End Class

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 11 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials