Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » 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.

Total page views :  20523
Total downloads :  181
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
SridharSubramanianFillGenericDataCollection.zip
 
Become a Sponsor


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.


Login to add your contents and source code to this article
 About the author
 
Sridhar Subramanian
Sridhar is working in Software field since 2000. He has good experience in Microsoft .NET and 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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
SridharSubramanianFillGenericDataCollection.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
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 | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.