Creating Your Own Procedures

As you write Visual Basic .NET applications, you'll want to break your code up into manageable “chunks.” This shouldn't be a new concept to you, and it should make sense. The larger the blocks of code you're working with, the harder it is to debug, maintain, and manage the code. You've seen several examples of this throughout this chapter already.

The building block of Visual Basic .NET code is the procedure. A procedure has a beginning (a declaration), a middle (the code inside the procedure) and an end (the End Sub statement, for example). As you'll see throughout this book, there are a number of types of procedures, but for now, we'll focus on Sub and Function procedures.

A Sub procedure is a block of code that includes code, takes some action, but doesn't return a value. A Function procedure takes some action but returns a single value. So far, you've seen event procedures—Sub procedures that run in reaction to events on pages.

Why use procedures? Certainly, if you find that you're writing the same lines of code in multiple places, you would want to create a procedure you could call from all the places you would otherwise use the code and copy that code into the new procedure.

If you double-click the Creating Procedures button on the VBLanguage.aspx Web Form, it will lead you to the procedure shown in Listing 7.5.

Listing 7.5. Procedures Are Useful for Breaking Up Code into More Manageable Chunks
Private Sub ProceduresSample()
  Dim strConn As String

  ' Call a procedure that
  ' doesn't return a value.
  InitControls()

  ' Call a Function to Return a Value
  strConn = ConnectStringBuild("BJones", "password")

  Response.Write("strConn = " & strConn & "<BR><BR>")
End Sub

The InitControls procedure is a simple Sub that takes an action (hiding a control) and returns no value at all:

Private Sub InitControls()
  ' Demonstrate a procedure
  ' that doesn't return a value.
  btnDataTypes.Visible = False
End Sub

The ConnectStringBuild procedure allows you to pass parameters, making it possible to create generalized functionality. VB6 developers should note that all parameters are passed by value in VB .NET, unless you specify otherwise using the ByRef keyword. (This is the exact opposite of the way VB6 works.) In addition, if you don't specify ByRef or ByVal, Visual Studio .NET inserts the ByVal keyword for you. The ConnectStringBuild procedure provides an example of this, allowing you to specify two parameters that the procedure uses in creating an appropriate ADO.NET connection string:

Private Function ConnectStringBuild( _
 ByVal LoginID As String, _
 ByVal Password As String) As String
  Return String.Format("Provider=sqloledb;" & _
   "Data Source=(local);Initial Catalog=Northwind;" & _
   "User ID={0};Password={1}", LoginID, Password)
End Function

Creating Classes

Creating your own classes allows you to encapsulate behavior in a reusable fashion and allows you to provide the templates for creating multiple instances of an object based on the template. That is, using classes, you can create your own additions to the base class library provided by the .NET Framework—every single object you use in your applications is based on some class, created by some developer, describing the behavior of that object.

The techniques for creating classes in VB .NET haven't changed much since VB6, although you can now have more than one class per file. You still need to create properties, methods, and possibly events. Methods and event declarations have not changed much since VB6, but creating properties requires a slightly different syntax.

As an example, we've provided the LoginInfo class, which provides LoginID, Password, and DataSource properties, and the ConnectStringBuild method.

Double-click Creating Classes on the VBLanguage.aspx Web Form to find a procedure that creates an object of the LoginInfo type. The definition for this class also resides in the VBLanguage.aspx file, just below the end of the Web Form's class. The code for this class is shown in Listing 7.6.

Listing 7.6. Classes Can Be Used to Group Data with Procedures That Interact with That Data
Public Class LoginInfo
  Private mstrLoginID As String
  Private mstrPassword As String
  Private mstrDataSource As String

  Property LoginID() As String
    Get
      Return mstrLoginID
    End Get
    Set(ByVal Value As String)
      mstrLoginID = Value
    End Set
  End Property

  Property Password() As String
    Get
      Return mstrPassword
    End Get
    Set(ByVal Value As String)
      mstrPassword = Value
    End Set
  End Property

  Property DataSource() As String
    Get
      Return mstrDataSource
    End Get
    Set(ByVal Value As String)
      mstrDataSource = Value
    End Set
  End Property

  Public Function ConnectStringBuild() As String
    Return String.Format("Provider=sqloledb;" & _
      "Data Source=(local);Initial Catalog=Northwind;" & _
      "User ID={0};Password={1}", Me.LoginID, Me.Password)
  End Function
End Class

To use this class, you will declare a new instance of it, set the properties you require, and then invoke the ConnectStringBuild method to have it return the value. Listing 7.7 shows an example of creating and using a class.

Listing 7.7. Using Your Own Class Is as Simple as Declaring a New Instance of the Class
Private Sub ClassSample()
  Dim oLogin As New LoginInfo()

  With oLogin
    .LoginID = "BJones"
    .Password = "password"
    .DataSource = "(local)"

    Response.Write("ConnectString=" & _
      .ConnectStringBuild() & "<BR>")
  End With
End Sub

One problem with the LogInfo class, as it stands, is that you must create a unique instance of the class each time you want to generate the connection string. Sometimes, you may want to be able to call a method of a class without needing to instantiate the object yourself. For example, when you used the String.Format method, you didn't need to create a String object variable, set it equal to a new String object, and then work with the object. The String class provides the Format method (among many of its methods) in a special way that allows the .NET Framework to instantiate an object for you, as necessary. By adding the Shared keyword to a method, you won't need to create an instance of the parent object before calling the method—the .NET Framework will handle this for you.

We've provided a class, in DataHandler.vb, that we'll use throughout many examples (and we'll expand the class as necessary). This class provides a shared ConnectStringBuild method—you pass it user ID and password values, and the method returns the appropriate connection string. The important thing to remem-ber is that because the method is shared, you needn't create an instance of the DataHandler class—simply call the method, and the .NET Framework will do the work for you.

The following procedure, called when you click Classes with Shared Methods on VBLanguage.aspx, calls the ConnectStringBuild method of the DataHandler class. Note that the code never creates an instance of the DataHandler class because the ConnectStringBuild method is shared. Here's the code:

Private Sub SharedMethodSample()
  Dim strConn As String

  strConn = _
   DataHandler.ConnectStringBuild("Bjones", "Password")

  Response.Write(strConn)
End Sub

The definition for the DataHandler class can be found in the DataHandler.vb file within the VBLanguage.sln solution. This class looks like this:

Public Class DataHandler
  Public Shared Function ConnectStringBuild( _
   ByVal LoginID As String, _
   ByVal Password As String) As String
    Dim strConn As String

    If LoginID = String.Empty Then
      LoginID = "sa"
    End If
    strConn = String.Format("Provider=sqloledb;" & _
     "Data Source=(local);Initial Catalog=Northwind;" & _
     "User ID={0};Password={1}", LoginID, Password)

    Return strConn
  End Function
End Class

Applying What You Learned

Let's now take some of the techniques you have learned throughout this chapter and apply them to the Northwind solution you are building. Follow these steps to add a class that will be used throughout the rest of this book:

1.
Bring up your Northwind.sln file.

2.
Set Option Strict to On.

3.
Select the Project, Add Class menu item.

4.
Set the class name to DataHandler.vb.

5.
Add a shared method named ConnectStringBuild to this DataHandler class. Re-create the code shown in the shared ConnectStringBuild method in this chapter.

6.
Bring up Main.aspx in the page designer.

7.
Double-click the Logout LinkButton control and modify the lnkLogout_Click procedure so it looks like this:

Private Sub lnkLogout_Click( _
 ByVal sender As System.Object, _
 ByVal e As System.EventArgs)
  Session.Abandon()
									Response.Redirect("Main.aspx")
End Sub

8.
Open Login.aspx in the page designer.

9.
Double-click the Login button and modify the btnLogin_Click procedure so that it looks like this:

Private Sub btnLogin_Click( _
 ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles btnLogin.Click
  Session("LoginID") = "sa"
									Session("Password") = ""
									Server.Transfer("Main.aspx")
End Sub

For now, you will just set LoginID to "sa" so you can log in to your SQL Server database.

10.
Change the Page_Load procedure of Main.aspx to set the Visible property, depending on whether Session("LoginID") is an empty string, as shown here:

Private Sub Page_Load(ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles MyBase.Load

  Dim blnShow As Boolean
  blnShow = _
   (Session("LoginID").ToString = String.Empty)

  lnkLogout.Visible = blnShow
  hypEmpMaint.Visible = blnShow
  hypPwdChange.Visible = blnShow
End Sub

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.255.250