Programming in visual basic Visual Basic Building Blocks
Embed Size (px)
Transcript of Programming in visual basic Visual Basic Building Blocks
PROGRAMMING IN VISUAL BASIC .NETVISUAL BASIC BUILDING BLOCKSBilal Munir Mughal*Chapter-5
In this chapter*Terminology You Must KnowUnderstanding NamespacesError HandlingIntroduction to Debugging
Objects and Classes*Objects belong to classesAll objects with the same characteristics (data and functions) constitute one class.A class and an object of that class has the same relationship as a data type and a variableDeclaring a class doesnt create any objects, just as mere existence of data type int doesnt create any variables.
Objects and Classes*A class serves only as a plan, or a template, or sketch of a number of similar things. It merely specifies what data and what functions will be included in objects of that class.A class is thus a description of a no. of similar objects.For instance, HUMAN is a class, and JOHN is its instance (object)
Understanding Members*In Visual Basic, the definition of a class may include properties, methods, and events. Collectively these parts of an object are known as its members.The modifiers (such as Public and Private) that precede the member definition are used to control the access to the member. For example, Private members cannot be accessed from VB code outside the class definition, but Public members can be. (discussed in Chapter 8)
Understanding Method Types*Methods are units of code within a class that perform a task, but they come in several different forms.The following are all statements that indicate execution of a method:Invoke a methodCall a functionExecute a procedure (or subroutine)Fire an eventEach of these statements is a variation on the same thing but has a specific connotation.
Understanding Method Types*The two most common types of methods are functions and subroutines.A function has a value, much like a mathematical function. A declaration at the end of the function declaration indicates the type of value returned by the function.(A function in VB also may have input parameters that control the return value.)Unlike the function, the subroutine itself does not have a value. However, it can still send values back to the caller using output parameters.
Understanding Method Types*Private Function GetCurrentTime(Optional ByVal IncludeSeconds As Boolean = True) As String If IncludeSeconds = False Then Return Format(Now, "hh:mm") Else Return Format(Now, "hh:mm:ss") End If End Function---------------------------------------------------------------------------------------------------------------------Private Sub GetCurrentTime(ByRef CurrentTime As String, Optional ByVal IncludeSeconds As Boolean = True) If IncludeSeconds = False Then CurrentTime = Format(Now, "hh:mm") Else CurrentTime = Format(Now, "hh:mm:ss") End If End Sub
Understanding Method Types*The following lines of code show how to call the function and subroutine. In each case, the output value of the GetCurrentTime method is assigned to a string variable, ReturnValue.
ReturnValue = GetCurrentTime(False) 'Calls the function GetCurrentTime(ReturnValue,False) 'Calls the sub
Understanding Events*An event is something external to your program e.g. when the user clicks a button he is causing an event. Windows applications are inherently event-driven, meaning that the flow of program execution is controlled by the events that occur as the program is running. The user or system can initiate events in any order. For example the user may click a button, scroll a list box, or close a window.
Selecting an Event Handler*The event handler is a special type of method that allows you to write code to respond to events.When an event fires it executes the procedure that handles the event. When the user clicks a button he is causing an event within the program, so there is an associated method that handles that event.When an object/event combination occurs at runtime and code has been written for that combination, Visual Basic executes the code. Otherwise, Visual Basic ignores the event.
Understanding Assembly & Namespace*The higher-level groupings (Above classes) :
An assembly provides a fundamental unit of physical code grouping. e.g. Each time you create an Application, Service, Class Library, with Visual Basic .NET, you're building a single assembly. Each assembly is stored as an .exe or .dll file.
Understanding Assembly & Namespace*A namespace provides a fundamental unit of logical code grouping.Namespaces do not replace assemblies, but.complement them
Examples of NamespacesNamePurposeSystem.MathMathematical functionsSystem.Drawing.GraphicsDrawing lines, and so onSystem.Windows.FormsWindows FormsSystem.Net.SocketsTCP Sockets
Error Handling*Syntax errors: are generally caught while you are typing the code and can be fixed easily because Visual Studio tells you it doesn't understand what you typed.Logic errors: can usually appear only after you compile and run your code. They can be identified by incorrect operation of the program and are fixed by examining and then correcting an erroneously designed section of code e.g. division by zeroRuntime errors:usually occur due to reasons beyond programmer's control (hence an exception to the normal process and order of code execution) e.g. File not found
Structured Error Handling with Exceptions*An exception is thrown back to the function that called it. You can write code to catch the exception and then handle the error appropriately.TryFile.Copy("myfile.txt", "yourfile.txt")MessageBox.Show("The file has been copied")
Catch FileMissingError As FileNotFoundExceptionDim strMessage As String
strMessage = FileMissingError.MessagestrMessage = strMessage & "Please make sure this file exists and try again.strMessage = strMessage & "The program will now exit.
MessageBox.Show(strMessage, "Error has occurred", MessageBoxButtons.OK, MessageBoxIcon.Error)
Unstructured Error Handling with On Error Goto (old syntax)* Dim Answer As DialogResult = DialogResult.Retry
On Error GoTo FileCopyErrorRetryHere: File.Copy("myfile.txt", "yourfile.txt") MessageBox.Show("The file has been copied") Answer = DialogResult.OK Exit Sub
FileCopyError: Dim strMessage As String If Err.Number = 53 Then strMessage = "Missing file: " & Err.Description Else strMessage = "Error " & Err.Number & ": " & Err.Description End If Answer = MessageBox.Show(strMessage, "Error has occurred") If Answer = DialogResult.Retry Then Resume RetryHere Else Application.Exit() End If
Introduction to Debugging*To help track down bugs in your program, Visual Basic provides several tools:
Breakpoints tell the debugger that an application should break, pause execution, at a certain point. When a break occurs, your program and the debugger are said to be in break mode. The Immediate window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging.The Output window can display status messages for various features in the integrated development environment (IDE). Watch You can use the Watch window to evaluate variables and expressions and keep the results. You can also use the Watch window to edit the value of a variable or register.
*Q & A?
The object is selected in the Code window's upper-left drop-down list box (the Class box); the appropriate event procedure is selected in the upper-right drop-down list box (the Method box). you enter a Code window by double-clicking an object, the Code window automatically selects that object's most commonly used event procedure. For example, if you double-click a command button at design time, the Code window is opened to that command button's Click event procedure.*The .NET Framework uses assemblies as the fundamental unit for several purposes:SecurityType IdentityReference ScopeVersioningDeployment*Imports System.Net
Dim skListen As System.Net.Sockets.Socket orDim skListen As Socket ***When an error has occurred, you use one of several statements to control the flow of the program:Exit the subroutine after informing the user of the error, with the Exit Sub statement.Use a Resume label statement to jump to another portion of codeUse a Resume Next statement to continue executing on the line following the error.**