Wednesday, July 8, 2020

Data Table Extensions

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Threading;
using System.Reflection.Emit;
using System.Web.Configuration;

namespace NOBOLO.Library.DataTableExtension
{
    public static class DataTableExtension
    {
        public static List<T> DTtoList<T>(DataTable table) where T : class, new()
        {
            try
            {
                List<T> list = new List<T>();

                foreach (var row in table.AsEnumerable())
                {
                    T obj = new T();

                    foreach (var prop in obj.GetType().GetProperties())
                    {
                        try
                        {
                            PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                            propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    list.Add(obj);
                }

                return list;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        ///  Convert a database data table to a runtime dynamic definied type collection (dynamic class' name as table name).
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        /// 
        public static dynamic ToDynamicList(DataTable dt, string className = "class", bool UsePagination = false, bool Addextracolumn = false)
        {
            if (UsePagination == true)
            {
                Dictionary<string, object> _obj = new Dictionary<string, object>();
                if (dt.Rows.Count > 0)
                {
                    _obj.Add("PageNo", Convert.ToInt32(dt.Rows[0]["PageNo"].ToString()));
                    _obj.Add("TotalRec", Convert.ToInt32(dt.Rows[0]["T_Rec"].ToString()));
                    _obj.Add("TotalPages", Convert.ToInt32(dt.Rows[0]["T_Pages"].ToString()));

                    dt.Columns.Remove("PageNo");
                    dt.Columns.Remove("T_Rec");
                    dt.Columns.Remove("T_Pages");


                }
                else
                {
                    //_obj.Add("PageNo", 0);
                    //_obj.Add("TotalRec", 0);
                    //_obj.Add("TotalPages", 0);

                    _obj.Add("PageNo", 1);
                    _obj.Add("TotalRec", 0);
                    _obj.Add("TotalPages", 0);
                }



                _obj.Add("Listing", ToDynamicList(ToDictionary(dt), getNewObject(dt.Columns, className)));
                return _obj;
            }

            if (Addextracolumn == true)
            {
                dt.Columns.Add("ConvertedDateTime");
            }

            return ToDynamicList(ToDictionary(dt), getNewObject(dt.Columns, className));
        }

        public static dynamic ToDynamicListOfCity(DataTable dt, string className = "class", bool Top5City = false, bool Addextracolumn = false)
        {
            if (Top5City == true)
            {
                Dictionary<string, object> _obj = new Dictionary<string, object>();
                if (dt.Rows.Count > 0)
                {
                    _obj.Add("City", dt.Rows[0]["City"].ToString());
                    _obj.Add("Country", dt.Rows[0]["Country"].ToString());
                    _obj.Add("State", dt.Rows[0]["State"].ToString());

                    dt.Columns.Remove("City");
                    dt.Columns.Remove("Country");
                    dt.Columns.Remove("State");

                }
                else
                {
                    //_obj.Add("PageNo", 0);
                    //_obj.Add("TotalRec", 0);
                    //_obj.Add("TotalPages", 0);
                    _obj.Add("City", "");
                    _obj.Add("Country", "");
                    _obj.Add("State", "");
                }



                _obj.Add("Landmarks", ToDynamicList(ToDictionary(dt), getNewObject(dt.Columns, className)));
                return _obj;
            }

            if (Addextracolumn == true)
            {
                dt.Columns.Add("ConvertedDateTime");
            }

            return ToDynamicList(ToDictionary(dt), getNewObject(dt.Columns, className));
        }

        public static dynamic ToDynamicObject(DataTable dt, string className = "class")
        {
            return ToDynamicObject(ToDictionary(dt), getNewObject(dt.Columns, className));
        }

        private static List<Dictionary<string, object>> ToDictionary(DataTable dt)
        {
            var columns = dt.Columns.Cast<DataColumn>();
            var Temp = dt.AsEnumerable().Select(dataRow => columns.Select(column =>
                                 new { Column = column.ColumnName, Value = dataRow[column] })
                             .ToDictionary(data => data.Column, data => data.Value)).ToList();
            return Temp.ToList();
        }

        private static List<dynamic> ToDynamicList(List<Dictionary<string, object>> list, Type TypeObj)
        {
            dynamic temp = new List<dynamic>();
            foreach (Dictionary<string, object> step in list)
            {
                object Obj = Activator.CreateInstance(TypeObj);

                PropertyInfo[] properties = Obj.GetType().GetProperties();

                Dictionary<string, object> DictList = (Dictionary<string, object>)step;

                foreach (KeyValuePair<string, object> keyValuePair in DictList)
                {
                    foreach (PropertyInfo property in properties)
                    {
                        if (property.Name == keyValuePair.Key)
                        {
                            if (keyValuePair.Value != null && keyValuePair.Value.GetType() != typeof(System.DBNull))
                            {
                                if (keyValuePair.Value.GetType() == typeof(System.Guid))
                                {
                                    property.SetValue(Obj, keyValuePair.Value, null);
                                }
                                else
                                {

                                    property.SetValue(Obj, keyValuePair.Value, null);
                                }
                            }
                            break;
                        }
                    }
                }
                temp.Add(Obj);
            }
            return temp;
        }

        private static dynamic ToDynamicObject(List<Dictionary<string, object>> list, Type TypeObj)
        {
            dynamic temp = null;
            foreach (Dictionary<string, object> step in list)
            {
                object Obj = Activator.CreateInstance(TypeObj);

                PropertyInfo[] properties = Obj.GetType().GetProperties();

                Dictionary<string, object> DictList = (Dictionary<string, object>)step;

                foreach (KeyValuePair<string, object> keyValuePair in DictList)
                {
                    foreach (PropertyInfo property in properties)
                    {
                        if (property.Name == keyValuePair.Key)
                        {
                            if (keyValuePair.Value != null && keyValuePair.Value.GetType() != typeof(System.DBNull))
                            {
                                if (keyValuePair.Value.GetType() == typeof(System.Guid))
                                {
                                    property.SetValue(Obj, keyValuePair.Value, null);
                                }
                                else
                                {

                                    property.SetValue(Obj, keyValuePair.Value, null);
                                }
                            }
                            break;
                        }
                    }
                }
                temp = Obj;
            }
            return temp;
        }

        private static Type getNewObject(DataColumnCollection columns, string className)
        {
            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name = WebConfigurationManager.AppSettings["AppName"].ToString();
            System.Reflection.Emit.AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder module = assemblyBuilder.DefineDynamicModule("YourDynamicModule");
            TypeBuilder typeBuilder = module.DefineType(className, TypeAttributes.Public);

            foreach (DataColumn column in columns)
            {
                string propertyName = column.ColumnName;
                //if (column.ColumnName == "NightPrice")
                //{
                //    column.DataType = typeof(float);
                //}

                FieldBuilder field = typeBuilder.DefineField(propertyName, column.DataType, FieldAttributes.Public);
                PropertyBuilder property = typeBuilder.DefineProperty(propertyName, System.Reflection.PropertyAttributes.None, column.DataType, new Type[] { column.DataType });
                MethodAttributes GetSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig;
                MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, column.DataType, new Type[] { column.DataType }); // Type.EmptyTypes);
                ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
                currGetIL.Emit(OpCodes.Ldarg_0);
                currGetIL.Emit(OpCodes.Ldfld, field);
                currGetIL.Emit(OpCodes.Ret);
                MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { column.DataType });
                ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
                currSetIL.Emit(OpCodes.Ldarg_0);
                currSetIL.Emit(OpCodes.Ldarg_1);
                currSetIL.Emit(OpCodes.Stfld, field);
                currSetIL.Emit(OpCodes.Ret);
                property.SetGetMethod(currGetPropMthdBldr);
                property.SetSetMethod(currSetPropMthdBldr);
            }
            Type obj = typeBuilder.CreateType();
            return obj;
        }
    }
}

No comments:

Post a Comment

Two Factor Authentication using .Net Core

Install Package dotnet add package GoogleAuthenticator --version 3.1.1 Model Changes public bool IsAuthenticatorReset { get; set; } public s...