using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.IO;
using System.Reflection;
public static class ObjectHelper
{
public static dynamic ToExpandoObject(this DataRow @this)
{
dynamic entity = new ExpandoObject();
var expandoDict = (IDictionary<string, object>)entity;
foreach (DataColumn column in @this.Table.Columns)
{
expandoDict.Add(column.ColumnName, @this[column]);
}
return expandoDict;
}
public static bool IsExcelFile(this string @this) {
var extensionFile = Path.GetExtension(@this).ToLower();
if (extensionFile == ".xls" || extensionFile == ".xlsx") {
return true;
}
return false;
}
public static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
T item = GetItem<T>(row);
data.Add(item);
}
return data;
}
private static T GetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
foreach (DataColumn column in dr.Table.Columns)
{
foreach (PropertyInfo pro in temp.GetProperties())
{
if (pro.Name == column.ColumnName)
pro.SetValue(obj, dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}
public static bool IsImageFile(this string @this)
{
var extensionFile = Path.GetExtension(@this).ToLower();
if (extensionFile == ".png" || extensionFile == ".gif" || extensionFile == ".jpg" || extensionFile == ".jpeg")
{
return true;
}
return false;
}
public static string ToJsonWithResponseData(this DataRow datarow, string Status="", string Message = "", bool isLowercase = true, bool isFormatBeauty = false)
{
var dict = new Dictionary<string, object>();
foreach (DataColumn col in datarow.Table.Columns)
{
dict.Add(isLowercase ? col.ColumnName.ToLower() : col.ColumnName, datarow[col]);
}
var responseData = new ResponsedData()
{
status = Status,
message =Message,
data = dict
};
return JsonConvert.SerializeObject(responseData, isFormatBeauty ? Formatting.Indented : Formatting.None);
}
/// <summary>
/// Hàm Convert 1 Datarow to Json Object cho Ajax sử dụng JSON.parse(response.d) sử dụng
/// </summary>
/// <param name="datarow"></param>
/// <param name="isLowercase"></param>
/// <param name="isFormatBeauty"></param>
/// <returns></returns>
public static string ToJson(this DataRow datarow, bool isLowercase = true, bool isFormatBeauty = false)
{
var dict = new Dictionary<string, object>();
foreach (DataColumn col in datarow.Table.Columns)
{
dict.Add(isLowercase ? col.ColumnName.ToLower() : col.ColumnName, datarow[col]);
}
return JsonConvert.SerializeObject(dict, isFormatBeauty ? Formatting.Indented : Formatting.None);
}
public static string ToJson<T>(this T anynomusType, bool isLowercase = true, bool isFormatBeauty = false)
{
return JsonConvert.SerializeObject(anynomusType, isFormatBeauty ? Formatting.Indented : Formatting.None);
}
}