Click here to Skip to main content
15,886,199 members
Articles / Programming Languages / C#

How to automate work when working with a Typed Dataset against a database (CSC)

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
22 Nov 2006CPOL2 min read 32.6K   462   15  
DatasetAdaptor encapsulates a dataset and permits automating the work between the database and the dataset.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DataDigest.Datas.Helper
{

    /// <summary>
    /// DatasetAdaptor encapsulate a dataset and permit to automatize the work between database and this dataset.
    /// </summary>
    /// <author>
    /// Blaise Braye
    /// </author>
    /// <remarks>
    /// It is working upside the tools generated by csc at design time
    /// Then you have to take care about the naming patterns used by this tool
    /// ex. 
    /// if you changed the name of the generated tableadaptors, 
    /// you should change the pattern in GetAdapter to build the good "AdapterNSC" string (adapternamespace)
    /// you can do this by extending this base class and override GetAdapter method for intance...
    /// Currently it doens't need to be generic... but it could be usefull in future...
    /// </remarks>
    /// <typeparam name="T">The type of the dataset to encapsulate</typeparam>
    public class DataSetAdaptor<T> where T : DataSet
    {
        private T dataset = null;

        /// <summary>
        /// Return the encapsulated dataset...
        /// </summary>
        public T Dataset
        {
            get { return dataset; }
        }

        /// <summary>
        /// Return the type of the encapsulted dataset
        /// </summary>
        private Type DataSetType { get { return dataset.GetType(); } }



        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="dataset">the dataset to manage</param>
        public DataSetAdaptor(T dataset)
        {
            this.dataset = dataset;
        }

        /// <summary>
        /// Load datas from database in the dataset
        /// </summary>
        public void Fill()
        {

            // EnforceConstraints permit us to load datas 
            // without care of integrity checking in the dataset during the datas downloading process

            dataset.EnforceConstraints = false;

            try
            {
                foreach (DataTable dt in dataset.Tables)
                {
                    object Adapter = GetAdapter(dt);

                    HlpReflexion.InvokeMethod(
                                      Adapter,
                                      "Fill",
                                      new object[] { dataset.Tables[dt.TableName] });

                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error On Filling", ex.InnerException);
            }

            dataset.EnforceConstraints = true;
        }


        /// <summary>
        /// Initialize the process of update
        /// </summary>
        public void SaveChanges()
        {
            List<DataTable> threated = new List<DataTable>();

            foreach (DataTable dt in dataset.Tables)
                SaveDt(dt, threated);


        }

        /// <summary>
        /// Ensure to save master tables before children by a recurse algorithme.
        /// </summary>
        /// <param name="dt">the table to save</param>
        /// <param name="threated">Allow us to know if a table has been threated or not yet</param>
        private void SaveDt(DataTable dt, List<DataTable> threated)
        {
            // ensure the table is not saved yet
            if (!threated.Contains(dt))
            {
                foreach (DataRelation rel in dt.ParentRelations)
                    // ensure the parent table is not saved yet and that this is not a recursive relation
                    if (!threated.Contains(rel.ParentTable) && !rel.ParentTable.Equals(dt))
                        SaveDt(rel.ParentTable, threated);

                // when each parent are well saved, make the job on the given table
                object Adapter = GetAdapter(dt);
                try
                {
                    HlpReflexion.InvokeMethod(
                                      Adapter,
                                      "Update",
                                      new object[] { dataset.Tables[dt.TableName] });
                }
                catch (Exception ex)
                {
                    throw new Exception("An error has occured while saving", ex.InnerException);
                }
                // flag the table to saved...
                threated.Add(dt);
            }
        }

        /// <summary>
        /// this method will create an instance an automatic adapater generated by csc at design time
        /// </summary>
        /// <param name="dt">the table which needs an adaptor</param>
        /// <returns>object TableAdapter</returns>
        protected object GetAdapter(DataTable dt)
        {
            string AdapterNSC = DataSetType.FullName + "TableAdapters." + dt.TableName + "TableAdapter";
            return HlpReflexion.CreateInstance(DataSetType.Assembly.GetType(AdapterNSC));
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Other UMH
Belgium Belgium
* Bachelor of Information Management at ISAT Charleroi in Belgium.
* Master II of Information science at UMH Mons.

I spend my time in small projects which can help me or small enterprises and
I am very interested in designing projects
with specifications of UML or in applying usual design patterns.

Comments and Discussions