Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1.NET Web Forms Language Fundamentals © 2002 by Jerry Post."— Presentation transcript:

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

2 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 3 Primitive Data Types Class NameDescriptionVisual BasicC# 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 BooleanTrue or FalseBooleanbool 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 4 Data Type Details Balena p. 96 VB.NETBytesValues ByteSystem.Byte10 to 255 (unsigned) ShortSystem.Int162-32,768 to 32,767 IntegerSystem.Int324-2,147,483,648 to 2,147,483,647 LongSystem.Int6489,223,372,036,854,775,808 SingleSystem.Single4-1.401298 E-45 to 3.402823 E38 DoubleSystem.Double8+/- 4.94 E-324 to +/- 1.7977 E308 BooleanSystem.Boolean4True/False CharSystem.Char20 to 65535 (unsigned) DateSystem.DateTime81/1/CE 12/31/9999 DecimalSystem.Decimal12+/- 7.9228 … (28 decimal digits) ObjectSystem.Object4Main parent holds all types. StringSystem.String10 + 2*length 0 to ~ 2 B Unicode chars

5 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 6 Data Type Conversion Dim i As Integer = 13 Dim 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 7 VB Classes Public Class Customer Public Title As String Public LastName As String Public FirstName As String Private Password As String Public Sub SetPassword(inPassword As String) ‘ Encrypt it Password = SomethingEncrypt(inPassword) End Sub Public Function TestPassword(inPassword As String) As Boolean Dim tstPass As String = SomethingEncrypt(inPassword) Return (tstPass = Password) End Function End Class Public Class CorpCustomer Inherits Customer Public OurSalesPerson As String End Class

8 8 C# Classes public class Customer { public string Title; public string LastName; public string FirstName; private string Password; public void SetPassword(string inPassword) { // Encrypt it Password = SomethingEncrypt(inPassword); } Public bool TestPassword(string inPassword) { string tstPass = SomethingEncrypt(inPassword); return (tstPass == Password); } public class CorpCustomer : Customer { public string OurSalesPerson; }

9 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 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 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 Boolean j += 3‘ Note shortcut notation ‘ But calling value is not changed Return (j > 4) End Function

12 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 Doto 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 13 Conditions if ( ) { // true } else { // false } switch (myVar) { case 1: // code 1 case 2: // code 2 default: // code 3 } C# If ( ) Then ‘ true Else ‘ false End If Select Case myVar Case 1 ‘ code 1 Case 2 ‘ code 2 Case Else ‘ code 3 End Select VB

14 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 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. Try x = y/z Catch e As Exception ‘ Error is in e.Message End Try Try x = y/z Catch e As DivideByZeroException ‘ Error is in e.Message Catch e As OverFlowException … Catch... End Try Try cnn.Open … Catch e As Exception ‘ Error is in e.Message Finally cnn.Close() End Try

16 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 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 Match m = rgx.Match(str) While m.Success Console.WriteLine(“Found “ & m.Groups(1).Value & _ “ at “ & m.Groups(1).Index.ToString()) m = m.NextMatch() End While Console.WriteLine(“There were {0} matches”, m.Count) Can also use IsMatch if you only care about whether there is any match.

18 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 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 String strFinal = Regex.Replace(strInput, “(b)”, “(a)”) Function MDYToDMY(input As String) As String Return Regex.Replace(input, _ "\b(? \d{1,2})/(? \d{1,2})/(? \d{2,4})\b", _ "${day}-${month}-${year}") End Function

20 20 RegEx: Pattern Characters PatternMeaningPatternMeaning characterMatches itself, except.$^{[(|)*+?\ \040ASCII octal character \aAlert/bell\x20ASCII hex character \bBackspace, or word boundary \cCASCII control char. \tTab\U0020Unicode character \rReturn\*Quoted override, this specific character (asterisk). Note that in C# you often need to use two back-slashes. \vVertical tab \fForm feed \nNew line \eEscape

21 21 RegEx: Pattern Character Classes PatternMeaningPatternMeaning [abcd]Any one of the characters in the list. \sAny white space character: space, tab, form-feed, newline, return, or vertical feed [^abcd]Anything except one of the characters in the list. \SAny non-white space char. [a-zA-Z]Any character in the specified range(s). Here, any lowercase or upper case letter. \wA word character, equivalent to [a-zA-Z_0-9] \dA decimal digit. Equivalent to [0-9] \WA non word character. \DA nondigit character. Equivalent to [^0-9]

22 22 RegExp: Position Characters PatternMeaningPatternMeaning ^Beginning of the line\GPosition where current search started. Useful for replacement. $End of the line\zThe exact end of the string. \ABeginning of the string. Similar to ^ but ignores Multiline option. \ZThe end of the string, or before the newline character. Similar to $ but ignores Multiline option. \bWord boundary \BNot on a word boundary

23 23 RegExp: Quantifiers PatternMeaningPatternMeaning *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 24 RegExp: Grouping PatternMeaning (substr)Find and number the substring (? substr)Find the substring and give it a name $NSubstitute last substring matched by group number N ${name}Substitute last matched substring by a ? (?(expr)yes | no)Conditional evaluation. | (vertical bar)Either or Also see: http://py-howto.sourceforge.net/regex/regex.htmlhttp://py-howto.sourceforge.net/regex/regex.html

25 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


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

Similar presentations


Ads by Google