using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Globalization;
using System.Threading;
using System.IO;
using System.Reflection;
using System.Configuration;
using System.Xml;
using System.Data;
using System.Collections;
using System.Text.RegularExpressions;
using System.Data.OleDb;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class utils
{
#region variables / properties
///
/// Number Format Information
///
public static NumberFormatInfo nfi
{
get { return Thread.CurrentThread.CurrentCulture.NumberFormat; }
set { Thread.CurrentThread.CurrentCulture.NumberFormat = value; }
}
#endregion
#region validation tools
///
/// Method to validate a folder, creates folder if it does not exist
///
///
public static void validateFolder(string directory)
{
DirectoryInfo dir = null;
try
{
dir = new DirectoryInfo(directory);
//check folder exists
if (!dir.Exists)
//create folder
dir.Create();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
///
/// This Function corrects any null values, as well as fix dates
///
///
///
///
public static object IsNull(object toCheck, Type dataType)
{
try
{
//fix nulls
if (toCheck == null || toCheck == DBNull.Value)
{
if (dataType == typeof(String))
toCheck = String.Empty;
else if (dataType == typeof(int))
toCheck = 0;
else if (dataType == typeof(Byte[]))
toCheck = new Byte[] { Byte.MinValue };
else
toCheck = Activator.CreateInstance(dataType);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return toCheck;
}
///
/// Function to fix dates according to date format in config file
///
///
/// string
public static string fixDate(object dDate)
{
string result = String.Empty;
try
{
if (dDate.GetType() == typeof(DateTime))
{
DateTime tempDate = (DateTime)dDate;
result = tempDate.ToString(ConfigurationManager.AppSettings["DateFormat"]).Replace("0001", "1900");
}
else
{
result = dDate.ToString().Replace("0001", "1900");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
public static string formatSqlString(string value)
{
return value.Replace("'", "`");
}
public static string ValidateIDNumber(string sData)
{
// validate the ID mumber according to the SA rules
string sDate = null;
string sTemp = null;
int iOdd = 0;
int iEven = 0;
int iTotal = 0;
int iYY = 0;
int iMM = 0;
int iDD = 0;
int iTemp = 0;
int iLoop = 0;
// default value for return
string bIsValidSAID = string.Empty;
// remove any leading / trailing spaces
sData = sData.Trim();
// ensure length is 13 characters
if (sData.Length != 13)
{
bIsValidSAID = "Invalid SA ID Number length - must be 13 digits.";
return bIsValidSAID;
}
// only number allowed
if (!isNumeric(sData, NumberStyles.Integer) || sData.IndexOf(".", 0, sData.Length) > 0 || sData.IndexOf("-", 0, sData.Length) > 0)
{
bIsValidSAID = "Invalid SA ID Number - only digits 0-9 are allowed.";
return bIsValidSAID;
}
// get the date portion of the ID number and check it
sDate = sData.Substring(0, 6);
iYY = Convert.ToInt32(sDate.Substring(0, 2));
iMM = Convert.ToInt32(sDate.Substring(2, 2));
iDD = Convert.ToInt32(sDate.Substring(sDate.Length - 2, 2));
// check the date components
if (iMM < 1 | iMM > 12)
{
// invalid month
bIsValidSAID = "Invalid month portion of the ID Number.";
return bIsValidSAID;
}
// check the number of days in the selected month
// determine the max number of days in the selected month
// create a date with the first of the month
DateTime MyDate = new DateTime();
MyDate = DateTime.Parse(utils.fixDate(MyDate));
MyDate = MyDate.AddYears(iYY);
MyDate = MyDate.AddMonths(iMM - 1);
// add 1 month
MyDate = MyDate.AddMonths(1);
//subtract 1 day = last day of previous / required month
MyDate = MyDate.AddDays(-1);
// get the number of days from the date
iTemp = MyDate.Day;
sTemp = Convert.ToString(MyDate);
if (iDD < 1 | iDD > iTemp)
{
// invalid days for the month / year combination
bIsValidSAID = "Invalid date portion of the ID Number.";
return bIsValidSAID;
}
// the date portion is valid - continue
if (Convert.ToInt32(sData.Substring(10, 1)) > 1)
{
// invalid ID number
bIsValidSAID = "This is an invalid SA ID Number.";
return bIsValidSAID;
}
// we cannot implement the gender check as we do not current know the gender - it is assumed
// males = val(mid$(sdata, 7, 4)) >= 5000
// females = val(mid$(sdata, 7, 4)) < 5000
// *** calculate the check digit of the number
// add all the odd digits togehter 1,3,5,7,9,11
// for all the even digits, multiple each by 2 and add the digits of the result together : 9 * 2 = 18; 1 + 8 = 9
iOdd = 0;
iEven = 0;
for (iLoop = 1; iLoop <= 12; iLoop++)
{
// determine if an even or odd digit
if (iLoop % 2 == 0)
{
// even digits
sTemp = (int.Parse(sData.Substring(iLoop - 1, 1)) * 2).ToString("00");
iEven += int.Parse(sTemp.Substring(0, 1)) + int.Parse(sTemp.Substring(sTemp.Length - 1, 1));
}
else
{
// odd digits
iOdd += int.Parse(sData.Substring(iLoop - 1, 1));
}
}
// now add the odd and even totals together to get the total
iTotal = iOdd + iEven;
string sTotal = iTotal.ToString("00");
// we are only interested in the last 2 digits of the total and we need to subtract that from 10
iTemp = 10 - int.Parse(sTotal.Substring(sTotal.Length - 1, 1));
// ensure that we are only dealing with a single digit
if (iTemp == 10)
{
iTemp = 0;
}
// now comapre this to the lsat digit of the ID number
if (Convert.ToInt32(sData.Substring(12, 1)) != iTemp)
{
// invalid check digit calculation
bIsValidSAID = "This is an invalid SA ID Number.";
return bIsValidSAID;
}
// if we got here it is because everything is correct
return bIsValidSAID;
}
///
/// bool to validate if a string is a numeric or decimal
///
///
///
///
public static bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle)
{
Double result;
return Double.TryParse(val, NumberStyle,
System.Globalization.CultureInfo.CurrentCulture, out result);
}
#endregion
#region return tools
public static string ApplicationPath()
{
return System.Windows.Forms.Application.StartupPath;
}
///
/// Function to split words at the upper case character
///
///
/// string
public static string SplitWords(string input)
{
string result = string.Empty;
Regex re = new Regex("([A-Z])");
try
{
result = re.Replace(input, " $1").Trim();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
///
/// decimal to return a decimal value from a string value
///
/// string value or amount
/// Decimal value
public static decimal returnDecimal(string value)
{
decimal result = 0;
try
{
if (value != null && value != String.Empty)
{
decimal.TryParse(value.Replace(nfi.CurrencySymbol, "").Replace(" ", ""), out result);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return decimal.Round(result, 2);
}
///
/// strimg to return a formatted decimal value in a type of string
///
/// string value or amount
/// Formatted Decimal value
public static string returnFormattedDecimal(string value)
{
decimal result = 0;
string formattedDecimal = String.Empty;
try
{
if (value != null && value != String.Empty)
{
decimal.TryParse(value.Replace(nfi.CurrencySymbol, "").Replace(" ", ""), out result);
formattedDecimal = String.Format("{0:0,0.00}", result);
//check if first digit is a zero
if (formattedDecimal.Length > 1 && formattedDecimal.Substring(0, 1) == "0")
{
formattedDecimal = formattedDecimal.Remove(0, 1);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return formattedDecimal;
}
///
/// Function to return a Byte Array from path
///
///
/// Byte[]
public static Byte[] ReturnByteArray(string path)
{
Byte[] result = null;
FileStream fs = null;
try
{
fs = new FileStream(path, FileMode.Open, FileAccess.Read);
result = new Byte[fs.Length];
//Read the File from the Memory stream
fs.Read(result, 0, result.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
fs.Close();
fs.Dispose();
}
return result;
}
///
/// return a value in proper (Title) case
///
///
/// proper case string
public static string returnProperCase(string value)
{
string result = String.Empty;
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
try
{
result = textInfo.ToTitleCase(value.ToLower());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
public static int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
///
/// Generates a random string with the given length
///
/// Size of the string
/// If true, generate lowercase string
/// Random string
public static string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
///
/// String to Generate a unique code
///
///
///
///
public static string GenerateUinqueCode(int prefixCount, int SuffixCount)
{
StringBuilder builder = new StringBuilder();
builder.Append(RandomString(prefixCount, true));
builder.Append(RandomNumber(1000, 9999));
builder.Append(RandomString(SuffixCount, false));
return builder.ToString();
}
#endregion
#region formatting
///
/// Format a mobile number
///
///
///
public static string FormatMobile(string mobile, string prefix)
{
string result = String.Empty;
try
{
if (mobile.Length > 8)
{
mobile = mobile.Replace(" ", "");
result = prefix + mobile.Substring(mobile.Length - 9, 9);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
///
/// DateTime of a a Birthdate calculated from a SA ID Number
///
///
///
public static DateTime FormatBirthdayFromID(string IDNumber)
{
DateTime result = new DateTime();
int year = 0;
int month = 0;
double day = 0;
try
{
if (IDNumber.Length > 5 && isNumeric(IDNumber, NumberStyles.Integer))
{
//get year
if (IDNumber.ToString().Substring(0, 1) == "0")
{
year = int.Parse(IDNumber.Substring(0, 2));
year += 100;
}
else { year = int.Parse(IDNumber.Substring(0, 2)); }
//get month
month = int.Parse(IDNumber.Substring(2, 2));
//get day
day = double.Parse(IDNumber.Substring(4, 2));
//set base date
result = DateTime.MinValue.AddYears(1899);
// add birth values to the result
result = result.AddYears(year);
result = result.AddMonths(month - 1);
result = result.AddDays(day - 1);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
///
/// String to format the gender based on a SA ID Number
///
///
/// String (M/F)
public static string formatGenderFromID(string IDNumber)
{
string result = String.Empty;
try
{
if (IDNumber.Length > 6 && isNumeric(IDNumber, NumberStyles.Integer))
{
if (int.Parse(IDNumber.Substring(6, 1)) > 4)
result = "M";//male
else
result = "F";//female
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
#endregion
#region Object Tools
///
/// Generic Function to compare two objects of the same type and return a list of the values changed.
///
///
///
/// List of String (values that were changed)
public static List CompareObjectsForChange(object objBeforeUpdate, object objAfterUpdate)
{
List result = new List();
string strMessage = String.Empty;
try
{
//enumerate the properties in the object before update
foreach (PropertyInfo beforeProp in objBeforeUpdate.GetType().GetProperties())
{
//enumerate the properties in the object after update
foreach (PropertyInfo afterProp in objAfterUpdate.GetType().GetProperties())
{
if (beforeProp.Name == afterProp.Name)//match in properties
{
if (objBeforeUpdate != null && objAfterUpdate != null)
{
//cater for decimals and doubles
if (beforeProp.PropertyType == typeof(Decimal) || beforeProp.PropertyType == typeof(Double))
{
decimal before = Convert.ToDecimal(beforeProp.GetValue(objBeforeUpdate, null));
decimal after = Convert.ToDecimal(afterProp.GetValue(objAfterUpdate, null));
if (before != after)
{
//clear message
strMessage = String.Empty;
strMessage += SplitWords(beforeProp.Name) + " changed from: ";
strMessage += before + " ";
strMessage += "to: " + after;
//append to result list
result.Add(strMessage);
}
}
else
{
//check if the values have changed
if (Convert.ToString(beforeProp.GetValue(objBeforeUpdate, null)) != Convert.ToString(afterProp.GetValue(objAfterUpdate, null)))
{
//clear message
strMessage = String.Empty;
strMessage += SplitWords(beforeProp.Name) + " changed from: ";
strMessage += Convert.ToString(beforeProp.GetValue(objBeforeUpdate, null)) + " ";
strMessage += "to: " + Convert.ToString(afterProp.GetValue(objAfterUpdate, null));
//append to result list
result.Add(strMessage);
}
}
}
//break out enumeration
break;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
///
/// Function to return a cloned object
///
///
/// Object
public static object CloneObject(object sourceObject)
{
object result = null;
Type t = null;
PropertyInfo[] props = null;
try
{
//get the type of object
t = sourceObject.GetType();
//create a new object of the same type as the original object
result = Activator.CreateInstance(t);
//get the list of properties
props = t.GetProperties();
//enumerate through all the properties of the object
foreach (PropertyInfo rfi in props)
{
//get the property from the source object
object objValue = rfi.GetValue(sourceObject, null);
//and set the corresponding property of the new object
rfi.SetValue(result, objValue, null);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
#endregion
#region Conversion Tools
///
/// Converts a CSV file to a DataSet
///
///
///
/// A DataSet
/// Graham 29/09/08
public static DataSet ConvertCSVToDataSet(string pathName, string fileName)
{
//Variable Declaration
OleDbConnection ExcelConnection = new OleDbConnection(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Text;", pathName));
OleDbCommand ExcelCommand = new OleDbCommand(string.Format("SELECT * FROM {0} ", fileName), ExcelConnection);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
DataSet ExcelDataSet = new DataSet();
try
{
//Open the connection
ExcelConnection.Open();
//Fill that DataSet
ExcelAdapter.Fill(ExcelDataSet);
//Dispose Command
ExcelCommand.Dispose();
//Dispose Adapter
ExcelAdapter.Dispose();
//close the Connection
ExcelConnection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//Throw exception
throw ex;
}
//return the DataSet
return ExcelDataSet;
}
///
/// Function to create a custom formatted DataSet for import
///
///
///
/// A Formatted DataSet
/// Graham 30/09/08
public static DataSet CustomFormatCSVtoDataSet(string pathName, string fileName)
{
//Variable Declaration
DataSet TempData = new DataSet();
DataSet ResultData = new DataSet();
System.Data.DataTable TableData = new System.Data.DataTable();
try
{
//Convert CSV to a DataSet
TempData = ConvertCSVToDataSet(pathName, fileName);
//Default the Column Headers
TableData.Columns.Add("CODE");
TableData.Columns.Add("SUBURB");
TableData.Columns.Add("CITY");
TableData.Columns.Add("TYPE");
TableData.Columns.Add("LANGUAGE");
TableData.Columns.Add("PROVINCE");
//Enumerate the Tables
foreach (System.Data.DataTable Table in TempData.Tables)
{
//Enumerate the Rows
foreach (DataRow Row in Table.Rows)
{
if ((Row[0].ToString() != "") && (Row[1].ToString() != ""))
{
//Default the Values Lists
List PostalValuesList = new List();
List ResidentialValuesList = new List();
//Append the Postal Values
if ((Row[1] != null) && (Row[1].ToString() != ""))
{
PostalValuesList.Add(string.Format("{0}", Row[1].ToString().Replace("'", "")));
PostalValuesList.Add(string.Format("{0}", Row[3].ToString().Replace("'", "")));
PostalValuesList.Add(string.Format("{0}", Row[5].ToString().Replace("'", "")));
PostalValuesList.Add("Postal");
PostalValuesList.Add("ENG");
PostalValuesList.Add(string.Format("{0}", Row[6].ToString().Replace("'", "")));
}
//Append the ResidentialValues
if ((Row[0] != null) && (Row[0].ToString() != ""))
{
ResidentialValuesList.Add(string.Format("{0}", Row[0].ToString().Replace("'", "")));
ResidentialValuesList.Add(string.Format("{0}", Row[2].ToString().Replace("'", "")));
ResidentialValuesList.Add(string.Format("{0}", Row[4].ToString().Replace("'", "")));
ResidentialValuesList.Add("Residential");
ResidentialValuesList.Add("ENG");
ResidentialValuesList.Add(string.Format("{0}", Row[6].ToString().Replace("'", "")));
}
//Insert the array into the Rows
TableData.Rows.Add(PostalValuesList.ToArray());
TableData.Rows.Add(ResidentialValuesList.ToArray());
}
}
//Add DataTable to Dataset
ResultData.Tables.Add(TableData);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//Throw exception
throw ex;
}
//Return the Dataset
return ResultData;
}
///
/// Convert a XML file to a DataSet
///
///
///
/// A DataSet
/// Graham 29/09/08
public static DataSet ConvertXMLToDataSet(string pathName, string fileName)
{
//Variable Declaration
DataSet dataset = new DataSet();
try
{
//Read XML file
dataset.ReadXml(pathName + fileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//Throw exception
throw ex;
}
//Return DataSet
return dataset;
}
///
/// Function to Convert an Excel file to a DataSet
///
///
///
/// A DataSet
/// Graham 29/09/08
public static DataSet ConvertExcelToDataSet(string pathName, string fileName)
{
DataSet ExcelDataSet = new DataSet();
OleDbConnection con;
System.Data.DataTable dt = null;
//Connection string for oledb
string conn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + pathName + fileName + "; Extended Properties=Excel 8.0;";
con = new OleDbConnection(conn);
try
{
con.Open();
//get the sheet name in to a table
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelsheets = new String[dt.Rows.Count];
int i = 0;
//using foreach get the sheet name in a string array called excelsheets[]
foreach (DataRow dr in dt.Rows)
{
excelsheets[i] = dr["TABLE_NAME"].ToString();
i++;
}
// here i manaually give the sheet number in the string array
foreach (string temp in excelsheets)
{
// Query to get the data for the excel sheet
//temp is the sheet name
if (temp == fileName.Replace(".xls", "").Replace(".xlsx", "") + "$")
{
string query = "select * from [" + temp + "]";
OleDbDataAdapter adp = new OleDbDataAdapter(query, con);
adp.Fill(ExcelDataSet, temp);//fill the excel sheet data into a dataset ds
adp.Dispose();
con.Close();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//Throw exception
throw ex;
}
//return the DataSet
return ExcelDataSet;
}
///
/// Function to convert a file List to a DataSet
///
///
/// A DataSet
/// Graham 29/09/08
public static DataSet ConvertFileListToDataSet(string pathName)
{
//Variable Declaration
System.Data.DataTable FileData = new System.Data.DataTable();
DataSet dataset = new DataSet();
try
{
//Default the columns
FileData.Columns.Add("FileName");
FileData.Columns.Add("FileType");
FileData.Columns.Add("Size");
FileData.Columns.Add("Modified");
FileInfo[] Files = new DirectoryInfo(pathName).GetFiles();
//Enumerate the items in the File list
foreach (FileInfo Item in Files)
{
if (Item.Extension.ToLower() == ".jpg" || Item.Extension.ToLower() == ".gif" || Item.Extension.ToLower() == ".png")
//Add data row to the file data
FileData.Rows.Add(Path.GetFileNameWithoutExtension(Item.FullName), Path.GetExtension(Item.FullName), Item.Length, Item.LastWriteTime);
}
//Add the FileData to the DataSet
dataset.Tables.Add(FileData);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//Throw exception
throw ex;
}
//Return the DataSet
return dataset;
}
///
/// Method to Export a DataSet to CSV format
///
///
///
///
/// Graham 29/09/08
public static void ExportDataSetToCSV(string pathName, string destinationFileName, DataSet data)
{
//Variable Declaration
FileInfo[] Files = new DirectoryInfo(pathName).GetFiles();
StringBuilder sBuilder = new StringBuilder();
try
{
//Deletes file in destination folder if it exists
if (File.Exists(pathName + destinationFileName) == true)
{
File.Delete(pathName + destinationFileName);
}
//Enumerate the Tables in the Dataset
foreach (System.Data.DataTable Table in data.Tables)
{
//Enumerate the Columns in the Table
foreach (DataColumn Column in Table.Columns)
{
//Append column name (header)
sBuilder.Append(Column.ColumnName + ",");
}
sBuilder.Replace(",", Environment.NewLine, sBuilder.Length - 1, 1);
//Enumerate the Rows in the Table
foreach (DataRow Row in Table.Rows)
{
foreach (Object field in Row.ItemArray)
{
sBuilder.Append(field.ToString() + ",");
}
sBuilder.Replace(",", Environment.NewLine, sBuilder.Length - 1, 1);
}
File.WriteAllText(pathName + destinationFileName, sBuilder.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//Throw exception
throw ex;
}
}
///
/// Method to Export a DataSet to XML format
///
///
///
///
/// Graham 29/09/08
public static void ExportDataSetToXML(string pathName, string destinationFileName, DataSet data)
{
try
{
//Deletes file in destination folder if it exists
if (File.Exists(pathName + destinationFileName) == true)
{
File.Delete(pathName + destinationFileName);
}
StreamWriter ws = new StreamWriter(pathName + destinationFileName);
XmlTextWriter writer = new XmlTextWriter(ws);
//Initialise XML Document
writer.WriteStartDocument();
//Write DataSet to XML
data.WriteXml(writer, XmlWriteMode.WriteSchema);
//End XML Document
writer.WriteEndDocument();
//Close Writer
writer.Close();
//close stream
ws.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//Throw exception
throw ex;
}
}
///
/// String to convert an HTML file to a string
///
///
///
public static string ConvertHTMLFiletoString(string htmPath)
{
string result = String.Empty;
StreamReader reader;
try
{
reader = new StreamReader(htmPath);
result = reader.ReadToEnd();
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//Throw exception
throw ex;
}
return result;
}
///
/// bool to convert an HTML file to a string
///
///
///
/// true if successful
public static bool ConvertStringtoHTMLFile(string value, string htmPath)
{
bool result = false;
StreamWriter writer;
try
{
writer = new StreamWriter(htmPath);
writer.Write(value);
writer.Close();
result = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//Throw exception
throw ex;
}
return result;
}
///
/// Function to Convert a DataTable to a list of objects of the specified type
///
///
///
/// ArrayList
public static ArrayList ConvertDataTableToList(System.Data.DataTable theDataTable, Type theObjectType)
{
ArrayList result = new ArrayList();
PropertyInfo[] listOfProperties;
string ResultList = String.Empty;
try
{
//assign list of properties from the object type
listOfProperties = theObjectType.GetProperties();
//enumerate rows in data table
foreach (DataRow row in theDataTable.Rows)
{
//create a new instance of the object
object newObject = Activator.CreateInstance(theObjectType);
//Match the Property to the DataColumn by enumeration
foreach (DataColumn column in theDataTable.Columns)
{
//Enumerate Each Property in List Of Properties
foreach (PropertyInfo singleProperty in listOfProperties)
{
//compare columns
if (column.ColumnName.ToUpper() == singleProperty.Name.ToUpper())
{
//Set the value to the object from the result query
singleProperty.SetValue(newObject, IsNull(row[column], singleProperty.PropertyType), null);
break;
}
}
}
//Add the Object to the result
result.Add(newObject);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
///
/// DataTable to convert an ArrayList to a DataTable
///
///
/// DataTable
public static System.Data.DataTable ConvertListToDataTable(ArrayList SourceList)
{
System.Data.DataTable resultTable = new System.Data.DataTable();
Type objectType;
PropertyInfo[] propertiesArray;
bool tableInitialised = false;
DataRow rowObject;
try
{
//enumerate the objects in the ArrayList
foreach (object singleItem in SourceList)
{
//get the type of object
objectType = singleItem.GetType();
//get the list of properties
propertiesArray = objectType.GetProperties();
//add columns
if (!tableInitialised)
{
//enumerate each property in the list of properties
foreach (PropertyInfo singleProperty in propertiesArray)
{
//add the column
resultTable.Columns.Add(singleProperty.Name, singleProperty.PropertyType);
}
tableInitialised = true;
}
//add rows
rowObject = resultTable.NewRow();
//enumerate each property in the list of properties
foreach (PropertyInfo singleProperty in propertiesArray)
{
object value = singleProperty.GetValue(singleItem, null);
if (value != null)//added for unusable dates
{
if (value.GetType() == typeof(DateTime))
value = Convert.ToDateTime(fixDate(value));
}
//set value to row
rowObject[singleProperty.Name] = value;
}
//add row
resultTable.Rows.Add(rowObject);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return resultTable;
}
#endregion
#region ImageTools
///
/// Bool to resize an image
///
///
///
///
///
///
///
///
public static bool ResizeImage(string originalFile, string destinationDir, string destinationFile, int thumbnailSize, bool removeOriginal, bool ConstrainWidth)
{
bool result = false;
FileStream fs = null;
FileInfo fileCheck = null;
int newWidth = 0;
int newHeight = 0;
try
{
fileCheck = new FileInfo(originalFile);
//check file exists
if (fileCheck.Exists)
{
//validate destination directory, create if does not exist
utils.validateFolder(destinationDir);
//open file into memory stream
fs = new FileStream(originalFile, FileMode.Open, FileAccess.Read);
//create bitmap from the file in memory
Bitmap originalBMP = new Bitmap(fs);
if (!ConstrainWidth)
{
// Calculate the new image dimensions
if (originalBMP.Width > originalBMP.Height)
{
//assign new width to thumbnail size
newWidth = thumbnailSize;
newHeight = originalBMP.Height * thumbnailSize / originalBMP.Width;
}
else//height is greater in this case
{
//set new width from the height to constrain the image proportion
newWidth = originalBMP.Width * thumbnailSize / originalBMP.Height;
newHeight = thumbnailSize;
}
}
else
{
// Calculate the new image dimensions by width constraint
//assign new width to thumbnail size
newWidth = thumbnailSize;
newHeight = originalBMP.Height * thumbnailSize / originalBMP.Width;
}
//create new bitmap with the adjusted sizes
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
//create the graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
//set the properties of the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
//Draw the new graphic based on bmp and graphics properties
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
//save newly resized image to destination
newBMP.Save(destinationDir + destinationFile);
fileCheck = new FileInfo(destinationDir + destinationFile);
//check file is created
if (fileCheck.Exists)
{
//file successfully resized
result = true;
}
//dispose objects
originalBMP.Dispose();
newBMP.Dispose();
oGraphics.Dispose();
fs.Close();
//remove original image if specified
if (removeOriginal)
{
fileCheck = new FileInfo(originalFile);
if (fileCheck.Exists)
{
//delete original file
fileCheck.Delete();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
///
/// Bool to resize an image
///
/// full path of the file
/// destination directory
/// destination filename
/// thumbnail size
/// bool if original image must be deleted
/// True if successful
public static bool ResizeImage(string originalFile, string destinationDir, string destinationFile, int thumbnailSize, bool removeOriginal)
{
return ResizeImage(originalFile, destinationDir, destinationFile, thumbnailSize, removeOriginal, false);
}
///
/// Byte[] to convert an Image to a Byte[]
///
///
///
///
public static byte[] ConvertImageToByteArray(System.Drawing.Image imageToConvert, ImageFormat formatOfImage)
{
byte[] Ret = null;
try
{
using (MemoryStream ms = new MemoryStream())
{
imageToConvert.Save(ms, formatOfImage);
Ret = ms.ToArray();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return Ret;
}
///
/// Convert a Byte Array to an image
///
///
///
///
public static Image ConvertByteArraytoImage(Byte[] MyData, ref MemoryStream ms)
{
Image myImage = null;
try
{
using (ms = new MemoryStream(MyData, 0, MyData.Length))
{
ms.Write(MyData, 0, MyData.Length);
myImage = Image.FromStream(ms, true);
// work with image here.
// You'll need to keep the MemoryStream open for
// as long as you want to work with your new image.
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return myImage;
}
#endregion
}