Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Visual C# » Populating a Generic Data List with Generic method

Populating a Generic Data List with Generic method

This article describes how to use a Generic List as a data object and how to fill it with a generic method.

Page Views : 24696
Downloads : 276
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
SridharSubramanianFillGenericDataCollection.zip
 
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


This approach helps us not to customize our Data Access Layer for different type of data classes. Consider we have some "Data class" in our application and we want the data class to act as a collection, Generally what  we do is declare a "Generic List" (New feature in 2.0) of that data class type and populate our data list from the database.

For populating the list, we loop through the data class with customized code and add the class to our list collection. This will be tedious and time consuming if we have hundreds of classes where we need to rewrite the same code again and again.

To avoid that I have conceived a new approach where we can pass the object of the class as a parameter and as a output we get a Generic Data List. Then we can typecast the Generic list back to our custom List collection.This is accomplished using reflection.

In the below example I will explain how to do it, consider we have a data class called Person.

Data Class Person Data Object

public class Person
{
   // Required to create multiple instance through reflection
    public object Clone()

    {
        Person person = new Person();
       
return (object)person;
    }

     private string _Name;
     public string Name

     {
      set{_Name=value;}
      get { return _Name; } 
     }

    private string _Address;
    public string Address
    {
        set { _Address = value; }
        get { return _Address; }
    }

    private string _City;
    public string City
    {
        set { _City = value; }
        get { return _City; }
    }

    private string _State;
    public string State
    {
        set { _State = value; }
        get { return _State; }
    }

    private string _Country;
    public string Country
    {
        set { _Country = value; }
        get { return _State; }
    }

In UI create the instance of the Data object and pass it to the method "ExecuteGenericList". ExecuteGenericList method process the passed object and creates a collection of the object depending upon number of rows we get from our select query. Little bit of type casting has to be done to the returned Generic List to convert it to our typed data list Person.

UI Page Load
 
//Create instance of data object
        Person person = new Person();
        DAL dal = new DAL();

       // dal.ExecuteGenericList(person) returns a Generic data list of the type  person

      // ConvertAll<Person>(new Converter<object, Person>(delegate(object o) { return (Person)o; })); typecasts the generic list to the type   List<Person> 
      
        List<Person> lstPerson = dal.ExecuteGenericList(person).ConvertAll<Person>(new Converter<object, Person>(delegate(object o) { return (Person)o; }));

        // Can be assigned to a DataSource
        GridView1.DataSource = lstPerson;
        GridView1.DataBind();

Our DAL class "ExecuteGenericList" uses reflection to iterate through all the properties of the class and creates a generic list collection for each and every row

DAL  Where our object is read and returned as List

    /// <summary>
    /// ExecuteGenericList is used to fill all properties any passed  data object
    /// Author :Sridhar Subramanian
    /// </summary>
    /// <param name="objectClass">Object which type has to be filled and returned as Generic List</param>
    /// <param name="parameter1">SQL query parameter,you can use SP </param>
    /// <returns>Generic List of the passed type </returns>
    public List<Object> ExecuteGenericList(object objectClass)
    {
        List<Object> lstGenric = null;
        try
        {
            sqlConnection = new SqlConnection(@"Server=SridharDev;Database=EntLibTest;Uid=Test;Pwd=Test;");
            sqlConnection.Open();
            sqlCommand = new SqlCommand("SELECT * FROM PERSON", sqlConnection);
            sqlDataReader = sqlCommand.ExecuteReader();
            lstGenric = new List<Object>();
            Type theType = objectClass.GetType();
            PropertyInfo[] p = theType.GetProperties();
            MethodInfo m = theType.GetMethod("Clone");
            ConstructorInfo ci = theType.GetConstructor(Type.EmptyTypes);
            object cunInv = ci.Invoke(null);
            object newObject = null;
            object[] custAttr = null;
            while (sqlDataReader.Read())
            {
                newObject = m.Invoke(cunInv, null);
                foreach (PropertyInfo pi in p)
                {
                    try
                    {
                        custAttr = pi.GetCustomAttributes(true);
                        if ((sqlDataReader[pi.Name] != System.DBNull.Value) && (custAttr.Length == 0))
                            pi.SetValue(newObject, sqlDataReader[pi.Name], null);
                   }
                    catch (System.IndexOutOfRangeException) { }
                }
                lstGenric.Add(newObject);
            }                      
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (sqlDataReader.IsClosed == false)
                sqlDataReader.Close();
            if (sqlConnection.State == ConnectionState.Open)
                sqlConnection.Close();
            sqlConnection.Dispose();
        }
        return lstGenric;
    }

Download Source code to see the worked out example.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Sridhar Subramanian
Sridhar is working in Software field since 2000. He has good experience in Microsoft .NET and web related technologies.

www.newsdabba.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
You should not expose List T by ts_az On October 17, 2008
You should not expose List(object) See: http://msdn.microsoft.com/en-us/library/ms182142(VS.80).aspx List(T) is designed for speed and for use as an internal implementation detail, whereas Collection(T) is designed for extensibility.
Reply | Email | Modify 
Slow Way by michael On November 17, 2008
For small result sets this will work but can be slow for larger sets. The sqlDataReader[pi.Name] has to perform look up by name to find the name in the data read every time through the loop. By using the Data Reader's GetSchemaTable() method, a mapping can be created between the reader and the property information. This removes the every time through the loop lokk up. For absolute blinding speed for result sets of more than 5,000 rows, the pi.SetValue, i.e - reflection, can be removed from the inside of the loop by using dynamic comipling. Dynamic comipling is blazingly fast but there are sme trade offs which is why I only use it for large result sets.
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.