480 likes | 613 Views
CSC209 Web Programming. Chapter 5 – Programming ASP .NET Web Pages Dr. Stephanos Mavromoustakos. Data Types and Variables. Declaring Variables and Asignning values Declaring a variable of type Integer Dim distanceInMiles As Integer Distance InMiles = 437
E N D
CSC209 Web Programming Chapter 5 – Programming ASP .NET Web Pages Dr. StephanosMavromoustakos
Data Types and Variables Declaring Variables and Asignning values Declaring a variable of type Integer Dim distanceInMiles As Integer Distance InMiles = 437 Declaring a variable to hold some text like first name Dim firstName As String firstName = Stephanos You can also declare a variable and assign a value in one line Dim distanceInMiles As Integer = 437
Data Types and Variables Common Type Systems (CTS)
Data Types and Variables Converting Data Types e.g. To convert an Object to a String, you can call its ToString() method. Output today’s date and time on a label: Label1.Text = System.DateTime.Now.ToString() Another way is to use the Convert class Converting 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 Variables Converting Data Types Another 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 isn’t always true. 2 ways: • CType – more flexible • DirectCast – slightly faster • TryCast – Similar to previous but when an object cannot be casted correctly, it returns Nothing, whereas DirectCastandCType result in a crash of the code
Data Types and Variables CtypeandDirectCast Dim O1 As Object = 1 Dim 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 = 1 Dim i3 As Integer = DirectCast (O2, Integer) `Fails-O2 not integer Dim i3 As Integer = CType (O2, Integer) `Works-O2 looks like an Integer
Data Types and Variables Using Arrays and Collections An 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 roles You 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) = “Administrators” Roles(1) = “ContentManagers”
Data Types and Variables If 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 Variables Collections 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 Variables Dim roles As New ArrayList() `creates a new ArrayList roles.Add(“Administrators”) `Add the first role roles.Add(“ContentManagers”) `Add the second role roles.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 Variables Generics Allows 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 string roles.Add(“Administrators”) roles.Add(“ContentManagers”) roles.Add (“Members”)
Data Types and Variables Also, 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)
Statements Assignment 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 another Mod Divides two whole numbers and returns the remainder
Statements Dim firstNumber As Integer = 100 Dim secondNumber As Single = 23.5 Dim result As Double = 0 result = firstNumber + secondNumber `123.5 result = firstNumber - secondNumber `76.5 result = firstNumber * secondNumber `2350 result = firstNumber / secondNumber `4.25531914893617 result = firstNumber \ secondNumber `4 Result = 2 ^ 3 `8 Result = 3 ^ 2 `9
Statements Dim firstNumber As Integer = 17 Dim secondNumber As Integer = 3 Dim result As Integer Result = firstNumber Mod secondNumber `2
Statements Comparison Operators = <> < > <= >= Is (compares two objects)
Statements The Is compares two instances of objects, using the TypeOf operator. Dim myTextBox As TextBox = New TextBox() If TypeOfmyTextBox Is TextBox Then `run some code when myTextBox is a TextBox End If
Statements Concatenation 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 = firstString Result = result & secondString Result = firstString Result &= secondString
Statements Dim firstNumber As String = “4” Dim secondNumber As String = “5” Dim 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 On This forces the compiler to generate errors when an implicit conversion is about to occur
Statements Logical Operators And – true when both expressions are true Or – true if at least one expression is true Not – reverses the outcome of an exrpession AndAlso – Allows you to short-circuit your logical condition checks OrElse – Allows you to short-circuit your logical condition checks
Statements Dim num1 As Integer = 3 Dim num2 As Integer = 7 If num1 = 3 And num2 = 7 Then `true If num1 = 2 And num2 = 7 Then `false If num1 = 3 Or num2 = 11 Then `true If Not num1 = 5 Then `true
Statements The difference between the AndAlso and OrElse with their counterparts AndandOr 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 num2 This is very simple but consider something may need more time e.g. If userName = “Administrator” And GetNUmberOfRecordsFromDatabase() > 0 Then `compared to If userName = “Administrator” AndAlsoGetNUmberOfRecordsFromDatabase() > 0 Then
Making Decisions If, IfElse, and ElseIf Constructs If User.IsInRole (“Administrators”) Then btnDeleteArticle.Visible = True End If If Not User.IsInRole(“Administrators”) Then btnDeleteArticle.Visible = False End If This creates a messy problem because of repetition (once for True and once for False). Solution? Use the Else block
Making Decisions If User.IsInRole (“Administrators”) Then btnDeleteArticle.Visible = True Else btnDeleteArticle.Visible= False End If For more complex scenarios you will need ElseIf
Making Decisions If User.IsInRole (“Administrators”) Then btnCreateArticle.Visible = True btnDeleteArticle.Visible = True ElseIfUser.IsInRole(“ContentManagers”) Then btnCreateArticle.Visible= True btnDeleteArticle.Visible = False ElseIfUser.IsInRole(“Members”) Then btnCreateArticle.Visible= False btnDeleteArticle.Visible = False End If
Making Decisions Select Case Construct E.g. Imagine you’re building a website for a concert hall that has shows on Saturday. During the week, visitors can buy tickets online for Saturday’s 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 Decisions Dim today As DateTime = DateTime.Now Dim discountRate As Double = 0 Select Case today.DayOfWeek Case DayOfWeek.Monday discountRate = 0.4 Case DayOfWeek.Tuesday discountRate = 0.3 Case DayOfWeek.Wednesday discountRate = 0.2 Case DayOfWeek.Thursday discountRate = 0.1 Case Else discountRate = 0 End Select
Practice – Simple Calculator • Under the Demos folder create a new file called CalculatorDemo.aspx • In 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 Cells • Add the following controls as shown
Practice – Simple Calculator • Double-click the Calculate button and add the following code (shown in the next slide) • Save all changes and press Ctrl+F5 • Enter 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 Calculator If 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 If
Loops For loop The 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 iteration Next [ counter ] e.g. For loopCount As Integer = 1 to 10 Label1.Text &= loopCount.ToString() & “<br />” Next
Loops For loopCount As Integer = 0 To roles.Length – 1 Label1.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 ForEach loop is a bit easier to use.
Loops For Each role As String In roles Label1.Text &= role & “<br />” 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.
Loops While Loop Dim success As Boolean = False While Not success success = 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 doesn’t.
Loops To avoid infinite loop, it is good to terminate it after certain number of tries, as below: Dim success As Boolean = False Dim loopCount As Integer = 0 While Not success And loopCount < 3 success = SendEmailMessage() loopCount = loopCount + 1 End While Also you can use the: loopCount += 1 (loopCount-= 1 to decrease by 1)
Functions and Subroutines Functions 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 doesn’t. 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 Subroutines Functions and subs generally take the following format: `Define a function Public Function FunctionName ([parameterList]) As DataType End Function `Define a subroutine Public Sub SubName([parameterList]) End Sub
Functions and Subroutines Public 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 Subroutines Public Function Add (ByVal a As Integer, ByVal b As Integer) As Integer Return a + b End Function Public Sub SendEmail (ByValemailAddress As String) `Code to send an email goes here End 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 Subroutines Public Sub ByValDemo (ByValsomeValue As Integer) someValue = someValue +20 End Sub Public Sub ByValDemo (ByValsomeValue As Integer) someValue = someValue +20 End Sub Dim x As Integer = 0 ByValDemo (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 Folder • The 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 page’s Code Behind. • To add the App_Code folder to your site, right-click the site’s name in the Solution Explorer and choose Add ASP.NET Folder App_Code. • The folder is added to the site and gets a special icon • Now 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 Calculator • Add the App_Code folder to your site as described before • Right-click the App_Code folder and choose Add New Item • Select 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 Calculator Public 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 Function End Class
Practice – Optimizing the Calculator • Next 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 Calculator Dim myCalculator As New Calculator() Select Case lstOperator.SelectedValue Case "+" 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.