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
Solved

How to instantiate my business object without useing 'new' keyword.

Posted on 2010-11-10
10
636 Views
Last Modified: 2012-05-10
Below is my Fetch procedure, and this is in BusinessObjectFactory class -  this procedure takes two parameters - 1st parameter I want to send the type of class and other parameter is datarow/data table/ data set.

AssetToleranceBO is my class.

I want to instantiate my class 'AssetToleranceBO ' as below.
AssetToleranceBO assetTol = BusinessObjectFactory.Fetch(typeof(AssetToleranceBO), dr);

Now my question is how to define the parameters in Fetch method?
And also, entitiType.InvokeMember is expecting object[] args - how do I pass this, I want to pass either datarow / data table / data set
Can anyone help me?

public static object Fetch(object objBusiness, object criteria) 
        {
            Type entitiType = objBusiness.GetType();
            object obj = Activator.CreateInstance(entitiType);
            entitiType.InvokeMember("FetchData", BindingFlags.InvokeMethod, null, obj, criteria);
            return obj;
        }


        public class AssetToleranceBO : EntityBusinessBase
    {
        string _acctID;
        string _name;
        
               
        public string ID
        {
            get { return _acctID; }
            set { _acctID = value; }
        }
        
        public string CLASS
        {
            get { return _name; }
            set { _name = value; }
        }


        /// <summary>
        /// Fetches the data.
        /// </summary>
        /// <param name="criteria"></param>
        protected override void FetchData(DataRow criteria)
        { 
            _acctID = criteria["gpq_acct_id"].ToString();
            _name = criteria["acct_name"].ToString();
        }
}

Open in new window

0
Comment
Question by:GouthamAnand
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 34105803
For starters the parameter type would be Type, as in:

     public static object Fetch(Type objBusiness, object criteria)
     {

     }

For the object[] parameter you would do:

     new object[] { yourParameterValue }
0
 
LVL 20

Expert Comment

by:Daniel Van Der Werken
ID: 34106219
This worked for me but I had to use the "new" keyword in the method call.  Otherwise, the type was System.RunTimeType in the Fetch() method and I wasn't able to figure out why.  
 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            BusinessObjectFactory.AssetToleranceBO assetTol = (BusinessObjectFactory.AssetToleranceBO)BusinessObjectFactory.Fetch( new BusinessObjectFactory.AssetToleranceBO(), "Hello There" );
        }
    }

    public static class BusinessObjectFactory
    {
        static BusinessObjectFactory() { }

        public static object Fetch( object objBusiness, object criteria )
        {
            Type entityType = objBusiness.GetType();
            if ( !string.Equals( entityType.UnderlyingSystemType.Name, "RunTimeType", StringComparison.InvariantCultureIgnoreCase ) )
            {
                object obj = Activator.CreateInstance( entityType );
                entityType.InvokeMember( "FetchData", BindingFlags.InvokeMethod, null, obj, new object[] { criteria } );
                return obj;
            }
            else
            {
                return null;
            }
        }

        public class AssetToleranceBO
        {
            public AssetToleranceBO() { }

            public void FetchData( string someString )
            {
                MessageBox.Show( someString );
            }
        }
    }
}

Open in new window

0
 

Author Comment

by:GouthamAnand
ID: 34106989
It says - No parameterless constructor defined for this object. - at object obj = Activator.CreateInstance( entityType );

I have defined parameterless constructor , but still it says - "No parameterless constructor defined for this object"
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 20

Expert Comment

by:Daniel Van Der Werken
ID: 34107707
That's what happened to me when I initially tried it with

BusinessObjectFactory.AssetToleranceBO assetTol = (BusinessObjectFactory.AssetToleranceBO)BusinessObjectFactory.Fetch( typeof( BusinessObjectFactory.AssetToleranceBO ), "Hello There" );


instead of BusinessObjectFactory.AssetToleranceBO assetTol = (BusinessObjectFactory.AssetToleranceBO)BusinessObjectFactory.Fetch( new BusinessObjectFactory.AssetToleranceBO(), "Hello There" );

which are you trying.  Are you trying to use a Type parameter or an object parameter?  I could not get it to work with the Type parameter.  Basically, the type it resolves out to is System.RunTimeType which apparently has no default parameterless constructor.  
0
 
LVL 7

Accepted Solution

by:
keustermans earned 500 total points
ID: 34119470
Try the Code below. You can create any kind of object with it.

 public class ObjectFactory
    {

        public static T CreateInstance<T>()
        {
            object instance = Activator.CreateInstance(typeof(T));
            return (T)instance;
        }


        public static T CreateInstance<T>(string invokeMember, object[] param)
        {
            Type type;
            type = typeof(T);
            object instance = Activator.CreateInstance(type);
            type.InvokeMember(invokeMember, BindingFlags.InvokeMethod, null, instance, param);
            return (T)instance;
        }
    }
0
 
LVL 7

Assisted Solution

by:keustermans
keustermans earned 500 total points
ID: 34119572
You can use the class as follows:

 public class TestClass
    {
        public string a { get; set; }
        public string b { get; set; }

        public string ab
        {
            get
            {
                return a + b;
            }
        }

        public void DoStuff(string arg1, string arg2)
        {
            a = arg1;
            b = arg2;
        }


    }

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TestClass test = ObjectFactory.ObjectFactory.CreateInstance<TestClass>();
            test.a = "abc";
            test.b = "efg";

        }

        private void button2_Click(object sender, EventArgs e)
        {
            TestClass test = ObjectFactory.ObjectFactory.CreateInstance<TestClass>("DoStuff",new object[]{"Test","Class"});
        }
    }
0
 

Author Comment

by:GouthamAnand
ID: 34123103
This is what I am lookin for. Thanks alot.
But I am getting an error at entityType.InvokeMember. It says - "Method Business.Entities.AssetToleranceBO.FetchData' not found.

I have 'FetchData' method in AssetToleranceBO. I am not sure why it is not able to reach there.

please help me. Below is my code.
DataRow dr = AssetToleranceDA.FetchTolerance(assetID);

            AssetToleranceBO assetTol = BusinessObjectFactory.CreateBusinessObject<AssetToleranceBO>(typeof(AssetToleranceBO), dr); 


public static TObject CreateBusinessObject<TObject>(Type objBusiness, object criteria) 
        {
            Type entityType;

            entityType = typeof(TObject);

            object objInstance = Activator.CreateInstance(entityType, true);

            object[] param = new object[] { criteria };

            entityType.InvokeMember("FetchData", BindingFlags.InvokeMethod, null, objInstance, param);

            return (TObject)objInstance;
            
        }

Open in new window

0
 

Author Closing Comment

by:GouthamAnand
ID: 34124264
Thanks a lot. This is exactly what I am looking for.
0
 
LVL 7

Expert Comment

by:keustermans
ID: 34126960
Hi,

It could be because your method si expecting a datarow and you are passing it an object.

Teh solution might be that you actualy put a datarow in the param object array.

I haven't tested this but it seems to be the obvious answer to me.
0
 
LVL 7

Expert Comment

by:keustermans
ID: 34126961
Oh by the way you might have to cast it back to Datarow in the the FetchData function.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

808 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