Functions and Procedures


In Chapter 2, we saw that when you double-click a button in Web Matrix, you get a new event handler, and that this handler contains a block of code that only runs when a user clicks the button. It's often useful to create a block of code that is self-contained, and that isn't associated with a particular control. You can then run it whenever you want.

In Visual Basic .NET, a self-contained block of code that has a name and that you can call from other parts of your program, is called a method. There are two types of method in Visual Basic .NET:

  • Functions – A method that does something, and then returns a result to the code that called the function.

    Calling a function is like asking a question where you expect an answer or response. For example, if my boss said to me "Hey Colt, put the minutes for the last five meetings in this folder and give it back to me." I would need to go out, put all the minutes together properly, and then return the folder to my boss.

  • Procedures – A method that does something, but doesn't return any result.

Calling a procedure is just like telling somebody to do something. For example, if my boss asks me to open a window, I simply open the window.

Both functions and procedures consist of any number of lines of code (called a code block, which is a term we have used before). This block is framed by a signature on the first line, which specifies the method's name and any values or parameters it expects to be handed, and the code inside will execute until reaching a line with the words of End Sub (for procedure) or End Function (for function). When the execution of this code block is complete, the code after the block will continue to execute as before.

Important

A procedure just carries out a set of instructions, while a function will carry out some instructions, then return something to the caller when it's finished.

For example, if you deposited an amount of money into a time deposit account, you would probably get the total balance (principal plus interest) at maturity. The calculation of such a total balance based on the interest rate would be:

 Function FindTotalBalance(Principal As Double, InterestRate As Double) _  As Double   FindTotalBalance = Principal + (Principal * InterestRate) End Function 

So let's take a look at a function that's a bit more fun than a financial calculator (unless you're an accountant and like these kinds of functions!)

Try It Out—Using Functions

Functions and procedures are very useful when there's something that you'll want to do over and over again, and in lots of different circumstances. One thing that you may want to do in your ASP.NET web pages is send e-mail messages. In this example, we'll do exactly that, and we'll end up with a function that you can use in any page where you want to send an e-mail, and return confirmation that the message was sent successfully.

Note

This example requires the use of an SMTP server, which stands for Simple Mail Transfer Protocol. This is used by your ISP or network to send e-mail from the client on your machine to your selected recipient. To run this example, you need to know the name of the server you use to send your e-mail, which you can find out by asking your network administrator or by asking your internet service provider nicely! If you don't have access to such a sever, then unfortunately, you won't be able to try out the example here.

  1. Create a new ASP.NET Page in Web Matrix and call it Function.aspx.

  2. First, we need to create our user interface. Start by entering Your email address:, and Your message: prompts onto two separate lines. Place a TextBox control next to each of the two prompts, and then add a Button and a Label, both on separate lines. Your page should now look like this:

    click to expand

  3. Change the Button's Text property to Send.

  4. The Your message: box is not wide enough or long enough to send a very interesting message. (On the bright side, it's not long enough to send a very boring one either!) We can fix this using the TextMode property that we saw in the previous chapter. Select the message TextBox and go to the Properties window. Now scroll down until you find the TextMode property, and choose MultiLine:

    Another problem is that the visitor will see some text at the bottom of the page that just says Label. We can change that by erasing the Text property of the Label.

  5. Now we can get down to writing some code. Double-click the Send button to add a Button1_Click event handler. Then, add the following code:

    Sub Button1_Click(sender As Object, e As EventArgs)  ' Call the SendMail function, and set Label1.Text to the   ' recipient's e-mail address  Label1.Text = SendMail("Feedback form", TextBox1.Text, TextBox2.Text) End Sub

    This line calls the SendMail() function. Label1.Text will be set to the value that the SendMail function returns when it is finished. We haven't written a SendMail() function yet, so if we run the page now the call won't work. Let's add the function now.

  6. First of all, we need to declare the function. This is a way of saying that the function exists, and of describing a few things about it. This is very simple, so we just need to add the following to the existing code:

     Function SendMail(Subject As String, FromAddress As String, _  Message As String) As String End Function 

    This tells ASP.NET that we are creating a function called SendMail() and that it has three argumentsSubject, FromAddress, and Message. In this case, every argument is a String, which basically means 'text'. Finally, with the final two words (As String), we tell ASP.NET that this function returns a String back to the code that called it.

  7. Now we need to add the code that actually sends our e-mail. Web Matrix will write most of this for us. You just need to pick the Send Email code builder from the Code Builders tab in the ToolBox and drag it to the blank line between Function SendMail ... and End Function.

  8. When you drop the code builder onto the code page, you should see the following dialog:

    click to expand

  9. Put your own e-mail address in the To box, and the name or IP address of your SMTP server in the SMTP Server box. The SMTP server is the computer used to distribute mail that your computer sends. If you are not sure what yours is called, you can usually find out by looking at the account properties in your usual e-mail program (for example, Outlook Express). If you are part of a network, your administrator should be able to tell you. Chances are it will be something like smtp.yourisp.com. Don't worry about the other settings for now.

  10. Click the OK button for this dialog box and the code is generated automatically. It looks like this:

    Function SendMail(Subject As String, FromAddress As String, _   Message As String) As String ' Build a MailMessage Dim mailMessage As System.Web.Mail.MailMessage = _  New System.Web.Mail.MailMessage mailMessage.From = "someone@example.com" mailMessage.To = "someone@example.com" mailMessage.Subject = "Email Subject" mailMessage.BodyFormat = System.Web.Mail.MailFormat.Text ' TODO: Set the mailMessage.Body property System.Web.Mail.SmtpMail.SmtpServer = "localhost" System.Web.Mail.SmtpMail.Send(mailMessage) End Function 

    Notice that we've kept the sample From, To, Subject, and SmtpServer properties set to the defaults for this example, but if you entered different details in the dialog box, then these values will be changed as appropriate in your generated code. You don't need to understand what all of the auto-generated code actually does, but as you work through this book, you'll start to work out what's actually going on here.

  11. We just need to make a few changes so that this code works with our page as we want it to. Go ahead and make the highlighted changes to the code in the function:

    ' Build a MailMessage Dim mailMessage As System.Web.Mail.MailMessage = _   New System.Web.Mail.MailMessage mailMessage.From = "someone@example.com" mailMessage.To = "someone@example.com" mailMessage.Subject = "Sending an e-mail from a web page" mailMessage.BodyFormat = System.Web.Mail.MailFormat.Text ' TODO: Set the mailMessage.Body property mailMessage.Body = Message System.Web.Mail.SmtpMail.SmtpServer = "localhost" System.Web.Mail.SmtpMail.Send(mailMessage)
  12. A function needs to give something back to the line of code that called it. This function returns some text, and our program is going to use that text to set the value of Label1.Text. Add the following line to the end of the function, just before the End Function line:

     SendMail = "Your message was sent to " & mailMessage.To End Function
  13. We're done! Run the page by pressing F5 or clicking the start button, and try sending a message to yourself. After you click Send, it should look something like this:

    Remember, you'll need to be online for this to work – ASP.NET needs to be able to connect to the SMTP server there and then, and both the web server and SMTP Virtual Server must running. This is because ASP.NET is hosting using a web server, in which the e-mail will be send via the SMTP server provided by your ISP, using the service provided by the SMTP Virtual Server in your computer – phew! OK, you can now just sit back and wait for the message to arrive!

How It Works

When you click the Send button, ASP.NET automatically knows to call the code in the Button1_Click event handler. This only contains one line of code:

Sub Button1_Click(sender As Object, e As EventArgs)   ' Call the SendMail function, and set Label1.Text to the   ' recipient's e-mail address   Label1.Text = SendMail("Feedback form", TextBox1.Text, TextBox2.Text) End Sub

This is the function call. It tells ASP.NET to call the SendMail() function. If you look at the function declaration you'll see that the items between the brackets match up, for example, "Feedback form" is the Subject, TextBox1.Text contains the FromAddress, and TextBox2.Text contains the Message:

  Label1.Text = SendMail("Feedback form", TextBox1.Text, TextBox2.Text)

Important

This is very important for functions and procedures – the arguments in the call need to match the arguments in the declaration.

Also, notice that we have As String at the end of each argument for the SendMail() function:

Function SendMail(Subject As String, FromAddress As String, _   Message As String) As String

This means that the information that you send to the arguments in this function needs to be of data type String – a programming term for 'text'. We'll find out more about strings and other types of data in the next chapter. Other functions will require different types of information – not every function we write will require strings!

The final important thing is that the whole function has another As String at the end. This one means that the whole function returns a String – so it's a good thing that Label1.Text is a string! When the function is called, all of the code in it runs. Most of the code was written for us, and we don't need to fully understand how it works, although it seems quite readable. We've set some properties that describe whom the mail message will be sent to, what the subject of our message is, and so on. We also know that it works, which is the important thing! Let's focus on the very last line:

SendMail = "Your message was sent to " & mailMessage.To

This is where we set the value of the SendMail() function itself. Since a function will return a result to another part of the program in its function name, we have to ensure that the left of the equals sign has the same name as the function name. What's to the right of the equals here gets returned by the SendMail() function, which then gets passed back to Label1.Text. Label1.Text ends up being set to "Your message was sent to" and then the e-mail address of the recipient.

You can now copy and paste this whole function into other pages, and call it from wherever you want on the page.

What About Procedures?

We've seen how to add functions, but we've not looked at how to add procedures. Don't worry though, procedures are even easier than functions – in fact you've already written some without even knowing it:

Sub Button1_Click(sender As Object, e As EventArgs)   ' Call the SendMail function, and set Label1.Text to the   ' recipient's e-mail address   Label1.Text = SendMail("Feedback form", TextBox1.Text, TextBox2.Text) End Sub

This is a procedure called Button1_Click (which is actually an event-handler procedure – we'll look at event handlers in just a moment). All procedures start with Sub, and end with End Sub. (Sub is short for subroutine, another word for a procedure.)

Like functions, procedures may have arguments. In the above example, we have an argument called sender and an argument called e – don't worry about what they mean, they are all system-generated arguments (which we'll look at in a moment), and the point is that they behave in exactly the same way as arguments in a function.

The other big differences are:

  • Procedures have no As Something after the arguments, because they do not
    return anything

  • Procedures do not have a final line where you set the procedure itself to a particular value, again, because there is no return value

This procedure is called automatically when you click Button1. You can also call a procedure any time you like just by adding a line of code with its name and some valid arguments.

For example, we could create a Reset() procedire that resets a form to its initial state (resetting values in controls), both when a page is first loaded, and if a button is clicked to reset the values manually. For example, if you had two textbox controls on a page, one to enter a name on a form, one to enter an age, and two buttons to either update a database, or to reset the form:

You can add code to the following sub to reset the form:

 Sub Reset()  Textbox1.Text = ""  Textbox2.Text = "0" End Sub 

Then you can call this sub from a couple of places. Firstly in the Page_Load event, and secondly, when the Reset button is clicked:

 Sub Page_Load(sender As Object, e As EventArgs)  If Not Page.IsPostback  Reset()  End If End Sub ... Sub btnReset_Click(sender As Object, e As EventArgs)  Reset() End Sub 

You can see this code in action in a file in the code download for this chapter, called Age.aspx, which also demonstrates some fun logic:

Since no-one knows how old Dave is, we've taken a guess!

Why Bother with Functions and Procedures?

Why not just type all the code into a single method, instead of breaking it into different functions and procedures? Well, using functions and procedures is probably the single best way to make your code easier to read and write. They enable you to take a fairly complicated set of instructions, and group them together under one name.

Functions and procedures allow you to take a complex task and break it down into a series of sub-tasks. Each procedure or function performs a specific distinct function or job. This provides code that is easier to maintain because specific functions can be rewritten without affecting the rest of the code, as long as they have the same inputs and outputs as the original function or procedure. The code that calls the function or procedure does not need to change.

Using functions and procedures also makes a long, complicated task easier to read by calling various functions to perform the detailed work. Additionally, functions are reusable because they should perform one specific task that may be needed by other functions and code. Sending an e-mail is a function that is used in many different programs, for instance. This function can be used over and over again.

If you name your functions and procedures carefully, people can read the name and gain an understanding of what the function or procedure is designed to do. They don't need to look at the code itself and try to figure it out.

This also makes code easier to write, because you can start thinking about things without too much detail, and just have a series of method names – then you can start to implement each method as you add more detail to your program. This process is known as step-wise refinement. It's a great, easy way to write code, as we'll see later in the book.

The other important thing is that you can write a function or procedure once, and then reuse it over and over again. Later in the book, we'll see how to create special libraries of useful functions and procedures that you can use in any page you like. You can even share your library with other programmers, to save them the time of writing those methods themselves.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

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