Results 1 to 9 of 9

Thread: Help Understanding Basic MEF development

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Feb 2013
    Posts
    985

    Help Understanding Basic MEF development

    Hi

    i just started looking into this today and i think i understand it but the example from microsoft that i was learning from has the usual extra stuff that doesnt really need to be there. and im having a hard time getting my head around it

    just for practice i want to hard code the 'part' since i know how to get the parts from files already.

    this is what i have so far

    1 form with 1 datagridview 1 textbox 1 button

    i want to put a path to an xl file press the button and let the 'part' start an oledb connection read the xl file close connection and then send the object back
    (as an object since i may use it for other types later) oledb is not a problem i can do that, its purely the MEF side of things.

    so... the code haha wait for it
    Code:
    Public module module1
    public interface IGetFileData
             Function GetFileData(fullpath as string)as object
    end interface
    
    <a program class i think needs to go here, its shown below, which will be instantiated when i press the button i think>
    
    end module
    and then i got stuck with the way microsoft showed it all on msdn
    this i think i need but it has parts of the calculator example on it <below>

    Code:
    Public Class Program
            Dim _container As CompositionContainer
    
            <Import(GetType(ICalculator))>
            Public Property calculator As ICalculator
    
    
            Public Sub New()
                'An aggregate catalog that combines multiple catalogs
                Dim catalog = New AggregateCatalog()
    
                'Adds all the parts found in the same assembly as the Program class
                catalog.Catalogs.Add(New AssemblyCatalog(GetType(Program).Assembly))
    
                'IMPORTANT!
                'You will need to adjust this line to match your local path!
                catalog.Catalogs.Add(New DirectoryCatalog("C:\Users\Main Admin\Documents\Visual Studio 2010\Projects\MEF Calculator\SimpleCalculator2\Extensions"))
    
    
                'Create the CompositionContainer with the parts in the catalog
                _container = New CompositionContainer(catalog)
    
                'Fill the imports of this object
                Try
                    _container.ComposeParts(Me)
                Catch ex As Exception
    
                End Try
            End Sub
    
        End Class
    and i need to strip the code here to start the 'Part' that i actually need to use, but it looks like theres more interfaces then i actually need, im not sure the example used a console heres some more <below>

    Code:
    <Export(GetType(ICalculator))>
        Public Class MySimpleCalculator
            Implements ICalculator
    
            <ImportMany()>
            Public Property operations As IEnumerable(Of Lazy(Of IOperation, IOperationData))
    
    
            Public Function Calculate(ByVal input As String) As String Implements ICalculator.Calculate
                Dim left, right As Integer
                Dim operation As Char
                Dim fn = FindFirstNonDigit(input) 'Finds the operator
                If fn < 0 Then
                    Return "Could not parse command."
                End If
                operation = input(fn)
                Try
                    left = Integer.Parse(input.Substring(0, fn))
                    right = Integer.Parse(input.Substring(fn + 1))
                Catch ex As Exception
                    Return "Could not parse command."
                End Try
                For Each i As Lazy(Of IOperation, IOperationData) In operations
                    If i.Metadata.Symbol = operation Then
                        Return i.Value.Operate(left, right).ToString()
                    End If
                Next
                Return "Operation not found!"
            End Function
    
            Private Function FindFirstNonDigit(ByVal s As String) As Integer
                For i = 0 To s.Length
                    If (Not (Char.IsDigit(s(i)))) Then Return i
                Next
                Return -1
            End Function
    
    
        End Class

    heres the interfaces and 1 of the parts <below>

    Code:
        Public Interface ICalculator
            Function Calculate(ByVal input As String) As String
        End Interface
    
        Public Interface IOperation
            Function Operate(ByVal left As Integer, ByVal right As Integer) As Integer
        End Interface
    
        Public Interface IOperationData
            ReadOnly Property Symbol As Char
        End Interface
    
    
        <Export(GetType(IOperation))>
        <ExportMetadata("Symbol", "+"c)>
        Public Class Add
            Implements IOperation
    
            Public Function Operate(ByVal left As Integer, ByVal right As Integer) As Integer Implements IOperation.Operate
                Return left + right
            End Function
        End Class
    please help , i understand what is happening a little
    but i never used an interface before but i looked it up i think i get that, why are they using so many though

    the import/export i understand is checking if the 'part' is allowed to be used, i dont understand the syntax though for them both,

    Code:
    <Export(GetType(IOperation))>
        <ExportMetadata("Symbol", "+"c)>
    
    <ImportMany()>
            Public Property operations As IEnumerable(Of Lazy(Of IOperation, IOperationData))
    i know someone who has done this should easily help me out here.
    Yes!!!
    Working from home is so much better than working in an office...
    Nothing can beat the combined stress of getting your work done on time whilst
    1. one toddler keeps pressing your AVR's power button
    2. one baby keeps crying for milk
    3. one child keeps running in and out of the house screaming and shouting
    4. one wife keeps nagging you to stop playing on the pc and do some real work.. house chores
    5. working at 1 O'clock in the morning because nobody is awake at that time
    6. being grossly underpaid for all your hard work


  2. #2

    Thread Starter
    Fanatic Member
    Join Date
    Feb 2013
    Posts
    985

    Re: Help Understanding Basic MEF development

    Maybe it wasnt clear what i wrote earlier ill try again sorry.....

    I'm trying to learn to use 'Managed Extensibility Framework' aka 'MEF' to create an application which i can add extensions (i think thats obvious )

    its using interfaces and implementations to use code from a method hard-coded/loaded as if it was a part of the main program itself. basically its a way of adding any code you want to a program at run-time.
    i just need a little guidence regarding 'interfaces and implements' keywords, and how i need to use them with the MEF

    second, the imports and exports keywords used with MEF, which basically need to match up to allow the main program to run added modules, i just need a little help understanding the syntax.

    any help would be appreciated, the sample project im learning with is 'SimpleCalculator MEF tutorial' at microsoft.com

    thanks
    Yes!!!
    Working from home is so much better than working in an office...
    Nothing can beat the combined stress of getting your work done on time whilst
    1. one toddler keeps pressing your AVR's power button
    2. one baby keeps crying for milk
    3. one child keeps running in and out of the house screaming and shouting
    4. one wife keeps nagging you to stop playing on the pc and do some real work.. house chores
    5. working at 1 O'clock in the morning because nobody is awake at that time
    6. being grossly underpaid for all your hard work


  3. #3
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Help Understanding Basic MEF development

    Quote Originally Posted by GBeats View Post
    I'm trying to learn to use 'Managed Extensibility Framework'...
    Good for you! It's kind of a lot to take in if you don't have a good basic programming base to go off of.

    The first place to look is always the documentation.

    I would recommend you take a look at the Interfaces in Visual Basic .NET documentation.

    Once you've gone through that take a look at the Managed Extensibility Framework (MEF) msdn article. It goes through and explains what's happening in the example you're trying to work through. The page has definitions of the Export, Import and ImportMany attributes which are tripping you up. If you click on the Attributed Programming Model Overview on the left hand side of the link you'll get a much more detailed breakdown.

    If after you've gone through those links you still have questions feel free to ask and we'll answer to the best of our knowledge.
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  4. #4

    Thread Starter
    Fanatic Member
    Join Date
    Feb 2013
    Posts
    985

    Re: Help Understanding Basic MEF development

    Ive got 3 tutorials here all on MEF, each one is doing it in different ways

    the one i like the best unfortunately is in C#, but it's quite clear because it seperates all the componnents into different projects so i can identify what part belongs to what object/component if you see what i mean. and its using the simplecalculator example like microsofts example. but its in C zzZZ. im not familiar with the class decorations in vb never mind c so im still a little confused.

    the C sample has these projects
    1 contract
    2 main program (calculator with form)
    3 composition helper

    from what i gather, the composition helper basically is what gets the extensions and what puts everything together into a usable program if you will.

    the contract basically is the program saying i want whatever interface type with whatever metadata(<metadata name>, <variable used for extension name>), and the extension saying i have whatever type with whatever metadata(<matching metadata name>, <extension name/what to call it with>)

    i understand the imports, allowing certain extensions from certain places etc

    why do you have to add main program to the library of extensions, is the program also considered an extension by the engine controlling everything?

    could someone explain these few things below (this is C code by the way, i also have the vb code. i just want a quick guide on whats happening with it).....

    [Export(typeof(ICalculator))] is the export linked with the import, or is it just used for the interfaces

    [Import(typeof(ICalculator))]
    public ICalculator CalciPlugin { get; set; } i have no idea what this is doing, is it like-- 'property calciplugin as icalculator.....'



    if i have a program, i need a function to call the extension and get a return value, im getting confused because i see several functions like that, are they all neccessary?
    Yes!!!
    Working from home is so much better than working in an office...
    Nothing can beat the combined stress of getting your work done on time whilst
    1. one toddler keeps pressing your AVR's power button
    2. one baby keeps crying for milk
    3. one child keeps running in and out of the house screaming and shouting
    4. one wife keeps nagging you to stop playing on the pc and do some real work.. house chores
    5. working at 1 O'clock in the morning because nobody is awake at that time
    6. being grossly underpaid for all your hard work


  5. #5

    Thread Starter
    Fanatic Member
    Join Date
    Feb 2013
    Posts
    985

    Re: Help Understanding Basic MEF development

    Ive got my UI ready, i just need to put the code so i can start making the extensions, so far all i have is ui, should i be creating another project for composition, or should everything be contained in 1 project for simplicity?

    btw the UI.. all it does is list the modules runs them and creates a report, leets say the modules will do simple file manipulations, so no ui or information is needed exept a report which all my modules will return to the program when finished
    Yes!!!
    Working from home is so much better than working in an office...
    Nothing can beat the combined stress of getting your work done on time whilst
    1. one toddler keeps pressing your AVR's power button
    2. one baby keeps crying for milk
    3. one child keeps running in and out of the house screaming and shouting
    4. one wife keeps nagging you to stop playing on the pc and do some real work.. house chores
    5. working at 1 O'clock in the morning because nobody is awake at that time
    6. being grossly underpaid for all your hard work


  6. #6
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Help Understanding Basic MEF development

    If you don't really understand the Interface and Implements keywords and the idea of polymorphism in OO, then you should probably hold off on MEF until you've got a bit more experience with them. It shouldn't take long to grasp them, though.

    An interface just defines the "shape" of an object, and lets code use anything that fits that "shape" without worrying about what exactly it's using. Essentially, it's like a base class (which you Inherit from) except there is no code in it or fields. In the same way that if you have ClassA and ClassB inheriting from BaseClass, you can put either an instance of ClassA or an instance of ClassB in a variable that is typed as BaseClass, you can do the same with an interface IDoSomething with classes DoSomethingA and DoSomethingB both implementing that interface, you can define a variable of type IDoSomething and put either an instance of DoSomethingA or DoSomethingB in there.

    Because the code that uses the myDoSomething variable doesn't reference DoSomethingA or DoSomethingB (only IDoSomething) then there's no reason you can't have some completely new implementation that you don't know about put in that variable. That's the basis of MEF, it simplifies finding and instantiating implementations at runtime. Without something like MEF (and MEF is by no means the only way of doing this) you'd need something that knew about those classes at compile time in order to instantiate them and supply them to the rest of the code.

  7. #7
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Help Understanding Basic MEF development

    Quote Originally Posted by GBeats View Post
    Ive got 3 tutorials here all on MEF, each one is doing it in different ways

    the one i like the best unfortunately is in C#, but it's quite clear because it seperates all the componnents into different projects so i can identify what part belongs to what object/component if you see what i mean. and its using the simplecalculator example like microsofts example. but its in C zzZZ. im not familiar with the class decorations in vb never mind c so im still a little confused.
    You can try using a converter to get vb.net from the C# example. This one usually does a pretty good job.

    I'll restate what I said in my original post though; get a grasp on interfaces before you jump into the DI / IoC scenarios. MEF is an excellent addition to app composition but you'll be doing yourself a huge favor to learn the basics and then build up from there.
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  8. #8

    Thread Starter
    Fanatic Member
    Join Date
    Feb 2013
    Posts
    985

    Re: Help Understanding Basic MEF development

    ok, im reading and reading and i come up with this.

    as far as MEF is concerned with interfaces

    you will have a class that sets up interfaces with modules(extensions) using the MEF engine

    then you create an interface with that class to use it within your project?

    in effect when you want to use module1 you tell the class to get module1 then through your interface and the classes own you can use that module.

    is that why im seeing more than 1 interface setup on these MEF examples?

    im still trying to get my head around it all
    Yes!!!
    Working from home is so much better than working in an office...
    Nothing can beat the combined stress of getting your work done on time whilst
    1. one toddler keeps pressing your AVR's power button
    2. one baby keeps crying for milk
    3. one child keeps running in and out of the house screaming and shouting
    4. one wife keeps nagging you to stop playing on the pc and do some real work.. house chores
    5. working at 1 O'clock in the morning because nobody is awake at that time
    6. being grossly underpaid for all your hard work


  9. #9

    Thread Starter
    Fanatic Member
    Join Date
    Feb 2013
    Posts
    985

    Re: Help Understanding Basic MEF development

    Hi

    i managed to put together a simple app, to be honest its more or less the example but i changed all the names so intelisense can point out where everything is linked, which helped.

    anyway it was quite easy doing it, i learned a couple more things, here it is....

    Code:
    Imports System.ComponentModel.Composition
    Imports System.ComponentModel.Composition.Hosting
    
    Public Module Module1
        Public Interface IActions
            'interface for the parts
            Function PartCode(ByVal input As String) As String
        End Interface
    
        <Export(GetType(IActions))> _
        Public Class MyActionEngine
            'this class is the part that will be imported
            Implements IActions
    
            Public Function PartCode(ByVal input As String) As String Implements IActions.PartCode
                Return input & " hello"
            End Function
        End Class
    
        Public Class Program
            Dim Mycontainer As CompositionContainer 'holds parts and performs composition(imports/exports)
    
            <Import(GetType(IActions))> _
            Public Property Action As IActions  'MEF finds exports based on type,if no type is given  the propert type will be assumed
    
            Public Sub New()
                'An aggregate catalog that combines multiple catalogs
                Dim catalog = New AggregateCatalog()
    
                'Adds all the parts found in the same assembly as the Program class
                catalog.Catalogs.Add(New AssemblyCatalog(GetType(Program).Assembly))
    
                'Create the CompositionContainer with the parts in the catalog
                Mycontainer = New CompositionContainer(catalog)
    
                'Fill the imports of this object
                Try
                    Mycontainer.ComposeParts(Me)
                Catch ex As Exception
                    Console.WriteLine(ex.ToString)
                End Try
            End Sub
        End Class
    
    End Module
    the form code

    Code:
     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim p As New Program()
            Dim InString As String = Me.TextBox1.Text
            Dim OutString As String
    
            OutString = p.Action.PartCode(InString)
            Me.TextBox1.Text = OutString
    
    End Sub

    next step is changing MyActionEngine Class to handle Choosing which part needs to be used based on my choice, i think i need another interface for that which will beused to interface the parts to the actionengine which in turn will be linked with the program class

    is this right
    Yes!!!
    Working from home is so much better than working in an office...
    Nothing can beat the combined stress of getting your work done on time whilst
    1. one toddler keeps pressing your AVR's power button
    2. one baby keeps crying for milk
    3. one child keeps running in and out of the house screaming and shouting
    4. one wife keeps nagging you to stop playing on the pc and do some real work.. house chores
    5. working at 1 O'clock in the morning because nobody is awake at that time
    6. being grossly underpaid for all your hard work


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width