Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Visual Basic 2005 (2006)

.pdf
Скачиваний:
219
Добавлен:
17.08.2013
Размер:
14.97 Mб
Скачать

Chapter 13

15.When the user clicks the OK button, you’ll need to validate the user’s credentials. Select btnOK in the Class Name combo box and the Click event in the Method combo box. Add the following highlighted code to the Click event handler:

Private Sub btnOK_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnOK.Click

‘Was a user name entered?

If txtUserName.Text.Trim.Length > 0 Then

‘Was the password correct?

If txtPassword.Text = “secret” Then

‘Successful login, set the User ID intUserID = 27

‘Raise the LoginSucceeded event

RaiseEvent LoginSucceeded(Me, New LoginEventArgs(intUserID))

‘Turn on the allow closing flag blnAllowClosing = True

Else

‘Inform the user that the password was invalid MessageBox.Show(“The password you entered was invalid.”, _

“Login”)

‘Increment the attempt count intAttemptCount += 1

‘Check the attempt count If intAttemptCount = 3 Then

‘Raise the LoginFailed event

RaiseEvent LoginFailed(Me, New EventArgs)

‘Set the Cancel dialog result

Me.DialogResult = Windows.Forms.DialogResult.Cancel

‘Turn on the allow closing flag blnAllowClosing = True

End If

End If

Else

‘Inform the user that they must supply a user name

MessageBox.Show(“You must supply a User Name.”, “Login”)

End If

End Sub

416

Creating Your Own Custom Controls

16.Finally, you need to perform some actions when the user clicks the Cancel button. Select btnCancel in the Class Name combo box and the Click event in the Method Name combo box. Add the following highlighted code to the Click event handler:

Private Sub btnCancel_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnCancel.Click

‘Raise the LoginCancelled event

RaiseEvent LoginCancelled(Me, New EventArgs)

‘Turn on the allow closing flag blnAllowClosing = True

End Sub

How It Works

The first thing that you had to do in this project was to set a reference to the System.Windows

.Forms.dll. The reason for this is that a Class Library project is compiled as a DLL and does not inherently know about Windows forms.

When you added your button controls, you set the DialogResult property. This causes the button controls to return a dialog box result of OK or Cancel when they are clicked and will automatically close the Login form and return the dialog box result to the caller.

The LoginEventArgs class is derived from the EventArgs class and extends it by providing a constructor and a public member called UserID. This public member will be accessible to the consumer of the LoginEventArgs class, which will be the LoginSucceeded event and, eventually, the end user of the Login class library.

To access the MessageBox class in the Login form to display messages, you must import the System

.Windows.Forms namespace. Remember that this is a Class Library project and it doesn’t inherently have access to this namespace. You set a reference to the System.Windows.Forms, but you still need to import the name space in your form class.

Imports System.Windows.Forms

You also added some private members to the Login form that will be used by the various methods in this class. The intAttemptCount variable will be used to count the number of attempts a user tries to enter a user name and password. The blnAllowClosing variable will be used to control whether the form is allowed to close, and the intUserID variable will be used to hold the User ID of the user who successfully logs in.

‘Private members

Private intAttemptCount As Integer = 0 Private blnAllowClosing As Boolean = False Private intUserID As Integer

You defined three events for the form: the LoginFailed event for when a user fails to provide authentication; the LoginSucceeded event for when a user successfully logs on; and the LoginCancelled event for when a user cancels his or her logon attempt.

417

Chapter 13

‘Public events

Public Event LoginFailed(ByVal sender As Object, ByVal e As EventArgs) Public Event LoginSucceeded(ByVal sender As Object, _

ByVal e As LoginEventArgs)

Public Event LoginCancelled(ByVal sender As Object, ByVal e As EventArgs)

The UserID property is a public ReadOnly property that will allow the consumer of this class to retrieve the User ID of the user who successfully logs on.

Public ReadOnly Property UserID() As Integer

Get

Return intUserID

End Get

End Property

After the form has loaded, the Activated event will be fired, and this is where you populate the User Name field with the user name of the user who is currently logged into Windows. This is done using the Name property of the Identity property of the User class in the My namespace. Since the User Name field has been populated with the user name, you want to set focus to the Password field so that users can just start typing their passwords. This is done by calling the Focus method on the txtPassword text box control.

Private Sub Login_Activated(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles Me.Activated

‘Populate the user name text box txtUsername.Text = My.User.Name

‘Set focus to the password text box txtPassword.Focus()

End Sub

You need to control when the form closes. By default, the form will close after it processes the code in the Click event for either the OK or the Cancel button. This is because you set the DialogResult property for the button controls. In the FormClosing event you control whether the form can close by querying the blnAllowClosing variable. If this variable is False, you set the Cancel property of the FormClosingEventArgs class to True, indicating that the form should cancel the FormClosing event and stay open.

Private Sub Login_FormClosing(ByVal sender As Object, _

ByVal e As System.Windows.Forms.FormClosingEventArgs) _

Handles Me.FormClosing

‘If we are not allowing the form to close...

If Not blnAllowClosing Then ‘Set the Cancel flag to True e.Cancel = True

End If End Sub

The code that you added for the OK button first ensures that some text has been entered into the txtUserName text box. You check this by first trimming any spaces from the Text property of the text

418

Creating Your Own Custom Controls

box using the Trim property and then checking the length of the text in that text box using the Length property. Remember that the Text property is derived from the String class, so all of the usual String methods and properties that you’re accustomed to are available in the Text property of the TextBox control.

If a user name has been entered, you check the password entered, if any. Here you compare the password entered against the password (here, a static value of secret). If the password matches, you set the intUserID variable (here, to a static value of 27), raise the LoginSucceeded event passing it the intUserID variable, and set the blnAllowClosing flag to True.

This section of code is where you would typically validate the user name and password against your database or other data store where you keep your user names and passwords.

Private Sub btnOK_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnOK.Click

‘Was a user name entered?

If txtUserName.Text.Trim.Length > 0 Then

‘Was the password correct?

If txtPassword.Text = “secret” Then

‘Successful login, set the User ID intUserID = 27

‘Raise the LoginSucceeded event

RaiseEvent LoginSucceeded(Me, New LoginEventArgs(intUserID))

‘Turn on the allow closing flag blnAllowClosing = True

If the password entered does not match the correct value for this user (here, the static text secret), you display a message box indicating that the password is invalid. Then you increment the intAttempt Count variable by a value of 1.

Next, you check the intAttemptCount variable and, if it is equal to a value of 3, you raise the Login Failed event and set the DialogResult property of the form to a dialog box result of Cancel. Then you set the blnAllowClosing flag to True, which will indicate that the form can close and return a dialog box result of Cancel.

Else

‘Inform the user that the password was invalid MessageBox.Show(“The password you entered was invalid.”, _

“Login”)

‘Increment the attempt count intAttemptCount += 1

‘Check the attempt count If intAttemptCount = 3 Then

419

Chapter 13

‘Raise the LoginFailed event

RaiseEvent LoginFailed(Me, New EventArgs)

‘Set the Cancel dialog result

Me.DialogResult = Windows.Forms.DialogResult.Cancel

‘Turn on the allow closing flag blnAllowClosing = True

End If

End If

If no text was entered into the User Name field, you display a message box indicating that the user must enter a user name.

Else

‘Inform the user that they must supply a user name

MessageBox.Show(“You must supply a User Name.”, “Login”)

End If

End Sub

The code that you entered for the Cancel button is really simple. If the user clicks the Cancel button, you want to raise the LoginCancelled event and set the blnAllowClosing flag to True.

Private Sub btnCancel_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnCancel.Click

‘Raise the LoginCancelled event

RaiseEvent LoginCancelled(Me, New EventArgs)

‘Turn on the allow closing flag blnAllowClosing = True

End Sub

Testing the FormsLibrary

To test the Login form in the FormsLibrary, you need to add a Windows Application project to your solution, just as you did when you needed to test your user controls. In this next Try It Out, you’ll examine the simplest method of using the Login form.

Try It Out

Testing the Login Form in an Application

1.Click on the File menu and select Add New Project. In the Add New Project dialog box, select Windows Application in the Templates pane and enter a project name of Secure Login and then click OK.

2.Next, you need to set up this new test application as the startup project, so right-click the Secure Login project in the Solution Explorer and select Set as StartUp Project from the context menu.

3.You now need to add a reference to the FormsLibrary project. Right-click the Secure Login project in the Solution Explorer and select Add Reference from the context menu. In the Add Reference dialog box, click the Projects tab. You’ll see that the FormsLibrary project is already listed, so just click OK.

420

Creating Your Own Custom Controls

4.Add a Label control to Form1 and set its Name property to lblUserID.

5.Now switch to the Code Editor for Form1 and add the following Imports statement above the

Class Form1 statement:

Imports FormsLibrary

6.Select (Form1 Events) in the Class Name combo box at the top of the Code Editor and the Load event in the Method Name combo box. Add the highlighted code to the Load event for the form:

Private Sub Form1_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

Using objLogin As New Login

If objLogin.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then ‘Update the label with the User ID

lblUserID.Text = “User ID = “ & objLogin.UserID

Else

‘Inform the user that the login failed MessageBox.Show(“Login Failed”)

‘Close this form since the login failed Me.Close()

End If End Using

End Sub

7.Now run the project, and the Login form will be displayed. Your domain name and user name will be populated in the User Name field. Enter any password except secret and click the OK button. You’ll receive a message indicating that the password is invalid. Do this two more times and you’ll receive a message indicating that the login failed, and the Secure Login project will end.

8.Now run the project again, and when the Login form is displayed, click the Cancel button. Again you’ll receive a message indicating that the login failed, and the Secure Login project will end.

9.Now run the project one final time. This time enter secret in the Password field and click the OK button. Remember that the password is case-sensitive. This time the login will be successful; Form1 will be displayed, and the user ID will appear in the Label control on the form.

How It Works

This Try It Out is a really good example of how you can provide a secure login for your application. If the user fails to log in successfully, then your application will end without even displaying the application’s main form, which is typically what you want to happen.

The first thing that you have to do in this project is set a reference to the FormsLibaray project through the Add Reference dialog box. Then you imported the FormsLibrary namespace in your form. This is not a necessary step, but it keeps you from having to fully qualify all references to the Login form in the

FormsLibrary class.

Imports FormsLibrary

421

Chapter 13

The code that you added to the Load event of Form1 was really simple. First you enclose all of your logic in a Using . . . End Using statement block. In the Using statement, you specify the object name of objLogin followed by a new instance of the Login form.

Then, inside the Using . . . End Using block, you use an If . . . Then . . . Else statement to show the Login form and check the dialog result returned. This is done by calling the ShowDialog method, passing a value of Me to this method for the owner parameter, and checking the dialog result returned against the OK constant of the DialogResult enumeration.

If the ShowDialog method of the Login form returns a dialog result of OK, then you update the label on Form1 with the user ID returned by UserID property of the Login form.

If the Login form returns any other dialog result other than OK (it will only return OK or Cancel), then you fall through to the code in the Else block of the If . . . Then . . . Else statement. Here you display a message block indicating that the login failed and then close the application by calling the Close method on Form1 using the Me keyword as a reference to Form1.

Private Sub Form1_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

Using objLogin As New Login

If objLogin.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then ‘Update the label with the User ID

lblUserID.Text = “User ID = “ & objLogin.UserID

Else

‘Inform the user that the login failed MessageBox.Show(“Login Failed”)

‘Close this form since the login failed Me.Close()

End If End Using

End Sub

Hooking Up the Events

Now that you’ve seen a simple method for using the Login form, you’ll want to examine a more complex method where you actually hook into the events that are exposed by the Login form. In this next Try It Out, you create an application that calls the Login form and also hooks into and handles the events that are raised by the Login form.

Try It Out

Receiving Events from the Login Form

1.Using the same solution with the two projects in it, right-click the solution in the Solution Explorer and select Add New Project. In the Add New Project dialog box, select Windows Application in the Templates pane and enter a project name of Access Control and then click OK.

2.Next, you need to set up this new test application as the startup project, so right-click the Access Control project in the Solution Explorer and select Set as StartUp Project from the context menu.

3.You now need to add a reference to the FormsLibrary project. Right-click the Secure Login project in the Solution Explorer and select Add Reference from the context menu. In the Add Reference dialog box, click the Projects tab. You’ll see that the FormsLibrary and Secure Login projects are already listed. Select the FormsLibrary project and then click OK.

422

Creating Your Own Custom Controls

4.Add a Button control to Form1, and set its Name property to btnLogin and its Text property to

Login.

5.Add a Label control to your form beneath the Button control, and set its Name property to lblMessage. You completed form should look similar to the one shown in Figure 13-7.

Figure 13-7

6.Now switch to the Code Editor for Form1 and add the following Imports statement above the

Class Form1 statement:

Imports FormsLibrary

7.You can tell Visual Basic 2005 that you want to automatically capture any events that an object raises by using the WithEvents keyword. The problem with this keyword is that it can’t be used in conjunction with New. In other words, you need to define a member to contain an instance of Login and create one when you need it. Add this code:

Public Class Form1

‘Declare events

Private WithEvents objLogin As Login

8.At this point, Visual Studio 2005 will pick up the member that raises events, and it adds that member to the Class Name and Method Name combo boxes at the top of the Code Editor. Select objLogin in the Class Name combo box and the LoginCancelled event in the Method Name combo box. Add this highlighted code to the LoginCancelled event:

Private Sub objLogin_LoginCancelled(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles objLogin.LoginCancelled

lblMessage.Text = “The login was canceled.” End Sub

9.Now select objLogin in the Class Name combo box and the LoginFailed event in the Method Name combo box. Add this highlighted code to the LoginFailed event:

Private Sub objLogin_LoginFailed(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles objLogin.LoginFailed

lblMessage.Text = “The login failed.” End Sub

10.Finally, select objLogin in the Class Name combo box and the LoginSucceeded event in the Method Name combo box. Add this highlighted code to the LoginSucceeded event:

Private Sub objLogin_LoginSucceeded(ByVal sender As Object, _

ByVal e As FormsLibrary.LoginEventArgs) Handles objLogin.LoginSucceeded

lblMessage.Text = “The login was successful for User ID “ & e.UserID End Sub

423

Chapter 13

11.One final piece of code that needs to be added is the code to actually call the Login form. Select btnLogin in the Class Name combo box and the Click event in the Method Name combo box. Add this highlighted code:

Private Sub btnLogin_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnLogin.Click

‘Instantiate a new instance of the Login form objLogin = New Login

‘Show the login form objLogin.ShowDialog(Me)

End Sub

12.Now you are ready to test this project, so start it up. Click the Login button on Form1, and when the Login form is displayed, click the Cancel button. The Label control on Form1 will be updated with text indicating that the login was canceled.

13.Now click the Login button again and enter any password other than secret in the Password field of the Login form. Keep clicking the OK button until the login fails. The Label control on Form1 will be updated with text indicating that the login failed.

14.Click the Login button one final time and then enter the password of secret in the Password field of the Login form. Click the OK button, and the Label control on Form1 will be updated with text indicating that the login was successful and will also display the user ID.

How It Works

This project demonstrates how an application that needs to expose restricted access to certain parts of an application could use the Login form to validate the user’s credentials and handle the various events that are raised by the Login form. All users would have access to most areas of the application, but you could secure other parts of the application and prompt users for the credentials before allowing them access to the more sensitive areas of the application.

This project starts out like the last project in that you first had to set a reference to the FormsLibrary project and then import the FormsLibrary namespace in you form. The difference comes in that in this project you declare an object to receive the events from the Login form.

‘Declare events

Private WithEvents objLogin As Login

Once this object is declared, the events exposed by the Login form are available in the Method Name combo box in the Code Editor, and you can select them to create the appropriate event handlers for the LoginCancelled, LoginFailed, and LoginSucceeded events. Once these events are raised, you display the appropriate message in a Label control on your form. Ideally, these event handlers are where you would perform some appropriate action based on the event raised.

The one event handler that needs to be pointed out is the event handler for the LoginSucceeded event. This event receives the LoginEventArgs class, which, if you recall, is a class that you created in the FormsLibrary project that exposes UserID as a public member of that class.

424

Creating Your Own Custom Controls

Here you simply access the UserID member of the LoginEventArgs to retrieve the user ID and display it in the Text property of the Label control.

Private Sub objLogin_LoginSucceeded(ByVal sender As Object, _

ByVal e As FormsLibrary.LoginEventArgs) Handles objLogin.LoginSucceeded

lblMessage.Text = “The login was successful for User ID “ & e.UserID End Sub

In the Click event for the Login button, you add the code to create a new instance of the Login form and then simply call the ShowDialog method of that form. In this project you actually don’t care what dialog result is returned from the ShowDialog method, because you handle the validation of the login through the event handlers.

Private Sub btnLogin_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnLogin.Click

‘Instantiate a new instance of the Login form objLogin = New Login

‘Show the login form objLogin.ShowDialog(Me)

End Sub

We have presented two methods for using the Login form here, and each has its own purpose, as explained in the first paragraphs of the How It Works sections. Basically, you have built a Login form that can be used in two very different scenarios. All you need to do now is to implement the actual code to validate a user’s credentials in the Login form against a database or other data store that handles user names and passwords.

Summar y

This chapter showed two ways of packaging a user interface together with some encapsulated functionality. You looked at building a user control that aggregated a number of existing controls usefully. You extended the new control with properties, methods, and events. This control, once compiled, was shown in the ToolBox under its own tab.

You also took a look at how to create a class library that encapsulated a form with prebuilt functionality, making it easy to provide a consistent interface in all of your applications that need to implement a login form.

To summarize, you should know:

What a Windows Forms Control is and how it works

How to create a control

How to add methods and events to your control

How to code for Design Time and Runtime

How to create a Class Library project that exposes a Windows form

425