Design add-on base Application - c#

I want to know that how design application , actually applications like Firefox or Chrome that you can download add-on for them and use ??!!
How do it in .Net ???

How to allow others to make Add-Ons for your app?
1>You create a DLL which has an interface.This interface defines a set of methods,properties,events you want others to define and implement.
the plugin developer need to define this interface.This DLL is required by your app and the plugin developer..
2>The plugin developer would use that shared DLL and implement the interface by defining the methods or properties in it.
3>Your app would now load that plugin and cast it to the shared DLL's interface and then call the desired methods,properties i.e anything that was defined in the interface..
How would your App fetch plugins?
You create a folder where you would search for the plugins.This is the folder where others plugins would be installed or placed.
Example
This is your shared dll
//this is the shared plugin
namespace Shared
{
interface IWrite
{
void write();
}
}
The plugin devloper
//this is how plugin developer would implement the interface
using Shared;//<-----the shared dll is included
namespace PlugInApp
{
public class plugInClass : IWrite //its interface implemented
{
public void write()
{
Console.Write("High from plugInClass");
}
}
}
this is your program
using Shared;//the shared plugin is required for the cast
class Program
{
static void Main(string[] args)
{
//this is how you search in the folder
foreach (string s in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*PlugIn.dll"))//getting plugins in base directory ending with PlugIn.dll
{
Assembly aWrite = Assembly.LoadFrom(s);
//this is how you cast the plugin with the shared dll's interface
Type tWrite = aWrite.GetType("PlugInApp.plugInClass");
IWrite click = (IWrite)Activator.CreateInstance(tWrite);//you create the object
click.write();//you call the method
}
}
}

You should use Managed Extensibility Framework (MEF).
http://mef.codeplex.com/
http://msdn.microsoft.com/en-us/library/dd460648.aspx

Use MEF.
The Managed Extensibility Framework (MEF) is a new library in .NET
that enables greater reuse of applications and components. Using MEF,
.NET applications can make the shift from being statically compiled to
dynamically composed. If you are building extensible applications,
extensible frameworks and application extensions, then MEF is for you.
useful link for MEF.
http://mef.codeplex.com/
http://www.codeproject.com/Articles/376033/From-Zero-to-Proficient-with-MEF
http://www.codeproject.com/Articles/232868/MEF-Features-with-Examples

Related

Instantiate plugin class in a DLL

I'm learning C# and am researching how to allow people to write plugins for an app I'm writing.
To start, I publish an API (a dll with interfaces) that their code must adhere to.
Now, I'm trying to understand how to work with their code. I've written a test plugin, built to a dll, and put it into a "plugins" directory that my script is watching.
I'm just not sure what to do next.
Since the API interfaces are shared my app knows what to expect. For example, they should have a main class which interfaces a Plugin interface.
// Example api interface:
public interface Plugin {
void Initialize();
}
// Example of their code:
public class TestPlugin : Plugin {
public void Initialize() {
// ... do stuff
}
}
My question is, how can I instantiate their TestPlugin, so that I can properly call Initialize and any other methods?
I have some ideas but am still too new to C# and don't want to jump the gun.
you need to find assemblies , load them and look for classes that implement IPlugin (please use Ixxx for interfaces)
There are helper libraries that do this for you although they feel over complex to me. MEF is the best known https://msdn.microsoft.com/en-us/library/dd460648(v=vs.110).aspx
If you want to roll your own.
Enumerate the 'plugins' directory for all .dll files
do an assembly.load on each one
enumerate the types and see if any classes supports IPLugin
if so do an activator.createinstance
good luck
The best way to do this would be to use MEF (Managed Extensibility Framework), otherwise known as the System.ComponentModel.Composition library.
If you did this, the library writer would put the following line above their class:
[Export(typeof(Plugin))]
Then you create some MEF classes to import any plugins. Start with a DirectoryCatalog since you are loading from a folder:
DirectoryCatalog pluginDir = new DirectoryCatalog("Plugins");
CompositionContainer mefContainer = new CompositionContainer(pluginDir);
Afterwards create a CompositionContainer from your catalog (shown above). Now you can have a class member marked with ImportMany like so:
[ImportMany]
private List<Plugin> plugins;
and call ComposeParts on the container, this will auto-populate your list with any exported classes found. Alternatively, you can directly ask for exports of a given type:
IEnumerable<Plugin> plugins = mefContainer.GetExportedValues<Plugin>();
One thing to note when using MEF, you get one, and only one, instance of each plugin. If you want multiple instances for some reason, have your users export a Factory.
If you want to go the hard way, you could load the assembly manually using Assembly.Load and then reflection to try and find the types implementing your interface. MEF does this work for you, so I would go with that.

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.

c# hide class members when exporting DLL

Can I only make some methods visible to the end user when I'm publishing a DLL to third party applications?
My code is built upon 7-8 different projects which call each other, they have different namespaces like "Company.ProjectName" which I think relate under the "Company" namespace, and I only want one of the projects (which has an interface defined BTW) to be visible to outer world.
Every project in the solution compiles into DLL's and then I'm combining them using ILASM.
BTW, there are other projects using these in the solution that are not related to this dll.
Edit: will the internal keyword work even if the namespaces are constructed like "CompanyName.Project1", "CompanyName.Project2" ? Will they see each other?
You don't need to combine them, you just need a friend assembly:
When you are developing a class library and additions to the library are contained in separate assemblies but require access to members in existing assemblies that are marked as Friend (Visual Basic) or internal (C#).
...
Only assemblies that you explicitly specify as friends can access Friend (Visual Basic) or internal (C#) types and members.
The InternalsVisibleTo attribute:
[assembly: InternalsVisibleTo("AssemblyB")]
helps to lock it down so only the specified assembly can access the internal items.
(In answer to your edit: this is specified at the assembly level, it doesn't matter what the namespace is).
Use internal
See the example below
public class MyPublicClass
{
public void DoSomething()
{
var myInternalClass = new MyInternalClass();
myInternalClass.DoSomething();
}
}
internal class MyInternalClass
{
public void DoSomething()
{
}
}
In your DLL, MyPublicClass will be visible to external users - those who reference your DLL.
MyInternalClass will not be visible.

How to keep dynamically loaded assemblies form breaking code at compile time?

I am linking one of the external resource at runetime in my code using something like below:
System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom("MyNice.dll");
Type type = assembly.GetType("MyType");
Tool = Activator.CreateInstance(type) as Tool;
Now as you can see that at the end of the object creation, it has to cast the resulting object into the tool class because there are a lot of references to the methods and properties of Tool class in my code that if it is no there then the code will error out on compile time.
Now, this is a bad situation because I wanted to remove the Dll from my references and have it loaded dynamically at runtime but at the same to there are pieces of my code that referes to and are dependent to the Tool assembly. How can I make it independent? Do I have to use reflection all over my code or there is any easy alternative out there?
for example:
if (Tool.ApplicationIsOpen)
return StatusResult.Success;
is there in the same class which assumes that Tool class already exists and will break if I remove it from my references folder.
Any suggesitons?
I would suggest making shared DLL to reference from both projects that contains an interface in which Tool inherits.
In this shared project, make an interface such as ITool, that exposes the functionality you need for the consumer project.
Shared Project
public interface ITool
{
void Something();
}
Separate Project
public class Tool : ITool
{
public void Something()
{
// do something
}
}
Consumer Project
System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom("MyNice.dll");
Type type = assembly.GetTypes().FirstOrDefault(t => t.IsAssignableFrom(typeof(ITool)));
ITool tool = Activator.CreateInstance(type) as ITool;
Now you can delete the reference to the project containing Tool, but you still need the reference to the shared project that contains ITool. If you truly don't want any references, then explore the reflection route, but be warned it'll probably be messy.
This strategy is the basis for many plugin systems. I'd recommend you check out some Dependency Injection (DI for short) libraries that can do a lot of this heavy lifting for you.
Here is a list of DI libraries: http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx
Personally I've been using Ninject lately.
Some relevant links:
Using Ninject in a plugin like architecture
Google something like "plugin framework DI C#"

How to organize code using an optional assembly reference?

I am working on a project and want to optionally use an assembly if available. This assembly is only available on WS 2008 R2, and my ideal product whould be a common binary for both computers with and without the assembly. However, I'm primarily developing on a Windows 7 machine, where I cannot install the assembly.
How can I organize my code so that I can (with minimum changes) build my code on a machine without the assembly and secondly, how do I ensure that I call the assembly functions only when it is present.
(NOTE : The only use of the optional assembly is to instantiate a class in the library and repeatedly call a (single) function of the class, which returns a boolean. The assembly is fsrmlib, which exposes advanced file system management operations on WS08R2.)
I'm currently thinking of writing a wrapper class, which will always return true if the assembly is not present. Is this the right way to go about doing this?
My approach would be to dynamically load the assembly, instead of hard-coding a reference. Your code could then decide whether to use the assembly (if it loaded) or return some other value. If you use the assembly, you'll need to use reflection to instantiate the class and use the method. That way your code will build and run on any platform, but it's behavior will change if it detects the presence of fsrmlib.
The System.Reflection.Assembly documentation has example code for doing this.
Hide the functionality behind an interface, say:
public interface IFileSystemManager
{
void Manage(IFoo foo);
}
Create two implementations:
An implementation that wraps the desired functionality from fsrmlib
A Null Object implementation that does nothing
Inject the IFileSystemManager into your consumers using Constructor Injection:
public class Consumer
{
private readonly IFileSystemManager fileSystemManager;
public Consumer(IFileSystemManager fileSystemManager)
{
if (fileSystemManager == null)
{
throw new ArgumentNullException("fileSystemManager");
}
this.fileSystemManager = fileSystemManager;
}
// Use the file system manager...
public void Bar()
{
this.fileSystemManager.Manage(someFoo);
}
}
Make the selection of IFileSystemManager a configuration option by delegating the mapping from IFileSystemManager to concrete class to the config file so that you can change the implementation without recompiling the application.
Configure applications running on WS 2008 R2 to use the implementation that wraps fsrmlib, and configure all other applications to use the Null Object implementation.
I would recommend that you use a DI Container for the configuration part instead of rolling this functionality yourself.
Alternatively you could also consider treating the IFileSystemManager as an add-in and use MEF to wire it up for you.

Categories

Resources