Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ASP.NET 2

.0.pdf
Скачиваний:
23
Добавлен:
17.08.2013
Размер:
24.67 Mб
Скачать

Code

Full would be 0, Short would be 1, and so on. The Short value has been enclosed within square brackets because Short is also a data type; using the square brackets tells .NET that this is the custom name rather than the data type. If you don’t want to use the default numbers for the values, you can specify them yourself. For example:

Public Enum DeliveryType

Post

Courier = 4

International

End Enum

Here the Post would be 0 and the Courier has an explicit value of 4. International doesn’t have an explicit value so automatic numbering starts again, at the last number used, so would therefore have a value of 5.

Enumerations are used when you need to allow one of a limited number of values for a selection. It’s used extensively in the ASP.NET server controls to allow only selected values, often allowing the behavior to change; the TextBox, for example, has a TextMode property that can be one of SingleLine, MultiLine, or Password. How the TextBox is displayed changes depending on which value is selected. When creating code yourself, for the day-to-day running of an application, there is perhaps less use for them (the Wrox United site doesn’t use any Enums), but they can be useful, perhaps when building central libraries of code.

Constants

Constants are another way to provide a human-readable form for values, but unlike enumerations, constants are a single value only and as their name suggests, they are constant and never change. This is useful for situations where you need to use a fixed value; using a constant means you can give that value a name and use the name throughout the code. The value is defined once, meaning it is easy to change, and because the readable name is used throughout the code, the code becomes more maintainable.

Even if the value is used only once, it’s sensible to use constants because they provide a way to centralize this type of fixed value. The syntax for a constant is as follows:

Private Const ConstantName As Type = Value

Const is what defines this as a constant, and Private is how visible the constant is — you’ll be looking at this later in the chapter. The rest of the declaration is just like any other variable, the difference being that the value is constant, and therefore cannot be changed.

For example, in the Wrox United web site there is a shopping cart to store items bought from the shop. Members of the fan club receive a 10% discount, so this value is stored as a constant:

Private Const MemberDiscountPercentage As Single = 0.1

When the total price of the order is calculated this constant can be used, just like any other variable:

MemberDiscount = SubTotal * MemberDiscountPercentage

Total = SubTotal – MemberDiscount

You’ll look at the implementation of the shopping cart later in the chapter.

309

Chapter 9

Statements

Statements are where the real action of code is, allowing you to control the program. You have seen many statements in code already in the book, and at the time it wasn’t convenient to explain what they meant or how they worked. Now is that time, because statements are what drive your code. Statements are what allow you to structure your code, to make decisions, to repeat actions a number of times. For example, to make a decision you use the If Then statement, which can be used to allow the code to react to external criteria. Take the Wrox United checkout page, where members of the fan club receive a discount. This is done with a decision, which goes something like this:

If person is a member of the fan club Then give that person a discount

End If

The If, Then and End If are the Visual Basic statements that test a condition — or ask a question. Think of the program as a person deciding what to do.

For repeating tasks there are statements called loops, and there are different types of loops for different tasks. Some (For Next) repeat a fixed number of times, whereas others (While) repeat until a condition is met, or while a condition is true.

Before conditions and loops can be examined in more detail, some other topics need to be covered.

Operators

The first thing to look at is operators, which are how values are manipulated. If you can remember back to your math lessons in school, this will be familiar. You’ve already seen the assignment operator, the equals sign (=), in action earlier in the chapter, and this simply assigns a value to a variable. The next several sections discuss how remaining operators allow you to carry out some predefined operation.

Concatenation

Concatenation is used to join strings together. For example, consider if you had the first and last names in a multi-dimensional array (as shown when you looked at arrays), and you wanted to have a single variable with the full name. You would use the concatenation operator, the ampersand (&), to do this:

Dim FullName As String

FullName = Names(0,0) & Names(0,1)

This takes the last name and joins it to the end of the first name. However, there is no space separating them, so the code could be

FullName = Names(0,0) & “ “ & Names(0,1)

Now you have two concatenations taking place. First a space is added and then the last name. You could have also used another form of the assignment operator:

FullName = Names(0,0)

FullName &= “ “

FullName &= Names(0,1)

310

Code

The use of &= simply says take the variable on the left of the assignment and append to it the contents on the right. This also works with arithmetic operators, which are the subject of the next section. The addition operator (+) can also be used for string concatenation.

Arithmetic Operators

Arithmetic operators allow you to perform, well, arithmetic on variables: addition, subtraction, and so on. The following table displays the arithmetic operators:

Operator

Action

 

 

+

Addition

-

Subtraction

*

Multiplication

/

Division

^

Exponentiation

Mod

Modulus

\

Integer division

 

 

The standard mathematical operators are easy to understand; they add, subtract, multiply, and divide in the way you’d expect:

Dim n1 As Integer = 6

Dim n2 As Single = 14.3

Dim n3 As Double

n3

= n1

+ n2

‘ results in: 20.3

n3

= n2

– n1

‘ results in: 8.3

n3

=

n1

/

n2

‘ results

in:

0.41958

n2

=

n1

*

n2

‘ results

in:

85.8

Exponentiation raises one number to the power of another:

Dim n1 As Integer = 10

Dim n2 As Integer

n2

=

n1

^

2

results

in:

100

n2

=

n1

^

3

results

in:

1000

Modulus divides two numbers and returns the remainder. One of the classic uses for this has been to test whether a number is odd or even:

Dim n1 As Integer

n1

= 1

Mod 2

‘ results in: 1

n1

= 2

Mod

2

‘ results in: 0

n1

=

3

Mod

2

‘ results

in:

1

n1

=

14 Mod 2

‘ results

in:

0

311

Chapter 9

So if a number Mod 2 is 0, then it’s even.

Integer division allows you to obtain the integer portion of a division — the number of times a divisor goes into a number:

Dim n1

As

Integer

 

 

 

n1

= 1

\ 2

 

‘ results in: 0

n1

= 2

\ 2

 

‘ results in: 1

n1

=

3

\ 2

 

‘ results

in:

1

n1

=

14 \

2

‘ results

in:

7

 

 

 

 

 

 

 

 

Like concatenation, operators can be combined with assignment. In order to add one to a number you can do this:

Dim n1 As Integer = 4

n1 = n1 + 1

This says take n1, add one to it, and assign that value back to n1. Remember that assignment works by taking the value on the right of the equals sign and assigning that to the variable of the left of the equals sign. This works even if the variable being assigned is on the right because the right side is calculated first. An alternative to this is to combine operators:

Dim n1 As Integer = 4

n1 += 1

This has the same result as the first example although it looks very different. In fact it’s just a shortcut that allows the addition operator to be combined with the assignment; it simply says take the n1 variable and add one to it. The other arithmetic operators can be used in the same way.

The subtraction operator is also used for negation, like so:

Dim n1 As Integer

Dim n2 As Integer

n1

=

-3

 

n2

=

-n1

‘ results in: 3

Negation can be used on any numeric type.

Comparison Operators

Comparison is how decisions are made in code; you’ll come onto the mechanism of that in due time, but the operators define what comparison is made. The comparison operators are shown in the following table:

Operator

Action

<

Less than

<=

Less than or equal to

312

Code

Operator

Action

 

 

>

Greater than

>=

Greater than or equal to

=

Equal to

<>

Not equal to

 

 

Comparison always involves an expression — the term for all operators and operands involved in the comparison. The result of a comparison expression is a Boolean value — it is either True or False. You’ll look at the mechanics of using expressions in decisions in a while, but these operators work just like the ones you’ve already seen. So if you have two variables, n1 with a value of 4 and n2 with a value of 5, the following could be used as expressions:

n1

>

n2

results

in:

False

n2

>

n1

results

in:

True

For numbers the comparison is obvious, but for other data types it might not be. Dates, for example, work in a similar way, but the test is whether one date is earlier or later than another. For example:

Dim d1

As

New DateTime(2005, 10, 1)

1

October

2005

Dim d2

As

New DateTime(2004. 1, 2)

2

January

2004

d1 > d2

 

 

‘ results in: True

 

 

 

 

 

 

 

The greater than operator tests to see if the first date is later than the second, so the result is True.

Two other comparison operators also are used with objects. The operator Is checks to see if two object references point at the same object. The IsNot operator does the opposite, checking to see if two object references point at different objects; they are the equivalent of equals (=) and not equals (<>) for objects. This is useful when dealing with objects, and many of the scenarios where this is used are covered in later chapters. However it’s worth showing an example here, and because databases have already been covered that can be the example. When using the data controls on pages you get a lot of functionality by just dropping a control onto a page and setting a few properties, but there are occasions where you need to explicitly deal with a database, and this becomes more true as you gain experience and write more complex applications. The checkout for Wrox United is one case, where the items from the shopping cart are written to the database. For this a SqlConnection object is used, which provides a way to connect to a specific database. For example:

Dim conn As New SqlConnection(“ . . .”) conn.Open()

‘ insert the checkout items

conn.Close()

This code fragment opens a database connection, inserts the checkout items, and then closes the connection. However, if there is an error when opening the connection, the conn variable wouldn’t contain an

313

Chapter 9

active connection, so the Close would fail. This is where the Is and IsNot tests are used, so the Close could be modified to

If conn IsNot Nothing Then conn.Close()

End If

If an error occurs, conn wouldn’t be assigned a value and would be Nothing, so conn is tested before being closed. If it is not Nothing (I’m sure the editors are having a fit about all these double negatives), the connection can be closed. You’ll see more about this topic in Chapter 15.

Logical Operators

Logical operators allow the combination of expressions. The operators are as follows:

Operator

Action

 

 

And

True if both sides of the expression are true

Or

True if one side of the expression is true

Xor

True if only one side of the expression is true

AndAlso

Short-circuited version of And

OrElse

Short-circuited version of Or

Not

Negates the expression

 

 

All except Not require two expressions, in the following form:

LeftExpression Operator RightExpression

The following table should make the result more obvious:

Operator

LeftExpression

RightExpression

Result

 

 

 

 

And

True

True

True

 

True

False

False

 

False

True

False

 

False

False

False

Or

True

True

True

 

True

False

True

 

False

True

True

 

False

False

False

 

 

 

 

314

Code

Operator

LeftExpression

RightExpression

Result

 

 

 

 

Xor

True

True

False

 

True

False

True

 

False

True

True

 

False

False

False

 

 

 

 

The AndAlso and OrElse operators have the same result as And and Or, but there is a subtle difference. With the normal versions, both expressions (left and right) are evaluated, but with the short-circuited operators this isn’t necessarily so. They will stop evaluating expressions if one of the expressions can guarantee a result. For example, consider the following code:

Dim Name As String = “Dave”

If Name = “Dave” Or Name = “Dan” Then ‘ name is either Dave or Dan

End If

In this case Name is checked to see if it is Dave and then checked to see if it is Dan. Now consider this:

If Name = “Dave” OrElse Name = “Dan” Then

Here Name is first checked to see if it is Dave. It is, so the second expression (the check for Dan) is never done — it’s not needed, because it won’t affect the result. In many cases it won’t matter which form (normal or short-circuited) you use, but there are times it does. For example, imagine instead of a simple test for a name you called a function that updated a database. When using the normal form the database would be updated, but the short-circuited version wouldn’t call the function and the database wouldn’t be updated. Using the standard And the code would be

If User.IsInRole(“Admin”) And UserAudit(“Admin”) Then

‘ user is an admin and their details have been updated End If

This would call the UserAudit function even if the current user weren’t in the Admin role because using And means that both parts of the test are done. To get around this the following could be used:

If User.IsInRole(“Admin”) AndAlso UserAudit(“Admin”) Then ‘ user is an admin and their details have been updated

End If

Now UserAudit is called only if the user is in the Admin role. Using AndAlso means that if the first part of the test fails, there is no point evaluating the second part, so it is never run.

Another time when the short-circuited form is useful is when you need to see if a property of an object has a value; you only want to check if the object actually exists, not if it is set to Nothing. For example, consider the following code, where data is fetched from a database and then some action needs to be performed only if some rows were returned:

315

Chapter 9

Dim rdr As SqlDataReader

rdr = DataLayer.GetProducts()

If rdr IsNot Nothing And rdr.HasRows Then

Assume that the database access fails for some reason, and rdr is set to a null value — that is, Nothing. With the normal form of And, both expressions are tested. First the check for Nothing is done, and this test returns False rdr is Nothing. Next the second test is done, to check the Boolean HasRows property, to see if any data was returned. But rdr is Nothing so this will generate an exception. To cure this problem you can use the short-circuited form of And:

If rdr IsNot Nothing AndAlso rdr.HasRows Then

Now there will be no exception. The first test is done, and because it is False the second test isn’t done. There’s no need because the first is False and the entire expression can never be True.

Operator Precedence

Operators aren’t limited to just one or two expressions, and can be combined in a multitude of ways. Before doing this however, you need to understand that there is an order of precedence, so the result you get might not be what you expected. Consider the simple expression:

1 + 2 * 3

This returns 7 because multiplication has a higher precedence than addition. You can use parentheses to force a change in order:

(1 + 2) * 3

This returns 9 because the expression in parentheses is evaluated first. It’s always a good idea to include parentheses in your expressions because it makes your intentions clear, and this is certainly a good thing when you (or someone else) comes to look at your code later.

If you don’t use parentheses the order of precedence is as follows, in descending order:

Exponentiation (^)

Unary negation (-)

Multiplication and division (*, /)

Integer division (\)

Modulus (Mod)

Addition and subtraction (+, -) and string concatenation (+)

String concatenation (&)

Arithmetic bitshift (<<, >>)

Comparison (=, <>, <, <=, >, <=, Like, Is, TypeOf...Is)

316

Code

Negation (Not)

Conjunction (And, AndAlso)

Disjunction (Or, OrElse, Xor)

This chapter hasn’t covered all of these operators because some of them you won’t use very often, or they are used in more advanced techniques. They have been included in the preceding list just so that you know where they fit into the order.

Decisions

Decisions are how you make code react to data, usually from a database or user input. You’ve already seen plenty of decisions throughout the book, and in this chapter logical operators covered how expressions play an important part of the decision-making process. Decisions can be made in two ways, and which way you use depends on the number of values an expression can be. For example, if an expression can return one of two values (True or False), the If statement is used. If the decision is a selection among a number of choices (perhaps the delivery method from the Wrox United shop), the Select statement is used.

Single Selections

Single selections are based around the If...Then statement, which always has three parts. The first is the expression being tested, which will result in a True or False value. The second is the block of code to be executed if the expression is True. Finally there is the End If, which ends the decision-making process. The syntax is as follows:

If condition Then

‘ code to run if condition is true

End If

This tests a single condition and only runs code if the condition is true. Alternatively there is

If condition Then

code to run if condition is true

Else

code to run if the condition is false End If

This tests a single condition but has code for both the true and false situations. For multiple tests you can use:

If condition Then

code to run if condition is true ElseIf condition1 Then

code to run if condition1 is true

Else

code to run if no conditions were true End If

There can be any number of ElseIf conditions.

317

Chapter 9

Consider Wrox United, where the club sends out a newsletter, but only to those fan club members who have checked the checkbox when they entered their details. The user settings are stored in the Profile object, which was shown in Chapter 5:

If Profile.Mailings = True Then

‘ send the newsletter to this person

End If

This is a simple case, where there is only one expression being tested, and one set of code to run.

If some code needs to be run when the expression is False, the Else statement can be used:

If Profile.Mailings = True Then

send the newsletter to this person

Else

don’t send the newsletter

End If

There is also a third statement, ElseIf, for choosing among several different expressions. For example:

If Profile.IsNewUser Then

‘ send introductory mail

ElseIf Profile.Mailings = True Then

send the newsletter to this person

Else

don’t send the newsletter

End If

In this example the expressions first checks to see if the member is a new user — that is, if they’ve only just joined and haven’t had any mailings yet. If so, the introductory mail is sent. If the first expression is False, that is, they aren’t a new user, the next expression is checked — do they require mailings? If so, then that code block is run, and if none of the expressions are True the Else block is run. If a condition tests true the appropriate code block is run and no more conditions are tested — the If statement ends.

Multiple Selections

For selections where the expression can be one of a number of possible answers, the If statement can become unwieldy. For example, consider the Wrox United shop where you can buy a range of branded merchandise. Currently items are sent using the standard postal service, but what if the club wanted to offer different delivery methods, perhaps by way of a drop-down list:

Dim delivery() As String = {“Next Day Post”, “3 Day Post”, _ “Courier”, “International”}

DeliveryDropDownList.DataSource = delivery

DeliveryDropDownList.DataBind()

The underscore at the end of the line is a line wrapping character. It must be preceded with a space and tells Visual Basic that the line of code hasn’t ended, but continues on the next line.

Maybe the data is from an array, or more likely from a database where the delivery type and associated cost are both included. When the total price is calculated, though, different action needs to be taken — perhaps to instruct the packing department which box type to use, or maybe to interface

318