Referencing a class that may exist in one of two assemblies - c#

I am currently working on a data harvester for a project. The way it works is it basically calls another program which collects the data, and that program returns a data structure containing a collection of queue information. The harvester then serializes out the data. The program that actually collects the data is maintained by another team, and recently they did an upgrade and decided to restructure their code. The method I am calling is still in the same location, however, the data structure I get back got moved to a different assembly (it's code remained the same). The fun part of this is that we have both versions of this product in the field right now, so depending on which version a client has, the data structure I need may be in one of two different assemblies. My boss wants to try to only have one version of the harvester program if possible.
So, my question is this: using C# and .NET 3.5, is there a way to pick which assembly to use at runtime? I think I could use reflections, but I'd like to know if there's any way I could write the code normally for compile time and then resolve the dependency at run time depending on the other program's version.

You could try using the Adapter (wrapper) design pattern.
interface IQueueInfoProvider
{
DataStructure FetchData();
}
class Version1QueueInfoProvider : IQueInfoProvider
{
DataStructure FetchData()
{
//Fetch using Version1 Assemblies.
}
}
class Version2QueueInfoProvider : IQueInfoProvider
{
DataStructure FetchData()
{
//Fetch using Version2 Assemblies.
}
}
I believe .NET won't attempt to load referenced assemblies if they aren't needed, but if i'm wrong, you can always use reflections.

You may want to investigate the assemblybinding tags.
http://msdn.microsoft.com/en-us/library/twy1dw1e.aspx

you should go for AppDomain
http://www.codeproject.com/KB/cs/Assemblies___Appdomains.aspx
And another one is most popular
http://www.west-wind.com/Weblog/posts/601200.aspx

Related

Best approach to build C# DLLs for different editions of a software?

I have to build three different editions of a DLL which contain API calls of our software. I have so far figured out the following way of doing it using inheritance. Can someone please confirm if I'm using inheritance the correct way (or if you have a suggestion for doing it a proper/better way?) I am new to this so still learning C# project programming.
So far I have main class of API_calls (which are common for all DLL editions) as follows:
namespace APIcalls
{
public partial class API_Calls
{
public void Common_function1()
{
}
public void Common_function2()
{
}
}
}
Then I have three .cs class files with something like the following in each of them (Edition_A, Edition_B, and Edition_C are the differing factors for each edition of DLL), any additional calls are included in partial class API_Calls as follows:
namespace dll_edition
{
public class Edition_A
{
public Edition_A()
{
// Code here for checking if current DLL is authorized
// Otherwise throw an exception
}
}
}
namespace APIcalls
{
public partial class API_Calls : Edition_A
{
public void Additional_Edition_A_function1()
{
}
public void Additional_Edition_A_function2()
{
}
}
}
In each assembly build I include Edition_A file, or Edition_B file, or Edition_C file and then I build all three assemblies which gives me three DLLs.
My question: Is this the proper way of doing it? Is there any negative about how I have done it? Or is there a better way of doing this? My ultimate goal is to have three editions of DLL with some common API calls in them and then various API calls specific to each DLL type.
Thank you for any input that you may have!
-DD
From what I understand, you have set of common functions in a common base class that is to be used by different other classes.
There are various ways of doing it with their own pros and cons:-
1) Creating seperate libraries for each type which you are doing, in which only limited functionality goes to end user and size of dll is small.This is better suited if you have dlls working on plus and play model where you just dump the dll in the bin amd new functiinality is in place.
This also makes your changes centric, so you know where your changes are. But what if you have distributed you dll to end clients and they need method in other dll, you again have to republish your changes.
2) Doing it all in 1 dll, unwanted functionality is exposed to client, deployment package could be heavy. But you have all the functionality readily available.
To summarize would mainly depend on your business and deployment model.
Personally I am a bigger fan of doing it all in one DLL and using a Factory Pattern to determine which version gets run at runtime, but if it must be 3 based on your requirements here is what I recommend.
Create 4 DLLs.
The first project will just contain the edition interface (e.g. The structure of the DLL, but no content on how it will work). This interface can be attached to the classes for the different versions of the DLL. Using this structure will set up the calling code so that it can use dependency injections for different editions of the DLL.
The other 3 DLLs will be the different editions of the DLL that you are required to build.

Interface change between versions - how to manage?

Here's a rather unpleasant pickle that we got into on a client site. The client has about 100 workstations, on which we deployed version 1.0.0 of our product "MyApp".
Now, one of the things the product does is it loads up an add-in (call it "MyPlugIn", which it first looks for on a central server to see if there's a newer version, and if it is then it copies that file locally, then it loads up the add-in using Assembly.Load and invokes a certain known interface. This has been working well for several months.
Then the client wanted to install v1.0.1 of our product on some machines (but not all). That came with a new and updated version of MyPlugIn.
But then came the problem. There's a shared DLL, which is referenced by both MyApp and MyPlugIn, called MyDLL, which has a method MyClass.MyMethod. Between v1.0.0 and v1.0.1, the signature of MyClass.MyMethod changed (a parameter was added). And now the new version of MyPlugIn causes the v1.0.0 client apps to crash:
Method not found: MyClass.MyMethod(System.String)
The client pointedly does not want to deploy v1.0.1 on all client stations, being that the fix that was included in v1.0.1 was necessary only for a few workstations, and there is no need to roll it out to all clients. Sadly, we are not (yet) using ClickOnce or other mass-deployment utilities, so rolling out v1.0.1 will be a painful and otherwise unnecessary exercise.
Is there some way of writing the code in MyPlugin so that it will work equally well, irrespective of whether it's dealing with MyDLL v1.0.0 or v1.0.1? Perhaps there's some way of probing for an expected interface using reflection to see if it exists, before actually calling it?
EDIT: I should also mention - we have some pretty tight QA procedures. Since v1.0.1 has been officially released by QA, we are not allowed to make any changes to MyApp or MyDLL. The only freedom of movement we have is to change MyPlugin, which is custom code written specifically for this customer.
The thing is that the changes you made have to be basically in addition and not the change. So if you want to be back compatible in your deployment (as much as I understood in current deployment strategy you have this is an only option) you should never change the interface but add a new methods to it and avoid tight linking of your plugin with shared DLL, but load it dynamically. In this case
you will add a new funcionality without disturbing a old one
you will be able to choose which version of dll to load at runtime.
I have extracted this code from an application I wrote some time ago and removed some parts.
Many things are assumed here:
Location of MyDll.dll is the current directory
The Namespace to get reflection info is "MyDll.MyClass"
The class has a constructor without parameters.
You don't expect a return value
using System.Reflection;
private void CallPluginMethod(string param)
{
// Is MyDLL.Dll in current directory ???
// Probably it's better to call Assembly.GetExecutingAssembly().Location but....
string libToCheck = Path.Combine(Environment.CurrentDirectory, "MyDLL.dll");
Assembly a = Assembly.LoadFile(libToCheck);
string typeAssembly = "MyDll.MyClass"; // Is this namespace correct ???
Type c = a.GetType(typeAssembly);
// Get all method infos for public non static methods
MethodInfo[] miList = c.GetMethods(BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly);
// Search the one required (could be optimized with Linq?)
foreach(MethodInfo mi in miList)
{
if(mi.Name == "MyMethod")
{
// Create a MyClass object supposing it has an empty constructor
ConstructorInfo clsConstructor = c.GetConstructor(Type.EmptyTypes);
object myClass = clsConstructor.Invoke(new object[]{});
// check how many parameters are required
if(mi.GetParameters().Length == 1)
// call the new interface
mi.Invoke(myClass, new object[]{param});
else
// call the old interface or give out an exception
mi.Invoke(myClass, null);
break;
}
}
}
What we do here:
Load dynamically the library and extract the type of MyClass.
Using the type, ask to the reflection subsystem the list of MethodInfo present in that type.
Check every method name to find the required one.
When the method is found build an instance of the type.
Get the number of parameters expected by the method.
Depending on the number of parameters call the right version using Invoke.
My team has made the same mistake you have more than once. We have a similar plugin architecture and the best advice I can give you in the long run is to change this architecture as soon as possible. This is a maintainability nightmare. The backwards compatibility matrix grows non-linearly with each release. Strict code reviews can provide some relief, but the problem is you always need to know when methods were added or changed to call them in the appropriate way. Unless both the developer and reviewer know exactly when a method was last changed you run the risk of there being a runtime exception when the method is not found. You can NEVER call a new method in MyDLL in the plugin safely, because you may run on a older client that does not have the newest MyDLL version with the methods.
For the time being, you can do something like this in MyPlugin:
static class MyClassWrapper
{
internal static void MyMethodWrapper(string name)
{
try
{
MyMethodWrapperImpl(name);
}
catch (MissingMethodException)
{
// do whatever you need to to make it work without the method.
// this may go as far as re-implementing my method.
}
}
private static void MyMethodWrapperImpl(string name)
{
MyClass.MyMethod(name);
}
}
If MyMethod is not static you can make a similar non-static wrapper.
As for long term changes, one thing you can do on your end is to give your plugins interfaces to communicate through. You cannot change the interfaces after release, but you can define new interfaces that the later versions of the plugin will use. Also, you cannot call static methods in MyDLL from MyPlugIn. If you can change things at the server level (I realize this may be outside your control), another option is to provide some sort of versioning support so that a new plugin can declare it doesn't work with an old client. Then the old client will only download the old version from the server, while newer clients download the new version.
Actually, it sounds like a bad idea to change the contract between releases. Being in an object-oriented environment, you should rather create a new contract, possibly inheriting from the old one.
public interface MyServiceV1 { }
public interface MyServiceV2 { }
Internally you make your engine to use the new interface and you provide an adapter to translate old objects to the new interface.
public class V1ToV2Adapter : MyServiceV2 {
public V1ToV2Adapter( MyServiceV1 ) { ... }
}
Upon loading an assembly, you scan it and:
when you find a class implementing the new interface, you use it directly
when you find a class implementing the old interface, you use the adapter over it
Using hacks (like testing the interface) will sooner or later bite you or anyone else using the contract - details of the hack have to be known to anyone relying on the interface which sounds terrible from the object-oriented perspective.
In MyDLL 1.0.1, deprecate the old MyClass.MyMethod(System.String)and overload it with the new version.
Could you overload MyMethod to accept MyMethod(string) ( version 1.0.0 compatible) and MyMethod(string, string) (v1.0.1 version)?
Given the circumstances, I think the only thing you can do really is have two versions of MyDLL running 'side by side',
and that means something like what Tigran suggested, loading the MyDLL dynamically - e.g. as an a side example not related but might help you, take a look at the the RedemptionLoader http://www.dimastr.com/redemption/security.htm#redemptionloader (that's for an Outlook plugins which often have problems crashing to each other referencing different versions of a helper dll, just as a background story - that's a bit more complex cause of the COM involved but doesn't change much here) -
it's what you can do, something similar. Load dynamically the dll by it's location, name - you can specify that location internally, hard-code, or even set it up from config or something (or check and do that if you see that MyDll is not of the right version),
and then 'wrap' the objects, calls form the dynamically loaded dll to match what you normally have - or do some trick like that (you'd have to wrap something or 'fork' on the implementation) to make everything work in both cases.
Also to add on the 'no-nos' and your QA sorrows :),
they should not break the backward compatibility from 1.0.0 to 1.0.1 - those are (usually) the minor changes, fixes - not breaking changes, major version # is needed for that.

Multiple plugin instance loading with MEF

In my last application, using MEF to load plugins went just fine, but now I'm running into a new issue. I have a solution for it that I explain at the end of this question, but I'm looking for other ways to do it.
Let's say I have an interface called ApplianceInterface. I also have two plugins that inherit from ApplianceInterface, let's call them Blender and Processor. Now, I would like to have multiple Blenders and Processors in my application, but I am not sure how to instantiate them properly.
Before, I would simply use the ImportMany attribute and upon calling ComposeParts, my application would load Blender and Processor. For example:
[ImportMany(typeof(ApplianceInterface))]
private IEnumerable<ApplianceInterface> Appliances { get; set; }
and my Blender and Processor plugins would be attributed like this:
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(MyInterface)]
public class Blender : ApplianceInterface
{
...
}
but what this ends up doing for me is populating Appliances with one Blender and one Processor. I need to be able to create an arbitrary number of Blender and Processor objects.
Now, from the documentation I understand that [PartCreationPolicy(CreationPolicy.NonShared)] is what allows MEF to create a new instance each time, but is there a similar "magical" way to create a specific number of instances of something using MEF? Up until now, I've relied on [Import] and [ImportMany] to resolve the assemblies.
Is my only option to use a global container, and then resolve the export manually using GetExportedValue<>? I have tried GetExportedValue<> and that implementation does work fine for me, but I was just curious if there is a better, more accepted way to do it.
UPDATE
I just realized a big mistake, and GetExportedValue<> isn't what I really want. I'm iterating over an IEnumerable, and when I get a match (based on some parameters), I want to instantiate a new object of the current value. GetExportedValue<> ends up failing in the case where I have two different plugins that both export ApplianceInterface.
I think my question is different now, and is probably a C# specific one.
ExportFactory is what you are looking for, but it is currently only available in Silverlight. Here is a question that explains how to handle this on the desktop: Multiple Instances of a single MEF DLL

C# code re-use via namespaces

I like to create a file full of custom functions which I have made, which I may use in another project or something. Now I don't fully understand how to go about this, normally in a language like php, you'd just create the php file and then go include("cust_lib.php") or whatever the file is called.
Now I think that the process involves the library having its own namespace, then either go using custom_lib; or custom_lib:: within the script (I don't want to get into a discussion over which is the best way to go here).
Is this right? Or should I create the library and convert it to a .dll, if so how do I go about this, what sort of syntax does a dll have inside it etc.
However if its just file within one project then I don't need to go down that route do I? I can just create the namespace and use that?
This is what I'm working for at the moment, and thought it would be something like this
namespace Custom_Lib{
~~functions to go here~~
}
However the functions have to exist within a class don't they? So that becomes something like
namespace Custom_Lib{
class custom_lib{
public string function1(string input){
return input;
}
}
}
So some help, pointers, examples would be appreciated so I can wrap my head around this
Thanks,
Psy.
(Yes I call them functions, that just comes from a long php/js etc background)
The normal approach would be to create a Class Library project, put your classes and methods in that project, making sure that those you want to expose are public. Then you add a reference to the resulting dll file in the client projects and you will have the functionality from the class library available to you.
Even if you decide to put it all into one single file, I would still recommend you to make it a class library since I imagine that will make it easier to maintain. For instance, consider the following scenarios:
You decide to put it in a file and include a copy of that file in all projects where you want to use it. Later you find a bug in the code. Now you will have a number of copies of the file in which to correct the bug.
You decide to put it in a file and include that same file in all projects. Now, if you want to change some behaviour in it, you will alter the behavior for all projects using it.
In those two cases, keeping it as a separate project will facilitate things for you:
You will have only one copy of the code to maintain
You can decide whether or not to update the dll used by a certain project when you make updates to the class library.
Regarding the syntax issues: yes all methods must exist within a class. However, if the class is merely a container of the methods, you can make it (and the methods static):
public static class CustomLib
{
public static string GetSomethingInteresting(int input)
{
// your code here...
}
}
That way you will not need to create an instance of CustomLib, but can just call the method:
string meaningOfLife = CustomLib.GetSomethingInteresting(42);
In addition to Fredrik Mörk's well-written and spot-on response, I'd add this:
Avoid creating a single class that is a kitchen-sink collection of functions/methods.
Instead, group related methods into smaller classes so that it's easier for you and consumers of your library to find the functionality they want. Also, if your library makes use of class-level variables, you can limit their scope.
Further, if you decide later on to add threading capabilities to your library, or if your library is used in a multi-threaded application, static methods will likely become a nightmare for you. This is a serious concern, and shouldn't be overlooked.
There no question here. You answered it yourself. Yes, you have to construct a class to include all helper methods. And yes, you can either compile it to a dll if you want to reuse in multiple projects it or just add the source file to the project.
Usually I declare the helper class and all functions as static to avoid initiating the class each time I use it.

Plugin based application in C#

I have to make a graphical user interface application using the language of my choice. The application will run on Windows XP. It will be some sort of a complex windows form application.
I think and as per most suggestions, C# will be the best to use.
The tree structure on the left of the GUI will populate after reading from a configuration file which will be a binary file . (but initially I can work with a simple ASCII file to test my code.). The application will accept some inputs from the user through this GUI and will write the back to the same config file and will reflect the changes in the tree structure or the labels or any other pertaining field on the form.
There will be 3 tabs and 3 corresponding config files for each of the tabs.
I need some help designing the application for now. I am planning to make a host application (main application) and use the 3 tab controls as plugins. Is this workable ? If so can you please guide me on this. I mean how do I make 3 plugins in C# and how do I write the interfaces so that the main application knows which plugin to load and when to load it ? Will there be a separate “Plugin” folder under my project folder ? I hope you got my point though this is too little of an information for you to begin with.
Also there are some .cpp files already existing in the project. These files along with some .h files contain some important definitions and constants in them. These need to be integrated with my C# application. I have no clue how to do that but I am sure that it is possible by compiling the .cpp code in a .dll and then exposing the compiled .dll to my C# application. Please let me know if you need some more information for the top level design.
Thanks,
Viren
To implement a plugin interface manually, you will need a method something like this. I've left some TODOs in, where you would want to enhance the error handling and/or make the implementation a little more case specific.
public List<T> LoadPlugin<T>(string directory)
{
Type interfaceType = typeof(T);
List<T> implementations = new List<T>();
//TODO: perform checks to ensure type is valid
foreach (var file in System.IO.Directory.GetFiles(directory))
{
//TODO: add proper file handling here and limit files to check
//try/catch added in place of ensure files are not .dll
try
{
foreach (var type in System.Reflection.Assembly.LoadFile(file).GetTypes())
{
if (interfaceType.IsAssignableFrom(type) && interfaceType != type)
{
//found class that implements interface
//TODO: perform additional checks to ensure any
//requirements not specified in interface
//ex: ensure type is a class, check for default constructor, etc
T instance = (T)Activator.CreateInstance(type);
implementations.Add(instance);
}
}
}
catch { }
}
return implementations;
}
Example to call:
List<IPlugin> plugins = LoadPlugin<IPlugin>(path);
As for the c++ part of your question. There are few different ways you could approach this, though the correct choice depends on your specific situation. You can make a clr compliant .dll in c++, which your c# project could reference and call like any other .dll it references. Additionally, you could use P/Invoke to call into a native .dll.
One of the easiest plugin concepts I have ever used was certainly the Managed Extensibility Framework which will be part of .NET 4 (afaik). Unfortunately it is not yet finished and only a preview is available which may differ from the final version. That being said, we used MEF Preview 3 for a uni project and it worked without problems and it certainly made the whole plugin stuff a lot easier.
Look at the System.Addin namespace :
http://msdn.microsoft.com/en-us/library/system.addin.aspx
Otherwise you can do everything yourself. Before this namespace was available, I used a common interface "IPlugin" that every plugin/addin needed to use. I then had a loader which inspected all the *.dll in a folder then used reflection to check for the interface. I could then create instances of classes which implemented my plugin/addin interface
The cpp files will probably need converting to c#, or you could possibly create a dll to reference.
Take a look to Castle.
.NET Framework use COM model in its guts. See http://blog.caljacobson.com/2007/07/26/creating-a-plug-in-framework-in-c-resources/ for a list of plugin example using this techique.

Categories

Resources