Published on

Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Advanced web technologies - 12261 Book1 contains partModules of Book 1 Slide No.Module 1 : Introduction to Basic Windows programming using 2Module 2 : Programming Concepts 17Module 3: Streams And Files 71Module 4 : Exception Handling 80Module 5 : OO Programming Concepts 97Module 6 : Namespaces 111Module 7: Accessing Data with .Net 139Module 8: Multi threading - Concept and Program 170 Book 2 contains part compiled by RJ , 9892544177 1
  2. 2. Module 1: Introduction to Basic Windows programming using VB.netShort note on development/ history of 4m) Microsoft has developed many languages before reaching to the .NET framework: 1964 – BASIC Prob : no support for UI 1975 – QBASIC Prob : slow response time 1976 – VB 1.0 , the series progressed uptill VB 5.0 ( 1997) Adv : Allowed good UI development , component library to share code. Library files are in .dll format. 2000 – VB 6.0 Prob : lots of garbage code due to garbage collection. Viva Q : what is Garbage collection? Therefore, finally a new and clean implementation developed = .NET framework. compiled by RJ , 9892544177 2
  3. 3. What is .NET ? compiled by RJ , 9892544177 3
  4. 4. Coding the First Visual Basic .Net Application with out using IDE1. Open notepad. Create a new file save as “step1.vb”2. Type the following code in step1.vb fileImports System // predefined package in the .NET frameworkPublic Class Step1Shared Sub Main()System.Console.WriteLine(“We are engineering students”)End SubEnd Class compiled by RJ , 9892544177 4
  5. 5. 3. launch the command prompt fromStart, Programs, Microsoft Visual Studio .NET 7.0, Visual Studio .NET Tools menu.4. (To test the compilier is running or not)Before you compile at the command prompt, type vbc and press Enter5.o/p isMicrosoft (R) Visual Basic.NET Compiler version 7.00.9254for Microsoft (R) .NET CLR version 1.00.2914.16Copyright Microsoft Corp 2001. All rights reserved.Visual Basic Compiler Options compiled by RJ , 9892544177 5
  6. 6. Viva : why type vbc ?To check the following• Visual Basic.NET installed• We have the appropriate permission to run the compiler• The system was able to find the file vbc.exe. ie vb compiler6. Compile and make exeC:TYVBC1>vbc step2.vb /t:exe Microsoft (R) Visual Basic.NET Compiler version 7.00.9254 for Microsoft (R) .NET CLR version 1.00.2914.16 Copyright Microsoft Corp 2001. All rights reserved.7. Run the executableC:TYVBC1>step2 We are engineering students compiled by RJ , 9892544177 6
  7. 7. What are command line switches? ( 4m )Command line switches are used to configure the output according to application requirement.Eg. Of switches are3. /target or /t : < winexe or exe or library or module>8. /out : < filename >11. /help ( or /?) compiled by RJ , 9892544177 7
  8. 8. List different components of IDE and its use? (4m)Before we begin with the using the IDE we must set the profile. Choose profile”VB developer Profile”.The main components are :Toolbox : has window controls, common controls, containers, menus and toolbars, data , components, printing, Dialogs, WPF interoperability, reporting, Vb power packs.Command / immediate window.Server explorer : contains all data base components, used only when we have SQL or Ms Access .Solution explorer : all forms , its GUI components.The development area, where the Form appears. compiled by RJ , 9892544177 8
  9. 9. Create a simple form (window application). The application must acceptname and phone_number.The name field must raise an exception when the numeric is entered or it isleft blank. Similarly validate the phone_no field.Step 1: Create the project Using the menus, choose the File, New, Project command, bringing up the New Project dialog. Select the Windows Application icon and change the project name from WindowsApplication1 to name_phno. (name_phno.vb)Step 2: Develop the User- Interface.Step 3: logic : “Raising an exception” means using validating or validated event on the textbox where the user would enter the name and phone no.Sub TextBox1_Validating(… )Sub TextBox2_Validating (… )Viva Q : difference between validating and validated event. Validating checks for input moment we enter data. Validated checks only after we leave the field and go to the next field. 9 compiled by RJ , 9892544177
  10. 10. Use ErrorProvider control to report an error message.If TextBox1.Text = "" Then ErrorProvider1.SetError(TextBox1, "plz enter a name") e.Cancel = True Indicates that theElse error control If IsNumeric(TextBox1.Text) Then should be shown. ErrorProvider1.SetError(TextBox1, "plz enter a correct name") e.Cancel = True Else ErrorProvider1.SetError(TextBox1, "") End If End IfApply similar logic with textbox2.Step 4: Running the project : press play button or F5. compiled by RJ , 9892544177 10
  11. 11. Coding stepsErrorProvider1.SetError(TextBox1, "") -Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ? Handles Button1.ClickEnd End Sub Viva : difference between end and exitSub Form1_Load (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load compiled by RJ , 9892544177 11
  12. 12. Create a simple login having 2 textboxes – username and password.Password must have “vesp” as input only. Provide 2 buttons “submit ”and “exit”. Allow maximum 3 login attempts.Step 1 : choose window application and create the UI as reqd.Step2 : logic :Both text boxes i.e the Username and password must have some data.If TextBox1.Text = "" Or TextBox2.Text = "" Then MsgBox("enter all fields")No restriction on data entered in Username field – Textbox1Check data entered in textbox2 = “vesp” or not.If TextBox2.Text = "vesp" Then MsgBox("login successfull") compiled by RJ , 9892544177 12
  13. 13. Maximum 3 attempts indicates set up a counter variableAll validation must be done on “Submit button” , so put the code inSub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Every textbox experiences TextBox1_TextChanged event when we give input. We need not handle it , as the logic is not asking for any validation on typing. Assignment “: Develop application to validate for numeric input on typing. Handle TextBox1_TextChanged event. compiled by RJ , 9892544177 13
  14. 14. Create a window application to calculate SI. It shouldaccept P, N and R as inputs. Raise exception if no input ortext is entered.Step 1: Create a window application. Develop the UI.Step 2: logic :Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating If TextBox1.Text = "" Then Blank not allowed ErrorProvider1.SetError(TextBox1, "enter an amount") e.Cancel = True Else If IsNumeric(TextBox1.Text) Then No numbers allowed ErrorProvider1.SetError(TextBox1, "") Else ErrorProvider1.SetError(TextBox1, "enter an correct amount") e.Cancel = True End If End If compiled by RJ , 9892544177 14
  15. 15. Logic of PNR / 100 to find SI is implemented on click of a button. Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click MessageBox.Show(((TextBox1.Text * TextBox2.Text * TextBox3.Text) / 100)) end sub compiled by RJ , 9892544177 15
  16. 16. Create a window application which highlights theimportance of validating event over validated.Step 1: Create Window application with 2 textboxes.Step2 : logic :On Textbox 1 handle validated event.On Textbox 2 handle validating event.Sub TextBox1_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.ValidatedSub TextBox2_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox2.Validating compiled by RJ , 9892544177 16
  17. 17. Module 2: Programming Concepts > Variable types > Built –In functions > String functions > Console Based programming.Q> List with ranges the different types of variables supported by VB.NET. ( 4m )VARIABLES: Defn : A temporary storage location.5. Integer6. Numbers with Decimal Places7. Strings and Characters8. Boolean9. Date compiled by RJ , 9892544177 17
  18. 18. Data Type ( integer) Size (Bytes) RangeByte 1 0 to 255Short 2 -32,768 to 32,767Integer 4 -2,147,483,648 to 2,147,483,647Long 8 –9,223,372,036, 854,775,808, 9,223,372,036, 854,775,807 compiled by RJ , 9892544177 18
  19. 19. Data Type ( number with decimal places) Size (Bytes) RangeSingle 4 –3.402823 × 10^38 to –1.401298 × 10^–45Double 8 for negative numbers; 1.401298 × 10^–45 to 3.402823 × 10^38 for positive numbers –1.797693134 86231 × 10^308 to –4.940656458 41247 × 10^–324 for negative numbers; 4.940656458 41247 × 10^–324 to 1.797693134 86232 × 10^308 for positive numbers compiled by RJ , 9892544177 19
  20. 20. Data Type Size (Bytes) RangeChar 2 One characterString 10+2 Up to 2 Per billion character charactersData Type Size (Bytes) RangeBoolean 2 True or FalseDate 8 January 1, 100 to December 31,9999 compiled by RJ , 9892544177 20
  21. 21. Declaring VariablesDim sFirstName As StringDim dblGrossDomesticProduct As DoubleDim bLearned As BooleanDim dtDateOfMagnaCartaSigning As Date = #DEC 15, 2010#Dim lPeopleOnEarth As Long = 6000000000 compiled by RJ , 9892544177 21
  22. 22. WAP to declare 3 arrays of integer, date and string type resp. demonstrate different ways of initialing the array . ( 4m ) – Refer pg 14 of notes1 ‘Simple declaration2 Dim iValues(3) As Integer // note no ; at end3 Dim dtDates() As Date4 Dim I As Integer5 For I = 1 To 3 // 1st way of init an array.6 iValues(I-1) = I7 Next compiled by RJ , 9892544177 22
  23. 23. 8 ‘Changing the size of an existing array9 ReDim dtDates(4)10 ‘fill the list of dates of sem 6 TT11 dtDates(0)=”4/24/2011” ‘management // 2nd way of initzn12 dtDates(1)=”4/27/2011” ‘s/w testing or DCNE13 dtDates(2)=”5/03/2011” ‘AJP7 dtDates(3)=”5/06/2011” ‘AWT15 ‘Declaration with Initialization16 Dim sMonths() As String = {“Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”, _• “Jul”,”Aug”,”Sep”,”Oct”,”Nov”,”Dec”} // 3rd way of initzn18 ‘Using arrays14 Console.WriteLine(“”)20 Console.WriteLine(“Second value in iValues = {0}”, iValues(1))21 Console.WriteLine(“Third date in dtDates = {0}”, dtDates(2))22 Console.WriteLine(“Eleventh month of the year = {0}”, sMonths(10)) compiled by RJ , 9892544177 23
  24. 24. ConstantsConstants are declared using one of the two formsConst PI = 3.1415 As DoubleConst DSN As String = “Random” compiled by RJ , 9892544177 24
  25. 25. BUILT-IN FUNCTIONS Refer awt pracs > variablesFunction DescriptionCBool Converts to a Boolean. Anything that evaluates to False or 0 will be set to False; otherwise, it will be True.CByte Converts to a Byte. Any value greater than 255, or any fractional information,will be lost.CChar Converts to a single character. If the value is greater than 65,535, it will be lost. If you convert a String, only the first character is converted.CDate Converts to a Date. One of the more powerful conversion functions, CDate can recognize some of the more common formats for entering a date.CDbl Converts to a Double.CInt Converts to an Integer. Fractions are rounded to the nearest value.CLng Converts to a Long. Fractions are rounded to the nearest value.CSht Converts to a Short. Fractions are rounded to the nearest value.CStr Converts to a String. If the value is a Date, this will contain the Short Date format.CType Converts to any type. This is a powerful function that enables you to convert any data type into any other type. Therefore, the syntax for this function is slightly different than the others. compiled by RJ , 9892544177 25
  26. 26. Syntax of CType( )oNewVariable = CType(oOldVariable, NewType)In which oNewVariable and oOldVariable are placeholders for the variables that we’re converting to and from, respectively. NewType is the type you are converting to.Eg : convert object of customer to employee.Dim oCust As Customer = New Customer ( “a”, “b”)Dim oEmp As Employee = New Employee ( “c”, “d”)// here assuming that the no. and type of attributes is the same In both the classes.Then oEmp = CType( oCust, Employee ) ‘ converts compiled by RJ , 9892544177 26
  27. 27. Example : uses the CBool function to convert expressions to Booleanvalues. If an expression evaluates to a nonzero value, CBool returnsTrue; otherwise, it returns False.Example : uses the CByte function to convert an expression to a Byte. compiled by RJ , 9892544177 27
  28. 28. Example: uses the CChar function to convert the first character of a Stringexpression to a Char type.The input argument to CChar must be of data type Char or String. You cannot use CChar toconvert a number to a character, because CChar cannot accept a numeric data type. Thefollowing example obtains a number representing a code point (character code) and convertsit to the corresponding character. It uses the InputBox function to obtain the string of digits,CInt to convert the string to type Integer, and ChrW to convert the number to type Char. compiled by RJ , 9892544177 28
  29. 29. Example: uses the CDate function to convert strings to Date values.Example of Cdbl compiled by RJ , 9892544177 29
  30. 30. Example of Clng() functionExample : uses the CObj function to convert a numeric value to Object. TheObject variable itself contains only a four-byte pointer, which points to theDouble value assigned to it. compiled by RJ , 9892544177 30
  31. 31. CSng ExampleExample: uses the CStr function to convert a numeric value to String. compiled by RJ , 9892544177 31
  32. 32. Example: uses the CStr function to convert Date values to String values. Or short note on CStr()CStr always renders a Date value in the standard short format for the current locale, forexample, "6/15/2003 4:35:47 PM". However, CStr suppresses the neutral values of 1/1/0001for the date and 00:00:00 for the time.Date/Time Conversions. Use the IsDate function to determine if a value can be converted to adate and time. CDate recognizes date literals and time literals but not numeric values. Toconvert a Visual Basic 6.0 Date value to a Date value in Visual Basic 2005 or later versions,you can use the DateTime.FromOADate method. compiled by RJ , 9892544177 32
  33. 33. String Manipulation Functions : The following table lists the functionsthat Visual Basic provides to search and manipulate strings. compiled by RJ , 9892544177 33
  34. 34. compiled by RJ , 9892544177 34
  35. 35. Example : uses the UCase function to return an uppercase version of a string. Example : uses the LTrim function to strip leading spaces and the RTrim function to strip trailing spaces from a string variable. It uses the Trim function to strip both types of spaces. Refer awt pracs > Console Application3 35 compiled by RJ , 9892544177
  36. 36. Example: uses the Mid function to return a specified number of characters froma string.Example : uses Len to return the number of characters in a string. compiled by RJ , 9892544177 36
  37. 37. Example: uses the InStr function to return the position of the first occurrenceof one string within another. compiled by RJ , 9892544177 37
  38. 38. Home AssignmentA> Specify the string functions which would1> Check len of the sPassword .2> if sPassword is containing “ Engineering students” find the postn of string “students”.Hint : be case sensitiveStringdemo.vb compiled by RJ , 9892544177 38
  39. 39. How to develop a Console Based application.Select File > New > Project > Console application.Eg : A simple console Application which reads 5 integers and calculates average. Print the average number.Refer exp4 > Module2.vbReadline() and writeline() functions are predefined inNameSpace = Systems.consoleEg : Make a console application and accept input via InputBox.Refer exp4 > Module1.vb compiled by RJ , 9892544177 39
  40. 40. Develop console application for showing different date and time formats.Dateformatspecifiers.vb Refer > console Application 1 compiled by RJ , 9892544177 40
  41. 41. Programming user-defined Routines or FunctionsThere are 2 types of proceduresSubroutine ( or sub in coding )FunctionSub does not return any value1 Sub ShowMessage(ByVal Message As String)2 Console.WriteLine(Message)3 End Sub4 ShowMessage(“Hello World from Visual Basic .NET”) compiled by RJ , 9892544177 41
  42. 42. Eg. Of function Function returns some value 1 Private Function GetValue(ByVal Prompt As String) As String 2 Console.Write(Prompt) 3 Return Console.ReadLine 5 End Function Analysis :Develop a console based application showing how to interchange or swap numbers.Define a sub or function to swap.Refer exp4 > Module3.vb compiled by RJ , 9892544177 42
  43. 43. Define scope of a Variable. Describe it with all details. The scope of a declared element is the set of all code that can refer to it without qualifying its name or making it available through an Imports Statement (.NET Namespace and Type). An element can have scope at one of the following levels:These levels of scope progress from the narrowest (block) to the widest (namespace), wherenarrowest scope means the smallest set of code that can refer to the element withoutqualification. compiled by RJ , 9892544177 43
  44. 44. Specify the scope of an element when you declare it. The scope can depend on the following factors:• The region (block, procedure, module, class, or structure) in which you declare the element• The namespace containing the elements declaration• The access level you declare for the elementBlock ScopeA block is a set of statements enclosed within initiating and terminatingdeclaration statements, such as the following:Do and LoopFor [Each] and NextIf and End IfSelect and End SelectSyncLock and End SyncLockTry and End TryWhile and End WhileWith and End With compiled by RJ , 9892544177 44
  45. 45. The scope of the integer variable cube is the block between If and End If, and you can no longer refer to cube when execution passes out of the block.Note : Even if the scope of a variable is limited to a block, its lifetime is still that ofthe entire procedure. If you enter the block more than once during the procedure,each block variable retains its previous value.Procedure scope :An element declared within a procedure is not available outside that procedure. Only theprocedure that contains the declaration can use it. Variables at this level are also known aslocal variables. You declare them with the Dim Statement (Visual Basic), with or without theStatic (Visual Basic) keyword.Procedure and block scope are closely related. If you declare a variable inside a procedurebut outside any block within that procedure, you can think of the variable as having blockscope, where the block is the entire procedure. compiled by RJ , 9892544177 45
  46. 46. Module Scope• The single term module level applies equally to modules, classes, and structures. You can declare elements at this level by placing the declaration statement outside of any procedure or block but within the module, class, or structure.• When you make a declaration at the module level, the access level you choose determines the scope. The namespace that contains the module, class, or structure also affects the scope. Refer awt pracs > ScopeVar compiled by RJ , 9892544177 46
  47. 47. Namespace ScopeIf you declare an element at module level using the Friend (Visual Basic) orPublic (Visual Basic) keyword, it becomes available to all procedures throughoutthe namespace in which the element is declared. Public strMsg As String compiled by RJ , 9892544177 47
  48. 48. • Namespace scope includes nested namespaces. An element available from within a namespace is also available from within any namespace nested inside that namespace.• If your project does not contain any Namespace Statements, everything in the project is in the same namespace. In this case, namespace scope can be thought of as project scope. Public elements in a module, class, or structure are also available to any project that references their project. Access level or Visibility Modifiers applicable to variables 1. Public or Friend variables 2. Private or local variables 3. Protected – only used during Inheritance. 4. Shared 5. Static compiled by RJ , 9892544177 48
  49. 49. Advantages of Local Variables• Local variables are a good choice for any kind of temporary calculation, for the following reasons:• Name Conflict Avoidance. Local variable names are not susceptible to conflict. For example, you can create several different procedures containing a variable called intTemp. As long as each intTemp is declared as a local variable, each procedure recognizes only its own version of intTemp. Any one procedure can alter the value in its local intTemp without affecting intTemp variables in other procedures.• Memory Consumption. Local variables consume memory only while their procedure is running. Their memory is released when the procedure returns to the calling code. By contrast, Shared (Visual Basic) and Static (Visual Basic) variables consume memory resources until your application stops running, so use them only when necessary. Instance variables consume memory while their instance continues to exist, which makes them less efficient than local variables, but potentially more efficient than Shared or Static variables.Q> Develop a console application to demonstrate scope of variables in a module.variableScope.vb compiled by RJ , 9892544177 49
  50. 50. How to: Control the Scope of a Variable (Visual Basic or make a variable visible only within a block• Place the Dim Statement (Visual Basic) for the variable between the initiating and terminating declaration statements of that block, for example between the For and Next statements of a For loop.To make a variable visible only within a procedure• Place the Dim statement for the variable inside the procedure but outside any block (such as a While...End While block).To make a variable visible throughout a module, class, or structure• Place the Dim statement for the variable inside the module, class, or structure, but outside any procedure.• Include the Private (Visual Basic) keyword in the Dim statement.• You can refer to the variable from anywhere within the module, class, or structure, but not from outside it. compiled by RJ , 9892544177 50
  51. 51. To make a variable visible throughout a namespace • Place the Dim statement for the variable inside the module, class, or structure, but outside any procedure. • Include the Friend (Visual Basic) or Public (Visual Basic) keyword in the Dim statement. • You can refer to the variable from anywhere within the namespace containing the module, class, or structure.Example: Declares a variable at module level and limits its visibility to code within the module. compiled by RJ , 9892544177 51
  52. 52. Case study 1: The Investment Calculation Application To be done by students as Home practicalsI/O of The Investment Calculator:1 InvestCalc.exe2 Initial Balance: 100003 Annual Interest (e.g. for 5%, enter 5): 54 Monthly Deposit: 2005 Years of Investment: 3067 If you start with $10,000.00,8 and invest $200.00 per month9 for 30 years10 at 5% interest.11 Your final balance would be: $211,129.17 compiled by RJ , 9892544177 52
  53. 53. Logic to be implementedThe program requires the user to enter the four values (Initial Balance, Annual Interest, Monthly Deposit, and Years of Investment). In turn, the program calculates the final balance. This calculation is known as the Future Value (FV) calculation.The formula( given in Question) for Future Value isFV = MonthlyDeposit * (((1 + MonthlyInterest)^Months - 1 ) / MonthlyInterest ) + StartingBalance * ( 1 + MonthlyInterest )^MonthsFV = 200 * ( ( ( 1+5 /1200) ^ 360 – 1) / (5 / 1200) ) + 10000 * ( 1+ (5/1200) ) ^ 360 Refer awt pracs> ConsoleApplication2 compiled by RJ , 9892544177 53
  54. 54. Solution• Create new project in Visual Basic .NET. Select option “visual Basic Console Application”.( Visual Basic .NET creates a new project with one module.)2. Rename the file using the Solution Explorer. Right-click on the filename Module1.vb in the Solution Explorer and select Rename. Change the filename to modInvest.vb.3. Change the name of the Startup Object, also. Right-click on the project in the Solution Explorer and select Properties. On the General page, change the Startup Object to Invest. compiled by RJ , 9892544177 54
  55. 55. Controlling Flow in ProgramsVisual consists of two categories of control statements:1. Choice statements ( If , If-Else ,If-Elseif-Else, and select case)2. Looping statements• For..Next loop• while..End While loop• Do loop compiled by RJ , 9892544177 55
  56. 56. Choice statementsThe If statementSYNTAX:If <condition>Then Code to execute if the condition is trueEnd IfExample program for If statementDevelop Application : Following are the grading rule of the mark list:1) If the marks is greater than 80 then the student get higher first class2) If the marks less than 80 and greater than 60 then the student get first class3) If the marks less than 60 and greater than 40 then the student get second class4) The last condition is , if the marks less than 40 then the student fail.Refer loop demo > Windows Application 7 [change mark in the program] compiled by RJ , 9892544177 56
  57. 57. Boolean Expressions and Boolean Logic1. Comparison Operators: – >, greater than – <, less than – =, equal to – <>, not equal to – >=, greater than or equal to – <=, less than or equal to – Like Special characters that can be used with Like include * to indicate any number of additional characters ? to represent one character # to represent any digit (0–9) Ranges ([a-g], for example) to specify that any character within that range should be considered a match. compiled by RJ , 9892544177 57
  58. 58. Example program using If statement and Like operator (PatternMatcher.vb)1 Public Class PatternMatcher2 Shared Sub Main()3 Dim sInput As String4 Dim sPattern As String5 Dim sMatch As String67 System.Console.Write(“Please Enter A Pattern:”)8 sInput = System.Console.ReadLine()9 sPattern = sInput1011 System.Console.Write(“Please Enter A String To Compare Against:”)12 sInput = System.Console.ReadLine()13 sMatch = sInput14 compiled by RJ , 9892544177 58
  59. 59. 15 If sMatch Like sPattern Then16 System.Console.WriteLine(sMatch & “ Matched with “ & sPattern)17 Else18 System.Console.WriteLine(sMatch & “ did not Match with “ & sPattern)19 End If20 End Sub7 End Class compiled by RJ , 9892544177 59
  60. 60. Loops :Whenever you face a situation in programming to repeat a task forseveral times (more than one times ) or you have to repeat a task tillyou reach a condtition, in these situations you can use loop statementsto achieve your desired results.• FOR NEXT Loop, FOR EACH Loop , WHILE Loop and DO WHILE Loop are the Commonly used loops in Visual Basic.NET 2010 .FOR NEXT Loop :• The FOR NEXT Loop , execute the loop body (the source code within For ..Next code block) to a fixed number of times.• For var=[startValue] To [endValue] [Step] [loopBody] Next [var]var : The counter for the loop to repeat the steps.starValue : The starting value assign to counter variable .endValue : When the counter variable reach end value the Loop will stop .loopBody : The source code between loop body. compiled by RJ , 9892544177 60
  61. 61. Show a messagebox 5 times and each time you want to see how many timesthe message box shows. Logic : refer loop demo > windows application31. startVal=12. endVal = 53. For var = startVal To endVal4. show message5. Next var compiled by RJ , 9892544177 61
  62. 62. If you want to Exit from FOR NEXT Loop even before completing the loopVisual Basic.NET provides a keyword Exit to use within the loop body.Refer loop demo > Windows Application 4Nested For loopCreate a 2 dimensional array using 2 for loops.Refer loop demo > Windows Application 6While ..End WhileSyntax :While [condition][loop body]End WhileRefer loop demo > Windows Application 5 compiled by RJ , 9892544177 62
  63. 63. Logical Operators:Binary : AND, OR, and XORUnary :NOTViva : What is Short Circuiting Concept? To make Visual Basic .NET short-circuit a Boolean expression, we need to use alternative forms of the AND and OR operators, ANDALSO and ORELSE. compiled by RJ , 9892544177 63
  64. 64. Example program to test ANDALSO:ShortCircuiting.vb1 Public Class ShortCircuiting23 Shared Sub Main()4 If Test(“Left”) ANDALSO Test(“Right”) Then5 ‘do something6 End If7 End Sub89 Shared Function Test(sInput As String) As Boolean10 System.Console.WriteLine(sInput)11 Test = FALSE12 End Function1314 End Class compiled by RJ , 9892544177 64
  65. 65. WhileSearch.vb1 Imports System Demonstrate use of AND operator2 Public Class WhileExample4 Shared Sub Main()4 Dim iCounter As Integer = 05 Dim arrList(10) As String6 Dim iMatch As Integer = -17 Dim sMatch As String8 sMatch = “Chembur”9 arrList(0) = “thane”10 arrList(1) = “Chembur”11 arrList(2) = “Ghatkopar”12 arrList(3) = “dadar”13 arrList(4) = “Borivali”14 arrList(5) = “andheri”15 arrList(6) = “Nerul”16 arrList(7) = “Panvel”17 arrList(8) = “Belapur”18 arrList(9) = “Worli”19 While iCounter <= 9 AND iMatch = -1 65 compiled by RJ , 9892544177
  66. 66. 20 If arrList(iCounter) Like sMatch Then21 iMatch = iCounter22 Else23 iCounter = iCounter + 124 End If6 End While26 If iMatch <> -1 Then27 System.Console.WriteLine(“Matched “ & iMatch)28 End If29 End Sub31 End Class compiled by RJ , 9892544177 66
  67. 67. Do Loop:SYNTAX:DoCode to be executedLoop The syntax doesn’t specify any exit condition so the code will continue to execute forever.There are 2 forms :Do While iMatch = 3 // note : Truewala// Code to be executedLoopDo Until Not (iMatch = 3) // note : Falsewala‘iMatch <> 3 would have also workedLoop compiled by RJ , 9892544177 67
  68. 68. Q> Write a Program to read from a file using Do…Loop and .NetFramework classes.NOTE:Use two different objects, both part of the System.IO namespace of the .Net Framework, System.IO.File and System.IO.StreamReader.System.IO.File has methods like open(), openText() , openRead() , openwrite()System.IO.StreamReader : has methods like read() and readLine() compiled by RJ , 9892544177 68
  69. 69. 1 Public Class ReadFromFile23 Shared Sub Main()4 Dim sFileName As String5 Dim srFileReader As System.IO.StreamReader6 Dim sInputLine As String78 sFileName = “MySampleFile.txt”9 srFileReader = System.IO.File.OpenText(sFileName)10 sInputLine = srFileReader.ReadLine()11 Do Until sInputLine is Nothing12 System.Console.WriteLine(sInputLine)13 sInputLine = srFileReader.ReadLine()14 Loop15 End Sub16 End ClassNote : To run this code create a text file with sample content in the same directory as the compiled executable. [ file class in detail in module 3 ] compiled by RJ , 9892544177 69
  70. 70. Define Recursion with an example. (RecursiveFactorial.vb )1 Public Class RecursiveFactorial2 Shared Sub Main()3 Dim sInput As String4 Dim iInput As Integer5 Dim iCounter As Integer6 Dim iFactorial As Integer7 System.Console.Write(“Please Enter A Number: “)8 sInput = System.Console.ReadLine()9 iInput = CInt(sInput)10 System.Console.WriteLine(Factorial(iInput))11 End Sub1213 Shared Function Factorial(n as Integer) as Integer1415 If n = 1 Then16 Return 117 Else18 Return n * Factorial(n-1)19 End If20 End Function21 End Class compiled by RJ , 9892544177 70
  71. 71. Module 3: Streams And FilesStream : It is a flow of information that passes in some sequential manner. compiled by RJ , 9892544177 71
  72. 72. Methods of the File Class Methods Description Copy Copies a file. Create Creates a new file. CreateText A special version of Create that creates a text file. Delete Deletes a file. Exists Returns True if the file exists. Open Opens a file for reading, writing, or both. OpenRead Specialized version of Open that always opens the file for reading. Specialized version of Open that opens text files only for reading. OpenText This would be a handy shortcut if you were writing an application that needed to read configuration information, or a log file. OpenWrite Specialized version of Open that always opens the file for writing. compiled by RJ , 9892544177 72
  73. 73. Methods and Properties of FileStream. Viva : why use Filestream class over File class? Filestream class is having more defined methods for reading, writing.Name Description// PropertyLength Number of bytes in the file.Position The current position in the file.Close ( ) Closes the FileStream.Read ( ) Reads a number of bytes from the FileStream. The return value is an array.Seek ( ) Moves forward or backward through the file.Write ( ) Writes a number of bytes to the FileStream. compiled by RJ , 9892544177 73
  74. 74. Viva Q : We always read from StreamReader which reads with FileStreamThe Read method of the FileStream class deals with bytes.If you apply a StreamReader to the FileStream we can readinformation in the file as Chars or ints or whatever form they are. compiled by RJ , 9892544177 74
  75. 75. Important Methods of the StreamReaderName DescriptionClose Closes the StreamReader.Read Reads the next character from the Stream. (one character at a time.)ReadBlock Reads a block of characters from the Stream.ReadLine Reads the next line from the Stream. Viva : used wrt FilesReadToEnd Reads all the characters from the Stream at once. This is the fastest way to get all the information out of the Stream and into a variable. compiled by RJ , 9892544177 75
  76. 76. Eg 1: Reading from a File . List steps for creating a file.A> 1st create obj of FileStream, 2nd create obj StreamReader1 Dim oFile As FileStream2 Dim oReader As StreamReader3 Dim sContents As String5 oFile = New FileStream(“MyFile.txt”, FileMode.OpenOrCreate, FileAccess.Read)7 oReader = New StreamReader(oFile)9 sContents = oReader.ReadToEnd()7 oReader.Close()8 oReader = Nothing9 oFile = Nothing compiled by RJ , 9892544177 76
  77. 77. Writing to a Text File using StreamWriterName DescriptionClose Closes the StreamWriter.Write Writes to the Stream.WriteLine Writes to the Stream, ending the added information with a new line. compiled by RJ , 9892544177 77
  78. 78. Eg 2: Writing to a File1 Dim oFile As FileStream2 Dim oWriter As StreamWriter3 oFile = New FileStream(“MyFile.txt”, _4 FileMode.OpenOrCreate, FileAccess.Write)5 oWriter = New StreamWriter(oFile)6 ’Writes the Integer 123 to the file7 oWriter.Write(123)8 ’Writes the String “Customer” to the file9 oWriter.Write(“Customer”)10 ’Writes the String “Suven Consultants” to the file, next writes will be on a new line11 oWriter.WriteLine(“Suven Consultants”) //Writes on the new line12 oWriter.Close()13 oWriter = Nothing14 oFile = Nothing compiled by RJ , 9892544177 78
  79. 79. Example: Create a temporary file and writes some text to it. Then open the file,using System.IO.FileMode.Open; that is, if the file did not already exist, itwould not be created.1> The declaration of the Open isPublic Shared Function Open (path As String, mode As FileMode ) As FileStreamrefer awt pracs > file demo. compiled by RJ , 9892544177 79
  80. 80. Module 4 : EXCEPTION HANDLINGSyntax for Try…End Try ( or syntax for exception handling )Q. Write a program with intentional exception, so you can see how it works and do exception handling.Ans > compiled by RJ , 9892544177 80
  81. 81. 1 Module modExceptional2 Sub Main()3 Dim dDividend As Decimal = 54 Dim dDivisor As Decimal = 06 Dim dResult As Decimal = 08 dResult = dDividend / dDivisor7 System.Console.ReadLine()8 End Sub910 End Module compiled by RJ , 9892544177 81
  82. 82. The o/p of the above program through IDE compiled by RJ , 9892544177 82
  83. 83. The o/p of the above program through command prompt1 Unhandled Exception: System.DivideByZeroException:2 An exception of type System.DivideByZeroException was thrown.3 System.Decimal.Divide(Decimal d1, Decimal d2)4 at Exceptions.modExceptional.Main() in5 modExceptional.vb:line 6Note : Moment the program runs , as it contains an exception , the line at which an exception occurs Just-In-Time Debugging dialog opens. Select No. then we see the above o/p. compiled by RJ , 9892544177 83
  84. 84. Exception handling in the Above program1 Module modExceptional2 Sub Main()3 Dim dDividend As Decimal = 54 Dim dDivisor As Decimal = 05 Dim dResult As Decimal = 06 Try7 dResult = dDividend / dDivisor8 Catch Ex As Exception9 System.Console.WriteLine(“A division by zero error has occurred.”)10 System.Console.WriteLine(“Please check the divisor.”)11 End Try12 System.Console.ReadLine()13 End Sub14 End Module compiled by RJ , 9892544177 84
  85. 85. Q. Can try-blocks be nested. Demonstrate with program which writes days current time and date to a file.( 4m )1 Sub WriteToFile(ByVal FileName As String)2 Dim fsOut As System.IO.FileStream3 Dim strOut As System.IO.StreamWriter4 Try5 ‘Open the File Open, OpenCreate,6 fsOut = _ OpenRead,OpenWrite7 New System.IO.FileStream(FileName, _8 System.IO.FileMode.OpenOrCreate, _9 System.IO.FileAccess.Write)10 Try11 ‘Write to the file12 strOut = _ Today , now attributes13 New System.IO.StreamWriter(fsOut)14 strOut.Write(DateTime.Today.ToString())15 Catch eIO As Exception compiled by RJ , 9892544177 85
  86. 86. 16 Console.WriteLine(“Couldn’t write to file: {0}.”, FileName)17 End Try18 Catch eFile As Exception19 Console.WriteLine(“Couldn’t open file: {0}.”, FileName)20 End Try21 End Sub compiled by RJ , 9892544177 86
  87. 87. Raising Exceptions by using “Throw” keywordThe Throw Statement1 Dim oCust As Customer = New Customer(“abc”, “xyz”)3 Dim oEmp As Employee = New Employee(“abc1”, “xyz1”)// assumption …3 Dim oSomething As Object4 oSomething = oEmp5 If TypeOf oSomething Is Customer Then6 oCust = oSomething7 Else8 Throw New InvalidCastException(“Cannot assign an Employee to a Customer.”)9 End IfO/p: Opens dialog box (by the default debugger) with the message above. compiled by RJ , 9892544177 87
  88. 88. List all the exceptions that might occur when calling the File.Open method. OrAll exceptions related to file operationsTo test this procedure, try a number of specific exceptions. For example, change the filename to be:In a valid path, but select a file that doesnt exist.On a drive that doesnt exist.In a path that doesnt exist.On a drive that isnt ready. compiled by RJ , 9892544177 88
  89. 89. If no file name given If wrong file name given If Nothing entered Self explanatorycompiled by RJ , 9892544177 89
  90. 90. compiled by RJ , 9892544177 90
  91. 91. List all exceptions under the ArgumentException class.ArgumentException is thrown when a method is invoked and at least one of the passedarguments does not meet the parameter specification of the called method. ArgumentNullException whenever a null reference (Nothing in Visual Basic) ispassed to a method that does not accept it as a valid argument. ArgumentOutOfRangeException when the value of an argument is outside therange of acceptable values; for example, when the value "46" is passed as the monthargument during the creation of a DateTime. InvalidEnumArgumentException thrown when using invalid arguments that areenumerators. compiled by RJ , 9892544177 91
  92. 92. 92compiled by RJ , 9892544177
  93. 93. Home assignment2. Specify with e.g.. ( not complete code ) use of following exceptions• ArgumentNullException• ArgumentOutOfRangeException• IndexOutOfRangeException• OverflowException• FileNotFoundException compiled by RJ , 9892544177 93
  94. 94. An IndexOutOfRangeException exception is thrown when an attempt is madeto access an element of an array or collection with an index that is outside thebounds of the array or less than zero.• Make sure that the maximum index on a list is less than the list size• Make sure the index is not a negative number.• Make sure data column names are correct. Example : Uses a Try…Catch block to trap the IndexOutOfRangeException when index i is outside the array bounds, 0 to 3. The example displays the following:• Element at index 0: 3• Element at index 2: 5• Element at index -1: IndexOutOfRangeException caught• Element at index 4: IndexOutOfRangeException caught compiled by RJ , 9892544177 94
  95. 95. compiled by RJ , 9892544177 95
  96. 96. The exception that is thrown when an arithmetic, casting, or conversionoperation in a checked context results in an overflow. compiled by RJ , 9892544177 96
  97. 97. Module 5 : OO Programming Concepts compiled by RJ , 9892544177 97
  98. 98. Creating Classes:Step 1 > Open up Visual Studio .NET, and create a new Empty Project from under the Visual Basic Projects folder.Step 2 > Add Class from the project menu. This adds a new, empty class to the project.Step 3> The above class is empty , therefore put Properties into it. In Vb.NET property is a special method which is designed to assign and read values of class data. Each property has 2 methods get( ) and set( ). Get is used for retr values and set used for initzn it. 98
  99. 99. Eg . Of Set and Get methodsUnderstand a class definition , using constructor.Refer exp 4> module 4.vb – this console application does not use get() and set()Understand class definition with get() and set() , interface definition.Refer exp 5> module 4.vb compiled by RJ , 9892544177 99
  100. 100. Why to create Properties.• To create a property within a class, you can either create a field (i.e.. a Public variable), or you can create a Private variable and expose the Private variable using a Property statement.There are several reasons to expose properties through a Property statement.• You can create a read-only or write-only property, as opposed to a Public variable, which will always be read-write.• You can add error handling within a Property statement to check for invalid values being set. You cant check for invalid values when setting a Public variable because there is no code that runs in response to setting a Public variable.• You can expose calculated values as properties even if they are not stored as actual data within the class. compiled by RJ , 9892544177 100
  101. 101. Properties can be1> ReadOnly2> WriteOnly For a write-only propertyDim m_sPassword As StringPublic WriteOnly Property Password() // no rtype as no get methodSet(ByVal Value As String)m_sPassword = ValueEnd Set compiled by RJ , 9892544177 101
  102. 102. Develop the sub main () to instantiate an object of class Line .output : compiled by RJ , 9892544177 102
  103. 103. Overloading : By using Overloads keyword ahead of the Function or SubDefinition:Use:Refer exp 5 > module3.vbHow would we call these methods with different set of parameters.> compiled by RJ , 9892544177 103
  104. 104. Inheritance : Child class deriving properties from a parent, using keyword inherits Understand single Inheritance Refer exp 5 > module1.vb Understand multi level Inheritance Refer exp 5 > solved.vb Understand multiple Inheritance ( same as java using Class and Interface) Refer exp 5 > module2.vb compiled by RJ , 9892544177 104
  105. 105. Over riding• Derived classes inherit properties and methods defined in their base class. This is useful because it means you can reuse these items when appropriate for the class you are using. If the inherited member cannot be used "as is" you have the option of using the Overrides keyword to define a new implementation, provided that the property or method in the base class is marked with the Overridable keyword, or shadowing the member by redefining it in the derived class.• Overridden members are used to implement polymorphism.The following rules apply to overriding methods.• You can only override members that are marked with the Overridable keyword in their base class.• Properties and methods are NotOverridable by default.• Overridden members must have the same arguments as the inherited members from the base class.• The new implementation of a member can call the original implementation in the parent class by specifying MyBase before the method name. compiled by RJ , 9892544177 105
  106. 106. Q> what is the use of the k/w “Overridable ”. For a child class to override some part of the base class, that portion must be marked Overridable in the base class definition.1 Public Class Vehicle23 ‘Code removed for simplicity....45 Public Overridable Function Description() As String6 Return “This is my generic vehicle description!”7 End Function8 End Class910 Public Class Car11 Inherits Vehicle1213 ‘Code removed for simplicity....1415 Public Overrides Function Description() As String16 Return “This is my Car Description”17 End Function1819 End Class compiled by RJ , 9892544177 106
  107. 107. Example defines a base class, Payroll, and a derived class, BonusPayroll, which overrides an inherited method, PayEmployee. A procedure, RunPayroll, creates and then passes a Payroll object and a BonusPayroll object to a function, Pay, that executes the PayEmployee method of both objects. 107compiled by RJ , 9892544177
  108. 108. ConstructorsConstructors and destructors control the creation and destruction of objects.• To create a constructor for a class, create a procedure named Sub New anywhere in the class definition. To create a parameterized constructor, specify the names and data types of arguments to Sub New.Eg : Sub New(ByVal sString As String)Constructors can be overloaded, as in the following code:Sub New(ByVal sString As String, iInt As Integer)• When you define a class derived from another class, the first line of a constructor must be a call to the constructor of the base class, unless the base class has an accessible constructor that takes no parameters. A call to the base class containing the above constructor, for example, would be MyBase.New(sString). Otherwise, MyBase.New is optional, and the Visual Basic .NET runtime calls it implicitly. compiled by RJ , 9892544177 108
  109. 109. Q> How to define a constructor? (4m)Ans: The creation of a constructor for Vehicle classStep 1: create a method named New that is public and has no parameters.Public Sub New()End SubStep 2: Initialize internalvariables of the class.Step 3: to call the Baseclass constructor fro mThe child class compiled by RJ , 9892544177 109
  110. 110. • Finalize Methods and Destructors• For the majority of the objects that an application creates, the .NET Frameworks garbage collector implicitly perform all the necessary memory management tasks.• However, when you create objects that encapsulate unmanaged resources, you must explicitly release the unmanaged resources when you are finished using them in your application. The most common type of unmanaged resource is an object that wraps an operating system resource, such as a file, window, or network connection. Although the garbage collector is able to track the lifetime of an object that encapsulates an unmanaged resource, it does not have specific knowledge about how to clean up the resource. For these types of objects, the .NET Framework provides the Object.Finalize method, which allows an object to clean up its unmanaged resources properly when the garbage collector reclaims the memory used by the object. Implementing Finalize methods or destructors can have a negative impact on performance and you should avoid using them unnecessarily. compiled by RJ , 9892544177 110
  111. 111. Module 6 : Namespaces (similar to concept of Packages in Java) Viva : Q : why is it needed. Namespaces organize the objects defined in an assembly. Assemblies can contain multiple namespaces, which can in turn contain other namespaces. Namespaces prevent ambiguity and simplify references when using large groups of objects such as class libraries. Example of Name Spaces :Within a namespace, you can define items such as modules, interfaces,classes, delegates, enumerations, structures, and other namespaces. Youcannot define items such as properties, procedures, variables and events atthe namespace level. These items must be declared within containers such asmodules, structures, or classes. compiled by RJ , 9892544177 111
  112. 112. When should we use global Keyword.If you have defined a nested hierarchy of namespaces, code inside thathierarchy might be blocked from accessing the System namespace of the .NETFramework. The following example illustrates a hierarchy in which theSpecialSpace.System namespace blocks access to System.As a result, the Visual Basic compiler cannot successfully resolve the referenceto System.Int32, because SpecialSpace.System does not define Int32. You canuse the Global keyword to start the qualification chain at the outermost level ofthe .NET Framework class library. This allows you to specify the Systemnamespace or any other namespace in the class library. The following exampleillustrates this. 112 compiled by RJ , 9892544177
  113. 113. compiled by RJ , 9892544177 113
  114. 114. • Console: Enables reading and writing to the command-line. compiled by RJ , 9892544177 114
  115. 115. Eg: Using the Console Class for Input and Output .1 Imports System2 Public Class ConsoleTest3 Private Const ITEM_COUNT As Integer = 104 Shared Sub Main()5 Dim I As Integer6 Dim sItems(ITEM_COUNT) As String7 Console.WriteLine(“Please enter {0} items. “ & _8 Press ENTER between items.”, ITEM_COUNT)8 For I = 0 To ITEM_COUNT-19 sItems(I) = Console.ReadLine10 Next11 Console.WriteLine()12 Console.WriteLine(“Items in reverse order:”)14 For I = ITEM_COUNT - 1 To 0 Step -114 Console.WriteLine(sItems(I))15 Next16 End Sub17 End Class compiled by RJ , 9892544177 115
  116. 116. Redirection: sending the o/p and error messages or recv the i/pfrom a device or place other than the defaultDg :1 Imports System2 Imports System.IO3 Public Class ConsoleTest4 Private Const ITEM_COUNT As Integer = 105 Shared Sub Main()13 Dim I As Integer compiled by RJ , 9892544177 116
  117. 117. 6 Dim I As Integer7 Dim sItems(ITEM_COUNT) As String8 Dim oFile As TextWriter = File.CreateText(“Output.txt”)9 Dim oOut As TextWriter = Console.Out //Needed to reset the output back from file to monitor.10 Console.WriteLine(“Please enter {0} items. Press ENTER between items.”, ITEM_COUNT)11 For I = 0 To ITEM_COUNT-112 sItems(I) = Console.ReadLine13 Next14 Console.WriteLine()15 Console.SetOut(oFile)16 Console.WriteLine(“Items in reverse order:”)17 For I = ITEM_COUNT - 1 To 0 Step -118 Console.WriteLine(sItems(I))19 Next compiled by RJ , 9892544177 117
  118. 118. Running the application:1 [c:workconsole]Console2.exe2 Please enter 10 items. Press ENTER between items.3 Aardvark4 Bandicoot5 Cassowary6 Dugong7 Echidna8 Finch9 Giraffe10 Hippopotamus11 Iguana12 Jackalope1314 Done compiled by RJ , 9892544177 118
  119. 119. The code should produce a file Output.txt with the following contents:1 Items in reverse order:2 Jackalope3 Iguana4 Hippopotamus5 Giraffe6 Finch7 Echidna8 Dugong9 Cassowary10 Bandicoot11 Aardvark compiled by RJ , 9892544177 119
  120. 120. 2. Environment class Provides information about, and means to manipulate, the current environment and platform. This class cannot be inherited. Refer awt pracs >console application 4 120
  121. 121. 121compiled by RJ , 9892544177
  122. 122. compiled by RJ , 9892544177 122
  123. 123. compiled by RJ , 9892544177 123
  124. 124. Use the Environment class to retrieve information such as command-linearguments, the exit code, environment variable settings, contents of the callstack, time since last system boot, and the version of the common languageruntime. compiled by RJ , 9892544177 124
  125. 125. Methods and Properties of the Environment Class 125 compiled by RJ , 9892544177
  126. 126. 3. Random :Represents a pseudo-random number generator, a device that produces asequence of numbers that meet certain statistical requirements for randomness.Constructors : Methods 126 compiled by RJ , 9892544177
  127. 127. Eg . Random classDim oRand As New RandomDim iValue As Integer = oRand.Next(1, 100) compiled by RJ , 9892544177 127
  128. 128. 4. Collection Classes in the .NET Framework The .NET Framework provides specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables.4. A . ArrayList : Is a Array which can hold objects . Intially it is empty and has the default initial capacity. The size can dynamically change. Dim arrList As New ArrayList ‘creates a new ArrayList, with 16 members initially Dim arrList2 As New ArrayList(20) ‘ creates a new ArrayList, with 20 members initially Methods : add(int n ), retrieve(int n), and delete(int n) compiled by RJ , 9892544177 128
  129. 129. compiled by RJ , 9892544177 129
  130. 130. compiled by RJ , 9892544177 130
  131. 131. compiled by RJ , 9892544177 131
  132. 132. 4.b) Queue : A Queue is a “first-in, first-out” (FIFO) collection compiled by RJ , 9892544177 132
  133. 133. Queues are useful for storing messages in the order they were received forsequential processing. This class implements a queue as a circular array. Objectsstored in a Queue are inserted at one end and removed from the other.The capacity of a Queue is the number of elements the Queue can hold. Aselements are added to a Queue, the capacity is automatically increased asrequired through reallocation. The capacity can be decreased by callingTrimToSize.The growth factor is the number by which the current capacity is multiplied when agreater capacity is required. The growth factor is determined when the Queue isconstructed. The default growth factor is 2.0. The capacity of the Queue willalways increase by at least a minimum of four, regardless of the growth factor.For example, a Queue with a growth factor of 1.0 will always increase in capacityby four when a greater capacity is required.Queue accepts Nothing as a valid value and allows duplicate elements. compiled by RJ , 9892544177 133
  134. 134. compiled by RJ , 134 9892544177
  135. 135. 4.c) Stack: Is a “first-in, last-out” (FILO) or LIFO collection 135 compiled by RJ , 9892544177
  136. 136. 4.d SortedList: Represents a collection of key/value pairs that are sorted bythe keys and are accessible by key and by index.A SortedList object internally maintains two arrays to store the elements of thelist; that is, one array for the keys and another array for the associated values.Each element is a key/value pair that can be accessed as a DictionaryEntryobject. A key cannot be Nothing, but a value can be. compiled by RJ , 9892544177 136
  137. 137. compiled by RJ , 9892544177 137
  138. 138. compiled by RJ , 9892544177 138
  139. 139. Module 7: Accessing Data with .NetADO.Net:ADO.NET is the data access technology that is part of the .NET Framework• In .NET, database access is handled by the classes in and under the System.Data namespace.• The namespace is divided into two distinct areas: the System.Data.OleDB classes and the System.Data.SQLClient classes. The first set, System.Data.OleDB, is designed to allow you to connect to any database for which we have an OLEDB provider i.e an ODBC driver.• System.Data.SQLClient, is designed to work only with Microsoft SQL Server, compiled by RJ , 9892544177 139
  140. 140. Standard Database Tasks( # )1> Connecting to Database:Requires 2 elements the connection object and a connection string.// in java we have simply make a connection object by providing a data source name.• In ADO.NET, there are two different connection objects (one for OLEDB and one for SQL Server). Before you can start coding, you should obtain the proper connection string for your database. Which can be obtained by opening special file of Microsoft Datalink.• Follow these steps to create a Microsoft Datalink file (.udl ) and retrieve from it connection string information: compiled by RJ , 9892544177 140
  141. 141. • Create a blank Microsoft Data Link file by creating a new text file and renaming it to something with a .udl file extension (New.udl)• Double-click the new file, and a dialog appears with a set of four tabs for creating and editing the connection information for your database.• Using the dialog that has just opened, start with the first tab, Provider, and set up the correct information for your database: – For the Access database select the Microsoft Jet 4.0 provider. – For SQL Server database, select the Microsoft OLEDB Provider for SQL Server. Now the second tab “ Connection tab “, select the path For Access (.mdb file.) // this depends on provider. compiled by RJ , 9892544177 141
  142. 142. • Test the connection (by Clicking the Test Connection button )• If the test successful then close datalink properties window• open the .udl fileIt contains the following connection string for access database[oledb]; Everything after this line is an OLE DB initstringProvider=Microsoft.Jet.OLEDB.4.0;Data Source=student;Persist Security Info=FalseThe contents of a .udl file configured for SQL Server is[oledb]; Everything after this line is an OLE DB initstringProvider=SQLOLEDB.1;Password=password;Persist Security Info=True;User ID=sa;Initial Catalog=CD;Data Source=(local) compiled by RJ , 9892544177 142
  143. 143. • To create a connection, you need to create a new instance of either the System.Data.OleDB.OLEDBConnection or the System.Data.SqlClient.SQLConnectionA connection string to make connection with .mdb1 Module Module12 Private Const sConnection As String =”Provider=Microsoft.Jet.OLEDB.4.0;” &_8 “Data Source=C:CD.mdb;”&_4 “Persist Security Info=False”567 Sub Main()8 Dim objConn As New System.Data.OleDb.OleDbConnection(sConnection)9 End Sub10 End Module compiled by RJ , 9892544177 143
  144. 144. 2> Opening Connection1 Module Module12 Private Const sConnection As String = “Provider= Microsoft.Jet.OLEDB.4.0;” & _3 “Data Source=C:CD.mdb;”&_4 “Persist Security Info=False”5 Sub Main()6 Dim objConn As New System.Data.OleDb.OleDbConnection(sConnection)7 Try8 objConn.Open()9 Catch myException As System.Exception10 Console.WriteLine(myException.Message)11 End Try12 Console.ReadLine()13 End Sub14 End Module compiled by RJ , 9892544177 144
  145. 145. For Opening a connection with the SQLServerUse SQLClient classModify the above program :First: Remove the Provider section from your connection string andsecond : Change your objConn declaration to refer to the System.Data.SQLClient.SQLConnection object instead of the OLEDB class. compiled by RJ , 9892544177 145
  146. 146. Opening connection with SQL server #1 Imports System2 Module Module13 Private Const sConnection As String4 sConnection = “Password=password;” & _5 “Persist Security Info=True;” & _6 “User ID=sa;” & _7 “Initial Catalog=CD;” & _8 “Data Source=(local)”9 Sub Main()10 Dim objConn As New Data.SqlClient.SqlConnection(sConnection)11 Try12 objConn.Open()13 Catch myException As Exception14 Console.WriteLine(myException.Message)15 End Try16 Console.ReadLine()17 End Sub18 End Module compiled by RJ , 9892544177 146
  147. 147. 3. Executing a SQL Statement After a connection is established we can add, delete, modify, and retrieve records. To accomplish any of those tasks, you can use a command object (SQLCommand or OleDBCommand) to represent and then execute a SQLstatement.Steps are:a) Create a connection object using the connection string.b) Create a command object of OLEDB command or SQL command.c) Open connection with database. Refer exp6 > Application1d) Create object of OleDbDataAdapter.e) Use fill().This executes the query. DataSet can hold one or more table objects.f) Use DataGrid.Dataset cannot show the records of the table, use Datagrid compiled by RJ , 9892544177 147
  148. 148. Data Set (System.Data.DataSet). .NET provides a totally disconnected model of data access through the Data Set (System.Data.DataSet). Data Sets are capable of loading information, from a database and then disconnecting. Here the data becomes independent of its original source. This independence from the data source is why this information is considered disconnected and can be kept for as long as needed in a totally offline environment.Note: If u make changes to the dataSet does it affect the data source.Ans > compiled by RJ , 9892544177 148
  149. 149. 1. Getting Data into a Data Set :# To load data from the database into a DataSet, we will need a data adapter. The data adapter objects, SQLDataAdapter and OleDBDataAdapter, are designed to provide the glue or link between your database and a DataSet object. This link works in two parts, filling the DataSet, and then sending changes on the DataSet back to the data source to update the original data.Steps : 1> Create a connection object. 2> Create the appropriate data adapter class (OLEDB or SQL) 3> Use the desired SQL statement, or a command object that refers to the correct SQL, and the connection object in the constructor of the data adapter, and it will be completely set up i.e. Data Adapter object is installed. compiled by RJ , 9892544177 149
  150. 150. 4.To fill the dataset with the results of query, a DataSet object must first be created.Dim objDS As New DataSet(“dummy_dataSet”)5. To load the data into the DataSet, use the Fill method of the DataAdapter, but before that will work, the connection object must be opened successfully:objConn.Open()objDataAdapter.Fill(objDS, “Disc”) After the above code has executed, a table has been created inside the DataSet, with the name “Disc”, and filled with the results of your SQL query.6. To work with its contents through the DataSet’s Tables collection:Console.WriteLine(“{0} Rows”, objDS.Tables(“Disc”).Rows.Count) compiled by RJ , 9892544177 150
  151. 151. Viva : dataset is a disconnected model . Justify. As the DataSet is a disconnected object, you could have completely closed the connection to your database before working with the DataSet’s contents; therefore,objDataAdapter.Fill(objDS, “Disc”)objConn.Close()Console.WriteLine(“{0} Rows”, objDS.Tables(“Disc”).Rows.Count)o/p : compiled by RJ , 9892544177 151
  152. 152. 2. Navigation Data1> After populating the Data Set, we have to retrieve 1 table out of the data Set.( Note : why?Because Dataset is a collection of tables.) Dim objTable As DataTable objTable = objDS.Tables(“Disc”) The DataTable object provides two collections :1> The Rows collection, which contains all the records from the table, and the Columns collection, which contains a collection of DataColumn objects describing each individual field in the table. The Rows collection can be used in one of several ways to loop through all the records of the table: compiled by RJ , 9892544177 152
  153. 153. Eg 1: Using a For Each loopDim objRow As DataRowFor Each objRow In objTable.RowsConsole.WriteLine(objRow.Item(“CDTitle”)) // Item() retrieves attr valueNext // it takes index value or attr nameEg 2: Using a regular For loopDim i As IntegerDim objRow As DataRowFor i = 0 To objTable.Rows.Count - 1objRow = objTable.Rows(i)Console.WriteLine(objRow.Item(“CDTitle”)) compiled by RJ , 9892544177 153
  154. 154. The Columns collection contains details of the fields of the DataTable, each one represented as a DataColumn object. We can loop through the table’s fields using either a For Each or a For loop:Dim objColumn As DataColumnFor Each objColumn In objTable.ColumnsConsole.WriteLine(“Column Name: {0} Data Type: {1}”, _objColumn.ColumnName, _objColumn.DataType.FullName)Next Develop an application - creating a table dynamically in the program and showing it in the DataGrid. Do not connect to any Database. Refer Exp6 > application2 compiled by RJ , 9892544177 154
  155. 155. Home Assignment Develop an application having UI to navigate through the database. Connect to the Student table having at least 2 columns – Roll no. , name. Use DataView and CurrencyManager object.Refer Exp6> application3 Develop an application to generate an XML file representing the table. The table ( DataTable object ) is created by adding some Columns. To generate XML ( tags showing the schema of the table) , use GetXml() method over the DataSet object.Refer Exp7>consolbased compiled by RJ , 9892544177 155
  156. 156. Develop an application – creating table and writing its schema to an xml file. Use WriteXML ( String, WriteXMLMode )Refer exp 7 > empdetialAnother Example :Refer exp 7 > solved// this program contains Contact informationRefer exp 7 > studentinfo// this program contains student information compiled by RJ , 9892544177 156
  157. 157. 3> Editing Data (Add, Edit, Delete) using DataSet object When we modify the database through the DataSet the changes are not committed. The changes you make to the DataSet will be translated by the DataAdapter into the SQL statements that need to be executed against the database.DataAdapter.Update Method Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified DataSet from a DataTable named "Table."Namespace: System.Data.Common The update is performed on a by-row basis. For every inserted, modified, and deleted row, the Update method determines the type of change that has been performed on it (Insert, Update or Delete). Depending on the type of change, the Insert, Update, or Delete command template executes to propagate the modified row to the data source. When an application calls the Update method, the DataAdapter examines the RowState property, and executes the required INSERT, UPDATE, or DELETE statements iteratively for each row, based on the order of the indexes configured in the DataSet. compiled by RJ , 9892544177 157
  158. 158. For example, Update might execute a DELETE statement, followed by an INSERT statement, and then another DELETE statement, due to the ordering of the rows in the DataTable. If INSERT, UPDATE, or DELETE statements have not been specified, the Update method generates an exception. However, you can create a SqlCommandBuilder or OleDbCommandBuilder object to automatically generate SQL statements for single-table updates if you set the SelectCommand property of a .NET Framework data provider. Then, any additional SQL statements that you do not set are generated by the CommandBuilder.Working of the Update method:• The Update method retrieves rows from the table listed in the first mapping before performing an update. The Update then refreshes the row using the value of the UpdatedRowSource property. Any additional rows returned are ignored.• After any data is loaded back into the DataSet, the OnRowUpdated event is raised, allowing the user to inspect the reconciled DataSet row and any output parameters returned by the command. After a row updates successfully, the changes to that row are accepted. compiled by RJ , 9892544177 158
  159. 159. When using Update, the order of execution is as follows:• The values in the DataRow are moved to the parameter values.• The OnRowUpdating event is raised.• The command executes.• If the command is set to FirstReturnedRecord, then the first returned result is placed in the DataRow.• If there are output parameters, they are placed in the DataRow.• The OnRowUpdated event is raised.• AcceptChanges is called. compiled by RJ , 9892544177 159
  160. 160. Adapter has many properties To create the SQL query To check for any updatecompiled by RJ , 9892544177 160
  161. 161. • SelectCommandNote : properties of adapter object. • InsertCommand • UpdateCommand • DeleteCommand compiled by RJ , 9892544177 161
  162. 162. Refercompiled by RJ , 9892544177 162
  163. 163. Short note on OleDbCommandBuilder• The OleDbDataAdapter does not automatically generate the SQL statements required to reconcile changes made to a DataSet with the associated data source.• OleDbCommandBuilder object is needed to automatically generate SQL statements for single-table updates if you set the SelectCommand property of the OleDbDataAdapter.• The OleDbCommandBuilder registers itself as a listener for RowUpdating events whenever you set the DataAdapter property. You can only associate one OleDbDataAdapter or OleDbCommandBuilder object with each other at one time.• To generate INSERT, UPDATE, or DELETE statements, the OleDbCommandBuilder uses the SelectCommand property to retrieve a required set of metadata automatically.• The OleDbCommandBuilder also uses the Connection, CommandTimeout, and Transaction properties referenced by the SelectCommand. The user should call RefreshSchema if one or more of these properties are modified, or if the SelectCommand itself is replaced. Otherwise the InsertCommand, UpdateCommand, and DeleteCommand properties retain their previous values. compiled by RJ , 9892544177 163
  164. 164. 1. Adding Records After you have created a connection, created a data adapter, and loaded some data into your DataSet, you can directly access a DataTable object:objDataAdapter.Fill(objDS, “Disc”)Dim objTable As DataTableobjTable = objDS.Tables(“Disc”) After you have that DataTable, you can access its contents through the Rows collection, which returns a DataRowCollection object. Dim drRows As DataRowCollection drRows = objTable.Rows This object represents all the records in the table as a collection of DataRow objects. The collection itself provides a method, Add, to create new records. compiled by RJ , 9892544177 164
  165. 165. Adding a DataRow to a Data Table by passing of a DataRow Object as the Parameter to the Add Method of DataRow collection.1 Dim drRows As DataRowCollection //Contains all Rows2 Dim objNewRow As DataRow3 drRows = objTable.Rows //Returns all Rows45 ‘Assume - we have 3 columns6 ‘ArtistID7 ‘ArtistName8 ‘CDTitle910 objNewRow = objTable.NewRow() //Instantiating a new Row object with schema/structure of the ObjTable.11 objNewRow(“ArtistID”) = 312 objNewRow(“ArtistName”) = “Mohit Chawan” compiled by RJ , 9892544177 165
  166. 166. 13 objNewRow(“CDTitle”) = “NewYork”2 drRows.Add(objNewRow) //Adding new Row to the DataTableNote : These changes are reflected to the Database Server only after the update( ). compiled by RJ , 9892544177 166
  167. 167. Steps similar to adding records. objDataAdapter.Fill(objDS, “Disc”) Dim objTable As DataTable2. Editing Records: objTable = objDS.Tables(“Disc”) Dim drRows As DataRowCollection Dim objRow As DataRow drRows = objTable.Rows objRow = drRows(5) ‘ retriving the 5th row Each individual DataRow object has several methods for editing: BeginEdit, EndEdit, and CancelEdit. BeginEdit and EndEdit put the DataRow into and out of edit mode, which is a special state in which the row maintains information about the in-progress edit, and therefore change events will not fire for each individual field modification. For Eg: objRow.BeginEdit() objRow(“student_name”) = “Suven” objRow.EndEdit() compiled by RJ , 9892544177 167
  168. 168. 3. Deleting Records:objDataAdapter.Fill(objDS, “Disc”)Dim objTable As DataTableobjTable = objDS.Tables(“Disc”)Dim drRows As DataRowCollectionDim objRow As DataRowdrRows = objTable.RowsobjRow = drRows(3) // Retreiving 3rd rowobjRow.delete() // or drRows.Remove(3)Note : Remove() used when changes are not to be committed to the database. Therefore used delete(). compiled by RJ , 9892544177 168
  169. 169. Demonstrate use of adapter.DeleteCommand and ExecuteNonQuery()Imports System.Data.SqlClientPublic Class Form1Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.ClickDim connetionString As StringDim connection As SqlConnectionDim adapter As New SqlDataAdapterDim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"connection = New SqlConnection(connetionString)sql = "delete product where Product_name =Product7"Try Refer awt pracs>DB Navigationconnection.Open()adapter.DeleteCommand = connection.CreateCommandadapter.DeleteCommand.CommandText = sqladapter.DeleteCommand.ExecuteNonQuery()MsgBox("Row(s) deleted !! ")Catch ex As ExceptionMsgBox(ex.ToString)End TryEnd Sub compiled by RJ , 9892544177 169End Class
  170. 170. Module 8: Multi threading - Concept and Program Multithreading is new to VB .NET. The .NET Framework, and thus VB.NET provides full support for multiple execution threads in a program. You can add threading functionality to your application by using the System.Threading namespace. – A thread in .NET is represented by the System.Threading.Thread class. We can create multiple threads in our program by creating multiple instances (objects) of this class. – A thread starts its execution by calling the specified method and terminates when the execution of that method gets completed. We can specify the method name that the thread will call when it starts by passing a delegate of the ThreadStart type in the Thread class constructor. The delegate System.Threading.ThreadStart may reference any method which has the void return type and which takes no arguments. compiled by RJ , 9892544177 170
  171. 171. Example below does not use Multithreading Public Sub Main() Fun1() Fun2() The output of the program is: Console.WriteLine("End of Main()") End Sub Fun1() writes: 1 Public Sub Fun1() Fun1() writes: 2 Dim i As Integer Fun1() writes: 3 For i = 1 To 5 Fun1() writes: 4 Console.WriteLine("Fun1() writes: {0}", i) Fun1() writes: 5 Next Fun2() writes: 10 Fun2() writes: 9 End Sub Fun2() writes: 8 Public Sub Fun2() Fun2() writes: 7 Dim i As Integer Fun2() writes: 6 For i = 10 To 6 Step -1 End of Main() Console.WriteLine("Fun2() writes: {0}", i) Next End Sub compiled by RJ , 9892544177 171
  172. 172. The method Fun2() only started its execution when Fun1() had completed itsexecution. This is because when a method gets called, the execution controltransfers to that method. And when the method returns the execution startsfrom the very next line of the code that called the method. i.e. the programimplicitly has only one execution path. Using multithreading, we can definemultiple concurrent execution paths within our program called threads.For example, we can use threads so that the two methods Fun1() andFun2() may execute without waiting for each other to terminate. Imports System.Threading Public Sub Main() Dim firstThread As New Thread(New ThreadStart(AddressOf Fun1)) Dim secondThread As New Thread(New ThreadStart(AddressOf Fun2)) firstThread.Start() secondThread.Start() Console.WriteLine("End of Main()") End Sub compiled by RJ , 9892544177 172
  173. 173. Public Sub Fun1() Here we have created two instancesDim i As Integer of the Thread class and passed aFor i = 1 To 5 ThreadStart type delegate in the constructor which references aConsole.WriteLine("Fun1() writes: {0}", i) method in our program. It is important that the methodNext referenced in the Thread classEnd Sub constructor, through the ThreadStart delegate is parameter-less and has no return type.Public Sub Fun2() We have to start the execution of aDim i As Integer thread by calling the Start() methodFor i = 10 To 6 Step -1 of the Thread class.Console.WriteLine("Fun2() writes: {0}", i) The output of the program would now be interleaving Fun1 () and Fun2()NextEnd SubEnd Module compiled by RJ , 9892544177 173
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.