Introduction
In this article we will see simple plugin architecture using reflection. I would recommend to use this plugin architecture for smaller scale applications. For larger level applications we can use the frameworks provided by Microsoft MEF (Managed Extensibility Framework). I will write an article about that in the future.
We will take an example of building a calculator application.
Create project of type Class Library and name it as Plugger. It will be responsible for connecting our main calculator application to sublibraries of calculator.
In this project we will add interface with name IPlugger as below:
- using System.Windows.Controls;
-
- namespace Plugger.Contracts
- {
- public interface IPlugger
- {
-
-
-
- string PluggerName { get; set; }
-
-
-
-
-
- UserControl GetPlugger();
- }
- }
Now we will create a plug board where all plugs are connected to the application. For this create a WPF Project and see the below code:
- using Plugger.Contracts;
- using System;
- using System.Configuration;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
-
- namespace PlugBoard.Calculator
- {
-
-
-
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- LoadView();
- }
-
-
-
-
- public void LoadView()
- {
- try
- {
-
- string plugName = ConfigurationSettings.AppSettings["Plugs"].ToString();
- TabItem buttonA = new TabItem();
- buttonA.Header = "Welcome";
- buttonA.Height = 30;
- buttonA.Content = "You welcome :)";
- tabPlugs.Items.Add(buttonA);
-
- var connectors = Directory.GetDirectories(plugName);
- foreach (var connect in connectors)
- {
- string dllPath = GetPluggerDll(connect);
- Assembly _Assembly = Assembly.LoadFile(dllPath);
- var types = _Assembly.GetTypes()?.ToList();
- var type = types?.Find(a => typeof(IPlugger).IsAssignableFrom(a));
- var win = (IPlugger)Activator.CreateInstance(type);
- TabItem button = new TabItem
- {
- Header = win.PluggerName,
- Height = 30,
- Content = win.GetPlugger()
- };
- tabPlugs.Items.Add(button);
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "Internal Error", MessageBoxButton.OK, MessageBoxImage.Error);
- }
-
- }
-
- private string GetPluggerDll(string connect)
- {
- var files = Directory.GetFiles(connect, "*.dll");
- foreach (var file in files)
- {
- if (FileVersionInfo.GetVersionInfo(file).ProductName.StartsWith("Calci"))
- return file;
- }
- return string.Empty;
- }
-
- private void BtnClose_Click(object sender, RoutedEventArgs e)
- {
- Close();
- }
-
- private void Window_MouseDown(object sender, MouseButtonEventArgs e)
- {
- if (e.ChangedButton == MouseButton.Left)
- this.DragMove();
- }
- }
- }
Create PlugBoard folder in solution and in App.Config add key to access the PlugBoard Folder. PlugBoard is the folder were all calculator libraries will be placed.
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7" />
- </startup>
- <appSettings>
- <add key="Plugs" value="Add Path Of Plugbaord\PlugBoard\"/>
- </appSettings>
- </configuration>
The Solution Explorer looks like below now:
This is the first snap of the Main window:
Now it is time to create plugins for the calculator plug board. Create a project of type class library. We will name it as “RegularCalculator”.
Delete Class1.cs and Create View folder.
Add a WPF UserControl to it with name RegularView.
Add Plugger Project as a reference to this project, the project structure looks like below:
In RegularView.xaml, provide regular calculator operation implementation as below:
- <UserControl x:Class="RegularCalculator.View.RegularView"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:local="clr-namespace:RegularCalculator.View"
- BorderBrush="Silver" BorderThickness="2"
- mc:Ignorable="d" Height="150" Width="600">
- <UserControl.Resources>
- <Style TargetType="Button">
- <Style.Triggers>
- <DataTrigger Binding="{Binding ElementName=txtA, Path=Text}" Value="">
- <Setter Property="IsEnabled" Value="False"/>
- </DataTrigger>
- <DataTrigger Binding="{Binding ElementName=txtB, Path=Text}" Value="">
- <Setter Property="IsEnabled" Value="False"/>
- </DataTrigger>
- </Style.Triggers>
- </Style>
- </UserControl.Resources>
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="30"/>
- <RowDefinition Height="50"/>
- <RowDefinition Height="50"/>
- </Grid.RowDefinitions>
- <Grid Grid.Row="0" Background="Orange">
- <Label Content="Regular Calci" Foreground="White" FontWeight="Bold"/>
- </Grid>
- <Grid Grid.Row="1">
- <StackPanel Orientation="Horizontal" Margin="5" HorizontalAlignment="Center">
- <TextBox Name="txtA" Height="30" Width="100" PreviewTextInput="AllowOnlyNumbers"/>
- <TextBox Name="txtB" Height="30" Width="100" Margin="5" PreviewTextInput="AllowOnlyNumbers"/>
- <Label Name="lblRes" Height="30" Margin="5" Content="0"/>
- </StackPanel>
- </Grid>
- <Grid Grid.Row="2" Margin="5" HorizontalAlignment="Center">
- <StackPanel Orientation="Horizontal">
- <Button Name="btnAdd" Height="30" Width="100" Content="Add" Background="{x:Null}" Click="BtnAdd_Click"/>
- <Button Name="btnSubstract" Height="30" Width="100" Content="Substract" Margin="5" Background="{x:Null}" Click="BtnSubstract_Click"/>
- <Button Name="btnMultiply" Height="30" Width="100" Content="Multiply" Margin="5" Background="{x:Null}" Click="BtnMultiply_Click"/>
- <Button Name="btnDivide" Height="30" Width="100" Content="Divide" Margin="5" Background="{x:Null}" Click="BtnDivide_Click"/>
- </StackPanel>
- </Grid>
- </Grid>
- </UserControl>
In RegularView.xaml.cs, for RegularView class inherit the interface IPlugger and provide implementation as below:
- using Plugger.Contracts;
- using System.Text.RegularExpressions;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
-
- namespace RegularCalculator.View
- {
-
-
-
- public partial class RegularView : UserControl, IPlugger
- {
- public RegularView()
- {
- InitializeComponent();
- }
-
-
-
-
- public string PluggerName { get; set; } = "Regular";
-
-
-
-
-
- public UserControl GetPlugger() => this;
-
- private void BtnAdd_Click(object sender, RoutedEventArgs e)
- {
- lblRes.Content = int.Parse(txtA.Text) + int.Parse(txtB.Text);
- }
-
- private void BtnSubstract_Click(object sender, RoutedEventArgs e)
- {
- lblRes.Content = int.Parse(txtA.Text) - int.Parse(txtB.Text);
- }
-
- private void BtnMultiply_Click(object sender, RoutedEventArgs e)
- {
- lblRes.Content = int.Parse(txtA.Text) * int.Parse(txtB.Text);
- }
-
- private void BtnDivide_Click(object sender, RoutedEventArgs e)
- {
- lblRes.Content = int.Parse(txtA.Text) / int.Parse(txtB.Text);
- }
-
- private void AllowOnlyNumbers(object sender, TextCompositionEventArgs e)
- {
- Regex regex = new Regex("[^0-9]+");
- e.Handled = regex.IsMatch(e.Text);
- }
-
- }
- }
We are implementing IPlugger here, because when we load Main Calculator application, the main application looks for class which is being inherited by IPugger and gets the plugger name by property PluggerName and loads User control on main app using method GetPlugger().
And in go to project Properties -> Application -> Assembly Information update the Product Name as Calci. While loading this assembly in main app, in this dll we need to check for IPlugger interface. So even if we have some other assemblies in a project which is not related to our project, we can skip it for loading on UI. Below is the snap of Assembly Information:
Now again go to project Properties -> Build and change the Outpath to PlugBoard folder. As we discussed earlier, PlugBoard is the folder where we are placing all our assemby dlls and in the main application App.Config we are configuring the path of PlugBoard.
Build the entire solution and set “PlugBoard.Calculator” project as startup project. Run the application, below is the output snap of window. Here you can see “Regular” is added:
We will follow the same process for creating projects with names “TableCalculator” and “TrigonometryCalculator” and below is the output snap of window. Now you can see two more options plugged to the main calculator application with the names “Table Calci” and “Trigonometry”.
For your reference, Project Solution is uploaded and you can download it. Before running the project remember to configure PlugBoard folder path in App.Config.
This is how we can just keep on adding plugs we need and building the project. After delivering it to the customer, if the customer requires more option we can keep on extending the calculator functionalities without touching the previous code. So basically it will obey the Open/Close Principle of solid principles; i.e. open for extension, close for modification.
Summary
In this article we have seen, how we can develop plug and play solutions to meet our requirements which need extensibility.