.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

Leave a Comment