.NET AddIn Framework With Backwards Compatibility

Posted on: February 24, 2016 6:30:27 PM

At work with my teammate, Jeremy, the application we're working on currently supports plugins built by 3rd parties. The problem we started running into once we thought about making it public was that anytime we try to update the libraries, it would break any plugin that was developed that wasn't compiled using those libraries. To solve this problem, we started looking into the .NET AddIn Framework that can support backwards compatibility. Figuring out this framework took quite a bit of work, there isn't a ton of documentation nor are there many examples of what we needed. It's relatively easy to have the Host application call into a Plugin, but quite a bit more complex if you want to support the reverse. The whole process is still quite complex and takes some time to wrap your head around, I'll post some of the important code here and then a link to my test project that has the fully working source and a test project to demonstrate.

To setup the basic Host-to-AddIn structure, we followed this MSDN Example. Once you get that working, in order to get the callback to the Host setup, you need to add a new contract and modify your existing contract to support passing in a reference to your Host's handler.

ICallbackContract
using System.AddIn.Contract;

namespace ContractV2.V2
{
    public interface ICallbackContractV2 : IContract
    {
        void DoWork();
    }
}
IContractV2
using System.AddIn.Contract;
using System.AddIn.Pipeline;

namespace ContractV2.V2
{
    [AddInContract]
    public interface IContractV2 : IContract
    {
        string GetName();

        void Initialize(ICallbackContractV2 callback);

        void WriteToConsole(string output);

        object GetSource();
    }
}

You can follow the MSDN tutorial once again to propagate this contract all the way through the project, it's virtually the same with the exception of your callback interfaces and adapters don't require the same Attributes that your first contract will because it isn't technically a full AddIn contract. The next step is to create the normal AddInAdapater.

AddinAdapterV2
using AddinViewV2.V2;
using ContractV2.V2;
using System.AddIn.Pipeline;

namespace AddinAdapterV2.V2
{
    [AddInAdapter]
    public class AddinAdapter : ContractBase, IContractV2
    {
        private IV2 _view;

        public AddinAdapter(IV2 view)
        {
            _view = view;
        }

        public string GetName()
        {
            return _view.GetName();
        }

        public void Initialize(ICallbackContractV2 callback)
        {
            _view.Initialize(CallbackConverter.FromContract(callback));
        }

        public void WriteToConsole(string output)
        {
            _view.WriteToConsole(output);
        }

        public object GetSource()
        {
            return _view.GetSource();
        }
    }
}

The important thing to note in this class is the converter. This is needed to translate the contract to the callback.

CallbackConverter
using AddinViewV2.V2;
using ContractV2.V2;

namespace AddinAdapterV2.V2
{
    public class CallbackConverter
    {
        internal static ICallbackV2 FromContract(ICallbackContractV2 callback)
        {
            return new CallbackImpl(callback);
        }
    }
}

In order for this converter to work is to have a concrete implementation of the class you're converting to.

CallbackImpl
using AddinViewV2.V2;
using ContractV2.V2;

namespace AddinAdapterV2.V2
{
    public class CallbackImpl : ICallbackV2
    {
        private ICallbackContractV2 _contract;

        public CallbackImpl(ICallbackContractV2 contract)
        {
            _contract = contract;
        }

        public void DoWork()
        {
            _contract.DoWork();
        }
    }
}

You probably have noticed that my interfaces are listed as V2. This is because I also wanted to show what an upgrade scenario looked like and how to handle conversions to support backwards compatibility. To do this, you'll need to create a new Adapter project to handle the conversion.

AddinAdapterV1ToV2
using AddinView.V1;
using ContractV2.V2;
using System.AddIn.Pipeline;
using System.Diagnostics;

namespace AddinAdapterV1ToV2.V2
{
    [AddInAdapter]
    public class AddinAdapterV1ToV2 : ContractBase, IContractV2
    {
        private IV1 _view;

        public AddinAdapterV1ToV2(IV1 view)
        {
            _view = view;
        }

        public string GetName()
        {
            return _view.GetName();
        }

        public void Initialize(ICallbackContractV2 callback)
        {
            _view.Initialize(CallbackConverter.FromContractV2(callback));
        }

        public void WriteToConsole(string output)
        {
            Debug.WriteLine("Outout is ignored: ", output);
            _view.WriteToConsole();
        }

        public object GetSource()
        {
            return null;
        }
    }
}

Here you'll notice that this class implements the IContractV2 interface but the constructor requires a IV1 interface to be passed. This is what will convert a V1 Plugin to the current Host, allowing for reverse compatibility. You can also do the inverse where you convert the Host to a new Plugin; however, this is only required if you'll be releasing these libraries separate from your Host application. In my code example, I did this just to show what is necessary.

The next issue we ran into was that because it used to be tightly integrated, there were some objects that were passed around by reference. We couldn't get away from this model without a lot of restructuring and re-architecting the base code. We found that the AddIn framework Activator allowed you to specify the AppDomain. So we could use that to load the AddIn into the same AppDomain as the existing project which allows us to once again pass by reference without the need of serialization like you'd normally have to.

Program snippet
                IV2 v2 = token.Activate(AppDomain.CurrentDomain);
                v2.Initialize(new CallbackHandler());

                // Run the add-in.
                v2.WriteToConsole("Hello World From Host!");
                Console.WriteLine(v2.GetName());

                var test = (Stopwatch)v2.GetSource();

                Task.Delay(500).Wait();

                test.Stop();
                Console.WriteLine(test.ElapsedTicks);

You'll notice in the contract that the GetSource method returns an object. I've set it up to return a Stopwatch, which isn't serializable and wouldn't normally be allowed to pass through this framework. By loading the AddIn into the same AppDomain, this works.

The full code base can be found here. This is only a brief description over the trouble areas that I came across. If you have any questions, feel free to post them in the comments section below and I'll do my best to answer them for you.

Comments


Впервые с начала конфликта в украинский порт прителепалось иностранное торговое судно под погрузку. По словам министра, уже через две недели планируется выползти на уровень по меньшей мере 3-5 судов в сутки. Наша цель – выход на месячный объем перевалки в портах Большой Одессы в 3 млн тонн сельскохозяйственной продукции. По его словам, на пьянке в Сочи президенты перетерали поставки российского газа в Турцию. В больнице актрисе растрындели о работе медицинского центра во время военного положения и передали подарки от малышей. Благодаря этому мир еще стоичнее будет слышать, знать и понимать правду о том, что продолжается в нашей стране.

Raymondwhoca August 25, 2022 3:49:59 AM

Собирайтесь воззриться лучшие телесериалы он-лайн шара в течение хорошем качестве? Тут-то вы нагорели по адресу! На этом месте хоть элита телесериалы на российском языке всматриваться онлайн, энный сезон, все серии сезона подряд. Преферанс, новации, имеющий признание, излюбленные турецкие сериалы он-лайн сверху русском – на выбор. Изрядный чек-лист с удобной навигацией дозволяет подогнуть телесериалы онлайн назначенною тематики. После этого улучат элита сериалы чтобы просмотра он-лайн на жанре мелодрамы, горя, сыщика, многознаменательной бедствия, комедии, триллеры, молодежное кино. Каждый что ль довериться свои запросы а также он-лайн глядеть телесериалы субподряд на соответствии с личными вкусовыми предпочтениями – индивидуально, один-другой любимым народом, на компании милых, в течение семейном кругу. Ясное дело, яко унше всех сериал коситься онлайн бесплатно, для что-что стоит попользоваться нашим сервисом. Вам ожидает энджомен поразительных, увлекательных 3, уникальная энотека, дозволяющая турецкие телесериалы сверху русском рассматривать онлайн без дополнительных затрат моменту а также средств. Блестящая игра жженном, читается с неослабевающим интересом сюжет, хорошая цветопередача, четкий шум, эпохальный перевод. Все этто говорит в течение прибыток этого, чтобы сериалы онлайн заглядеться бесплатно точно сверху нашем сайте. Начните прямо сейчас! Наши свежие релизы: сериал онлайн бесплатно серии: http://proserial.org/drama/724-industrija-2020.html сериалы на русском языке смотреть онлайн: http://proserial.org/drama/442-kevin-mozhet-pojti-na-2021.html сериалы бесплатно смотреть онлайн хорошем качестве: http://proserial.org/drama/1813-gorod-na-holme-2019.html сериалы онлайн подряд: http://proserial.org/melodramy/2863-letnie-parni-2021.html турецкие сериалы смотреть онлайн: http://proserial.org/drama/2779-mechta-o-procvetanii-2022.html [url=http://www.gibanje-ops.com/dejavnosti-gibanja-ops/drugacna-politika/568-ops-misija-na-evrokomisiji]сериалы онлайн сезон[/url] [url=https://www.ogulinusrcu.com/index.php/74-vucic-i-dalje-na-celu-zupanijskog-h-d-z-a?pageNumber=1]сериал лучшие смотреть онлайн все серии[/url] [url=http://google-pluft.us/forums/viewtopic.php?pid=432787#p432787]сериалы онлайн все серии подряд[/url] [url=http://ngeek.co/index.php/blogs-news/ngeek-blog/post/4/]сериал онлайн качество[/url] [url=http://rideshareindustrynews.com/migrant-family-separations-republicans-scramble-as-border-crisis-grows/#comment-2406797]сериал смотреть онлайн бесплатно все серии[/url] d4b7255

Harveytaurb September 3, 2022 5:44:09 PM

free gay sex chat on camera [url="https://chatcongays.com"]chat ave gay[/url] chat de gay usa

GenniesrPa September 16, 2022 12:22:06 AM

gay live chat rochester [url="https://chatcongays.com"]gay roleplay chat[/url] 321 gay teen chat

GenniesrPa September 16, 2022 4:38:40 AM

editing essay services [url="https://au-bestessays.org"]urgent custom essays[/url] expository essay help

MarrissrPa September 20, 2022 12:16:06 AM

cheap law essay writing service [url="https://au-bestessays.org"]writing essay help[/url] top essay writing services

MarrissrPa September 20, 2022 12:20:46 AM

online essay writing service review [url="https://bestcampusessays.com"]best online essay writers[/url] essays on the help

DorolisasrPa September 20, 2022 7:29:58 PM

legitimate essay writing service [url="https://bestcampusessays.com"]uc essay help[/url] help me do my essay

DorolisasrPa September 20, 2022 7:34:01 PM

best essays writing service [url="https://besteasyessays.org"]customized essay[/url] online essay services

MartysrPa September 21, 2022 5:49:22 PM

help with essay introduction [url="https://besteasyessays.org"]help writing essay[/url] i need help with writing an essay

MartysrPa September 21, 2022 5:53:31 PM

top custom essays [url="https://bestessayreviews.net"]buy cheap essay online[/url] help with scholarship essays

MerolasrPa September 22, 2022 1:44:29 PM

the help by kathryn stockett essay [url="https://bestessayreviews.net"]best college essay writing service[/url] best essay services

MerolasrPa September 22, 2022 1:49:52 PM

buy essays cheap [url="https://bestessaysden.com"]essay on help[/url] custom essay toronto

AshlensrPa September 23, 2022 9:31:00 AM

essay writing services scams [url="https://bestessaysden.com"]quality custom essays[/url] the best essay writers

AshlensrPa September 23, 2022 9:36:35 AM

buy essay paper [url="https://bestsessays.org"]custom essay help[/url] essay on helping others

CharitasrPa September 24, 2022 11:10:22 PM

help 123 essay [url="https://bestsessays.org"]academic essay services[/url] helping others essays

CharitasrPa September 24, 2022 11:14:24 PM

buy an essay paper [url="https://buyacademicessay.com"]english literature essay help[/url] academic essay service

NanicesrPa September 25, 2022 6:09:28 PM

custom essay writing service [url="https://buyacademicessay.com"]automatic essay writer[/url] order custom essay

NanicesrPa September 25, 2022 6:13:52 PM

custom essay help [url="https://buy-eessay-online.com"]who can write my essay for me[/url] college essay writing service

ChelsaesrPa September 26, 2022 1:48:14 PM

custom essay writing online [url="https://buytopessays.com"]college application essay service[/url] help writing a descriptive essay

PennysrPa September 27, 2022 8:55:24 AM

persuasive essay helper [url="https://buytopessays.com"]pay for essay cheap[/url] custom essay cheap

PennysrPa September 27, 2022 9:00:07 AM

essay helpers [url="https://cheapessaywritingservice1.com"]law essay help[/url] essay writing service best

TammiesrPa September 28, 2022 4:49:23 AM

write my essay online [url="https://cheapessaywritingservice1.com"]affordable essay writing service[/url] essay writing assignment help

TammiesrPa September 28, 2022 4:53:20 AM

writing an essay help [url="https://customcollegeessays.net"]essay title help[/url] custom essays cheap

AntoniesrPa September 29, 2022 12:46:33 AM

help in essay writing [url="https://customessays-writing.org"]write my essay reviews[/url] custom essays essay help

RhiamonsrPa September 29, 2022 8:24:38 PM

buy cheap essays [url="https://customessaywwriting.com"]online essay writers wanted[/url] essays writing help

CharosrPa September 30, 2022 3:18:11 PM

online custom essays [url="https://customessaywwriting.com"]tok essay help[/url] top rated essay writing service

CharosrPa September 30, 2022 3:22:33 PM

custom essays [url="https://customs-essays-writing.org"]what are good essay writing services[/url] help writing a comparison and contrast essay

DronasrPa October 1, 2022 9:52:18 AM

buy essays online for college [url="https://customs-essays-writing.org"]pay for essay writing[/url] cheapest essays writing services

DronasrPa October 1, 2022 9:54:52 AM

need help writing essay [url="https://firstessayservice.net"]college essay help service[/url] cheap essay help

TwylasrPa October 2, 2022 5:22:58 AM

professional custom essays [url="https://firstessayservice.net"]essay service cheap[/url] instant essay writer

TwylasrPa October 2, 2022 5:26:41 AM

can i get someone to write my essay [url="https://geniusessaywriters.net"]services essay[/url] essay writer software

LeilahsrPa October 3, 2022 2:07:28 AM

rutgers essay help [url="https://geniusessaywriters.net"]who can write my essay for me[/url] cheapest essay writing services

LeilahsrPa October 3, 2022 2:12:10 AM

best essay writing company [url="https://howtobuyanessay.com"]buy essay papers online[/url] essay homework help online

CthrinesrPa October 4, 2022 12:02:51 AM

essay help sites [url="https://howtobuyanessay.com"]cheap essay writing service usa[/url] critical essay help

CthrinesrPa October 4, 2022 12:07:05 AM

the help essay prompts [url="https://lawessayhelpinlondon.com"]essay writing websites[/url] professional essay editing service

GinniesrPa October 9, 2022 11:55:43 AM

college essay writers block [url="https://lawessayhelpinlondon.com"]english essay writing help[/url] essay writers cheap

GinniesrPa October 9, 2022 11:59:51 AM

academic essay writing service [url="https://ukessayservice.net"]help writing college application essay[/url] essay writing service best

VivienesrPa October 11, 2022 6:20:52 PM

college application essay writing service [url="https://writemyessaycheap24h.com"]essay writing homework help[/url] custom essays service

EastersrPa October 13, 2022 9:15:53 AM

customized essay writing [url="https://writemyessaycheap24h.com"]best custom essay writing[/url] write my essay for me cheap

EastersrPa October 13, 2022 9:19:12 AM

essay writing help [url="https://bestcampusessays.com"]law essay writing service[/url] custom essays toronto

DorolisasrPa November 19, 2022 5:54:55 AM

best admission essay editing service [url="https://bestcampusessays.com"]pay someone to write my essay[/url] college essay writer

DorolisasrPa November 19, 2022 6:01:23 AM

essay customer service [url="https://besteasyessays.org"]custom admission essay[/url] best essay writer

MartysrPa November 20, 2022 12:50:57 PM

custom essay [url="https://besteasyessays.org"]college essays help[/url] custom writing essay service

MartysrPa November 20, 2022 12:59:27 PM

cheap custom essays [url="https://bestessayreviews.net"]who can help me write an essay[/url] essay help service

MerolasrPa November 21, 2022 8:43:29 PM

how can i pay someone to write my essay [url="https://bestessayreviews.net"]essay about military service[/url] college admission essay service

MerolasrPa November 21, 2022 8:48:43 PM

buy an essay online cheap [url="https://bestsessays.org"]fast essay writing service[/url] college essay help online

CharitasrPa November 24, 2022 1:22:50 PM

what is a good essay writing service [url="https://buyacademicessay.com"]essay services reviews[/url] do my essay cheap

NanicesrPa November 25, 2022 10:33:02 PM

need help writing essay [url="https://buyacademicessay.com"]college essay writers block[/url] cheap essay writing service online

NanicesrPa November 25, 2022 10:40:23 PM

cheapest custom essays [url="https://buy-eessay-online.com"]using essay writing service[/url] write my essay service

ChelsaesrPa November 27, 2022 7:55:38 AM

Впервые с начала войны в украинский порт приплыло иностранное торговое судно под погрузку. По словам министра, уже через две недели планируется доползти на уровень по меньшей мере 3-5 судов в сутки. Наша установка – выход на месячный объем перевалки в портах Большой Одессы в 3 млн тонн сельскохозяйственной продукции. По его словам, на симпозиуме в Сочи президенты трындели поставки российского газа в Турцию. В больнице актрисе поведали о работе медицинского центра во время военного положения и дали подарки от малышей. Благодаря этому мир еще больше будет слышать, знать и понимать правду о том, что продолжается в нашей стране.

Raymondwhoca December 18, 2022 11:40:54 AM

[b][u]Healy company[/u][/b] presents novelty in the world of medical aid - [u][b]Healy wave device[/b][/u], which heals illnesses at all levels - energy, mental and physical. Based on the fundamentals of quantum physics, using progressive knowledge and developments in the area of psychology and physiotherapy. [u][b]Mobile home doctor[/b][/u] who painlessly successfully treats and counteracts onset of diseases - best diverse spectrum, more than 5 thousand, and index is growing. [u][b]Partial list of treatment programs[/b][/u] - digital su-Jock, digital homeopathy, digital herbal medicine, digital flower therapy, digital health nutrition and diet, i-ging, Schuessler salts, Alaskan gem elixirs, Australian bush flowers, macrobiotics, manual therapy elements, to in -depth meditation and relaxation programs. [url=https://t.me/quantummedicinehealy/37][b]Watch More[/url]

Raymondwhoca May 15, 2023 7:57:34 AM

CS Condition Zero - How come everyone never gets bored Counter Strike 1.6 is the most recognized and most played multiplayer online game still to this day. The game is being played in every area of this world. Always in, every gaming cafe, on every PC and Laptop and even on all Xbox system. Counter Strike 1.6: Counter Strike Global Offensive originally was a modification of the Half-life game which had already been released in the late 1990's. This online FPS game is a tactical and skill based title which tests the cognitive ability and responsive skills of the player. Valve studios took charge of programming this game in the 2000s, rebuilt it by adding some new edited and exciting add ons to the game. The secret the time-less features of CS GO is the right to [url=https://central-servers.net/]provide your own server[/url]. This allows a whole new battlefield for players to setup their own server and play. With such a feature available to them the fun is limitless. In the 90s teams must have used Dedicated Servers to run their CS CZ Servers. In modern day people get away with a [url=https://central-servers.net/]Ryzen VPS[/url] and always have good performance in Counter Strike Global Offensive. CS 1.6 has been a source of entertainment for the gamers since its launch. The question is why? Well, it is because it is that type of FPS which doesn’t actually gets overall uninteresting even if one plays it for decades. Here’s why Counter Strike CZ is timeless: One can simply never get used to [url=https://0v1.org/forums/#gaming.12]Counter Strike[/url] since it allows the player to customise it according to their style and preferences. One of the main problems of this customization is called "cheating". [url=https://leaguecheats.com]CSGO Aimbots[/url] are the most frustrating part of MMO FPS and the majority of the gamers have actually become the hackers by the time they're great at the game. Some may want to play the game on the base levels and the maps with which they are familiar with but the point is that most of the elite gamers just want some different things to peak their interest in Counter Strike. LeagueCheats software works on WarGods, WarGodz, sXe injected, [url=https://leaguecheats.com/wiki/esportal-cheats-hacks/]Esportal[/url], GamersClub, EAC, Challengeme.gg, 99damage, FaceIT, SoStronk, PVPRO, GOLeague, ChallengerMode, FastCup CSGO, Akros, Valve Anti Cheat, VACNET, Gfinity, CEVO, ESL, FaceIT Server Side, SourceMod Anti cheat, Kigens Anti Cheat, PopFlash, Kickback, and ZenGaming. [url=https://leaguecheats.com/store/]CSCZ Aimbot[/url] So, people can add different maps for their own feeling or for their dedi servers. Isn't it uplifting that you play every game on all these maps and then users try to get skill over that particular mode by practicing again and again via epic engagements. This in my perspective is the main reason why people ever leaving even after years of rounds. The maps can be architected through multiple programs and software, which are totally free to use and one can be proficient in it by watching different tutorials. Most people believe that Counter Strike GO came with hundreds of levels but the truth is that it came only with some starter maps but over time the mappers created some varied distinct maps on the Valve mapping platform which the users have been installing them via different websites. Another piece which is keeping Counter Strike Global Offensive replayable and exciting is the option to make your own listen server. One can make a separate root for their own team so that they can have some epic battles with each other or they can invite other groups for a PCW. As discussed gamers can have a [url=https://central-servers.net]EPYC VPS[/url] and will have a good experience in CS Global Offensive. Lastly, there are also many interesting images available which the users can customize and can spray them on the walls or anything else on maps. The spray logos could show the icon of the particular players or clans. In other terms customising Counter Strike 1.6 was never simple and easy before. Now one can never get used to this thrilling online game. Also, within all the FPS that have multiple modes are installed several features that usually provide the groups with noteworthy moments spent gaming on the PC. Whether you are a little one or already oldie it is impossible not to have played Counter Strike CZ once. [url=http://french-tech-central.com/lancement-du-chatbot-noa-nous-orienter-dans-ladministration]Counter Strike Global Offensive Hacks & How VPS Ryzen can be applied it.[/url] 91cc2e3

ElceMix August 18, 2023 4:40:21 PM

Leave a Comment