chapter 5 – programming asp.net web pages dr. stephanos mavromoustakos

48
CSC209 Web Programming Chapter 5 – Programming ASP .NET Web Pages Dr. Stephanos Mavromoustakos

Upload: lawrence-perry

Post on 01-Jan-2016

220 views

Category:

Documents


1 download

TRANSCRIPT

Slide 1

CSC209 Web Programming Chapter 5 Programming ASP .NET Web PagesDr. Stephanos MavromoustakosData Types and VariablesDeclaring Variables and Asignning valuesDeclaring a variable of type IntegerDim distanceInMiles As IntegerDistance InMiles = 437

Declaring a variable to hold some text like first nameDim firstName As StringfirstName = Stephanos

You can also declare a variable and assign a value in one lineDim distanceInMiles As Integer = 437Data Types and VariablesCommon Type Systems (CTS)

VB.NETDescriptionByte0-255 numbersShort-32768 - 32768Integer-2,147,483,648 - 2,147,483,647SingleLarge numbers with decimalsDoubleCan hold fractional numbersBooleanTrue / FalseDateSystem.DateTimeCharSingle characterStringText up to 2 billion charsObjectParent of all data types in .NET, including the CTS types and types you may define yourself. Each data type is also an objectData Types and VariablesConverting Data Typese.g. To convert an Object to a String, you can call its ToString() method.Output todays date and time on a label:Label1.Text = System.DateTime.Now.ToString()

Another way is to use the Convert classConverting a String containing a value that looks like a Boolean into a true Boolean type:Dim myBoolean1 As Boolean = Convert.ToBoolean (True)Data Types and VariablesConverting Data TypesAnother way is to use casting. Force one type into another only works for compatible types e.g. Double to an Integer or a String to an Object. The reverse of the latter example isnt always true. 2 ways:CType more flexibleDirectCast slightly fasterTryCast Similar to previous but when an object cannot be casted correctly, it returns Nothing, whereas DirectCast andCType result in a crash of the code

Data Types and VariablesCtype and DirectCastDim O1 As Object = 1Dim i1 As Integer = DirectCast (O1, Integer)Dim i2 As Integer = Ctype (O1, Integer)

`Both work above because o1 is an Integer

Dim O2 As Double = 1Dim i3 As Integer = DirectCast (O2, Integer) `Fails-O2 not integerDim i3 As Integer = CType (O2, Integer) `Works-O2 looks like an Integer Data Types and VariablesUsing Arrays and CollectionsAn array is a list of the same type of things. Each item in the array is identified by a sequential number (index) starting at 0. Dim roles(1) As String`can hold two rolesYou define the array size by specifying the upper bound (last element in the array)To enter the roles names into the array you use:Roles(0) = AdministratorsRoles(1) = ContentManagers Data Types and VariablesIf you need to create more room in the array you can use the ReDim statement:ReDim Preserve roles (2)Roles(2) = Members

The Preserve keyword is necessary to leave the current items in the array intact.

Data Types and VariablesCollections are similar to arrays in that they allow you to store more than one object in a single variable. The difference is how they allow you to work with the data there. Most collections expose an Add method that allows you to add an item to the collection. Similarly, they have Remove and Clear methods to remove one or all items from the collection.

The ArrayList allows you to add arbitrary objects that are then stored in the order you add them, while the Hashtable allows you to store objects referenced by a custom key. The main benefit compared to the arrays is that these can grow on demand.

Data Types and VariablesDim roles As New ArrayList() `creates a new ArrayListroles.Add(Administrators) `Add the first roleroles.Add(ContentManagers) `Add the second roleroles.Add (Members) `Keep adding roles

Problem with ArrayList not strongly typed. You can add any object to the list using the Add method. This means that the objects can be different types at the same time. E.g. Create a drop down list where one item in the list is not a string.To overcome this problem in .NET 2.0 a concept called generics was introduced.

Data Types and VariablesGenericsAllows you to write a code template that can be used in different scenarios with different types. With generics, you can define a generic code template without specifying a type (for reusability). Dim roles As New List(Of String) `now accepts only stringroles.Add(Administrators) roles.Add(ContentManagers)roles.Add (Members)

Data Types and VariablesAlso, you can create lists to hold other types, e.g.

Dim intList As New List (Of Integer)Dim boolList As New List (Of Boolean)Dim buttonList As New List (Of Button)

StatementsAssignment Operators+ adds values like integers or String (concatenated)- Subtracts one from another* Multiplies values/ Divides values\ Divides values but returns a rounded integer^ Raises one value to the power of anotherMod Divides two whole numbers and returns the remainderStatementsDim firstNumber As Integer = 100Dim secondNumber As Single = 23.5Dim result As Double = 0

result = firstNumber + secondNumber `123.5result = firstNumber - secondNumber `76.5result = firstNumber * secondNumber `2350result = firstNumber / secondNumber `4.25531914893617result = firstNumber \ secondNumber `4Result = 2 ^ 3 `8Result = 3 ^ 2 `9

StatementsDim firstNumber As Integer = 17Dim secondNumber As Integer = 3Dim result As Integer

Result = firstNumber Mod secondNumber `2

StatementsComparison Operators=

=Is (compares two objects)StatementsThe Is compares two instances of objects, using the TypeOf operator.

Dim myTextBox As TextBox = New TextBox()

If TypeOf myTextBox Is TextBox Then`run some code when myTextBox is a TextBoxEnd If

StatementsConcatenation Operators (&= and +)Dim firstString As String = Hello Dim secondString As String = World

`The next three blocks are the same, resulting to Hello World

Result = firstString & secondString

Result = firstStringResult = result & secondString

Result = firstStringResult &= secondStringStatementsDim firstNumber As String = 4Dim secondNumber As String = 5Dim result As String = firstNumber + secondNumber

The VB.NET compiler will silently concert the String 4 into a number 4, therefore resulting to a 9 and not 45.To avoid this ambiguity, always use the & and &= operators to concatenate values. You can also tell VB.NET to stop concerting these values for you automatically by adding this line to the top of your code files:Option Strict OnThis forces the compiler to generate errors when an implicit conversion is about to occurStatementsLogical OperatorsAnd true when both expressions are trueOr true if at least one expression is trueNot reverses the outcome of an exrpessionAndAlso Allows you to short-circuit your logical condition checksOrElse Allows you to short-circuit your logical condition checksStatementsDim num1 As Integer = 3Dim num2 As Integer = 7If num1 = 3 And num2 = 7 Then `trueIf num1 = 2 And num2 = 7 Then `falseIf num1 = 3 Or num2 = 11 Then `trueIf Not num1 = 5 Then `true

StatementsThe difference between the AndAlso and OrElse with their counterparts And and Or is that with the AndAlso and OrElse operators, the second expression is never evaluated when the first one already determines the outcome of the entire expression. So with the simple And:If num1 = 2 And num2 = 7 Then `both expressions are checked

If num1 = 2 AndAlso num2 = 7 Then `no need to check for num2This is very simple but consider something may need more time e.g.If userName = Administrator And GetNUmberOfRecordsFromDatabase() > 0 Then `compared toIf userName = Administrator AndAlso GetNUmberOfRecordsFromDatabase() > 0 Then

Making DecisionsIf, If Else, and ElseIf ConstructsIf User.IsInRole (Administrators) Then btnDeleteArticle.Visible = TrueEnd IfIf Not User.IsInRole (Administrators) Then btnDeleteArticle.Visible = FalseEnd If

This creates a messy problem because of repetition (once for True and once for False). Solution? Use the Else block

Making DecisionsIf User.IsInRole (Administrators) Then btnDeleteArticle.Visible = TrueElse btnDeleteArticle.Visible = FalseEnd If

For more complex scenarios you will need ElseIf

Making DecisionsIf User.IsInRole (Administrators) Then btnCreateArticle.Visible = True btnDeleteArticle.Visible = TrueElseIf User.IsInRole (ContentManagers) Then btnCreateArticle.Visible = True btnDeleteArticle.Visible = FalseElseIf User.IsInRole (Members) Then btnCreateArticle.Visible = False btnDeleteArticle.Visible = FalseEnd If

Making DecisionsSelect Case ConstructE.g. Imagine youre building a website for a concert hall that has shows on Saturday. During the week, visitors can buy tickets online for Saturdays gig. To encourage visitors to buy tickets as early as possible, you decide to give them an early-bird discount. The earlier in the week they buy their tickets, the cheapest they are.Making DecisionsDim today As DateTime = DateTime.NowDim discountRate As Double = 0

Select Case today.DayOfWeek Case DayOfWeek.MondaydiscountRate = 0.4 Case DayOfWeek.TuesdaydiscountRate = 0.3 Case DayOfWeek.WednesdaydiscountRate = 0.2 Case DayOfWeek.ThursdaydiscountRate = 0.1 Case ElsediscountRate = 0End SelectPractice Simple CalculatorUnder the Demos folder create a new file called CalculatorDemo.aspxIn Design View, click the dashed rectangle to put the focus on it, and add a table with three rows and three columns using TableInsert Table. Merge all three cells of the first row by selecting them, right-click and choose ModifyMerge CellsAdd the following controls as shown Practice Simple CalculatorControl TypeIDProperty SettingsLabellblResultClear its propertyTextBoxtxtValue1DropDownListlstOperatorAdd four ListItems:+-*/TextBoxtxtValue2ButtonbtnCalculateSet the Text property of the button to CalculatePractice Simple Calculator

Practice Simple CalculatorDouble-click the Calculate button and add the following code (shown in the next slide)Save all changes and press Ctrl+F5Enter a number in the first and second text boxes, choose an operator from the drop-down list, and then click the Calculate button.Go ahead and try different numbers and operators

Practice Simple CalculatorIf txtValue1.Text.Length > 0 AndAlso txtValue2.Text.Length > 0 Then Dim result As Double = 0 Dim value1 As Double = Convert.ToDouble(txtValue1.Text) Dim value2 As Double = Convert.ToDouble(txtValue2.Text)

Select Case lstOperator.SelectedValue Case "+" result = value1 + value2 Case "-" result = value1 - value2 Case "*" result = value1 * value2 Case "/" result = value1 / value2 End Select lblResult.Text = result.ToString() Else lblResult.Text = String.Empty End IfPractice Simple Calculator

LoopsFor loopThe For loop simply repeats its code a predefined number of times. The For loop takes the following format:For counter [ As datatype ] = start To end [ Step step] `Code that must be executed for each iterationNext [ counter ]

e.g.For loopCount As Integer = 1 to 10 Label1.Text &= loopCount.ToString() &
NextLoopsFor loopCount As Integer = 0 To roles.Length 1Label1.Text &= roles (loopCount) & br />Next

Remember that arrays are zero-based. This means that you need to address the first item with roles(0). The Length property of an array returns the total number of items that the array contains. So when there are three roles in the array, Length returns 3 as well. Therefore, the code subtracts one from the Length and uses that value as the end condition of the loop to run from 0 to 2, accessing all three elements.If you are looping over an array or collection of data, the For Each loop is a bit easier to use.LoopsFor Each role As String In rolesLabel1.Text &= role &
Next

Since the roles variable is an array of strings, you need to set up the loop with a String as well. Likewise, if the collection that is being looped over contained Integer or Boolean data types, you would set up the loop with an Integer or Boolean, respectively.LoopsWhile LoopDim success As Boolean = FalseWhile Not successsuccess = SendEmailMessage()End While

This code tries to send an email message and will do so until it succeeds-that is, as long as the variable success contains the value False (The Not is used to reverse the value of success).The SendEmailMessage method is supposed to return True when it succeeds and False when it doesnt. LoopsTo avoid infinite loop, it is good to terminate it after certain number of tries, as below:

Dim success As Boolean = FalseDim loopCount As Integer = 0While Not success And loopCount < 3success = SendEmailMessage()loopCount = loopCount + 1End While

Also you can use the:loopCount += 1 (loopCount -= 1 to decrease by 1)

Functions and SubroutinesFunctions and Subroutines are very similar; both allow you to create a reusable block of code that you can call from other locations in your site. The difference is that a function can return data while a sub doesnt. Both are referred to as Methods.

To make them more useful, they can be parameterized. That is, you can pass in additional information that be used inside the function or subs. Functions and SubroutinesFunctions and subs generally take the following format:

`Define a functionPublic Function FunctionName ([parameterList]) As DataType

End Function

`Define a subroutinePublic Sub SubName ([parameterList])

End SubFunctions and SubroutinesPublic is referred to as the method signature as it defines the look of the function, its name and its parameters.

The Public keyword is called an access modifier and defines to what extend other web pages or code files can see this method.

The parameter list is optional.

Functions and SubroutinesPublic Function Add (ByVal a As Integer, ByVal b As Integer) As IntegerReturn a + bEnd Function

Public Sub SendEmail (ByVal emailAddress As String)`Code to send an email goes hereEnd Sub

ByVal in front of each parameter is the default type for all parameters. The opposite is ByRef. When you specify ByVal, a copy of the variable is made. Any changes made to that copy inside the method are lost as soon as the method finishes. In contrast, when you specify ByRef, a reference to the variable is sent to the method. Any changes made to the incoming variable reflect on the original variable as well. Functions and SubroutinesPublic Sub ByValDemo (ByVal someValue As Integer)someValue = someValue +20End Sub

Public Sub ByValDemo (ByVal someValue As Integer)someValue = someValue +20End Sub

Dim x As Integer = 0ByValDemo (x)Label1.Text = x.ToString() `prints out 0; a copy of x is sent `to ByValDemo, leaving the original value of x unmodified.

Dim y As Integer = 0 ByRefDemo (y)Label2.Text = y.ToString() `Prints out 20; A reference to y is `sent to ByRefDemo so when that method modified someValue, it `also changed the variable y.App_Code FolderThe App_Code folder is designed specifically to hold code files, like classes. Code that only applies to one page (e.g. button control click) should remain in the pages Code Behind. To add the App_Code folder to your site, right-click the sites name in the Solution Explorer and choose Add ASP.NET Folder App_Code. The folder is added to the site and gets a special iconNow you can start adding class files to it. Class files have an extension of your programming language (e.g. .vb or .cs). Inside these class files you can create classes that in turn contain methods (functions and subs) that carry out common tasks.Practice Optimizing the CalculatorAdd the App_Code folder to your site as described beforeRight-click the App_Code folder and choose Add New ItemSelect Class and type Calculator as the name of the file and click Add. This creates a class called Calculator.Right after the line of code that defines the Calculator class add the following four methods:Practice Optimizing the CalculatorPublic Class Calculator Public Function Add(ByVal a As Double, ByVal b As Double) As Double Return a + b End Function

Public Function Subtract(ByVal a As Double, ByVal b As Double) As Double Return a - b End Function

Public Function Multiply(ByVal a As Double, ByVal b As Double) As Double Return a * b End Function

Public Function Divide(ByVal a As Double, ByVal b As Double) As Double Return a / b End FunctionEnd ClassPractice Optimizing the CalculatorNext modify the Code Behind of the CalculatorDemo.aspx page so it uses the class you just created.You will need to make two changes: first you need to add a line of code that creates an instance of the Calculator and then you need to modify the Case block to use the relevant calculation methods in the calculator.Practice Optimizing the CalculatorDim myCalculator As New Calculator()Select Case lstOperator.SelectedValueCase "+"result = myCalculator.Add(value1, value2)Case "-"result = myCalculator.Subtract(value1, value2)Case "*"result = myCalculator.Multiply(value1, value2)Case "/"result = myCalculator.Divide(value1, value2)End Select

Save all changes and run it on a browser. The calculator works as before; only this time the calculations are not carried out in the Code Behind file, but by the Calculator class in the App_Code folder instead.