Solved

CreateInstance Method Parameter Question on ActivationAttributes

Posted on 2003-11-05
11
1,020 Views
Last Modified: 2007-12-19
I am doing the following to utalize a DLL in my application that may/may not exist.  Anyway, all I need to figure out is how to pass an object as an argument to the class constructor when the instance is created.

If I were doing it with a dll I had a reference to in the project I could just do the following:
Dim oMyNewObject as New vtxObject.Company(oSettings)

However, when I do it like this using reflection I can't figure out how to pass the argument object, it makes me supply more info than I know/understand.

Dim ofrmCustom As Object
Dim myDLL As [Assembly]

Try
      myDLL = [Assembly].LoadFrom("My.dll")
      ofrmCustom = myDLL.CreateInstance("vtxEDCFSC.Form1")  'I NEED TO SUPPLY ARGS HERE
      ofrmCustom.MdiParent = Me
      ofrmCustom.Show()
      ofrmCustom.BringToFront()
Catch ex As Exception
      Debug.WriteLine("Threw Error: " & ex.Message)
End Try

Having problem with activation attributes.  Please tell me what to put where the ?? are below, I can't figure it out.  As far as I know my new class doesn't need any of the ?? parameters.

ofrmCustom = myDLL.CreateInstance(oModules.ClassName, True, BindingFlags.CreateInstance, ??, oSettings, ??, ??)

Please don't provide me with the CreateInstance method documentation, I've seen it.  I just need an example of what to put where the ??'s are above.  Please provide the entire line including all arguments in the method call exactly as you think they will work.

Thanks, I appreciate your time.   Scott Carullo
0
Comment
Question by:carullos
  • 5
  • 5
11 Comments
 
LVL 4

Expert Comment

by:NetPointer
ID: 9689541
0
 

Author Comment

by:carullos
ID: 9690448
Thanks, I tried using NULL but never dawned on me to try Nothing, dah..  It is happy with the argument except for the Args now - where I have oObject below: (see below code for more explanation)

    Private Sub mnuVortexModule(ByVal sGUID As String)
        Dim ofrmCustom As Object
        Dim myDLL As [Assembly]
        Dim oModules As New vtxObject.Modules(oSettings)
        Dim oObject As Object = oSettings

        If oModules.Load(sGUID) Then
            Try
                'Dim sDLLName As String = "vtxEDCFSC.dll"
                myDLL = [Assembly].LoadFrom(Application.StartupPath & oModules.DLLPath & oModules.DLLName)
                Debug.WriteLine("Object loaded...")
                'Dim sFeature As String = "vtxEDCFSC.Form1"
                ofrmCustom = myDLL.CreateInstance(oModules.ClassName, True, BindingFlags.CreateInstance, Nothing, oObject, Nothing, Nothing)
                Debug.WriteLine("Instance created...")
                ofrmCustom.MdiParent = Me
                ofrmCustom.Show()
                ofrmCustom.BringToFront()
                'Debug.WriteLine(ofrmCustom.HW)
            Catch ex As Exception
                Debug.WriteLine("Threw Error: " & ex.Message)
            End Try
        End If
    End Sub

What I want to send to the class constructor is another instance of a different class that has all my application settings defined.  Typically I do something like the following:

Dim oSettings as new vtxObject.Settings
oSettings.Load
'Now I have Settings, open another form (class)
Dim oForm as new Form1(oSettings)
oForm.Show

The Form1 (or any class) Constructor looks like this in my app:
==================================================
    Private oSettings As Settings
    Private sConnectionString As String
    Private iCommandTimeout As Integer

    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByRef AppSettings As Settings)
        Me.New()
        oSettings = AppSettings
        sConnectionString = oSettings.ConnectionString
        iCommandTimeout = oSettings.CommandTimeout
    End Sub

    Public Property ConnectionString() As String
        Get
            Return sConnectionString
        End Get
        Set(ByVal Value As String)
            sConnectionString = Value
        End Set
    End Property

    Public Property CommandTimeout() As Integer
        Get
            Return iCommandTimeout
        End Get
        Set(ByVal Value As Integer)
            iCommandTimeout = Value
        End Set
    End Property
================================================

I need to send all these settings in my oSettings class instance to the new class I am trying to creat an instance of above - its just that the DLL is an optional module so its being loaded if available at runtime and I'm not sure how to allow it to access all the information available publically in the main app that opened it.  There may even be a totally different way thats easier??

Any ideas?  I need a solution asap.  Increasing points to 500.  Thanks.
0
 
LVL 4

Expert Comment

by:NetPointer
ID: 9690594
ofrmCustom = myDLL.CreateInstance(oModules.ClassName, True, BindingFlags.CreateInstance, Nothing, oObject, Nothing, Nothing)

What I understood is u r passing your settings as oObject as a constructor arg..right?

this should work, if yr constructor of omodule.classname is accepting that param....
is it so?

as an alternative, u can create a method Init or something in your class which accepts this osettings object and do your work..and clients has to call this method at first...just an idea..

by the way what is the error u r getting?

Regards,
NetPointer
0
 

Author Comment

by:carullos
ID: 9690901
The error I am receiving is:

Specified cast is not valid.

I'm wondering if the Args have to be specifically an array or any object.  I was just sending an instance of a class saved to an object var like:

Dim oSettings as New vtxObject.Settings
oSettings.Load   'this populates the properties from db
Dim oObject as Object = oSettings

then:
ofrmCustom = myDLL.CreateInstance(oModules.ClassName, True, BindingFlags.CreateInstance, Nothing, oObject, Nothing, Nothing)

I presume the cast problem is with the object and the way I was trying to send it.  Anyone know how to pass my oSettings instance, and can I pass it by reference to a class from an external dll like this or does it have to be by value?  

Thanks -Scott Carullo

0
 
LVL 4

Expert Comment

by:NetPointer
ID: 9691518
what is the signature of constructor???

check that it is like this.

Public sub new (osetting as Object)

and not your class name...
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:carullos
ID: 9691526
Looks like this:

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private oSettings As vtxObject.Settings

#Region " Windows Form Designer generated code "

    Public Sub New(ByVal oObject As Object)
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call
        oSettings = oObject
    End Sub
0
 
LVL 4

Expert Comment

by:NetPointer
ID: 9695377
if u try the following way, it will show us that whether problem is in calling or when casting it back to osettings.

Public Sub New(ByVal oObject As Object)
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()
        msgbox("Before casting")
        'Add any initialization after the InitializeComponent() call
        oSettings = oObject
        msgbox("after casting")
    End Sub
0
 

Author Comment

by:carullos
ID: 9695727
Its kinda interesting, but while waiting on a possible solution to this problem I went on to working on the next part of my program, which sends different kinds of email (html, text, web page etc..) to different target audiences based on groups.  Anyway, I could not remember off the top of my head how to quickly add a new row to a datatable that was just filled so I went to Google, and ran across this method and used it in my program:

        If Len(txtToAddress.Text.Trim) > 0 Then
            moDT.Rows.Add(New Object() {"", "", "", "", txtToName.Text.Trim, txtToAddress.Text.Trim})
        End If

That led me to thinking, hey, this create instance wants an object I'll try feeding it like this:

                ofrmCustom = myDLL.CreateInstance(oModules.ClassName, True, BindingFlags.CreateInstance, Nothing, New Object() {oSettings}, Nothing, Nothing)

It worked...  Could someone be so kind as to explain why, what the difference is etc.

To answer your question netpointer, the error was being generated on the createinstance call itself, it never did get to the constructor of the class it was creating an instance of.  I'm past it I just want to understand more about it.

Thanks -Scott
0
 

Author Comment

by:carullos
ID: 9695742
I should have asked more specifically what this is doing:

New Object() {oSettings}

or

New Object() {"", "", "", "", txtToName.Text.Trim, txtToAddress.Text.Trim}

Thanks -Scott
0
 
LVL 4

Accepted Solution

by:
NetPointer earned 500 total points
ID: 9697067
It creates a new object from the given values between {}

in first case it takes osettings and from it it creates a new object and pass it further...

in second case, it creates new object with all the fields name given within {} corresponds to the column names..so it returns the new row object in that case which will be added to the rows collection then..

hope this clears this.

in further investing above things we were trying...
Dim oSettings as New vtxObject.Settings
oSettings.Load   'this populates the properties from db
Dim oObject as Object = oSettings

now if we check the type of oobject i assume that it will return settings....and that might be the reason it was not taking that as a arg to the new.

regards,
netpointer
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 10255874
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

Accept: NetPointer {http:#9697067}

Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

TheLearnedOne
EE Cleanup Volunteer
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now