Using VB.NET with ASP.NET

childlikenumberΑσφάλεια

5 Νοε 2013 (πριν από 4 χρόνια και 1 μήνα)

133 εμφανίσεις

Using VB.NET with ASP.NET
Page

Chapter Objectives

Object
-
Oriented Programming


Programming statements, or code,
combined into logical groupings,
functions, event handlers, and procedures

Object
-
Oriented Programming

(continued)


Objects and Classes


create objects based upon a class


An object is a set of related code that is
compartmentalized and built upon these classes


access the object across multiple Web pages


Create an object


the object definition, called the class


creating an instance of the class


use the class as the template for creating the new object

Object
-
Oriented Programming
(continued)


Instantiation


Declaring and initializing an object from a
class


You create objects from the same definition


Public Class TaraStoreClass

Private StoreName As String = "Tara Store"

End Class

Object
-
Oriented Programming
(continued)


Restrict applications access to the class


Public

-

interact with other objects outside of
the base class


Private

-

called only from within the base
class


Protected

-

called from within the base class,
and within subclasses


Subclass



a class that inherits from a base
class


Friend

-

called anywhere from within the
same application

Object
-
Oriented Programming
(continued)


Instantiate an object based on the class
definition


Declare a variable


keyword
Dim

-

to store the object


keyword
New

-

to identify that this is an object
based on a class definition


Dim Ch5Class As New Chapter5.TaraStoreClass()

Object
-
Oriented Programming
(continued)


Decision control structures

-

organize the
order in which the code is executed


Event handlers

-

execute when the event
occurs


Procedures

-

named grouping of one or
more programming statements


Parameters

-

values passed; multiple values
are separated in a comma delimited list within
parentheses


Functions

-

named grouping of
programming statements that can return a
value

Object
-
Oriented Programming
(continued)


Properties


Set the value of a variable defined within an
object


Identified by the object name, a period, and
the name


Assigned a default value within the object
definition, or the value is set as “undefined”


All new objects inherit the same properties as
the original object definition

Object
-
Oriented Programming
(continued)


Inheritance


Derive the interface and behaviors from
another class


Inherits keyword allows you to inherit from
another .NET class


All objects are inherited from the
System.Object


Properties like ToString apply to most objects


Encapsulation


Inner workings of the object are maintained
within the object

Introduction to Visual Basic
.NET



Windows Application


User interface is called the Form


Windows Forms tab in the Toolbox


Created from System.Windows.Forms


Web Pages


Code behind the page contains class
definition


Inherits keyword


Create classes in a file, or code behind the
page


Import the class into the page


Create a new object using the class

Creating a Class

TaraStoreClass.vb (Page 215
)


Create Chapter5 Web application, create
images folder, import images, and data
files


Create the TaraStoreClass class
(TaraStoreClass.vb)


Modify the Code View Options


Automatic outlining and add line numbers


Create Ch5Class (in ClassVariables.aspx)


Retrieve values inherited from
TaraStoreClass


View the IL using the ILDASM

TaraStoreClass.vb (continued)

TaraStoreClass.vb (continued)

ClassVariables.aspx

ClassVariables.aspx (continued)

ClassVariables.aspx (continued)

Chapter5.dll

Variables


Declaring a variable


Declaration keywords, variable name, data
type


Data type identifies what kind of data the variable
can store


Process of reserving the memory space for
the variable before it is used in the program


Declare all variables before they are used


Variable Declaration


Where the variable is defined determines
where the variable can be used within the
application


Scope



where access variable


Lifetime



how long variable and its value
persist in memory

Variable Declaration (continued)


Keywords specify the variable scope


Private

-

available only to code within the local
class


Public

-

used outside the class


Friend

-

used only within the current
application or project

Variable Declaration (continued)

Variable Declaration (continued)


Naming variables


Descriptive name


No commands or keywords


Begin with a letter


Do not use a period or space


Avoid special characters except underscore


Visual Basic .NET commands and variables
are not case sensitive


First letter of each word is usually capitalized

Variable Declaration (continued)

First Three Characters

Identify the Data Type

Data Type

Prefix

Sample Variable Name

Boolean

Bln

BlnMember

Byte

Byt

BytZero

Char

Chr

ChrLetter

Date

Dat

DatBirthdate

Double

Dbl

DblWeight

Decimal

Dec

DecProductPrice

Integer

Int

IntNumberProducts

Long

Lng

LngSalary

Single

Sng

SngAverage

Short

Sho

ShoYears

String

Str

StrLastName

Assigning Values to Variables


The assignment operator is the equal sign
(=)


Remember Visual Basic .NET is NOT case
sensitive. However, Visual Studio .NET will
place Dim, As, and String in upper case
characters



Dim LastName, FirstName as String

Dim StoreName As String =
"
Tara Store
"


Constants


A variable that does not change


Examples
-

tax rates, shipping fees, and
values used in mathematical equations


Declare a constant


Const keyword
-

Name is usually all
uppercase


When you declare a constant, you need to
assign the value to the constant


Const TAXRATE As Integer = 8

Concatenation



Process of joining one or more strings


Concatenation operator (&)


Can also use (+) only with strings


Join a literal string, or the result returned
from an expression, or a variable that
contains a string


Dim lblControlContent =
Ch5Class.StoreName.ToString() _

& "<br/>" & Ch5Class.StoreEmail.ToString()

lblContact.Text = lblControlContent

Data Types


Reference types


Strings, classes, arrays, collections, and
objects


Memory addresses stored in the managed
heap


Value types


Referred to as primitive types or structures


Stores the actual data in the stack


Boolean and Char


DateTime (Date in Visual Basic .NET)


All numeric data types

String


Strings are variable in length


Do not have to specify the number of
characters


Several built
-
in methods manipulate
strings


LCase and UCase
-

converts case to lower
and upper


Dim Password As String

Password = LCase(txtPassword.Value)

LblPassword.Text = Password

Char


Store a single text value as a number
between 0 and 65,535


Represents a character in categories such
as digit, letter, punctuation, and control
characters


Numeric


Byte

-

stores an integer between 0 and 255


Short

-

16
-
bit number from
-
32,768 to
32,767


Integer

-

32
-
bit whole number


Long

-

64
-
bit number


Real number data types


Single

-

a single
-
precision floating point
number


Double

-

larger numbers than the single data
type


Decimal

-

up to 28 decimal places and often
used to store currency data

DateTime


Dates between 01/01/0001 and
12/31/9999


Formats are mm/dd/yyyy and hh:mm:ss


Enclosed within a pair of pound signs


Dim MyBirthday As DateTime

MyBirthday = #3/22/2002#

Object Browser

Boolean


Two possible values: True or False


In binary math:


1 represents true


0 represents false


In Visual Studio .NET


True value is converted to
-
1


False value is converted to 0

Using a Property to Retrieve
and Set the Value of a Variable


Use a variable outside of a class


Use the property function


Declare the variable public


Property methods


Used to keep private variables


To retrieve and set the variable’s value


Set the value and retrieve them indirectly

Using a Property to Retrieve and
Set the Value of a Variable
(continued)


ReadOnly prevents you from writing to the
property


WriteOnly allows the value to be changed,
but not retrieved from the property


Public ReadOnly Property NewStoreName() As
String

Public

WriteOnly Property NewStoreName()



As String

Collections


Data stored in structures called collections


System.Collections namespace provides
access to classes that manage data


Each item is referred to as an element


These five collections


ArrayList
,
HashTable
, and
SortedList

-

access
any element without having to rotate through
the other elements


Queue

and
Stack

-

rotate through the
collection sequentially to locate an element

The ArrayList


Stores each item in sequential order


Each item is indexed with a number


Do not need to define the size of the ArrayList


Each item is identified using an
index number

that indicates its position


Zero
-
based

-

first item is at position 0


ArrayList size of 3 means it has 4 items

The ArrayList (continued)


Create an ArrayList

Dim StateAbbrev As New ArrayList

StateAbbrev.Add("IL")

StateAbbrev.Add("MI")

StateAbbrev.Add("IN")


Retrieve the value individually

Response.Write(StateAbbrev(0))


Insert an element into the first position and
remove it

StateAbbrev.Insert(0, "OK")

StateAbbrev.Remove("OK")

The ArrayList (continued)


Properties and Methods


Add

and
Remove

-

add or delete a single element


Insert

and
RemoveAt

-

add and remove elements at a
specific index position


AddRange

and
RemoveRange

-

add or remove a
group of elements


IndexOf

-

find the position of the element in the list


A value of
-
1 means the element was not found in the list.


Count

-

identifies the number of items in the array


which will be the largest index number plus 1.


Clear

-

remove all of the elements

The HashTables


Creates the index of elements using an
alphanumeric key like an encyclopedia


keys

-

a collection of alphanumeric values


values

-

a collection of elements


Add

and
Remove

method


Items added using key and value pair
separated with a comma


Key passed with quotation marks


Second parameter is the value

Other Collections


The

SortedList
Class
-

Indexed by both the
key and the item so the index position will
change frequently


The

Queue

Class
-

sequential access to
the elements


Stores them in First In, First Out (FIFO)


Roller coaster ride


People in the first car are let out first


The

Stack

class
-

sequential access



Stores them in Last In, First Out (LIFO) order


Line in a theatre, church, or crowded elevator


First one to enter the room is the last one to leave

Procedures


Subprocedures


Do not return values


Cannot be used in an expression value


Event Procedures


Not executed until an event triggers the
procedure


Known as an event procedure


Does not return a value


Page_Load event triggered when the page is
loaded


Functions


A block of code that is grouped into a named unit.


Built
-
in functions inherit from a .NET Framework
class


User defined functions

Subprocedures


Subprocedures


Other keywords
-

Public

or
Private
,
Exit
Sub


Sub SubprocedureName(parameters)

Action and Control Statements

End Sub



Call keyword


calls the procedure

[Call] SubprocedureName(arguments)

Event Procedure


Event Names


Based on object name and event name


Identified with the prefix “on” and event name


Underscore (_) separate object and event
name


Sub objectName_eventHandler



(sender as Object, e as EventArgs)



action and control statements

End Sub

Functions


Are declared


Public functions
-

visible to all other
functions


Private functions
-

only available within the
context where they are declared


Public Function GetStoreName() As Integer

'This function returns an integer



Return 23422

End Function

Passing an Argument

to a Function


A pair of parentheses follows with zero or
more arguments, also known as
parameters
, which are passed to the
function when it is called


If no arguments are passed, you use an
empty pair of parentheses


If multiple arguments are used, you use a
comma to separate each argument

Returning a Value From a
Function

& Exiting a Function


Keyword
Return



Identify the value returned to the function call


Exiting a Function


Exit Function

keywords


A jumping control; jumping controls allow you
to temporarily halt the execution of a code
block, and move to another section of code
outside the function

Exiting a Function

Public Function GetStoreName() As String

Dim UserName As String

UserName = txtUserName.Text.ToString

If UserName = "Admin" then

Return "Welcome Administrator!"

Exit Function

Else

Return "Welcome!"

Exit Function

End If

End Function

Creating a Function

Public Class TaraStoreClass

Public Function GetStoreName() As String

Return
"
Tara Store
"

End Function

End Class



GetTheFunction(New
TaraStoreClass().GetStoreName)

Using Visual Basic .NET in a Web
Page SampleUsingVB.aspx (Page
239)

Using Visual Basic .NET in a Web
Page SampleUsingVB.aspx
(continued)

Using Visual Basic .NET in a Web
Page SampleUsingVB.aspx
(continued)

Using Visual Basic .NET in a Web
Page SampleUsingVB.aspx
(continued)

Using Visual Basic .NET in a Web
Page SampleUsingVB.aspx
(continued)

Introduction to C#


Syntax similar to JavaScript and C++


Compiled by the C# compiler


into the same managed Intermediate
Language code that is also generated by the
Visual Basic .NET compiler


Base Classes and development
environment are available across
programming languages


Access to the same Windows Form tools
and ASP.NET Web Form tools

Introduction to C# (continued)


Language Differences


C# is case sensitive


Array using C#, use square brackets around
index position


One or more statements;

enclose code in curly braces { }


Assign a value to a variable, specify the data
type first, then specify the variable name


String StoreName = "Tara Store";

int counter = 1;

Introduction to C# (continued)


Comments in C# are similar to comments in
JavaScript


// This is a single line comment

/*

This is a multiline comment

Always document your code

*/


Declare the variable public in C#


Use all lower case letters for the keyword public


Declaration of variables

Introduction to C# (continued)


C# Sample

String s1;

String s2 = "Welcome to ";

s2 += "Tara Store";

s1 = s2 + " !!!";

Label1.Text = s1.ToString();


J# Sample (this is the sample shown in the
book)

String s1;

String s2 = "Welcome to ";

s2 += "Tara Store";

s1 = s2 + " !!!";

Label1.set_Text(s1);

Introduction to C# (continued)


JScript Sample
-

this goes inline in the HTML
code view



<%@ Page Language="jscript" . . . %>



<%

// Write the message to the Web page

var s1 : String;

var s2 : String = "Welcome to ";

s2 += "Tara Store";

s1 = s2 + " !!!";

Response.Write(s1);

Response.Write(s3);

%>



Introduction to C# (continued)


StringBuilder Class


Import System and
System.Text


C# Sample

StringBuilder s3 = new StringBuilder();

s3.Append("Welcome to ");

s3.Append("Tara Store");

s3.Append(" !!!");

Label1.Text = s3.ToString();


J# Sample (this is the sample shown in the book)

StringBuilder s3 = new StringBuilder();

s3.Append("Welcome to ");

s3.Append("Tara Store");

s3.Append(" !!!");

Label1.set_Text(s3.ToString());

Summary


Process of creating an object from a class
is instantiation


Create multiple classes within a single
class file


Assign a data type to a variable when the
variable is created


Properties set the value of a variable
defined within an object


Constants store values in variables that do
not change within the application


Concatenation operator is the ampersand

Summary (continued)


Each item in the collection is referred to by
its index position


Procedures organize the order in which
the code is executed


Event handlers execute code when an
event occurs


Functions return values


C# is a new programming language that
can be used to create ASP.NET
applications