Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

CreateInstance Method Parameter Question on ActivationAttributes

Posted on 2003-11-05
11
Medium Priority
?
1,074 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

 

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
 

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 1500 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

Application Discovery Service in AWS

In the era of the cloud, customers migrating away from their existing on-premise infrastructure. This requires lots of planning, strategies, and effort to identify their existing resources and determine how best to migrate.  Datacenter migrations happen in four phases -

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

715 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