首页    期刊浏览 2024年11月25日 星期一
登录注册

文章基本信息

  • 标题:Building Plug-ins with C# .NET: Part 1
  • 作者:Nathan Good
  • 期刊名称:Dev Source
  • 出版年度:2004
  • 卷号:May 2004
  • 出版社:DEVsource

Building Plug-ins with C# .NET: Part 1

Nathan Good

This article is the first in a four-part series that focuses on building and using plug-ins in C#. The task that I'll use as an example throughout this series is user authentication since it that works well for showing off the use of plug-ins. The information needed to authenticate a user is usually pretty standard across applications: you provide a username and password, and find out whether the attempt was successful.

The plug-in doesn't care how the application got the username and password, nor does it care what the application does with the result. The application calling the plug-in doesn't care whether the user authentication is done using a database lookup, a file lookup, or other means (such as LDAP or Active Directory authentication). Plug-ins are useful for this type of task because, as the application grows and the needs of the business grow, more plug-ins can be developed to handle different methods of authentication without touching any of the application code.

The sample application I'll use in this article is a simple Windows form that loads a plug-in, finds the correct class to use from the plug-in, and executes a method and processes the result.

Building an Interface

The first step in making the authentication plug-in, after creating a blank solution, is to create a common project. You'll use it to hold classes that will be accessed by both the plug-ins and the application that calls them. The object of doing this is to keep the dependancies down; there is little advantage in creating plug-ins if the application has to refer to the plug-in project to compile or run.

The new project to hold these objects is AuthenticationPlugin.Common. Right now, it will just contain one interface and one class that extends Attribute, which will be covered a little later in this article.

The interface used here is IAutheticationPlugin. As shown in Listing 1.1, the IAuthenticationPlugin interface has only one method: IsLoginValid, which takes a username and password as a string and returns a boolean value that will be true if the user has been authenticated:

bool IsLoginValid( string username, string password )

Each plug-in is in its own seperate project, as it will be in its own assembly that is loaded by the application. The project for each plug-in uses a project reference to refer to the AuthenticationPlugin.Common project to be able to access the IAuthenticationPlugin interface.

Listing 1.1

using System;
 
namespace AuthenticationPlugin.Common
{
       /// <summary>
       /// Interface for the AuthenticationPlugin.  Each plug-in that is
       /// developed for authentication must implement this interface.
       /// </summary>
       public interface IAuthenticationPlugin
       {
        /// <summary>
        /// Authentication method
        /// </summary>
        /// <param name="username">Name of user as a string</param>
        /// <param name="password">User's password as a string</param>
        /// <returns>true if user is autenticated</returns>
              bool IsLoginValid( string username, string password );
       }
}

Using Attributes

The other class that will be added to the AuthenticationPlugin.Common project and namespace is a class that extends the .NET Framework Attribute class, called AuthenticationPluginAttribute. This class allows metadata to be defined that identifies the class that implements the IAuthenticationPlugin interface and will be loaded by the application.

There is certainly more than one way to skin this cat, and using metadata is only one of them. One alternative is to use method info to iterate through the types in an assembly to find the type that has IsLoginValid as a method. If anything, the use of an attribute here is to demonstrate how one can be used in reflection.

Another technique used to load types might be to stick the type in a configuration file used by the application. The problem with it, for this plug-in system, is that it doesn't work well with how the application works. The test application prompts the user for a file, then loads it. The assumption, therefore, might be that the user doesn't know the type inside the assembly.

The attribute, AuthenticationPluginAttribute, is listed in Listing 1.2. It contains nothing fancy—it doesn't require any parameters, as it will only be used to identify a class. The AuthenticationPluginAttribute class inherits from the Attribute class provided with .NET:

public sealed class AuthenticationPluginAttribute : Attribute

The class is sealed because there is no reason to inherit from it. However, it inherits all of the properties and methods provided by the Attribute class.

To use the attribute in the first test plug-in, [AuthenticationPlugin] is typed directly above the class declaration of the plug-in. The plug-in must also include and reference the AuthenticationPlugin.Common namespace, but it had to do that to use the AuthenticationPlugin interface.

Listing 1.2

using System;
 
namespace AuthenticationPlugin.Common
{
       /// <summary>
       /// The AuthenticationPluginAttribute is used to identify
       /// the main class of an Authentication plugin.
       /// </summary>
       [AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
       public sealed class AuthenticationPluginAttribute : Attribute
       {
    }
}

The MyTest Plug-in

The MyTestAuthenticator class is a working—albeit simple—example plug-in. It implements the IAuthenticationPlugin interface, is identified by [AthenticationPlugin] attribute, and is included in its own project, which compiles to an assembly file called AuthenticationPlugin.Plugins.MyTest.dll. This plug-in simply compares the username and passwords to hard-coded values.

If you are developing your own plug-ins, you'd replace this hard-coded comparison with something more complicated, such as comparing the username and password against database values, a flat file, an XML file, or even Active Directory. Some of these will be covered in the rest of the articles in this series.

Our first plug-in is shown in its entirety in Listing 1.3. Notice that aside from the System namespace, the only namespace that it needs to reference is the AuthenticationPlugin.Common namespace. It is very useful to keep the dependencies as light as possible for these plug-ins.

Listing 1.3

using System;
 
using AuthenticationPlugin.Common;
 
namespace AuthenticationPlugin.Plugins.MyTest
{
       /// <summary>
       /// A Test Authentication plugin
       /// </summary>
       [AuthenticationPlugin]
       public class MyTestAuthenticator : IAuthenticationPlugin
       {
        /// <summary>
        /// The method that is called to do the authentication and 
        /// return a result.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool IsLoginValid( string username, string password )
        {
            return username.Equals( "foo" ) && password.Equals( "bar" );
        }
       }
}

The steps to create another plug-in are:

Add using AuthenticationPlugin.Common to the using block. Implement the IAuthenticationPlugin by tacking : IAuthenticationPlugin on to the end of the class declaration and by adding the IsLoginValid method. Identify the plug-in class by adding AuthenticationPlugin above the class declaration.

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!" );

Summary

The downloadable solution contains three projects: AuthenticationPlugin.Common, AuthenticationPlugin.Plugins.MyTest, and AuthenticationPlugin.UI.UITester. The AuthenticationPlugin.Common project contains the IAuthenticationPlugin interface and the AuthenticationPluginAttribute, which are used to develop new plug-ins and call them with other applications. The AuthenticationPlugin.Plugins.MyTest project contains a very simple plug-in. The AuthenticationPlugin.UI.UITester project contains a Windows application that can be run to visually test the plug-in.

Some of the concepts that were reviewed in this article are the use of interfaces, inheritance, and reflection.

The basic steps that were followed to create the solution were:

Create a common project with an interface and an attribute class which will be used by the plug-ins and applications to define, load, and call the plug-ins. Create a plug-in by adding a new project that will compile to its own .NET assembly. This project will refer to the common project. The implementation class implements the interface and is identified by an attribute. The attribute is metadata that is used in reflection later to know which class, or type, to load and use. Create an application that uses the .NET reflection classes Assembly and Activator to load the assembly, find the implementation class, and run the correct method.

The downloadable solution contains the three projects and code that demonstrates these concepts.

The next article in this series will cover what happens when one of these plug-ins requires its own configuration, and will also cover authenticating users against an XML file.

Download the code for this project here.

Copyright © 2004 Ziff Davis Media Inc. All Rights Reserved. Originally appearing in Dev Source.

联系我们|关于我们|网站声明
国家哲学社会科学文献中心版权所有