1.NET Web Forms Language Fundamentals © 2002 by Jerry Post.

25
1 .NET Web Forms Language Fundamentals © 2002 by Jerry Post

Transcript of 1.NET Web Forms Language Fundamentals © 2002 by Jerry Post.

1

.NET Web Forms

Language Fundamentals

© 2002 by Jerry Post

2

NameSpaces

Internal .NET functions are grouped into classes that can be referenced by their full name. Dim sb As System.Text.StringBuilder

Or, you can use it by Import (VB) or using (C#). Enter one of these lines at the top of your code file. Imports System.Text using System.Text;

3

Primitive Data TypesClass Name Description Visual Basic C#

Integer

Byte

Int16

Int32

Int64

8-bit unsigned

16-bit unsigned

32-bit unsigned

64-bit unsigned

Byte

Short

Integer

Long

byte, sbyte, ubyte

short, ushort

Int, uint

long, ulong

Floating point

Single

Double

32-bit single prec.

64-bit double prec.

Single

Double

float

double

Logical

Boolean True or False Boolean bool

Other

Char

DateTime

Decimal

Object

String

Unicode character

Date and Time class

96-bit decimal

Object definition

Fixed length Unicode

Char

Date

Decimal

Object

String

char

datetime

decimal

object

String

4

Data Type DetailsBalena p. 96

VB .NET Bytes Values

Byte System.Byte 1 0 to 255 (unsigned)

Short System.Int16 2 -32,768 to 32,767

Integer System.Int32 4 -2,147,483,648 to 2,147,483,647

Long System.Int64 8 9,223,372,036,854,775,808

Single System.Single 4 -1.401298 E-45 to 3.402823 E38

Double System.Double 8 +/- 4.94 E-324 to +/- 1.7977 E308

Boolean System.Boolean 4 True/False

Char System.Char 2 0 to 65535 (unsigned)

Date System.DateTime

8 1/1/CE 12/31/9999

Decimal System.Decimal 12 +/- 7.9228 … (28 decimal digits)

Object System.Object 4 Main parent holds all types.

String System.String 10 + 2*length

0 to ~ 2 B Unicode chars

5

Variable Declaration

Dim sLastName As String

Dim sFirstName As String = “Default Value”

Dim aryInt(10) As Integer (All arrays are zero-based)

Dim aryString() As String = {“One”, “Two”, “Three”}

Dim j, k As Integer (This one works now!)

6

Data Type Conversion

Dim i As Integer = 13Dim s1 As String = i.toString()Dim s2 As String = CType(i, String) ‘ More general/more robust

int i = 13;string s1 = i.toString();string s2 = (string) i; ‘ More general/more robust

VB

C#

Because of CLS, languages are strongly typed. You must explicitly write (almost) all conversions. Conversions from wider to narrow types will usually generate errors because of potential loss of data.

7

VB ClassesPublic Class Customer

Public Title As StringPublic LastName As StringPublic FirstName As StringPrivate Password As StringPublic Sub SetPassword(inPassword As String)

‘ Encrypt itPassword = SomethingEncrypt(inPassword)

End SubPublic Function TestPassword(inPassword As String) As Boolean

Dim tstPass As String = SomethingEncrypt(inPassword)Return (tstPass = Password)

End FunctionEnd Class

Public Class CorpCustomerInherits CustomerPublic OurSalesPerson As String

End Class

8

C# Classespublic class Customer{

public string Title;public string LastName;public string FirstName;private string Password;public void SetPassword(string inPassword){

// Encrypt itPassword = SomethingEncrypt(inPassword);

}Public bool TestPassword(string inPassword){

string tstPass = SomethingEncrypt(inPassword);return (tstPass == Password);

}}

public class CorpCustomer : Customer{

public string OurSalesPerson;}

9

Arrays and Pointers (not)

Arrays exist and are defined as typical for the language VB: Dim myArray(5,5) as Integer C#: Int32[,] myArray = new Int32[5,5];

CLR handles all memory, so pointers do not really exist (except in C++ which is largely unmanaged).

Call back functions and event handlers use delegates instead of pointers.

10

Collections: Dynamic

Use collections instead of arrays when content is dynamic. Think of them as lists.

Public URLHistory As New Microsoft.VisualBasic.Collection

URLHistory.Add(URLAddress)

For Each URLAddress in URLHistory

do something with URLAddress

Next URLAddress

11

VB: Functions and Routines

Parameters are passed ByVal by default, and explicitly noted.

Array values are references and CAN be modified within a subroutine even when array is passed ByVal.

Functions use the Return statement to return values. When in doubt, think in C. VB is only different by

syntax.

Public Function myTest(ByVal j As Integer) As Booleanj += 3 ‘ Note shortcut notation

‘ But calling value is not changedReturn (j > 4)

End Function

12

VB Loops and Conditions

Do While … Loop Do Until … Loop Do … Loop While Do … Loop Until While … End While (obsolete but sometimes used) For j = 1 to n step 1 … next j For Each obj In collection … Next obj Exit Do to break out of the loop (or Exit For)

Short Circuit Conditions (finally, but they should be the default) OrElse AndAlso

Do Until ((rst.EOF) OrElse (rst(“ID”) > 15))‘ Operate on rst

Loop

Without short circuit test, this statement will crash at EOF.

13

Conditions

if ( ) {

// true} else{

// false}

switch (myVar){

case 1:// code 1

case 2:// code 2

default:// code 3

}

C#If ( ) Then

‘ trueElse

‘ falseEnd If

Select Case myVarCase 1

‘ code 1Case 2

‘ code 2 Case Else

‘ code 3End Select

VB

14

Internal Functions are Class-based

Strings Avoid using old VB: Trim(LastName) Instead, use the String class methods: LastName.Trim()

Math: All cool functions are in System.Math Dim dbl As Double = Math.Sin(Math.PI*2)

15

Error Handling: Try/Catch/Finally

Concepts are identical with VB and C# (and C++), just slightly different syntax.

You can get tricky handling with different Catch options, but usually that’s a pain; unless you are looking for several specific types of errors.

Tryx = y/z

Catch e As Exception‘ Error is in e.Message

End Try

Tryx = y/z

Catch e As DivideByZeroException‘ Error is in e.Message

Catch e As OverFlowException…

Catch...

End Try

Trycnn.Open …

Catch e As Exception‘ Error is in e.Message

Finallycnn.Close()

End Try

16

Regular Expressions

Extremely powerful pattern matching and string extraction system.

Standard methods developed in Unix, available in many systems. Now in .NET (VB and C# and …)

Tricky to learn. Can be extremely difficult to read. See Balena, Ch. 12, p. 481-510, esp. 486-490

17

RegEx: Matching

Does a string contain a specified pattern? How many?

Imports System.Text.RegularExpression

Dim str As String = “Test Methane medium”Dim rgx As New Regex(“me”, RegexOptions.IgnoreCase)Dim m As Matchm = rgx.Match(str)While m.Success

Console.WriteLine(“Found “ & m.Groups(1).Value & _“ at “ & m.Groups(1).Index.ToString())

m = m.NextMatch()End WhileConsole.WriteLine(“There were {0} matches”, m.Count)

Can also use IsMatch if you only care about whether there is any match.

18

RegEx: Splitting

A list of items in a string can be split or parsed into elements in an array.

Similar to the String.Split command, but vastly more powerful because of the expression matching.

In the example, the delimiter is any white space (space, return, tab, etc.). The pattern is given as “\s+”, where \s means white space, and the plus sign represents one or more contiguous such characters.

Dim str As String = “one,two,three,four”delim As String = “\s+”Dim rgx As Regex = New Regex(delim)Dim sArr() As String = rgx.Split(str)

19

RegEx: Replacing

Simple replacement is easy. Just enter the search and replace texts.

You can build substantially more complex replacements that conditionally replace text or even re-order elements. But that is tricky to code. The second example comes from the Help system: Example: Changing Date Formats.

Dim strInput As String = “Change (b) to (a). Again (b).”Dim strFinal As StringstrFinal = Regex.Replace(strInput, “(b)”, “(a)”)

Function MDYToDMY(input As String) As String Return Regex.Replace(input, _ "\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b", _ "${day}-${month}-${year}") End Function

20

RegEx: Pattern CharactersPattern Meaning Pattern Meaning

character Matches itself, except .$^{[(|)*+?\

\040 ASCII octal character

\a Alert/bell \x20 ASCII hex character

\b Backspace, or word boundary

\cC ASCII control char.

\t Tab \U0020 Unicode character

\r Return \* Quoted override, this specific character (asterisk). Note that in C# you often need to use two back-slashes.

\v Vertical tab

\f Form feed

\n New line

\e Escape

21

RegEx: Pattern Character ClassesPattern Meaning Pattern Meaning

[abcd] Any one of the characters in the list.

\s Any white space character: space, tab, form-feed, newline, return, or vertical feed

[^abcd] Anything except one of the characters in the list.

\S Any non-white space char.

[a-zA-Z] Any character in the specified range(s). Here, any lowercase or upper case letter.

\w A word character, equivalent to [a-zA-Z_0-9]

\d A decimal digit. Equivalent to [0-9]

\W A non word character.

\D A nondigit character. Equivalent to [^0-9]

22

RegExp: Position CharactersPattern Meaning Pattern Meaning

^ Beginning of the line \G Position where current search started. Useful for replacement.

$ End of the line \z The exact end of the string.

\A Beginning of the string. Similar to ^ but ignores Multiline option.

\Z The end of the string, or before the newline character. Similar to $ but ignores Multiline option.

\b Word boundary

\B Not on a word boundary

23

RegExp: QuantifiersPattern Meaning Pattern Meaning

* Zero or more characters.

[N,M] Between N and M matches

+ One or more characters

*? First match that uses as few repeats as possible.

? Zero or one match +? First match with as few repeats as possible, but at least one.

{N} Exactly N matches ?? Zero repeats if possible, or one.

{N,} At least N matches {N,}? As few repeats as possible, but at least N

{N,M}? As few repeats as possible, but between N and M.

24

RegExp: GroupingPattern Meaning

(substr) Find and number the substring

(?<name>substr) Find the substring and give it a name

$N Substitute last substring matched by group number N

${name} Substitute last matched substring by a ?<name>

(?(expr)yes | no) Conditional evaluation.

| (vertical bar) Either or

Also see: http://py-howto.sourceforge.net/regex/regex.html

25

Text Files You could use the old VB file commands, but avoid them. Instead, use the new class: System.IO

FileStream BinaryReader BinaryWriter StreamReader StreamWriter

Binary example (from help system)

Dim fs As FileStream = New FileStream("c:\data.txt", FileMode.CreateNew) Dim w As BinaryWriter = New BinaryWriter(fs) Dim r As BinaryReader = New BinaryReader(fs) Dim i As Integer ' Takes the series of integers and stores them in a buffer. For i = 0 To 11

w.Write(CStr(i)) Next ' Sets the pointer to the beginning of the file. w.Seek(0, SeekOrigin.Begin) ' Writes the contents of the buffer to the console. For i = 0 To 11

Console.WriteLine(CStr(i)) Next