using NReco.VideoConverter; // Pro-9 - Video Gallery using OfficeOpenXml; using OfficeOpenXml.Style; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.UI; using System.Xml; namespace framework_library { public static 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 Session handling /// /// bool to verify a session is active /// /// /// public static bool verifyApplication(string applicationValue) { bool result = false; try { //verify application if (HttpContext.Current.Application[applicationValue] != null) result = true; } catch (Exception ex) { //to do throw ex; } return result; } /// /// method to dispose a Application value /// /// public static void disposeApplication(string applicationValue) { try { //dispose application HttpContext.Current.Application[applicationValue] = null; } catch (Exception ex) { //to do throw ex; } } /// /// bool to verify a session is active /// /// /// public static bool verifySession(string sessionValue) { bool result = false; try { //verify session if (HttpContext.Current.Session[sessionValue] != null) result = true; } catch (Exception ex) { //to do throw ex; } return result; } /// /// method to dispose a Session value /// /// public static void disposeSession(string sessionValue) { try { //dispose session HttpContext.Current.Session[sessionValue] = null; } catch (Exception ex) { //to do throw ex; } } #endregion #region validation tools public static bool validateEmail(string email) { string strRegex = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"; Regex re = new Regex(strRegex); if (re.IsMatch(email)) return (true); else return (false); } public static bool validateEmailBak(string email) { string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; Regex re = new Regex(strRegex); if (re.IsMatch(email)) return (true); else return (false); } /// /// 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } } /// /// 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return toCheck; } /// /// Function to fix dates according to date format in config file /// /// /// string public static string fixDate(object dDate) { string result = String.Empty; DateTime tempDate = DateTime.MinValue; try { if (DateTime.TryParse(dDate.ToString(), out tempDate)) { if (tempDate == DateTime.MinValue) tempDate = DateTime.Parse("1900/01/01"); } if (tempDate.Year < 1900) tempDate = DateTime.Parse("1900/01/01"); result = tempDate.ToString(ConfigurationManager.AppSettings["DateFormat"]); } catch (Exception) { result = DateTime.Parse("1900/01/01/").ToString(ConfigurationManager.AppSettings["DateFormat"]); } return result; } /// /// Validate that the data set has data before using /// Dirk Strauss - 20 July 2016 /// /// The data set to validate /// The index of the table expected in the data set /// public static bool ValidateDataSet(DataSet dsData, int tableIndexToValidate) { bool blnValid = false; if (dsData.Tables.Count != 0) { if (dsData.Tables[tableIndexToValidate].Rows.Count >= 1) return true; } return blnValid; } public static string formatSqlString(string value) { return value.Replace("``", "''").Replace("'", "''").Replace("`", "''").Replace("’", "''"); } public static string stripCharacters(string value) { /* CVH 2016-10-05 Strip comma */ return value.Replace(" ", "").Replace("&", "").Replace("+", "").Replace("?", "").Replace(".", "").Replace(":", "").Replace(";", "").Replace("-", "").Replace("|", "").Replace("%", "").Replace("/", "").Replace("\\", "").Replace("[", "").Replace("]", "").Replace("(", "").Replace(")", "").Replace("=", "").Replace("{", "").Replace("}", "").Replace("#", "").Replace("@", "").Replace("*", "").Replace("'", "").Replace(">", "").Replace("<", "").Replace("$", "").Replace("\r\n", "").Replace("\n", "").Replace("\r", "").Replace(",", ""); } public static string stripSpecialCharacters(string value) { return value.Replace("%", "").Replace("/", "").Replace("\\", "").Replace("=", "").Replace("#", "").Replace("@", "").Replace("*", "").Replace("'", "").Replace(">", "").Replace("<", "").Replace("$", "").Replace("\r\n", "").Replace("\n", "").Replace("\r", ""); } public static DateTime formatStringToDate(string value) { DateTime formatDate = DateTime.Now; string[] formats = { "dd/MM/yyyy", "MM/dd/yyyy", "yyyy/MM/dd", "MMMM yyyy", "yyyy-MM-dd" }; DateTime.TryParseExact(value, formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out formatDate); return formatDate; } public static DateTime formatStringToTime(string value) { DateTime formatDate = DateTime.Now; string[] formats = { "HH:mm", "HH:mm:ss:fff" }; DateTime.TryParseExact(value, formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out formatDate); return formatDate; } public static DateTime formatStringToDateTime(string value) { string format = "dd/MM/yyyy"; if (ConfigurationManager.AppSettings["DisplayDate"] != null) format = ConfigurationManager.AppSettings["DisplayDate"]; DateTime formatDate = DateTime.Now; format += " hh:mm tt"; DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out formatDate); return formatDate; } public static string formatDateToString(DateTime value) { string format = "dd/MM/yyyy"; if (ConfigurationManager.AppSettings["DisplayDate"] != null) format = ConfigurationManager.AppSettings["DisplayDate"]; return value.ToString(format); } public static string formatDateYearWiseToString(DateTime value) { string format = "yyyy/MM/dd"; if (ConfigurationManager.AppSettings["DisplayDate"] != null) format = ConfigurationManager.AppSettings["DisplayDate"]; return value.ToString(format); } public static string formatDateToStringWithTime(DateTime value) { string format = "dd/MM/yyyy"; if (ConfigurationManager.AppSettings["DisplayDate"] != null) format = ConfigurationManager.AppSettings["DisplayDate"]; return value.ToString(format + " hh:mm tt"); } public static string formatTimeToString(DateTime value) { string format = "HH:mm"; return value.ToString(format); } public static string displayDateFormat() { string format = "dd/MM/yyyy"; if (ConfigurationManager.AppSettings["DisplayDate"] != null) format = ConfigurationManager.AppSettings["DisplayDate"]; return format; } public static string displayTimeFormat() { string format = "HH:mm"; return format; } 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); } public static bool ValidateCheckDigit(string input) { bool returnValue = false; int digitToValidate = Convert.ToInt32(input.Substring(input.Length - 1)); int validationDigit = GetValidationCheckDigit(input.Substring(0, input.Length - 1)); if (validationDigit == digitToValidate) returnValue = true; return returnValue; } public static int GetValidationCheckDigit(string input) { string reverseInput = Reverse(input); string firstSet = "", secondSet = ""; for (int i = 0; i < reverseInput.Length; i++) { if (i % 2 == 0) firstSet += reverseInput[i]; else secondSet += reverseInput[i]; } int firstSetSum = 0; for (int i = 0; i < firstSet.Length; i++) { firstSetSum += Convert.ToInt32(firstSet[i].ToString()); } firstSetSum = firstSetSum * 3; int secondSetSum = 0; for (int i = 0; i < secondSet.Length; i++) { secondSetSum += Convert.ToInt32(secondSet[i].ToString()); } int resultSet = firstSetSum + secondSetSum; int validationDigit = 10 - (resultSet % 10); if (validationDigit == 10) validationDigit = 0; return validationDigit; } public static string Reverse(string s) { char[] charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } #endregion #region return tools public static class HumanFriendlyInteger { static string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; static string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; static string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; static string[] thousandsGroups = { "", " Thousand", " Million", " Billion" }; private static string FriendlyInteger(int n, string leftDigits, int thousands) { if (n == 0) { return leftDigits; } string friendlyInt = leftDigits; if (friendlyInt.Length > 0) { friendlyInt += " "; } if (n < 10) { friendlyInt += ones[n]; } else if (n < 20) { friendlyInt += teens[n - 10]; } else if (n < 100) { friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0); } else if (n < 1000) { friendlyInt += FriendlyInteger(n % 100, (ones[n / 100] + " Hundred"), 0); } else { friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands + 1), 0); } return friendlyInt + thousandsGroups[thousands]; } public static string IntegerToWritten(int n) { if (n == 0) { return "Zero"; } else if (n < 0) { return "Negative " + IntegerToWritten(-n); } return FriendlyInteger(n, "", 0); } } public static bool AreAllColumnsEmpty(DataRow dr) { if (dr == null) { return true; } else { foreach (var value in dr.ItemArray) { if (value != null && value.ToString() != String.Empty) { return false; } } return true; } } /// /// returns a Date Time with time added to it from string /// /// /// /// /// /// public static DateTime Get24HourTime(DateTime date, int hour, int minute, string ToD) { int year = date.Year; int month = date.Month; int day = date.Day; if (hour <= 12) if (ToD.ToUpper() == "PM") hour = (hour % 12) + 12; return new DateTime(year, month, day, hour, minute, 0); } /// /// Returns the Server Map Path /// /// public static string AppPath() { return HttpContext.Current.Server.MapPath("."); } 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 { if (input != null) result = re.Replace(input, " $1").Trim(); } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return decimal.Round(result, 2); } public static decimal DecimalParse(object r) { decimal result = 0; decimal.TryParse(r.ToString(), out result); return result; } /// /// 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, bool isCurrency = false) { decimal result = 0; string formattedDecimal = String.Empty; try { if (value != null && value != String.Empty) { decimal.TryParse(value.Replace(nfi.CurrencySymbol, "").Replace(" ", ""), out result); if (isCurrency) { if (ConfigurationManager.AppSettings["defaultCulture"] != null) { CultureInfo culture = new CultureInfo(ConfigurationManager.AppSettings["defaultCulture"]); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; } formattedDecimal = String.Format("{0:C2}", result); } else formattedDecimal = String.Format("{0:N2}", 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } 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(); } /// /// Geograph of coordinates based on address /// /// /// public static void AddGeoCoordinates(ref oGeograph geoGraphItem) { string url = "http://maps.google.com/maps/api/geocode/xml?address=" + geoGraphItem.Address + "&sensor=false"; WebRequest request = WebRequest.Create(url); using (WebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { DataSet dsResult = new DataSet(); dsResult.ReadXml(reader); foreach (DataRow row in dsResult.Tables["result"].Rows) { string geometry_id = dsResult.Tables["geometry"].Select("result_id = " + row["result_id"].ToString())[0]["geometry_id"].ToString(); DataRow location = dsResult.Tables["location"].Select("geometry_id = " + geometry_id)[0]; geoGraphItem.Address = row["formatted_address"].ToString(); geoGraphItem.Latitude = location["lat"].ToString(); geoGraphItem.Longitude = location["lng"].ToString(); break; } } } } public static List> TimeZones() { var list = new List>(); list.Add(new KeyValuePair("Dateline Standard Time", "(GMT-12:00) International Date Line West")); list.Add(new KeyValuePair("Samoa Standard Time", "(GMT-11:00) Midway Island, Samoa")); list.Add(new KeyValuePair("Hawaiian Standard Time", "(GMT-10:00) Hawaii")); list.Add(new KeyValuePair("Alaskan Standard Time", "(GMT-09:00) Alaska")); list.Add(new KeyValuePair("Pacific Standard Time", "(GMT-08:00) Pacific Time (US and Canada); Tijuana")); list.Add(new KeyValuePair("Mountain Standard Time", "(GMT-07:00) Mountain Time (US and Canada)")); list.Add(new KeyValuePair("Mexico Standard Time 2", "(GMT-07:00) Chihuahua, La Paz, Mazatlan")); list.Add(new KeyValuePair("U.S. Mountain Standard Time", "(GMT-07:00) Arizona")); list.Add(new KeyValuePair("Central Standard Time", "(GMT-06:00) Central Time (US and Canada)")); list.Add(new KeyValuePair("Canada Central Standard Time", "(GMT-06:00) Saskatchewan")); list.Add(new KeyValuePair("Mexico Standard Time", "(GMT-06:00) Guadalajara, Mexico City, Monterrey")); list.Add(new KeyValuePair("Central America Standard Time", "(GMT-06:00) Central America")); list.Add(new KeyValuePair("Eastern Standard Time", "(GMT-05:00) Eastern Time (US and Canada)")); list.Add(new KeyValuePair("U.S. Eastern Standard Time", "(GMT-05:00) Indiana (East)")); list.Add(new KeyValuePair("S.A. Pacific Standard Time", "(GMT-05:00) Bogota, Lima, Quito")); list.Add(new KeyValuePair("Atlantic Standard Time", "(GMT-04:00) Atlantic Time (Canada)")); list.Add(new KeyValuePair("S.A. Western Standard Time", "(GMT-04:00) Caracas, La Paz")); list.Add(new KeyValuePair("Pacific S.A. Standard Time", "(GMT-04:00) Santiago")); list.Add(new KeyValuePair("Newfoundland and Labrador Standard Time", "(GMT-03:30) Newfoundland and Labrador")); list.Add(new KeyValuePair("E. South America Standard Time", "(GMT-03:00) Brasilia")); list.Add(new KeyValuePair("S.A. Eastern Standard Time", "(GMT-03:00) Buenos Aires, Georgetown")); list.Add(new KeyValuePair("Greenland Standard Time", "(GMT-03:00) Greenland")); list.Add(new KeyValuePair("Mid-Atlantic Standard Time", "(GMT-02:00) Mid-Atlantic")); list.Add(new KeyValuePair("Azores Standard Time", "(GMT-01:00) Azores")); list.Add(new KeyValuePair("Cape Verde Standard Time", "(GMT-01:00) Cape Verde Islands")); list.Add(new KeyValuePair("GMT Standard Time", "(GMT) Greenwich Mean Time: Dublin, Edinburgh, Lisbon, London")); list.Add(new KeyValuePair("Greenwich Standard Time", "(GMT) Casablanca, Monrovia")); list.Add(new KeyValuePair("Central Europe Standard Time", "(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague")); list.Add(new KeyValuePair("Central European Standard Time", "(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb")); list.Add(new KeyValuePair("Romance Standard Time", "(GMT+01:00) Brussels, Copenhagen, Madrid, Paris")); list.Add(new KeyValuePair("W. Europe Standard Time", "(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna")); list.Add(new KeyValuePair("W. Central Africa Standard Time", "(GMT+01:00) West Central Africa")); list.Add(new KeyValuePair("E. Europe Standard Time", "(GMT+02:00) Bucharest")); list.Add(new KeyValuePair("Egypt Standard Time", "(GMT+02:00) Cairo")); list.Add(new KeyValuePair("FLE Standard Time", "(GMT+02:00) Helsinki, Kiev, Riga, Sofia, Tallinn, Vilnius")); list.Add(new KeyValuePair("GTB Standard Time", "(GMT+02:00) Athens, Istanbul, Minsk")); list.Add(new KeyValuePair("Israel Standard Time", "(GMT+02:00) Jerusalem")); list.Add(new KeyValuePair("South Africa Standard Time", "(GMT+02:00) Harare, Pretoria")); list.Add(new KeyValuePair("Russian Standard Time", "(GMT+03:00) Moscow, St. Petersburg, Volgograd")); list.Add(new KeyValuePair("Arab Standard Time", "(GMT+03:00) Kuwait, Riyadh")); list.Add(new KeyValuePair("E. Africa Standard Time", "(GMT+03:00) Nairobi")); list.Add(new KeyValuePair("Arabic Standard Time", "(GMT+03:00) Baghdad")); list.Add(new KeyValuePair("Iran Standard Time", "(GMT+03:30) Tehran")); list.Add(new KeyValuePair("Arabian Standard Time", "(GMT+04:00) Abu Dhabi, Muscat")); list.Add(new KeyValuePair("Caucasus Standard Time", "(GMT+04:00) Baku, Tbilisi, Yerevan")); list.Add(new KeyValuePair("Transitional Islamic State of Afghanistan Standard Time", "(GMT+04:30) Kabul")); list.Add(new KeyValuePair("Ekaterinburg Standard Time", "(GMT+05:00) Ekaterinburg")); list.Add(new KeyValuePair("West Asia Standard Time", "(GMT+05:00) Islamabad, Karachi, Tashkent")); list.Add(new KeyValuePair("India Standard Time", "(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi")); list.Add(new KeyValuePair("Nepal Standard Time", "(GMT+05:45) Kathmandu")); list.Add(new KeyValuePair("Central Asia Standard Time", "(GMT+06:00) Astana, Dhaka")); list.Add(new KeyValuePair("Sri Lanka Standard Time", "(GMT+06:00) Sri Jayawardenepura")); list.Add(new KeyValuePair("N. Central Asia Standard Time", "(GMT+06:00) Almaty, Novosibirsk")); list.Add(new KeyValuePair("Myanmar Standard Time", "(GMT+06:30) Yangon Rangoon")); list.Add(new KeyValuePair("S.E. Asia Standard Time", "(GMT+07:00) Bangkok, Hanoi, Jakarta")); list.Add(new KeyValuePair("North Asia Standard Time", "(GMT+07:00) Krasnoyarsk")); list.Add(new KeyValuePair("China Standard Time", "(GMT+08:00) Beijing, Chongqing, Hong Kong SAR, Urumqi")); list.Add(new KeyValuePair("Singapore Standard Time", "(GMT+08:00) Kuala Lumpur, Singapore")); list.Add(new KeyValuePair("Taipei Standard Time", "(GMT+08:00) Taipei")); list.Add(new KeyValuePair("W. Australia Standard Time", "(GMT+08:00) Perth")); list.Add(new KeyValuePair("North Asia East Standard Time", "(GMT+08:00) Irkutsk, Ulaanbaatar")); list.Add(new KeyValuePair("Korea Standard Time", "(GMT+09:00) Seoul")); list.Add(new KeyValuePair("Tokyo Standard Time", "(GMT+09:00) Osaka, Sapporo, Tokyo")); list.Add(new KeyValuePair("Yakutsk Standard Time", "(GMT+09:00) Yakutsk")); list.Add(new KeyValuePair("A.U.S. Central Standard Time", "(GMT+09:30) Darwin")); list.Add(new KeyValuePair("Cen. Australia Standard Time", "(GMT+09:30) Adelaide")); list.Add(new KeyValuePair("A.U.S. Eastern Standard Time", "(GMT+10:00) Canberra, Melbourne, Sydney")); list.Add(new KeyValuePair("E. Australia Standard Time", "(GMT+10:00) Brisbane")); list.Add(new KeyValuePair("Tasmania Standard Time", "(GMT+10:00) Hobart")); list.Add(new KeyValuePair("Vladivostok Standard Time", "(GMT+10:00) Vladivostok")); list.Add(new KeyValuePair("West Pacific Standard Time", "(GMT+10:00) Guam, Port Moresby")); list.Add(new KeyValuePair("Central Pacific Standard Time", "(GMT+11:00) Magadan, Solomon Islands, New Caledonia")); list.Add(new KeyValuePair("Fiji Islands Standard Time", "(GMT+12:00) Fiji Islands, Kamchatka, Marshall Islands")); list.Add(new KeyValuePair("New Zealand Standard Time", "(GMT+12:00) Auckland, Wellington")); list.Add(new KeyValuePair("Tonga Standard Time", "(GMT+13:00) Nuku'alofa")); return list; } public static string PadString(string input, int length) { string returnString = string.Empty; string leftPad = string.Empty, rightPad = string.Empty; int inputLength = input.Length; if (inputLength >= length) returnString = input; else { int diff = length - inputLength; if (diff % 2 > 0) //odd number - add extra space at the back { rightPad = " "; diff--; //make diff even number and add rest both sides } for (int i = 0; i < diff / 2; i++) { leftPad += " "; rightPad += " "; } returnString = leftPad + input + rightPad; } return returnString; } /// /// Calculate the percentage value of a decimal value /// /// The decimal value amount to act on /// The percentage to calculate /// The percentage amount public static decimal CalculatePercentageValue(this decimal value, decimal percentage) { return ((value / 100) * percentage); } /// /// Check if object is null /// /// /// /// public static bool IsNull(this T obj) where T : class { return obj == null; } #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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// String To Format the Age and return the years, months, days excluded for now /// /// BirthDate /// Current Date /// oAge public static oAge FormatAge(DateTime start, DateTime end) { oAge result = new oAge(); try { if (start.ToShortDateString() == "1900/01/01" || start.ToShortDateString() == "01/01/1900") { //not valid dates } else { // Compute the difference between start //year and end year. int years = end.Year - start.Year; int months = 0; int days = 0; // Check if the last year was a full year. if (end < start.AddYears(years) && years != 0) { --years; } start = start.AddYears(years); // Now we know start <= end and the diff between them // is < 1 year. if (start.Year == end.Year) { months = end.Month - start.Month; } else { months = (12 - start.Month) + end.Month; } // Check if the last month was a full month. if (end < start.AddMonths(months) && months != 0) { --months; } start = start.AddMonths(months); // Now we know that start < end and is within 1 month // of each other. days = (end - start).Days; //assign result result.days = days; result.years = years; result.months = months; } } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// Method to return a custom created object /// /// /// /// private static Type GetCustomType(string typeName) { Type result = null; //get object from assemblies foreach (System.Reflection.Assembly tmpAasembly in System.AppDomain.CurrentDomain.GetAssemblies()) { dynamic tempType = tmpAasembly.GetType(typeName); if (tempType != null) { result = tempType; break; // TODO: might not be correct. Was : Exit For } } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //Throw exception throw ex; } //return the DataSet return ExcelDataSet; } /// /// Get Data Table from Excel /// /// /// public static DataTable getDataTableFromExcel(string path) { using (var pck = new OfficeOpenXml.ExcelPackage()) { using (var stream = File.OpenRead(path)) { pck.Load(stream); } var ws = pck.Workbook.Worksheets.First(); DataTable tbl = new DataTable(); bool hasHeader = true; // adjust it accordingly( i've mentioned that this is a simple approach) foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column]) { tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column)); } var startRow = hasHeader ? 2 : 1; for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++) { var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column]; var row = tbl.NewRow(); foreach (var cell in wsRow) { string s = cell.Text; s = Regex.Replace(s, @"[^\u0000-\u007F]", string.Empty); if (tbl.Columns.Count >= cell.Start.Column) { row[cell.Start.Column - 1] = s; } } if (!AreAllColumnsEmpty(row)) tbl.Rows.Add(row); } return tbl; } } /// /// Remove Duplicate Rows /// /// /// /// public static DataTable RemoveDuplicateRows(DataTable dTable, string colName) { Hashtable hTable = new Hashtable(); ArrayList duplicateList = new ArrayList(); foreach (DataRow drow in dTable.Rows) { if (hTable.Contains(drow[colName])) duplicateList.Add(drow); else hTable.Add(drow[colName], string.Empty); } foreach (DataRow dRow in duplicateList) dTable.Rows.Remove(dRow); return dTable; } /// /// Export Data To Excel File /// /// /// public static void ExportDataTabletoExcel(DataTable dataTable, string destinationpath) { FileInfo myFile = new FileInfo(destinationpath); using (ExcelPackage package = new ExcelPackage(myFile)) { ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Results"); /* CVH 2016-06-20 Changing B1 to A1, otherwise upload doesn't work */ // Load the datatable into the sheet, starting from cell A1. worksheet.Cells["A1"].LoadFromDataTable(dataTable, true); int colNumber = 1; foreach (DataColumn col in dataTable.Columns) { if (col.DataType == typeof(DateTime)) { worksheet.Column(colNumber).Style.Numberformat.Format = "yyyy/mm/dd hh:mm:ss AM/PM"; } if (col.DataType == typeof(Decimal) || col.DataType == typeof(Double)) { worksheet.Column(colNumber).Style.Numberformat.Format = "#,##0"; } colNumber++; } worksheet.View.FreezePanes(2, 1); // freeze first row & column worksheet.Row(1).Style.Font.Bold = true; worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(); // autofit column width var table = worksheet.Cells[worksheet.Dimension.Address]; table.Style.Border.BorderAround(ExcelBorderStyle.Thin); table.Style.Fill.PatternType = ExcelFillStyle.Solid; table.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.AliceBlue); for (int rowNumber = worksheet.Dimension.Start.Row; rowNumber <= worksheet.Dimension.End.Row; rowNumber++) { int rowIndex = rowNumber % 2; // even => 0, odd => 1 ExcelRow excelRow; ExcelFill excelFillRow; switch (rowIndex) { case 0: excelRow = worksheet.Row(rowNumber); excelFillRow = excelRow.Style.Fill; excelFillRow.PatternType = ExcelFillStyle.Solid; excelFillRow.BackgroundColor.SetColor(System.Drawing.Color.White); break; case 1: excelRow = worksheet.Row(rowNumber); excelFillRow = excelRow.Style.Fill; excelFillRow.PatternType = ExcelFillStyle.Solid; excelFillRow.BackgroundColor.SetColor(System.Drawing.Color.AliceBlue); break; } } try { // Write to client package.Save(); } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //Throw exception throw ex; } } } public static void ExportDataTabletoExcelFormatted(DataTable dataTable, string destinationpath, bool formatHeadingWithSpaces = true, bool lastRowBold = false, string imagePath = "", string startCell = "B1") { FileInfo myFile = new FileInfo(destinationpath); using (ExcelPackage package = new ExcelPackage(myFile)) { /* CVH 2016-06-27 Worksheet name = datatable name, default = "Results" */ string sheetName = "Results"; if (dataTable.TableName != "") sheetName = dataTable.TableName; ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sheetName); /* CVH 2016-06-27 Format column names with a space. Checking for upper case letters. */ foreach (DataColumn col in dataTable.Columns) { if (formatHeadingWithSpaces) { StringBuilder colName = new StringBuilder(); colName.Append(col.ColumnName.Substring(0, 1)); string prev = colName.ToString(); for (int i = 1; i < col.ColumnName.Length; i++) { if (col.ColumnName.Substring(i, 1).ToUpper() == col.ColumnName.Substring(i, 1) && (prev.ToUpper() != prev || prev == ".") && prev != "(" && !("0123456789 -+.".Contains(col.ColumnName.Substring(i, 1)))) colName.Append(" " + col.ColumnName.Substring(i, 1)); else colName.Append(col.ColumnName.Substring(i, 1)); prev = col.ColumnName.Substring(i, 1); } col.ColumnName = colName.ToString(); } } //load image if given if (imagePath != "") { worksheet.Row(1).Height = 125; ExcelRow imageRow = worksheet.Row(1); ExcelFill imageFillRow = imageRow.Style.Fill; imageFillRow.PatternType = ExcelFillStyle.Solid; imageFillRow.BackgroundColor.SetColor(System.Drawing.Color.White); var picture = worksheet.Drawings.AddPicture("logo", new FileInfo(imagePath)); picture.SetPosition(2, 290); picture.EditAs = OfficeOpenXml.Drawing.eEditAs.Absolute; } // Load the datatable into the sheet, starting from cell A1. string tempStartCell = startCell; if (tempStartCell.Length < 2) tempStartCell = "B1"; worksheet.Cells[tempStartCell].LoadFromDataTable(dataTable, true); int colNumber = 1; foreach (DataColumn col in dataTable.Columns) { colNumber++; if (col.DataType == typeof(DateTime)) { worksheet.Column(colNumber).Style.Numberformat.Format = "yyyy/mm/dd hh:mm:ss AM/PM"; } if (col.DataType == typeof(Decimal) || col.DataType == typeof(Double)) { worksheet.Column(colNumber).Style.Numberformat.Format = "#,##0.00"; } } //worksheet.View.FreezePanes(2, 1); // freeze first row & column worksheet.View.FreezePanes(worksheet.Cells[tempStartCell].Start.Row + 1, 1); //worksheet.Row(1).Style.Font.Bold = true; worksheet.Row(worksheet.Cells[tempStartCell].Start.Row).Style.Font.Bold = true; worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(); // autofit column width var table = worksheet.Cells[worksheet.Dimension.Address]; //var table = worksheet.Cells[worksheet.Cells[tempStartCell].Start.Row, worksheet.Cells[tempStartCell].Start.Column, worksheet.Cells[worksheet.Dimension.Address].Rows, dataTable.Columns.Count + worksheet.Cells[tempStartCell].Start.Column - 1]; table.Style.Border.BorderAround(ExcelBorderStyle.Thin); table.Style.Fill.PatternType = ExcelFillStyle.Solid; table.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.AliceBlue); //if image is loaded in first row, need to set all even rows colour and uneven rows white, otherwise vice versa int whiteRow = 0; int colourRow = 1; if (imagePath != "") { whiteRow = 1; colourRow = 0; //add border to image row //var tableIm = worksheet.Cells[1, 1, 1, dataTable.Columns.Count]; var tableIm = worksheet.Cells[1, 1, 1, worksheet.Cells[worksheet.Dimension.Address].Columns]; tableIm.Style.Border.BorderAround(ExcelBorderStyle.Thin); } for (int rowNumber = worksheet.Dimension.Start.Row; rowNumber <= worksheet.Dimension.End.Row; rowNumber++) { int rowIndex = rowNumber % 2; // even => 0, odd => 1 ExcelRow excelRow; ExcelFill excelFillRow; if (rowIndex == whiteRow) { excelRow = worksheet.Row(rowNumber); excelFillRow = excelRow.Style.Fill; excelFillRow.PatternType = ExcelFillStyle.Solid; excelFillRow.BackgroundColor.SetColor(System.Drawing.Color.White); } else if (rowIndex == colourRow) { excelRow = worksheet.Row(rowNumber); excelFillRow = excelRow.Style.Fill; excelFillRow.PatternType = ExcelFillStyle.Solid; excelFillRow.BackgroundColor.SetColor(System.Drawing.Color.AliceBlue); } } if (lastRowBold) worksheet.Row(worksheet.Dimension.End.Row).Style.Font.Bold = true; try { // Write to client package.Save(); } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //Throw exception throw ex; } } } public static void ExportDataTablesToExcelGLOB1FinancialSummary(DataTable dtInvoices, DataTable dtReceipts, DataTable dtDebitNotes, DataTable dtCreditNotes, decimal vatTotal, decimal total, string destinationpath) { FileInfo myFile = new FileInfo(destinationpath); using (ExcelPackage package = new ExcelPackage(myFile)) { string sheetName = "Results"; ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sheetName); /* CVH 2016-06-27 Format column names with a space. Checking for upper case letters. */ foreach (DataColumn col in dtInvoices.Columns) { StringBuilder colName = new StringBuilder(); colName.Append(col.ColumnName.Substring(0, 1)); string prev = colName.ToString(); for (int i = 1; i < col.ColumnName.Length; i++) { if (col.ColumnName.Substring(i, 1).ToUpper() == col.ColumnName.Substring(i, 1) && (prev.ToUpper() != prev || prev == ".") && prev != "(" && !("0123456789 -+.".Contains(col.ColumnName.Substring(i, 1)))) colName.Append(" " + col.ColumnName.Substring(i, 1)); else colName.Append(col.ColumnName.Substring(i, 1)); prev = col.ColumnName.Substring(i, 1); } col.ColumnName = colName.ToString(); } foreach (DataColumn col in dtReceipts.Columns) { StringBuilder colName = new StringBuilder(); colName.Append(col.ColumnName.Substring(0, 1)); string prev = colName.ToString(); for (int i = 1; i < col.ColumnName.Length; i++) { if (col.ColumnName.Substring(i, 1).ToUpper() == col.ColumnName.Substring(i, 1) && (prev.ToUpper() != prev || prev == ".") && prev != "(" && !("0123456789 -+.".Contains(col.ColumnName.Substring(i, 1)))) colName.Append(" " + col.ColumnName.Substring(i, 1)); else colName.Append(col.ColumnName.Substring(i, 1)); prev = col.ColumnName.Substring(i, 1); } col.ColumnName = colName.ToString(); } foreach (DataColumn col in dtDebitNotes.Columns) { StringBuilder colName = new StringBuilder(); colName.Append(col.ColumnName.Substring(0, 1)); string prev = colName.ToString(); for (int i = 1; i < col.ColumnName.Length; i++) { if (col.ColumnName.Substring(i, 1).ToUpper() == col.ColumnName.Substring(i, 1) && (prev.ToUpper() != prev || prev == ".") && prev != "(" && !("0123456789 -+.".Contains(col.ColumnName.Substring(i, 1)))) colName.Append(" " + col.ColumnName.Substring(i, 1)); else colName.Append(col.ColumnName.Substring(i, 1)); prev = col.ColumnName.Substring(i, 1); } col.ColumnName = colName.ToString(); } foreach (DataColumn col in dtCreditNotes.Columns) { StringBuilder colName = new StringBuilder(); colName.Append(col.ColumnName.Substring(0, 1)); string prev = colName.ToString(); for (int i = 1; i < col.ColumnName.Length; i++) { if (col.ColumnName.Substring(i, 1).ToUpper() == col.ColumnName.Substring(i, 1) && (prev.ToUpper() != prev || prev == ".") && prev != "(" && !("0123456789 -+.".Contains(col.ColumnName.Substring(i, 1)))) colName.Append(" " + col.ColumnName.Substring(i, 1)); else colName.Append(col.ColumnName.Substring(i, 1)); prev = col.ColumnName.Substring(i, 1); } col.ColumnName = colName.ToString(); } int colNumber = 1; int rowNumber = 1; // Load the datatable into the sheet, starting from cell B1. // Invoices worksheet.Cells[rowNumber, 2].Value = "Invoices"; worksheet.Row(rowNumber).Style.Font.Bold = true; worksheet.Row(rowNumber).Style.Font.Size = 14; rowNumber++; string tempStartCellIN = "B" + rowNumber; worksheet.Cells[tempStartCellIN].LoadFromDataTable(dtInvoices, true); foreach (DataColumn col in dtInvoices.Columns) { colNumber++; if (col.DataType == typeof(DateTime)) { worksheet.Cells[rowNumber, colNumber, dtInvoices.Rows.Count + 1, colNumber].Style.Numberformat.Format = "yyyy/mm/dd hh:mm:ss AM/PM"; } if (col.DataType == typeof(Decimal) || col.DataType == typeof(Double)) { worksheet.Cells[rowNumber, colNumber, dtInvoices.Rows.Count + 1, colNumber].Style.Numberformat.Format = "#,##0.00"; } } worksheet.Row(worksheet.Cells[tempStartCellIN].Start.Row).Style.Fill.PatternType = ExcelFillStyle.Solid; worksheet.Row(worksheet.Cells[tempStartCellIN].Start.Row).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.AliceBlue); worksheet.Row(worksheet.Cells[tempStartCellIN].Start.Row).Style.Font.Bold = true; worksheet.Row(rowNumber + dtInvoices.Rows.Count).Style.Font.Bold = true; rowNumber = rowNumber + dtInvoices.Rows.Count + 3; colNumber = 1; //Payments worksheet.Cells[rowNumber, 2].Value = "Receipts"; worksheet.Row(rowNumber).Style.Font.Bold = true; worksheet.Row(rowNumber).Style.Font.Size = 14; rowNumber++; string tempStartCellPM = "B" + rowNumber; worksheet.Cells[tempStartCellPM].LoadFromDataTable(dtReceipts, true); foreach (DataColumn col in dtReceipts.Columns) { colNumber++; if (col.DataType == typeof(DateTime)) { worksheet.Cells[rowNumber, colNumber, rowNumber + dtReceipts.Rows.Count + 1, colNumber].Style.Numberformat.Format = "yyyy/mm/dd hh:mm:ss AM/PM"; } if (col.DataType == typeof(Decimal) || col.DataType == typeof(Double)) { worksheet.Cells[rowNumber, colNumber, rowNumber + dtReceipts.Rows.Count + 1, colNumber].Style.Numberformat.Format = "#,##0.00"; } } worksheet.Row(worksheet.Cells[tempStartCellPM].Start.Row).Style.Fill.PatternType = ExcelFillStyle.Solid; worksheet.Row(worksheet.Cells[tempStartCellPM].Start.Row).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.AliceBlue); worksheet.Row(worksheet.Cells[tempStartCellPM].Start.Row).Style.Font.Bold = true; worksheet.Row(rowNumber + dtReceipts.Rows.Count).Style.Font.Bold = true; rowNumber = rowNumber + dtReceipts.Rows.Count + 3; colNumber = 1; //Debit notes worksheet.Cells[rowNumber, 2].Value = "Debit Notes"; worksheet.Row(rowNumber).Style.Font.Bold = true; worksheet.Row(rowNumber).Style.Font.Size = 14; rowNumber++; string tempStartCellDN = "B" + rowNumber; worksheet.Cells[tempStartCellDN].LoadFromDataTable(dtDebitNotes, true); foreach (DataColumn col in dtDebitNotes.Columns) { colNumber++; if (col.DataType == typeof(DateTime)) { worksheet.Cells[rowNumber, colNumber, rowNumber + dtDebitNotes.Rows.Count + 1, colNumber].Style.Numberformat.Format = "yyyy/mm/dd hh:mm:ss AM/PM"; } if (col.DataType == typeof(Decimal) || col.DataType == typeof(Double)) { worksheet.Cells[rowNumber, colNumber, rowNumber + dtDebitNotes.Rows.Count + 1, colNumber].Style.Numberformat.Format = "#,##0.00"; } } worksheet.Row(worksheet.Cells[tempStartCellDN].Start.Row).Style.Fill.PatternType = ExcelFillStyle.Solid; worksheet.Row(worksheet.Cells[tempStartCellDN].Start.Row).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.AliceBlue); worksheet.Row(worksheet.Cells[tempStartCellDN].Start.Row).Style.Font.Bold = true; worksheet.Row(rowNumber + dtDebitNotes.Rows.Count).Style.Font.Bold = true; rowNumber = rowNumber + dtDebitNotes.Rows.Count + 3; colNumber = 1; //Credit notes worksheet.Cells[rowNumber, 2].Value = "Credit Notes"; worksheet.Row(rowNumber).Style.Font.Bold = true; worksheet.Row(rowNumber).Style.Font.Size = 14; rowNumber++; string tempStartCellCN = "B" + rowNumber; worksheet.Cells[tempStartCellCN].LoadFromDataTable(dtCreditNotes, true); foreach (DataColumn col in dtCreditNotes.Columns) { colNumber++; if (col.DataType == typeof(DateTime)) { worksheet.Cells[rowNumber, colNumber, rowNumber + dtCreditNotes.Rows.Count + 1, colNumber].Style.Numberformat.Format = "yyyy/mm/dd hh:mm:ss AM/PM"; } if (col.DataType == typeof(Decimal) || col.DataType == typeof(Double)) { worksheet.Cells[rowNumber, colNumber, rowNumber + dtCreditNotes.Rows.Count + 1, colNumber].Style.Numberformat.Format = "#,##0.00"; } } worksheet.Row(worksheet.Cells[tempStartCellCN].Start.Row).Style.Fill.PatternType = ExcelFillStyle.Solid; worksheet.Row(worksheet.Cells[tempStartCellCN].Start.Row).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.AliceBlue); worksheet.Row(worksheet.Cells[tempStartCellCN].Start.Row).Style.Font.Bold = true; worksheet.Row(rowNumber + dtCreditNotes.Rows.Count).Style.Font.Bold = true; rowNumber = rowNumber + dtCreditNotes.Rows.Count + 3; colNumber = 1; worksheet.Cells[rowNumber, worksheet.Dimension.End.Column - 1].Value = "Financial Summary"; worksheet.Row(rowNumber).Style.Font.Bold = true; worksheet.Row(rowNumber).Style.Font.Size = 14; rowNumber++; int vatRow = rowNumber; //vat worksheet.Cells[vatRow, worksheet.Dimension.End.Column - 1].Value = "VAT"; worksheet.Cells[vatRow, worksheet.Dimension.End.Column].Value = vatTotal; worksheet.Cells[vatRow, worksheet.Dimension.End.Column].Style.Numberformat.Format = "#,##0.00"; worksheet.Row(vatRow).Style.Font.Bold = true; worksheet.Row(vatRow).Style.Font.Size = 12; //total worksheet.Cells[vatRow + 1, worksheet.Dimension.End.Column - 1].Value = "TOTAL"; worksheet.Cells[vatRow + 1, worksheet.Dimension.End.Column].Value = total; worksheet.Cells[vatRow + 1, worksheet.Dimension.End.Column].Style.Numberformat.Format = "#,##0.00"; worksheet.Row(vatRow + 1).Style.Font.Bold = true; worksheet.Row(vatRow + 1).Style.Font.Size = 12; worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(); // autofit column width //var table = worksheet.Cells[worksheet.Dimension.Address]; ////var table = worksheet.Cells[worksheet.Cells[tempStartCell].Start.Row, worksheet.Cells[tempStartCell].Start.Column, worksheet.Cells[worksheet.Dimension.Address].Rows, dataTable.Columns.Count + worksheet.Cells[tempStartCell].Start.Column - 1]; //table.Style.Border.BorderAround(ExcelBorderStyle.Thin); //table.Style.Fill.PatternType = ExcelFillStyle.Solid; //table.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.AliceBlue); //if image is loaded in first row, need to set all even rows colour and uneven rows white, otherwise vice versa //int whiteRow = 0; //int colourRow = 1; //for (int iRow = worksheet.Dimension.Start.Row; iRow <= worksheet.Dimension.End.Row; iRow++) //{ // int rowIndex = iRow % 2; // even => 0, odd => 1 // ExcelRow excelRow; // ExcelFill excelFillRow; // if (rowIndex == whiteRow) // { // excelRow = worksheet.Row(iRow); // excelFillRow = excelRow.Style.Fill; // excelFillRow.PatternType = ExcelFillStyle.Solid; // excelFillRow.BackgroundColor.SetColor(System.Drawing.Color.White); // } // else if (rowIndex == colourRow) // { // excelRow = worksheet.Row(iRow); // excelFillRow = excelRow.Style.Fill; // excelFillRow.PatternType = ExcelFillStyle.Solid; // excelFillRow.BackgroundColor.SetColor(System.Drawing.Color.AliceBlue); // } //} try { // Write to client package.Save(); } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //Throw exception throw ex; } } } /// /// 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //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().Replace(",", ";").Replace("\n", " ").Replace("\r", " ") + ","); } sBuilder.Replace(",", Environment.NewLine, sBuilder.Length - 1, 1); } File.WriteAllText(pathName + destinationFileName, sBuilder.ToString()); } } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //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.IgnoreSchema); //End XML Document writer.WriteEndDocument(); //Close Writer writer.Close(); //close stream ws.Close(); ws.Dispose(); } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //Throw exception throw ex; } return result; } /// /// bool to convert a HTML file to a PDF document /// /// /// /// true if conversion successful public static bool ConvertHTMLToPDFFile(string htmData, string pdfPath, bool isPortrait, string header, string footer, bool showPageNumbers = true, string watermarkUrl = "", string secondHeader = "") { bool result = false; SautinSoft.PdfMetamorphosis pdf; try { //intantiate new PDF Metamorphasis pdf = new SautinSoft.PdfMetamorphosis(); //License PDF pdf.SetSerial("10016715513"); //set pdf defaults pdf.PageStyle.PageSize.A4(); pdf.HtmlOptions.PreserveNestedTables = true; pdf.HtmlOptions.PreserveTables = true; pdf.PageStyle.PageMarginBottom.Inch(0.3f); pdf.PageStyle.PageMarginLeft.Inch(0.3f); pdf.PageStyle.PageMarginTop.Inch(0.3f); pdf.PageStyle.PageMarginRight.Inch(0.3f); if (showPageNumbers) pdf.PageStyle.PageNumFormat = "Page {page} of {numpages}"; if (isPortrait)//portrait pdf.PageStyle.PageOrientation.Portrait(); else//Landscape pdf.PageStyle.PageOrientation.Landscape(); //if (watermarkUrl != "") //{ // //Create a new watermark object // SautinSoft.PdfMetamorphosis.WaterMark wm1 = new SautinSoft.PdfMetamorphosis.WaterMark(); // //Load watermark from image file // WebRequest req = WebRequest.Create(watermarkUrl); // WebResponse response = req.GetResponse(); // Stream stream = response.GetResponseStream(); // Image img = Image.FromStream(stream); // stream.Close(); // wm1.Img = img; // //Set w&h by 2 inch for watermark and place it at the center of Letter page (8.5 x 11 inches) // wm1.PositionInch(3.25f, 4.5f, 2f, 2f); // //Specify that watermark will appear at all pages // wm1.PageNumAll(); // //set 5% transparency // wm1.Transparency(5); // //add watermark to watermarks ArrayList // pdf.PageStyle.WaterMarks.Add(wm1); //} //cater for headers and footers if (header != String.Empty) { //pdf.Header.Html(""); pdf.HeaderOnFirstPage.Html(header); } if (footer != String.Empty) { pdf.Footer.Html(footer); } pdf.HtmlOptions.BaseUrl = HttpContext.Current.Server.MapPath("~"); //Convert to PDF int res = pdf.HtmlToPdfConvertStringToFile(htmData, pdfPath); if (res == 0) { result = true; } //success result = true; } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //Throw exception throw ex; } return result; } /// /// bool to convert a HTML file to a PDF document /// /// /// /// true if conversion successful public static bool ConvertHTMLFileToPDFFile(string htmPath, string pdfPath, bool isPortrait, string header, string footer) { bool result = false; SautinSoft.PdfMetamorphosis pdf; try { //intantiate new PDF Metamorphasis pdf = new SautinSoft.PdfMetamorphosis(); //License PDF pdf.SetSerial("10016715513"); //set pdf defaults pdf.PageStyle.PageSize.A4(); pdf.HtmlOptions.PreserveNestedTables = true; pdf.HtmlOptions.PreserveTables = true; pdf.PageStyle.PageMarginBottom.Inch(0.3f); pdf.PageStyle.PageMarginLeft.Inch(0.3f); pdf.PageStyle.PageMarginTop.Inch(0.3f); pdf.PageStyle.PageMarginRight.Inch(0.3f); pdf.PageStyle.PageNumFormat = "Page {page} of {numpages}"; if (isPortrait)//portrait pdf.PageStyle.PageOrientation.Portrait(); else//Landscape pdf.PageStyle.PageOrientation.Landscape(); //cater for headers and footers if (header != String.Empty) pdf.Header.Html(header); if (footer != String.Empty) pdf.Footer.Html(footer); //Convert htm file to PDF int res = pdf.HtmlToPdfConvertFile(htmPath, pdfPath); if (res == 0) { result = true; } //success result = true; } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); //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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// Function to Convert a DataTable to a list of objects of the specified type /// /// /// /// ArrayList public static ArrayList ConvertDataTableToListParallel(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 in parallel processing Parallel.ForEach(theDataTable.AsEnumerable(), row => { //create a new instance of the object object newObject = Activator.CreateInstance(theObjectType); lock (theDataTable.Columns.SyncRoot) { //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) { throw ex; } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return resultTable; } // Convert an object to a byte array public static byte[] ObjectToByteArray(Object obj) { if (obj == null) return null; BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, obj); return ms.ToArray(); } // Convert a byte array to an Object public static Object ByteArrayToObject(byte[] arrBytes) { MemoryStream memStream = new MemoryStream(); BinaryFormatter binForm = new BinaryFormatter(); memStream.Write(arrBytes, 0, arrBytes.Length); memStream.Seek(0, SeekOrigin.Begin); Object obj = (Object)binForm.Deserialize(memStream); return obj; } public static DataTable ObjectToData(object o) { DataTable dt = new DataTable(); DataRow dr = dt.NewRow(); dt.Rows.Add(dr); o.GetType().GetProperties().ToList().ForEach(f => { try { f.GetValue(o, null); dt.Columns.Add(f.Name, f.PropertyType); dt.Rows[0][f.Name] = f.GetValue(o, null); } catch { } }); return dt; } /// /// Change values with 0 to null /// /// /// public static DataTable ChangeDataTableColumnZerosToNull(DataTable dataTable, string colName = "") { DataTable result = new DataTable(); List dcNames = new List(); if (colName != String.Empty)//column name provided { dcNames = dataTable.Columns .Cast() .Where(x => x.ColumnName == colName) .Select(x => x.ColumnName) .ToList(); //This querying of the Column Names, you could do with LINQ } else//all columns { dcNames = dataTable.Columns .Cast() .Select(x => x.ColumnName) .ToList(); //This querying of the Column Names, you could do with LINQ } Parallel.ForEach(dataTable.AsEnumerable(), drow => { lock (dataTable.Columns.SyncRoot) { foreach (string columnName in dcNames) { dataTable.Columns[columnName].AllowDBNull = true; drow[columnName] = (int)drow[columnName] == 0 ? DBNull.Value : drow[columnName]; } } }); result = dataTable.Copy(); return result; } /// /// Specify datatable column order /// /// /// public static void SetDataTableColumnOrder(ref DataTable table, params String[] columnNames) { int columnIndex = 0; foreach (var columnName in columnNames) { table.Columns[columnName].SetOrdinal(columnIndex); columnIndex++; } } #endregion #region ImageTools /// /// Bool to resize an image based on thumbnail size /// /// 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); } /// /// Bool to resize an image on thumbnail size /// /// /// /// /// /// /// /// 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.Default; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; //Draw the new graphic based on bmp and graphics properties oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight); if (fileCheck.Extension.ToLower().Contains("gif")) { //save newly resized image to destination newBMP.Save(destinationDir + destinationFile, ImageFormat.Gif); } else if (fileCheck.Extension.ToLower().Contains("jpg") || fileCheck.Extension.ToLower().Contains("jpeg")) { //save newly resized image to destination newBMP.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } else if (fileCheck.Extension.ToLower().Contains("png")) { newBMP.Save(destinationDir + destinationFile, ImageFormat.Png); } else { newBMP.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// Bool to resize an image on maxWidth /// /// /// /// /// /// /// /// public static bool ResizeImageMaxWidth(string originalFile, string destinationDir, string destinationFile, bool removeOriginal, bool ConstrainWidth, int maxWidth) { bool result = false; FileStream fs = null; FileInfo fileCheck = null; 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); int originalBitmapWidth = originalBMP.Width; originalBMP.Dispose(); fs.Close(); if (originalBitmapWidth < maxWidth) result = ResizeImage(originalFile, destinationDir, destinationFile, originalBitmapWidth, removeOriginal, ConstrainWidth); else result = ResizeImage(originalFile, destinationDir, destinationFile, maxWidth, removeOriginal, ConstrainWidth); } } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// Bool to resize an image to a constrained height /// /// /// /// /// /// /// /// public static bool ResizeImageH(string originalFile, string destinationDir, string destinationFile, int thumbnailSize, bool removeOriginal) { 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); //set new width from the height to constrain the image proportion newWidth = originalBMP.Width * thumbnailSize / originalBMP.Height; newHeight = thumbnailSize; //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.Default; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; //Draw the new graphic based on bmp and graphics properties oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight); if (fileCheck.Extension.ToLower().Contains("gif")) { //save newly resized image to destination newBMP.Save(destinationDir + destinationFile, ImageFormat.Gif); } else if (fileCheck.Extension.ToLower().Contains("jpg") || fileCheck.Extension.ToLower().Contains("jpeg")) { //save newly resized image to destination newBMP.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } else if (fileCheck.Extension.ToLower().Contains("png")) { newBMP.Save(destinationDir + destinationFile, ImageFormat.Png); } else { newBMP.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// Bool to resize and crop an image to thumbnail size specified /// /// /// /// /// /// /// /// public static bool ResizeImageCrop(string originalFile, string destinationDir, string destinationFile, int thumbnailSize, bool removeOriginal) { bool result = false; FileStream fs = null; FileInfo fileCheck = null; FileInfo destCheck = null; int newWidth = 0; int newHeight = 0; string destTemp = String.Empty; 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); // Calculate the new image dimensions if (originalBMP.Width > originalBMP.Height) { //set height to thumb size so width is wider to be cropped newWidth = originalBMP.Width * thumbnailSize / originalBMP.Height; newHeight = thumbnailSize; } else//height is greater in this case { //assign width to thumb size as height remians larger and needs to be cropped 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.Default; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; //Draw the new graphic based on bmp and graphics properties oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight); destTemp = "temp_" + destinationFile; if (fileCheck.Extension.ToLower().Contains("gif")) { //save newly resized image to destination newBMP.Save(destinationDir + destTemp, ImageFormat.Gif); } else if (fileCheck.Extension.ToLower().Contains("jpg") || fileCheck.Extension.ToLower().Contains("jpeg")) { //save newly resized image to destination newBMP.Save(destinationDir + destTemp, ImageFormat.Jpeg); } else if (fileCheck.Extension.ToLower().Contains("png")) { newBMP.Save(destinationDir + destTemp, ImageFormat.Png); } else { newBMP.Save(destinationDir + destTemp, ImageFormat.Jpeg); } destCheck = new FileInfo(destinationDir + destTemp); //check file is created if (destCheck.Exists) { //file successfully resized result = true; } //dispose objects originalBMP.Dispose(); newBMP.Dispose(); oGraphics.Dispose(); fs.Close(); if (result) { //now crop image System.Drawing.Rectangle cropRect = new System.Drawing.Rectangle(0, 0, thumbnailSize, thumbnailSize); Bitmap src = Image.FromFile(destinationDir + destTemp) as Bitmap; Bitmap target = new Bitmap(cropRect.Width, cropRect.Height); using (Graphics g = Graphics.FromImage(target)) { g.DrawImage(src, new System.Drawing.Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel); if (destCheck.Extension.ToLower().Contains("gif")) { //save newly resized image to destination target.Save(destinationDir + destinationFile, ImageFormat.Gif); } else if (destCheck.Extension.ToLower().Contains("jpg") || fileCheck.Extension.ToLower().Contains("jpeg")) { //save newly resized image to destination target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } else if (destCheck.Extension.ToLower().Contains("png")) { target.Save(destinationDir + destinationFile, ImageFormat.Png); } else { target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } } src.Dispose(); target.Dispose(); destCheck.Delete(); } //remove original image if specified if (removeOriginal) { fileCheck = new FileInfo(originalFile); if (fileCheck.Exists) { //delete original file fileCheck.Delete(); } } } } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// Bool to resize and crop an image to thumbnail size specified /// /// /// /// /// /// /// /// public static Bitmap ResizeImageConstrained(Image originalFile, int widthsize, int heightsize) { Bitmap result = null; int newWidth = 0; int newHeight = 0; string destTemp = String.Empty; try { //create bitmap from the file in memory Bitmap originalBMP = (Bitmap)originalFile; // Calculate the new image dimensions if (originalBMP.Width > originalBMP.Height) { if (originalBMP.Width < widthsize) { //assign width to thumb size as height remians larger and needs to be cropped newWidth = widthsize; newHeight = originalBMP.Height * widthsize / originalBMP.Width; } else { //set height to thumb size so width is wider to be cropped newWidth = originalBMP.Width * heightsize / originalBMP.Height; newHeight = heightsize; } } else//height is greater in this case { if (originalBMP.Height < heightsize) { if (originalBMP.Width > originalBMP.Height) { //set height to thumb size so width is wider to be cropped newWidth = originalBMP.Width * heightsize / originalBMP.Height; newHeight = heightsize; } else { newWidth = widthsize; newHeight = originalBMP.Height * widthsize / originalBMP.Width; } } else { //assign width to thumb size as height remians larger and needs to be cropped newWidth = widthsize; newHeight = originalBMP.Height * widthsize / 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.Default; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; //Draw the new graphic based on bmp and graphics properties oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight); result = newBMP; //dispose objects originalBMP.Dispose(); oGraphics.Dispose(); } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// Bool to resize an image /// /// /// /// /// /// /// /// public static Bitmap ImageCropHeight(Image originalFile, int widthSize, int cropHeight) { Bitmap result = null; try { //now crop image System.Drawing.Rectangle cropRect = new System.Drawing.Rectangle(0, 0, widthSize, cropHeight); Bitmap src = (Bitmap)originalFile; Bitmap target = new Bitmap(cropRect.Width, cropRect.Height); using (Graphics g = Graphics.FromImage(target)) { g.DrawImage(src, new System.Drawing.Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel); } src.Dispose(); result = target; } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// Bool to resize an image /// /// /// /// /// /// /// /// public static bool ResizeImageCropH(string originalFile, string destinationDir, string destinationFile, int widthSize, int cropHeight, bool removeOriginal) { bool result = false; FileStream fs = null; FileInfo fileCheck = null; FileInfo destCheck = null; int newWidth = 0; int newHeight = 0; string destTemp = String.Empty; 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); //assign width to thumb size as height remians larger and needs to be cropped newWidth = widthSize; newHeight = originalBMP.Height * widthSize / 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.Default; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; //Draw the new graphic based on bmp and graphics properties oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight); destTemp = "temp_" + destinationFile; if (fileCheck.Extension.ToLower().Contains("gif")) { //save newly resized image to destination newBMP.Save(destinationDir + destTemp, ImageFormat.Gif); } else if (fileCheck.Extension.ToLower().Contains("jpg") || fileCheck.Extension.ToLower().Contains("jpeg")) { //save newly resized image to destination newBMP.Save(destinationDir + destTemp, ImageFormat.Jpeg); } else if (fileCheck.Extension.ToLower().Contains("png")) { newBMP.Save(destinationDir + destTemp, ImageFormat.Png); } else { newBMP.Save(destinationDir + destTemp, ImageFormat.Jpeg); } destCheck = new FileInfo(destinationDir + destTemp); //check file is created if (destCheck.Exists) { //file successfully resized result = true; } //dispose objects originalBMP.Dispose(); newBMP.Dispose(); oGraphics.Dispose(); fs.Close(); if (result) { //now crop image System.Drawing.Rectangle cropRect = new System.Drawing.Rectangle(0, 0, widthSize, cropHeight); Bitmap src = Image.FromFile(destinationDir + destTemp) as Bitmap; Bitmap target = new Bitmap(cropRect.Width, cropRect.Height); using (Graphics g = Graphics.FromImage(target)) { g.DrawImage(src, new System.Drawing.Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel); if (destCheck.Extension.ToLower().Contains("gif")) { //save newly resized image to destination target.Save(destinationDir + destinationFile, ImageFormat.Gif); } else if (destCheck.Extension.ToLower().Contains("jpg") || fileCheck.Extension.ToLower().Contains("jpeg")) { //save newly resized image to destination target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } else if (destCheck.Extension.ToLower().Contains("png")) { target.Save(destinationDir + destinationFile, ImageFormat.Png); } else { target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } } src.Dispose(); target.Dispose(); destCheck.Delete(); } //remove original image if specified if (removeOriginal) { fileCheck = new FileInfo(originalFile); if (fileCheck.Exists) { //delete original file fileCheck.Delete(); } } } } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// Bool to crop an image /// /// /// /// /// /// /// /// public static bool CropImage(string originalFile, string destinationDir, string destinationFile, int cropWidth, int cropHeight, bool removeOriginal) { bool result = false; FileStream fs = null; FileInfo fileCheck = null; string destTemp = String.Empty; 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); //crop image System.Drawing.Rectangle cropRect = new System.Drawing.Rectangle(0, 0, cropWidth, cropHeight); Bitmap src = originalBMP; Bitmap target = new Bitmap(cropRect.Width, cropRect.Height); using (Graphics g = Graphics.FromImage(target)) { g.DrawImage(src, new System.Drawing.Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel); if (fileCheck.Extension.ToLower().Contains("gif")) { //save newly resized image to destination target.Save(destinationDir + destinationFile, ImageFormat.Gif); } else if (fileCheck.Extension.ToLower().Contains("jpg") || fileCheck.Extension.ToLower().Contains("jpeg")) { //save newly resized image to destination target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } else if (fileCheck.Extension.ToLower().Contains("png")) { target.Save(destinationDir + destinationFile, ImageFormat.Png); } else { target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } } src.Dispose(); target.Dispose(); //remove original image if specified if (removeOriginal) { fileCheck = new FileInfo(originalFile); if (fileCheck.Exists) { //delete original file fileCheck.Delete(); } } } } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// Bool to resize an image /// /// /// /// /// /// /// /// public static bool ResizeCropImagePrecise(string originalFile, string destinationDir, string destinationFile, int cropWidth, int cropHeight, bool removeOriginal) { bool result = false; FileInfo fileCheck = null; try { fileCheck = new FileInfo(originalFile); //check file exists if (fileCheck.Exists) { Image original = Image.FromFile(originalFile); if (original.Width == cropWidth && original.Height == cropHeight)//dont resize { original.Save(destinationDir + destinationFile); original.Dispose(); } else if (original.Width < cropWidth || original.Height < cropHeight) { Bitmap resized = ResizeImageConstrained(original, cropWidth, cropHeight); Bitmap target = new Bitmap(FixedSize(resized, cropWidth, cropHeight, true)); target.Save(destinationDir + destinationFile); original.Dispose(); resized.Dispose(); } else { //chekc proportions if width greater than height lets check if pic is also width greater than height if (cropWidth > cropHeight) { if (original.Height > original.Width)//we have a protrait for a landscape, lets crop the height to correct { Bitmap cropped = ImageCropHeight(original, original.Width, cropHeight); Bitmap target = new Bitmap(FixedSize(cropped, cropWidth, cropHeight, true)); if (fileCheck.Extension.ToLower().Contains("gif")) { target.Save(destinationDir + destinationFile, ImageFormat.Gif); } else if (fileCheck.Extension.ToLower().Contains("jpg") || fileCheck.Extension.ToLower().Contains("jpeg")) { target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } else if (fileCheck.Extension.ToLower().Contains("png")) { target.Save(destinationDir + destinationFile, ImageFormat.Png); } else { target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } original.Dispose(); cropped.Dispose(); } else { Bitmap target = new Bitmap(FixedSize(original, cropWidth, cropHeight, true)); if (fileCheck.Extension.ToLower().Contains("gif")) { target.Save(destinationDir + destinationFile, ImageFormat.Gif); } else if (fileCheck.Extension.ToLower().Contains("jpg") || fileCheck.Extension.ToLower().Contains("jpeg")) { target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } else if (fileCheck.Extension.ToLower().Contains("png")) { target.Save(destinationDir + destinationFile, ImageFormat.Png); } else { target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } original.Dispose(); } } else { Bitmap target = new Bitmap(FixedSize(original, cropWidth, cropHeight, true)); if (fileCheck.Extension.ToLower().Contains("gif")) { target.Save(destinationDir + destinationFile, ImageFormat.Gif); } else if (fileCheck.Extension.ToLower().Contains("jpg") || fileCheck.Extension.ToLower().Contains("jpeg")) { target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } else if (fileCheck.Extension.ToLower().Contains("png")) { target.Save(destinationDir + destinationFile, ImageFormat.Png); } else { target.Save(destinationDir + destinationFile, ImageFormat.Jpeg); } original.Dispose(); } } if (removeOriginal) { fileCheck.Delete(); } } } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } public static System.Drawing.Image FixedSize(Image image, int Width, int Height, bool needToFill) { #region много арифметики int sourceWidth = image.Width; int sourceHeight = image.Height; int sourceX = 0; int sourceY = 0; double destX = 0; double destY = 0; double nScale = 0; double nScaleW = 0; double nScaleH = 0; nScaleW = ((double)Width / (double)sourceWidth); nScaleH = ((double)Height / (double)sourceHeight); if (!needToFill) { nScale = Math.Min(nScaleH, nScaleW); } else { nScale = Math.Max(nScaleH, nScaleW); destY = (Height - sourceHeight * nScale) / 2; destX = (Width - sourceWidth * nScale) / 2; } if (nScale > 1) nScale = 1; int destWidth = (int)Math.Round(sourceWidth * nScale); int destHeight = (int)Math.Round(sourceHeight * nScale); #endregion System.Drawing.Bitmap bmPhoto = null; try { bmPhoto = new System.Drawing.Bitmap(destWidth + (int)Math.Round(2 * destX), destHeight + (int)Math.Round(2 * destY)); } catch (Exception ex) { throw new ApplicationException(string.Format("destWidth:{0}, destX:{1}, destHeight:{2}, desxtY:{3}, Width:{4}, Height:{5}", destWidth, destX, destHeight, destY, Width, Height), ex); } using (System.Drawing.Graphics grPhoto = System.Drawing.Graphics.FromImage(bmPhoto)) { grPhoto.InterpolationMode = InterpolationMode.Low; grPhoto.CompositingQuality = CompositingQuality.HighSpeed; grPhoto.SmoothingMode = SmoothingMode.HighSpeed; System.Drawing.Rectangle to = new System.Drawing.Rectangle((int)Math.Round(destX), (int)Math.Round(destY), destWidth, destHeight); System.Drawing.Rectangle from = new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight); //Console.WriteLine("From: " + from.ToString()); //Console.WriteLine("To: " + to.ToString()); grPhoto.DrawImage(image, to, from, System.Drawing.GraphicsUnit.Pixel); return bmPhoto; } } /// /// bitmap to Return a Rotated image /// /// /// /// public static Bitmap rotateImage(Bitmap b, float angle) { //create a new empty bitmap to hold rotated image Bitmap returnBitmap = new Bitmap(b.Width, b.Height); //make a graphics object from the empty bitmap Graphics g = Graphics.FromImage(returnBitmap); //move rotation point to center of image g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2); //rotate g.RotateTransform(angle); //move image back g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2); //draw passed in image onto graphics object g.DrawImage(b, new System.Drawing.Point(0, 0)); return returnBitmap; } public static Bitmap RotateImg(Bitmap bmp, float angle, Color bkColor) { int w = bmp.Width; int h = bmp.Height; PixelFormat pf = default(PixelFormat); if (bkColor == Color.Transparent) { pf = PixelFormat.Format32bppArgb; } else { pf = bmp.PixelFormat; } Bitmap tempImg = new Bitmap(w, h, pf); Graphics g = Graphics.FromImage(tempImg); g.Clear(bkColor); g.DrawImageUnscaled(bmp, 1, 1); g.Dispose(); GraphicsPath path = new GraphicsPath(); path.AddRectangle(new RectangleF(0f, 0f, w, h)); Matrix mtrx = new Matrix(); //Using System.Drawing.Drawing2D.Matrix class mtrx.Rotate(angle); RectangleF rct = path.GetBounds(mtrx); Bitmap newImg = new Bitmap(Convert.ToInt32(rct.Width), Convert.ToInt32(rct.Height), pf); g = Graphics.FromImage(newImg); g.Clear(bkColor); g.TranslateTransform(-rct.X, -rct.Y); g.RotateTransform(angle); g.InterpolationMode = InterpolationMode.HighQualityBilinear; g.DrawImageUnscaled(tempImg, 0, 0); g.Dispose(); tempImg.Dispose(); return newImg; } /// /// 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } 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) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return myImage; } /// /// Remove File from disk /// /// /// public static bool RemoveFile(string FileToRemove) { try { FileInfo fileCheck = new FileInfo(FileToRemove); if (fileCheck.Exists) { //delete original file fileCheck.Delete(); } return true; } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); return false; } } /// /// MEthod to Embellish an Image /// /// /// /// public static void EmbellishImage(Image myPic, Image myFrame, string destinationFile) { Bitmap embellished; try { using (myPic) { using (embellished = new Bitmap(myFrame.Width, myFrame.Height)) { using (var canvas = Graphics.FromImage(embellished)) { canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; canvas.DrawImage(myPic, new Rectangle(0, 0, myFrame.Width, myFrame.Height), new Rectangle(0, 0, myPic.Width, myPic.Height), GraphicsUnit.Pixel); canvas.DrawImage(myFrame, new Rectangle(0, 0, myPic.Width, myPic.Height), new Rectangle(0, 0, myPic.Width, myPic.Height), GraphicsUnit.Pixel); canvas.Save(); } try { //save to image to file embellished.Save(destinationFile, myPic.RawFormat); } catch (Exception) { } } } } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } } #endregion #region VideoTools /// /// Extract a Thumbnail Image from a Video /// /// The file location of the video /// The output location of the Thumbnail Image /// A boolean for success or failure /// NReco Video Converter for .NET (FFMpeg C# wrapper) - https://www.nrecosite.com/video_converter_net.aspx public static bool GetVideoThumbnail(string videoFilePath, string thumbnailFilePath, out string errorMessage) { bool blnCompleted = true; errorMessage = ""; try { var thumbnailGenerator = new FFMpegConverter(); //thumbnailGenerator.GetVideoThumbnail(videoFilePath, thumbnailFilePath); FileStream jpegOutputStream = new FileStream(thumbnailFilePath, FileMode.Create); // stream for thumbnail jpeg image output var thumbSettings = new ConvertSettings() { VideoFrameRate = 1, VideoFrameCount = 1, // extract exactly 1 frame Seek = 0, // frame position in seconds CustomOutputArgs = "" // any ffmpeg arguments that goes before output param }; thumbnailGenerator.ConvertMedia(videoFilePath, null, jpegOutputStream, "mjpeg", thumbSettings); } catch (Exception ex) { errorMessage = $"{ex.Message} ||| {ex.StackTrace}"; blnCompleted = false; } return blnCompleted; } #endregion #region Merge Tools /// /// List of tyope oMergeField built from an Object /// /// /// List (oMergeField) public static List BuildFieldCodeList(Object myObject, bool includeObjPrefix = false) { List result = new List(); PropertyInfo[] listOfProperties; try { listOfProperties = myObject.GetType().GetProperties(); //enumerate list foreach (PropertyInfo property in listOfProperties) { oMergeField FieldCode = new oMergeField(); if (includeObjPrefix) FieldCode.FieldCode = myObject.GetType().Name + "." + property.Name; else FieldCode.FieldCode = property.Name; FieldCode.FieldType = property.PropertyType; if (property.PropertyType == typeof(DateTime)) { object value = property.GetValue(myObject, null); FieldCode.FieldValue = string.Empty; if (null != value) { DateTime dateValue = DateTime.Parse(property.GetValue(myObject, null).ToString()); FieldCode.FieldValue = dateValue.ToString(ConfigurationManager.AppSettings["DateFormat"]); } } else { FieldCode.FieldValue = property.GetValue(myObject, null)?.ToString() ?? string.Empty; } //append Field Code result.Add(FieldCode); } } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return result; } /// /// Method to Merge fields with HTML data /// /// /// public static void MergeHTMData(ref string htmData, List fieldCodes) { try { //enumerate field codes foreach (oMergeField field in fieldCodes) { if (field.FieldType == typeof(DateTime))//date time field type { DateTime TempValue = DateTime.Parse(field.FieldValue); if (TempValue.TimeOfDay.Seconds == 0 && TempValue.TimeOfDay.Hours == 0 && TempValue.TimeOfDay.Minutes == 0) htmData = htmData.Replace("{" + field.FieldCode + "}", TempValue.ToString("dd MMM yyyy")); else htmData = htmData.Replace("{" + field.FieldCode + "}", TempValue.ToString("dd MMM yyyy HH:mm tt")); } else //standard merge field { htmData = htmData.Replace("{" + field.FieldCode + "}", field.FieldValue); } } } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } } #endregion #region Calculation Tools /// /// Method to calculate and return VAT amount /// /// /// /// public static decimal CalculateVAT(decimal vatRate, decimal input, bool reverse = false) { try { if (vatRate > 0) { if (reverse) return input / ((100M + vatRate) / 100M); else return input + (input / 100M * vatRate); } else return input; } catch (Exception ex) { exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); return 0; } } /// /// Method to calculate age from eithe dob or idnumber /// /// /// /// public static int CalculateAge(DateTime? dob = null, string idNumber = null) { DateTime dtDob = DateTime.Now; if (dob.HasValue) { dtDob = dob.Value; } if (idNumber != null) { dtDob = FormatBirthdayFromID(idNumber); } oAge age = FormatAge(dtDob, DateTime.Now); return age.years; } #endregion #region Extensions /// /// Check if the Data Table is valid /// /// The data table to act on /// True if the data table is not null and contains rows. Else false. public static bool TableIsValid(this DataTable dtData) { bool blnValid = false; if (dtData != null && dtData.Rows.Count > 0) blnValid = true; return blnValid; } /// /// Generate a List of Dynamic Parameters /// /// The object to act on /// The object to generate a parameter list from /// Comma separated list of fields to exclude on the object /// A Parameter list public static List ToDynamicParamList(this List objProperties, object src, string exclusionList = "") { int propertyCount = objProperties.Count(); List lstExcludedFields = exclusionList.Split(',').ToList(); List oParamList = new List(objProperties.Count()); foreach (PropertyInfo prop in objProperties) { if (!(lstExcludedFields.Contains(prop.Name.ToString(), StringComparer.OrdinalIgnoreCase))) { oDynamicParam paramItem = new oDynamicParam(); paramItem.paramDisplayName = prop.Name; paramItem.paramObject = prop.GetValue(src, null); oParamList.Add(paramItem); } } return oParamList; } public static IEnumerable FindControls(this Control control, bool recurse) where T : Control { List found = new List(); Action search = null; search = ctrl => { foreach (Control child in ctrl.Controls) { if (typeof(T).IsAssignableFrom(child.GetType())) { found.Add((T)child); } if (recurse) { search(child); } } }; search(control); return found; } /// /// Parse a string to an Integer /// /// /// /// public static int ToInt(this string value, int defaultIntValue = -1) { int parsedInt; if (int.TryParse(value, out parsedInt)) { return parsedInt; } return defaultIntValue; } /// /// Parse a string to Decimal /// /// /// /// public static decimal ToDecimal(this string value, decimal defaulDecimalValue = 0.00m) { decimal parsedDecimal; if (decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out parsedDecimal)) { return parsedDecimal; } return defaulDecimalValue; } /// /// Parse a string to a DateTime /// /// /// A valid or default date public static DateTime ToDate(this string value, string format = "dd/MM/yyyy") { DateTime defaultDateValue = DateTime.MinValue; DateTime parsedDate; if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate)) { return parsedDate; } return defaultDateValue; } /// /// Get a friendly file size description /// /// The file size in bytes /// Formatted File Size Description public static string ToFileSizeDescription(this long sizeInBytes) { const double Terabyte = 1099511627776; const double Gigabyte = 1073741824; const double Megabyte = 1048576; const double Kilobyte = 1024; string result = string.Empty; double the_size = 0; string units = string.Empty; if (sizeInBytes >= Terabyte) { the_size = sizeInBytes / Terabyte; units = " Tb"; } else { if (sizeInBytes >= Gigabyte) { the_size = sizeInBytes / Gigabyte; units = " Gb"; } else { if (sizeInBytes >= Megabyte) { the_size = sizeInBytes / Megabyte; units = " Mb"; } else { if (sizeInBytes >= Kilobyte) { the_size = sizeInBytes / Kilobyte; units = " Kb"; } else { the_size = sizeInBytes; units = " bytes"; } } } } if (units != "bytes") { result = the_size.ToString("N3") + " " + units; } else { result = the_size.ToString() + " " + units; } return result; } /// /// Generate a Stream from a string value /// /// /// public static Stream ToStream(this string value) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(value); writer.Flush(); stream.Position = 0; return stream; } /// /// Convert an Enumerable source to a Data Table /// /// /// /// public static DataTable ConvertToDataTable(this IEnumerable source) { DataTable table = new DataTable(); var properties = TypeDescriptor.GetProperties(typeof(T)); foreach (PropertyDescriptor property in properties) { if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) table.Columns.Add(property.Name, property.PropertyType.GetGenericArguments()[0]); else table.Columns.Add(property.Name, property.PropertyType); } object[] values = new object[properties.Count]; foreach (var item in source) { for (int i = 0; i < properties.Count; i++) values[i] = properties[i].GetValue(item); table.Rows.Add(values); } return table; } /// /// Remove the ~|~~2~ characters from addresses /// /// The address which could be as "~1~1 Main street~|~~2~Suburb~|~~3~City~|~~4~Province~|~~5~Country~|~~6~Zip" /// The delimiter to replace the sanitized values with. Defaults to a space. /// A sanitized address sanitized with a comma space "1 Main street, Suburb, City, Province, Country, Zip" public static string SanitizeAddressString(this string value, string replaceWithDelimiter = " ") { string sanitizadString = ""; try { string pattern1 = @"[~]\d[~]"; string pattern2 = @"[~]\W[~]"; Regex rgx1 = new Regex(pattern1); string result = rgx1.Replace(value, ""); Regex rgx2 = new Regex(pattern2); sanitizadString = rgx2.Replace(result, replaceWithDelimiter); } catch (Exception ex) { sanitizadString = value; exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return sanitizadString; } /// /// Find any list of strings in a single string /// /// /// /// /// public static bool EqualsAny(this string value, string defaultCommaSeparatedStringToFind, string overrideDelimiter = ",") { bool blnFound = false; string[] arrDelimiter = new string[] { $"{overrideDelimiter}" }; try { if (defaultCommaSeparatedStringToFind.Contains(overrideDelimiter)) { List lstValuesToFind = defaultCommaSeparatedStringToFind.Split(arrDelimiter, StringSplitOptions.None).ToList(); int iFoundCount = (from f in lstValuesToFind where f.ToLower().Equals(value.ToLower()) select f).Count(); if (iFoundCount > 0) { blnFound = true; } } } catch (Exception ex) { blnFound = false; exception.HandleException("utils:", MethodBase.GetCurrentMethod().Name, ex, HttpContext.Current.Session["userId"]); } return blnFound; } #endregion } }