When working with ASP.NET applications, the authentication of a user can be extremely easy. Using Forms or Windows authentication, ASP.NET code can identify the current user simply by accessing the User property of a page. It isn't quite that simple when working with Windows Forms applications, especially smart clients.
When working with smart clients, many client applications use the back-end web service for user authentication by supplying user credentials over a secure connection to a web service. Users can also be authenticated against a local database or even an XML file. Regardless of the method of validating user credentials, most smart clients need to be able to prompt the user for their credentials, validate those credentials, and then shut the application down if the credential validation fails.
This section shows you how to create a reusable Windows Form that can be used to prompt users for credentials and even validate those credentials without knowledge of the underlying validation scheme or persistence medium.
To start, create a new Windows Forms project and add a new form to it called LoginPrompt. It should have a text box for the user name, a text box for the password, and a button labeled Login. The code in Listing 38.2 shows the code in LoginPrompt.cs.
Listing 38.2. A Universal Login Dialog
To use this dialog, all you need to do is instantiate the dialog and supply a delegate that will be invoked to validate the user's name and password. The hardest part about using a login prompt is shutting the application down elegantly when the credential validation fails. To do this properly, you need to modify the Program.cs file that is created when you create your Windows Forms application, as shown in Listing 38.3.
Listing 38.3. Using a Universal Login Dialog