- Building an Interface
- Using Attributes
- The Test UI Application
- Summary
The Test UI Application
The test application is a Windows application that is created in its own project and references the AuthenticationPlugin.Common namespace. Aside from that namespace, it also needs to refer to the System.Reflection namespace to access the Assembly and Activator classes which are covered later.
The application is shown in Listing 1.4. The code that we are most interested in is the btnLogin_Click method, which is executed when the btnLogin button is clicked on the form. For convenience, an OpenFileDialog control grabs a file name by using the btnBrowse button.
For this sample to work, the filename should be the name of the assembly created in the test plug-in, AuthenticationPlugin.Plugins.MyTest.dll. The full path name is required, so if the assembly is located in your C:\Temp directory, the file name should be C:\Temp\AuthenticationPlugin.Plugins.MyTest.dll.
When the btnLogin button is clicked, the string in the txtFileName textbox is used as a filename, loading the assembly (using Assembly.LoadFile) after a simple check to ensure the file exists. A very simple method, called ShowError, opens a message box with an error message if the file does not exist.
Listing 1.4.
using System; using System.Diagnostics; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.IO; using System.Reflection; using AuthenticationPlugin.Common; namespace AuthenticationPlugin.UI.UITester { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.OpenFileDialog ofdPluginFile; private System.Windows.Forms.TextBox txtFileName; private System.Windows.Forms.TextBox txtUserName; private System.Windows.Forms.TextBox txtPassword; private System.Windows.Forms.Button btnLogin; private System.Windows.Forms.Button btnBrowse; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code // after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnLogin = new System.Windows.Forms.Button(); this.ofdPluginFile = new System.Windows.Forms.OpenFileDialog(); this.btnBrowse = new System.Windows.Forms.Button(); this.txtFileName = new System.Windows.Forms.TextBox(); this.txtUserName = new System.Windows.Forms.TextBox(); this.txtPassword = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // btnLogin // this.btnLogin.Location = new System.Drawing.Point(368, 88); this.btnLogin.Name = "btnLogin"; this.btnLogin.TabIndex = 0; this.btnLogin.Text = "Login"; this.btnLogin.Click += new System.EventHandler(this.btnLogin_Click); // // btnBrowse // this.btnBrowse.Location = new System.Drawing.Point(368, 56); this.btnBrowse.Name = "btnBrowse"; this.btnBrowse.TabIndex = 2; this.btnBrowse.Text = "Browse..."; this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click); // // txtFileName // this.txtFileName.Location = new System.Drawing.Point(8, 56); this.txtFileName.Name = "txtFileName"; this.txtFileName.Size = new System.Drawing.Size(352, 20); this.txtFileName.TabIndex = 3; this.txtFileName.Text = ""; // // txtUserName // this.txtUserName.Location = new System.Drawing.Point(8, 8); this.txtUserName.Name = "txtUserName"; this.txtUserName.TabIndex = 4; this.txtUserName.Text = "Enter Username"; // // txtPassword // this.txtPassword.Location = new System.Drawing.Point(8, 32); this.txtPassword.Name = "txtPassword"; this.txtPassword.TabIndex = 5; this.txtPassword.Text = "Enter Password"; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(448, 117); this.Controls.Add(this.txtPassword); this.Controls.Add(this.txtUserName); this.Controls.Add(this.txtFileName); this.Controls.Add(this.btnBrowse); this.Controls.Add(this.btnLogin); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } private void btnLogin_Click(object sender, System.EventArgs e) { try { /* Initialize some standard objects * that will be used to load up the * assembly. */ Assembly assembly = null; string typeName = string.Empty; Type pluginType = null; if ( File.Exists( txtFileName.Text ) ) { assembly = Assembly.LoadFile( txtFileName.Text ); } else { /* The file that was specified does not exist. * Checking here is much faster than waiting * until the catch block to handle an * FileDoesNotExist exception. Substitute the * error message code with logging code, etc. */ ShowError( string.Format ( "The specified file '{0}' does not exist.", txtFileName.Text ) ); } if ( null != assembly ) { /* Now the Assembly has been loaded. * We should look to see if we * can find a type that uses the * AuthenticationPlugin attribute */ foreach ( Type type in assembly.GetTypes() ) { if ( type.IsAbstract ) continue; if (type.IsDefined ( typeof( AuthenticationPlugin.Common.AuthenticationPluginAttribute ), true ) ) { /* We've found the authentication plugin * type, so we'll stop here. This is the * first instance. More code could be * added to throw an exception if more * than one is defined, etc. */ pluginType = type; break; } } /* Make sure before trying to act * on the object that a type * was actually found. */ if ( null != pluginType ) { bool isValidUser = ((IAuthenticationPlugin)Activator.CreateInstance (pluginType)). IsLoginValid(txtUserName.Text, txtPassword.Text); /* Display the result */ MessageBox.Show( ( isValidUser ) ? "Login successful!" : "Login failed!" ); } else { throw new ApplicationException ("The plugin does not contain the correct type."); } } } catch ( System.InvalidCastException ) { /* The object didn't implement the * IAuthenticationPlugin interface, and could * not be cast correctly */ ShowError ("The authentication object does not implement the correct interface."); } catch ( System.BadImageFormatException ) { /* The Assembly is invalid * It is not a valid .NET Assembly file. */ ShowError( string.Format ( "Invalid plugin file '{0}'", txtFileName.Text)); } catch ( System.Exception ex ) { ShowError( ex.ToString() ); } } private void ShowError( string message ) { MessageBox.Show( message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } private void btnBrowse_Click(object sender, System.EventArgs e) { ofdPluginFile.ShowDialog(); if ( ofdPluginFile.FileName != string.Empty ) { txtFileName.Text = ofdPluginFile.FileName; } } } }
The code that does the file loading is:
assembly = Assembly.LoadFile( txtFileName.Text );
This method throws System.BadImageFormatException if the file specified by txtFileName.Text is not a valid .NET assembly. This exception is caught later at the end of the method.
Once the assembly is loaded, the next step is to get the types from the assembly, and iterate through them to see if the AuthenticationPluginAttribute is defined. The method stops at the first instance that it finds, and sets the pluginType variable to the type it found:
if ( type.IsDefined( typeof( AuthenticationPlugin.Common.AuthenticationPluginAttribute ), true ) ) { /* We've found the authentication plugin type, so we'll * stop here. This is the first instance. More code * could be added to throw an exception if more than one * is defined, etc. */ pluginType = type; break; }
As mentioned in the comments, this could be expanded to do stricter checking, such as making sure that no more than one type exists in the assembly that has the AuthenticationPluginAttribute defined. For brevity, the application is satisfied by the first type that it finds.
Now that the application has the type, it can use the Activator class to create an instance of the type and cast it to IAuthenticationPlugin. Casting the instance to IAuthenticationPlugin allows the code to execute IsLoginValid since it knows that if the class implemented the interface, IsLoginValid must be present. In the sample application, the values in the txtUserName and txtPassword textboxes are passed as the username and password, respectively.
Once the application has the result, it prints out a message to a message box to show if the login was successful:
MessageBox.Show( ( isValidUser ) ? "Login successful!" : "Login failed!" );