EchoTex_Payroll/Ease.Core/Utility/Global.cs

1590 lines
54 KiB
C#
Raw Normal View History

2024-10-14 10:01:49 +06:00
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 23/07/2012 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Net;
using System.Text;
using System.Linq;
//using System.Management;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace Ease.Core.Utility
{
#region Delegates
public delegate IntPtr KeyboardProc(int code, IntPtr wParam, IntPtr lParam);
public delegate IntPtr MouseProc(int code, IntPtr wParam, IntPtr lParam);
#endregion
#region Win32Structure & Class
internal class AnimateWindow
{
private AnimateWindow()
{
}
public static int AW_HOR_POSITIVE = 0x1;
public static int AW_HOR_NEGATIVE = 0x2;
public static int AW_VER_POSITIVE = 0x4;
public static int AW_VER_NEGATIVE = 0x8;
public static int AW_CENTER = 0x10;
public static int AW_HIDE = 0x10000;
public static int AW_ACTIVATE = 0x20000;
public static int AW_SLIDE = 0x40000;
public static int AW_BLEND = 0x80000;
}
[StructLayout(LayoutKind.Sequential)]
internal struct POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
internal struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SIZE
{
public int cx;
public int cy;
}
[StructLayout(LayoutKind.Sequential)]
internal struct TRACKMOUSEEVENTS
{
public uint cbSize;
public uint dwFlags;
public IntPtr hWnd;
public uint dwHoverTime;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MSG
{
public IntPtr hwnd;
public int message;
public IntPtr wParam;
public IntPtr lParam;
public int time;
public int pt_x;
public int pt_y;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct BLENDFUNCTION
{
public byte BlendOp;
public byte BlendFlags;
public byte SourceConstantAlpha;
public byte AlphaFormat;
}
[StructLayout(LayoutKind.Sequential)]
public struct LOGBRUSH
{
public uint lbStyle;
public uint lbColor;
public uint lbHatch;
}
#endregion
#region Global Class
public sealed class Global
{
#region Declartion/Constructor
private Global()
{
}
#endregion
#region String functions
public class StringFuncions
{
public static bool IsEmptyOrNull(object o)
{
string s = (o == null) ? string.Empty : o.ToString();
return StringFuncions.IsEmptyOrNull(s);
}
public static bool IsEmptyOrNull(string s)
{
s = (s == null) ? string.Empty : s;
return string.IsNullOrEmpty(s);
}
public static bool IsEmpty(object o)
{
string s = (o == null) ? string.Empty : o.ToString();
return StringFuncions.IsEmpty(s);
}
public static bool IsEmpty(string s)
{
s = (s == null) ? string.Empty : s;
return (s == string.Empty || s.Trim().Length <= 0);
}
public static bool IsNotEmpty(string s)
{
return !StringFuncions.IsEmpty(s);
}
public static bool IsNotEmpty(object o)
{
return !StringFuncions.IsEmpty(o);
}
public static string FormatString(string format, params object[] args)
{
return string.Format(format, args);
}
public static string StringReverse(string s)
{
string tmp = string.Empty;
for (int i = s.Length - 1; i >= 0; i--)
tmp = string.Format("{0}{1}", tmp, s[i]);
return tmp;
}
public static string MakeItSentence(string inputString)
{
for (int i = 0; i < inputString.Length; i++)
{
char a = Convert.ToChar(inputString.Substring(i, 1));
if (Char.IsUpper(a))
{
if (i != 0 && inputString.Substring(i - 1, 1) != " ")
inputString = inputString.Insert(i, " ");
}
}
return inputString;
}
public static string Left(string inputString, int length)
{
if (length < inputString.Length && length > 0)
return inputString.Substring(0, length);
else
return inputString;
}
public static string Right(string inputString, int length)
{
if (length < inputString.Length && length > 0)
return inputString.Substring((inputString.Length - length), length);
else
return inputString;
}
public static string Mid(string inputString, int start, int length)
{
if ((start + length) < inputString.Length)
return inputString.Substring(start, length);
else if (start < inputString.Length)
return inputString.Substring(start);
else
return inputString;
}
public static string Mid(string inputString, int start)
{
if (start < inputString.Length)
return inputString.Substring(start);
else
return inputString;
}
public static void Mid(ref string inputString, int start, int length, string value)
{
if ((start + length) > inputString.Length)
throw new Exception("Inputstring has not enough length");
string part1 = inputString.Substring(0, start);
string part2 = inputString.Substring(start + length);
value = value.Length < length ? value.PadRight(length, ' ') : value;
value = value.Length > length ? StringFuncions.Left(value, length) : value;
inputString = string.Format("{0}{1}{2}", part1, value, part2);
}
public static bool IsStrongPassword(string password)
{
string pattern = @"(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$";
return Regex.IsMatch(password, pattern);
}
public static bool IsEmailAddress(string emailAddress)
{
string pattern =
@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
return Regex.IsMatch(emailAddress, pattern);
}
}
#endregion
#region Date Functions
public class DateFunctions
{
public static bool IsDateTime(string s, FormatOptions f)
{
if (string.IsNullOrEmpty(s))
throw new Exception("Invalid use of empty string.");
string[] vals = s.Split(new char[] { '-', '/', '.', ' ' });
if (vals == null || vals.Length < 3)
throw new Exception("Invalid use of date format.");
bool ret = true;
int day = 0, month = 0, year = 0;
#region For the format "MM/dd/yyyy"
if (f == FormatOptions.MMddyyyy)
{
if (!NumericFunctions.IsNumeric(vals[1].Trim()))
return false;
day = Convert.ToInt32(vals[1].Trim());
if (!NumericFunctions.IsNumeric(vals[0].Trim()))
return false;
month = Convert.ToInt32(vals[0].Trim());
if (!NumericFunctions.IsNumeric(vals[2].Trim()))
return false;
year = Convert.ToInt32(vals[2].Trim());
//Making year
if (year < 100 && vals[2].Trim().Length < 4)
year = 2000 + year;
//Month validation
if (month < 1 || month > 12)
ret = false;
//Day validation
if (ret && (day < 1 || day > DateTime.DaysInMonth(year, month)))
ret = false;
}
#endregion
#region For the format "dd/MM/yyyy" or "dd/MM/yyyy hh:mm:ss AM/PM"
if (f == FormatOptions.ddMMyyyy)
{
if (!NumericFunctions.IsNumeric(vals[0].Trim()))
return false;
day = Convert.ToInt32(vals[0].Trim());
if (!NumericFunctions.IsNumeric(vals[1].Trim()))
return false;
month = Convert.ToInt32(vals[1].Trim());
if (!NumericFunctions.IsNumeric(vals[2].Trim()))
return false;
year = Convert.ToInt32(vals[2].Trim());
//Making year
if (year < 100 && vals[2].Trim().Length < 4)
year = 2000 + year;
//Month validation
if (month < 1 || month > 12)
ret = false;
//Day validation
if (ret && (day < 1 || day > DateTime.DaysInMonth(year, month)))
ret = false;
}
#endregion
#region For the format "dd/MMM/yyyy" or "dd/MMM/yyyy hh:mm:ss AM/PM"
if (f == FormatOptions.ddMMMyyyy)
{
if (!NumericFunctions.IsNumeric(vals[0].Trim()))
return false;
day = Convert.ToInt32(vals[0].Trim());
if (!NumericFunctions.IsNumeric(vals[2].Trim()))
return false;
year = Convert.ToInt32(vals[2].Trim());
//Making year
if (year < 100 && vals[2].Trim().Length < 4)
year = 2000 + year;
//Month validation
month = monthIndex(vals[1]);
if (month < 1 || month > 12)
ret = false;
//Day validation
if (ret && (day < 1 || day > DateTime.DaysInMonth(year, month)))
ret = false;
}
#endregion
return ret;
}
public static bool IsDateTime(object o, FormatOptions f)
{
string s = (o == null) ? string.Empty : o.ToString();
return DateFunctions.IsDateTime(s, f);
}
public static DateTime GetDate(string s, FormatOptions f)
{
if (StringFuncions.IsEmptyOrNull(s))
throw new Exception("Invalid use of empty string.");
string[] vals = s.Split(new char[] { '-', '/', '.', ' ' });
if (vals == null || vals.Length < 3)
throw new Exception("Invalid use of date format.");
int day = 0, month = 0, year = 0;
#region For format$ "MM/dd/yyyy"
if (f == FormatOptions.MMddyyyy)
{
day = Convert.ToInt32(vals[1].Trim());
month = Convert.ToInt32(vals[0].Trim());
year = Convert.ToInt32(vals[2].Trim());
//Making year
if (year < 100 && vals[2].Trim().Length < 4)
year = 2000 + year;
//Month validation
if (month < 1 || month > 12)
throw new Exception("Invalid date format for month overflow.");
//Day validation
if (day < 1 || day > DateTime.DaysInMonth(year, month))
throw new Exception("Invalid date format for day overflow.");
return new DateTime(year, month, day);
}
#endregion
#region For format "dd/MM/yyyy"
if (f == FormatOptions.ddMMyyyy)
{
day = Convert.ToInt32(vals[0].Trim());
month = Convert.ToInt32(vals[1].Trim());
year = Convert.ToInt32(vals[2].Trim());
if (year < 100 && vals[2].Trim().Length < 4)
year = 2000 + year;
//Month validation
if (month < 1 || month > 12)
throw new Exception("Invalid date format for month overflow.");
//Day validation
if (day < 1 || day > DateTime.DaysInMonth(year, month))
throw new Exception("Invalid date format for day overflow.");
return new DateTime(year, month, day);
}
#endregion
#region For format "dd/MMM/yyyy"
if (f == FormatOptions.ddMMMyyyy)
{
day = Convert.ToInt32(vals[0].Trim());
year = Convert.ToInt32(vals[2].Trim());
if (year < 100 && vals[2].Trim().Length < 4)
year = 2000 + year;
//Month Validation
month = monthIndex(vals[1]);
if (month < 1 || month > 12)
throw new Exception("Invalid date format for month overflow.");
//Day validation
if (day < 1 || day > DateTime.DaysInMonth(year, month))
throw new Exception("Invalid date format for day overflow.");
return new DateTime(year, month, day);
}
#endregion
return new DateTime(1, 1, 1);
}
public static DateTime GetDate(object o, FormatOptions f)
{
if (o == null)
throw new Exception("Invalid use of null reference.");
string s = o.ToString();
return DateFunctions.GetDate(s, f);
}
/// <summary>
/// This function return the first date of month of param date
/// </summary>
/// <param name="forDate">A valid date</param>
/// <returns>Return the date of month</returns>
public static DateTime FirstDateOfMonth(DateTime forDate)
{
return new DateTime(forDate.Year, forDate.Month, 1);
}
public static DateTime FirstDateOfMonth(int year, int month)
{
return new DateTime(year, month, 1);
}
public static DateTime FirstDateOfYear(DateTime forDate)
{
return new DateTime(forDate.Year, 1, 1);
}
public static DateTime FirstDateOfYear(int year)
{
return new DateTime(year, 1, 1);
}
public static DateTime LastDateOfYear(DateTime forDate)
{
return new DateTime(forDate.Year, 12, 31);
}
public static DateTime LastDateOfYear(int year)
{
return new DateTime(year, 12, 31);
}
public static DateTime LastDateOfMonth(DateTime forDate)
{
DateTime ldom = new DateTime(forDate.Year, forDate.Month, 1);
ldom = ldom.AddMonths(1);
ldom = ldom.AddDays(-1);
return ldom;
}
public static DateTime LastDateOfMonth(int year, int month)
{
DateTime ldom = new DateTime(year, month, 1);
ldom = ldom.AddMonths(1);
ldom = ldom.AddDays(-1);
return ldom;
}
public static bool IsFirstDayOfMonth(DateTime onDate)
{
return (onDate.Day == 1);
}
public static bool IsFirstDayOfYear(DateTime onDate)
{
return (onDate.Month == 1 && onDate.Day == 1);
}
public static bool IsLastDayOfMonth(DateTime onDate)
{
int days = DateTime.DaysInMonth(onDate.Year, onDate.Month);
return (days <= onDate.Day);
}
public static bool IsLastDayOfYear(DateTime onDate)
{
return (onDate.Month == 12 && onDate.Day == 31);
}
/// <summary>
/// This function return the integer value in accordance with stringformat
/// </summary>
/// <param name="Date1">Subtract from this value and must be datetime</param>
/// <param name="Date2">Subtract this value and must be datetime</param>
/// <param name="Interval">There are three types of format 1=d/D return difference in days, 2=m/M return difference in month, 3=y/Y return difference in years// </param>
/// <returns></returns>
public static int DateDiff(string interval, DateTime date1, DateTime date2)
{
int diffVale = 0;
DateTime fromDate, toDate;
if (date1 > date2)
{
toDate = date1;
fromDate = date2;
}
else
{
fromDate = date1;
toDate = date2;
}
switch (interval)
{
case "D":
case "d":
for (int curYear = fromDate.Year + 1; curYear <= toDate.Year; curYear++)
diffVale += new DateTime(curYear, 12, 31).DayOfYear;
diffVale += toDate.DayOfYear - fromDate.DayOfYear;
break;
case "M":
case "m":
diffVale = toDate.Year - fromDate.Year;
diffVale = diffVale * 12;
diffVale += toDate.Month - fromDate.Month;
break;
case "Y":
case "y":
if (toDate.DayOfYear < fromDate.DayOfYear)
diffVale = toDate.Year - fromDate.Year - 1;
else
diffVale = toDate.Year - fromDate.Year;
break;
}
if (date1 > date2)
diffVale = -diffVale;
return diffVale;
}
/// <summary>
/// This function return the year, month, day with space delimeter
/// </summary>
/// <param name="Date1">Subtract from this value and must be datetime</param>
/// <param name="Date2">Subtract this value and must be datetime</param>
/// <returns>Return a string year, month, day with space delimeter
/// e.g 2 Years 9 months 27 days or 8 months 16 days or 16 days
/// </returns>
public static string DateDiff(DateTime Date1, DateTime Date2)
{
int diff = 0;
DateTime calcDate;
string retVal = string.Empty;
if (Date1 > Date2)
{
calcDate = Date2;
Date2 = Date1;
Date1 = calcDate;
}
//Finding the year difference
diff = DateFunctions.DateDiff("Y", Date1, Date2);
if (diff > 0)
{
if (diff == 1)
retVal = "1 Year ";
else
retVal = diff + " Years ";
}
//Finding the month difference
calcDate = new DateTime(Date1.Year, Date1.Month, Date1.Day);
calcDate = calcDate.AddYears(diff);
diff = Math.Abs(DateFunctions.DateDiff("M", calcDate, Date2));
if (diff > 0)
{
if (diff == 1)
retVal = retVal + "1 Month ";
else
retVal = retVal + diff + " Months ";
}
//Finding the day difference
calcDate = calcDate.AddMonths(diff);
diff = Math.Abs(DateFunctions.DateDiff("D", calcDate, Date2));
if (diff > 0)
{
if (diff == 1)
retVal = retVal + "1 Day";
else
retVal = retVal + diff + " Days";
}
//Finally trimming the spaces
retVal = retVal.Trim();
return retVal;
}
/// <summary>
/// This function add number with date in accordance with interval
/// </summary>
/// <param name="Interval">There are three types of interval 1:= d/D add day(s), 2:= m/M add month(s), 3: =y/Y add year(s) with input date</param>
/// <param name="Number">Value to be added</param>
/// <param name="Date">Input date add with this value</param>
/// <returns>Return datatime after operation</returns>
public static DateTime DateAdd(string interval, int number, DateTime date)
{
DateTime retValue = date;
switch (interval)
{
case "D":
case "d":
retValue = retValue.AddDays(number);
break;
case "M":
case "m":
retValue = retValue.AddMonths(number);
break;
case "Y":
case "y":
retValue = retValue.AddYears(number);
break;
}
return retValue;
}
private static int monthIndex(string monthName)
{
int index = 0;
string[] months = null;
System.Globalization.DateTimeFormatInfo df = new System.Globalization.DateTimeFormatInfo();
if (monthName.Trim().Length <= 2)
if (NumericFunctions.IsNumeric(monthName))
return Convert.ToInt32((monthName.Trim()));
if (monthName.Trim().Length == 3)
months = df.AbbreviatedMonthNames;
else
months = df.MonthNames;
foreach (string item in months)
{
index++;
if (item.ToLower() == monthName.ToLower())
return index;
}
return -1;
}
public static List<DateTime> DatesOfDay(DayOfWeek day, DateTime date1, DateTime date2)
{
return DateFunctions.DatesOfDay(day, date1, date2, null);
}
public static List<DateTime> DatesOfDay(DayOfWeek day, DateTime date1, DateTime date2,
List<DateTime> holidays)
{
List<DateTime> dates = new List<DateTime>();
DateTime onDate = date1 < date2 ? date1 : date2;
date2 = date1 > date2 ? date1 : date2;
while (onDate.DayOfWeek != day)
onDate = onDate.AddDays(1);
while (onDate <= date2)
{
if (holidays == null || !holidays.Contains(onDate))
dates.Add(onDate);
onDate = onDate.AddDays(7);
}
return dates;
}
}
#endregion
#region Numeric functions
public class NumericFunctions
{
private static string HundredWords(int inputValue)
{
string hundredWords = "", numStr = "", pos1 = "", pos2 = "", pos3 = "";
string[] digits = new string[10]
{ "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
string[] teens = new string[10]
{
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen"
};
string[] tens = new string[10]
{ "", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
numStr = StringFuncions.Right(inputValue.ToString("000"), 3);
if (StringFuncions.Left(numStr, 1) != "0")
pos1 = digits.GetValue(Convert.ToInt32(StringFuncions.Left(numStr, 1))) + " hundred";
else
pos1 = "";
numStr = StringFuncions.Right(numStr, 2);
if (StringFuncions.Left(numStr, 1) == "1")
{
pos2 = Convert.ToString(teens.GetValue(Convert.ToInt32(StringFuncions.Right(numStr, 1))));
pos3 = "";
}
else
{
pos2 = Convert.ToString(tens.GetValue(Convert.ToInt32(StringFuncions.Left(numStr, 1))));
pos3 = Convert.ToString(digits.GetValue(Convert.ToInt32(StringFuncions.Right(numStr, 1))));
}
hundredWords = pos1;
if (hundredWords != "")
{
if (pos2 != "")
{
hundredWords = hundredWords + " ";
}
}
hundredWords = hundredWords + pos2;
if (hundredWords != "")
{
if (pos3 != "")
{
hundredWords = hundredWords + " ";
}
}
hundredWords = hundredWords + pos3;
return hundredWords;
}
private static string InWords(double inputValue, string beforeDecimal, string afterDecimal)
{
int commaCount = 0, digitCount = 0;
string sign = "", takaWords = "", numStr = "", taka = "", paisa = "", pow = "";
string[] pows = new string[3] { "crore", "thousand", "lakh" };
if (inputValue < 0)
{
sign = "Minus";
inputValue = Math.Abs(inputValue);
}
numStr = inputValue.ToString("0.00");
paisa = HundredWords(Convert.ToInt32(StringFuncions.Right(numStr, 2)));
if (paisa != "")
{
paisa = paisa.Substring(0, 1).ToUpper() + paisa.Substring(1);
paisa = afterDecimal + " " + paisa;
}
numStr = StringFuncions.Left(numStr, numStr.Length - 3);
taka = HundredWords(Convert.ToInt32(StringFuncions.Right(numStr, 3)));
if (numStr.Length <= 3)
{
numStr = "";
}
else
{
numStr = StringFuncions.Left(numStr, numStr.Length - 3);
}
commaCount = 1;
if (numStr != "")
{
do
{
if (commaCount % 3 == 0)
{
digitCount = 3;
}
else
{
digitCount = 2;
}
pow = HundredWords(Convert.ToInt32(StringFuncions.Right(numStr, digitCount)));
if (pow != "")
{
if (Convert.ToString(inputValue).Length > 10)
{
pow = pow + " " + pows.GetValue(commaCount % 3) + " crore ";
}
else
{
pow = pow + " " + pows.GetValue(commaCount % 3);
}
}
if (taka != "")
{
if (pow != "")
{
pow = pow + " ";
}
}
taka = pow + taka;
if (numStr.Length <= digitCount)
{
numStr = "";
}
else
{
numStr = StringFuncions.Left(numStr, numStr.Length - digitCount);
}
commaCount = commaCount + 1;
} while (numStr != "");
}
if (taka != "")
{
taka = taka.Substring(0, 1).ToUpper() + taka.Substring(1);
taka = beforeDecimal + " " + taka;
}
takaWords = taka;
if (takaWords != "")
{
if (paisa != "")
{
takaWords = takaWords + " and ";
}
}
takaWords = takaWords + paisa;
if (takaWords == "")
{
takaWords = beforeDecimal + " Zero";
}
takaWords = sign + takaWords + " Only";
return takaWords;
}
public static string AmountInWords(decimal inputValue, string beforeDecimal, string afterDecimal)
{
return NumericFunctions.InWords(Convert.ToDouble(inputValue), beforeDecimal, afterDecimal);
}
public static string AmountInWords(float inputValue, string beforeDecimal, string afterDecimal)
{
return NumericFunctions.InWords(Convert.ToDouble(inputValue), beforeDecimal, afterDecimal);
}
public static string AmountInWords(double inputValue, string beforeDecimal, string afterDecimal)
{
return NumericFunctions.InWords(inputValue, beforeDecimal, afterDecimal);
}
public static string TakaWords(decimal inputValue)
{
return NumericFunctions.TakaWords(Convert.ToDouble(inputValue));
}
public static string TakaWords(float inputValue)
{
return NumericFunctions.TakaWords(Convert.ToDouble(inputValue));
}
public static string TakaWords(double inputValue)
{
return NumericFunctions.InWords(inputValue, "Taka", "Paisa");
}
public static bool IsNumeric(char chrValue)
{
return char.IsDigit(chrValue);
}
/// <summary>
/// Checks the string whether it is numeric or not
/// </summary>
/// <param name="str">String Type</param>
/// <returns>Returns true if number otherwise false</returns>
public static bool IsNumeric(string s)
{
if (string.IsNullOrEmpty(s))
return false;
s = s.Trim();
if (s.StartsWith("+") || s.StartsWith("-"))
s = s.Substring(1);
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (!char.IsNumber(c) && c != '.')
return false;
}
return true;
}
/// <summary>
/// Checks the string whether it is numeric or not
/// </summary>
/// <param name="objValue">Object Type</param>
/// <returns>Returns true if number otherwise false</returns>
public static bool IsNumeric(object o)
{
string s = o == null ? String.Empty : Convert.ToString(o);
return (StringFuncions.IsNotEmpty(s) && IsNumeric(s));
}
/// <summary>
/// Checks the string whether it is decimal or not
/// </summary>
/// <param name="str"></param>
/// <returns>Returns true if decimal otherwise false</returns>
public static bool IsDecimal(string strValue)
{
return (!string.IsNullOrEmpty(strValue) && new Regex("[^0-9\\.\\-\\+]").IsMatch(strValue) == false);
}
/// <summary>
/// Checks the string whether it is currency or not
/// </summary>
/// <param name="str"></param>
/// <returns>Returns true if currency otherwise false</returns>
public static bool IsCurrency(string s)
{
return (!string.IsNullOrEmpty(s) && new Regex("[^$0-9\\,\\.\\-\\+]").IsMatch(s) == false);
}
public static double RoundOff(decimal inputValue)
{
return Convert.ToDouble(Math.Round(inputValue));
}
public static double RoundOff(decimal inputValue, int digits)
{
return RoundOff(Convert.ToDouble(inputValue), digits);
}
public static double RoundOff(double inputValue, int digits)
{
double rmndr = 0.0, retVal = 0.0;
if (digits < 0)
{
retVal = Math.Pow(10, Math.Abs(digits));
rmndr = ((inputValue % retVal) / retVal);
if (rmndr >= 0.5)
{
rmndr = 1 * retVal;
}
else
{
rmndr = 0;
}
retVal = (((inputValue - (inputValue % retVal)) / retVal) * retVal) + rmndr;
}
else
{
retVal = Math.Round(inputValue, digits);
}
return retVal;
}
public static double RoundOff(double inputValue)
{
return Math.Round(inputValue);
}
public static double RoundOff(float inputValue, int digits)
{
return RoundOff(Convert.ToDouble(inputValue), digits);
}
public static double RoundOff(float inputValue)
{
return Math.Round(inputValue);
}
public static string TakaFormat(decimal inputValue, char digitSeparator, char decimalSeparator, byte digits)
{
return NumericFunctions.TakaFormat(Convert.ToDouble(inputValue), digitSeparator, decimalSeparator,
digits);
}
public static string TakaFormat(decimal inputValue, byte digits)
{
return NumericFunctions.TakaFormat(Convert.ToDouble(inputValue), ',', '.', digits);
}
public static string TakaFormat(decimal inputValue, char digitSeparator, char decimalSeparator)
{
return NumericFunctions.TakaFormat(Convert.ToDouble(inputValue), digitSeparator, decimalSeparator);
}
public static string TakaFormat(decimal inputValue)
{
return NumericFunctions.TakaFormat(Convert.ToDouble(inputValue), ',', '.');
}
public static string TakaFormat(float inputValue, char digitSeparator, char decimalSeparator, byte digits)
{
return NumericFunctions.TakaFormat(Convert.ToDouble(inputValue), digitSeparator, decimalSeparator,
digits);
}
public static string TakaFormat(float inputValue, byte digits)
{
return NumericFunctions.TakaFormat(Convert.ToDouble(inputValue), ',', '.', digits);
}
public static string TakaFormat(float inputValue, char digitSeparator, char decimalSeparator)
{
return NumericFunctions.TakaFormat(Convert.ToDouble(inputValue), digitSeparator, decimalSeparator);
}
public static string TakaFormat(float inputValue)
{
return NumericFunctions.TakaFormat(Convert.ToDouble(inputValue), ',', '.');
}
public static string TakaFormat(double inputValue, char digitSeparator, char decimalSeparator, byte digits)
{
string format = "##,##,###";
if (digits > 0)
format = string.Format("{0}.{1}", format, new string('0', digits));
return NumericFunctions.CustomFormat(inputValue, digitSeparator, decimalSeparator, format);
}
public static string TakaFormat(double inputValue, byte digits)
{
return NumericFunctions.TakaFormat(inputValue, ',', '.', digits);
}
public static string TakaFormat(double inputValue, char digitSeparator, char decimalSeparator)
{
return NumericFunctions.CustomFormat(inputValue, digitSeparator, decimalSeparator, "##,##,###.00");
}
public static string TakaFormat(double inputValue)
{
return NumericFunctions.TakaFormat(inputValue, ',', '.');
}
public static string MillionFormat(decimal inputValue, char digitSeparator, char decimalSeparator,
byte digits)
{
return NumericFunctions.CustomFormat(inputValue, digitSeparator, decimalSeparator,
string.Format("N{0}", digits));
}
public static string MillionFormat(decimal inputValue, byte digits)
{
return NumericFunctions.CustomFormat(inputValue, ',', '.', string.Format("N{0}", digits));
}
public static string MillionFormat(decimal inputValue, char digitSeparator, char decimalSeparator)
{
return NumericFunctions.CustomFormat(inputValue, digitSeparator, decimalSeparator, "N2");
}
public static string MillionFormat(decimal inputValue)
{
return NumericFunctions.CustomFormat(inputValue, ',', '.', "N2");
}
public static string MillionFormat(float inputValue, char digitSeparator, char decimalSeparator,
byte digits)
{
return NumericFunctions.CustomFormat(inputValue, digitSeparator, decimalSeparator,
string.Format("N{0}", digits));
}
public static string MillionFormat(float inputValue, byte digits)
{
return NumericFunctions.CustomFormat(inputValue, ',', '.', string.Format("N{0}", digits));
}
public static string MillionFormat(float inputValue, char digitSeparator, char decimalSeparator)
{
return NumericFunctions.CustomFormat(inputValue, digitSeparator, decimalSeparator, "N2");
}
public static string MillionFormat(float inputValue)
{
return NumericFunctions.CustomFormat(inputValue, ',', '.', "N2");
}
public static string MillionFormat(double inputValue, char digitSeparator, char decimalSeparator,
byte digits)
{
return NumericFunctions.CustomFormat(inputValue, digitSeparator, decimalSeparator,
string.Format("N{0}", digits));
}
public static string MillionFormat(double inputValue, byte digits)
{
return NumericFunctions.CustomFormat(inputValue, ',', '.', string.Format("N{0}", digits));
}
public static string MillionFormat(double inputValue, char digitSeparator, char decimalSeparator)
{
return NumericFunctions.CustomFormat(inputValue, digitSeparator, decimalSeparator, "N2");
}
public static string MillionFormat(double inputValue)
{
return NumericFunctions.CustomFormat(inputValue, ',', '.', "N2");
}
public static string CustomFormat(decimal inputValue, string format)
{
return NumericFunctions.CustomFormat(Convert.ToDouble(inputValue), ',', '.', format);
}
public static string CustomFormat(decimal inputValue, char digitSeparator, char decimalSeparator,
string format)
{
return NumericFunctions.CustomFormat(Convert.ToDouble(inputValue), digitSeparator, decimalSeparator,
format);
}
public static string CustomFormat(float inputValue, string format)
{
return NumericFunctions.CustomFormat(Convert.ToDouble(inputValue), ',', '.', format);
}
public static string CustomFormat(float inputValue, char digitSeparator, char decimalSeparator,
string format)
{
return NumericFunctions.CustomFormat(Convert.ToDouble(inputValue), digitSeparator, decimalSeparator,
format);
}
public static string CustomFormat(double inputValue, string format)
{
return NumericFunctions.CustomFormat(inputValue, ',', '.', format);
}
public static string CustomFormat(double inputValue, char digitSeparator, char decimalSeparator,
string format)
{
string sign = string.Empty, formattedValue = string.Empty;
if (inputValue < 0)
{
sign = "-";
inputValue = (-inputValue);
}
//Format starts with N
if (format.ToUpper().StartsWith("N"))
{
formattedValue = inputValue.ToString(format);
formattedValue = formattedValue.Replace(',', digitSeparator);
formattedValue = formattedValue.Replace('.', decimalSeparator);
return string.Format("{0}{1}", sign, formattedValue);
}
//Split whole number foramt wnd faction number
string wPart = string.Empty, fPart = string.Empty;
string[] tokens = format.Split(decimalSeparator);
if (tokens.Length >= 2)
{
wPart = tokens[0];
fPart = tokens[1];
}
else
{
wPart = format;
fPart = string.Empty;
}
//Split whole number and faction number
string fNum = string.Empty;
string wNum = string.Empty;
tokens = inputValue.ToString("0.00000000").Split('.');
if (tokens.Length >= 2)
{
wNum = tokens[0];
fNum = tokens[1];
}
else
{
wNum = tokens[0];
}
//Format whole part first
int remLn = wNum.Length;
tokens = wPart.Split(',');
while (remLn > 0)
{
for (int i = tokens.Length - 1; i >= 0; i--)
{
if (remLn > 0)
{
int ln = tokens[i].Length;
string s = string.Empty;
remLn -= ln;
if (remLn < wNum.Length && remLn > 0)
s = wNum.Substring(remLn);
else
s = wNum;
if (remLn > 0)
wNum = wNum.Substring(0, remLn);
else
wNum = string.Empty;
if (remLn > 0)
formattedValue = string.Format("{0}{1}{2}", digitSeparator, s, formattedValue);
else
formattedValue = string.Format("{0}{1}", s, formattedValue);
}
}
}
//Add afranctional part
if (fNum.Length > 0 && fPart.Length > 0)
{
if (fNum.Length > fPart.Length)
formattedValue = string.Format("{0}{1}{2}", formattedValue, decimalSeparator,
fNum.Substring(0, fPart.Length));
else
formattedValue = string.Format("{0}{1}{2}", formattedValue, decimalSeparator,
Convert.ToInt32(fNum).ToString(fPart));
}
return string.Format("{0}{1}", sign, formattedValue);
}
}
#endregion
#region Cipher functions
public class CipherFunctions
{
public static string Encrypt(string data)
{
try
{
return new Encryption().Encrypt(Encryption.DefaultPrivateKey, data);
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public static string Encrypt(string key, string data)
{
try
{
return new Encryption().Encrypt(key, data);
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public static string Decrypt(string data)
{
try
{
return new Encryption().Decrypt(Encryption.DefaultPrivateKey, data);
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public static string Decrypt(string key, string data)
{
try
{
return new Encryption().Decrypt(key, data);
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public static string EncryptByTDS(string data)
{
try
{
return new TDSEncryption().Encrypt(Encryption.DefaultPrivateKey, Encryption.DefaultPublicKey, data);
}
catch (Exception e)
{
throw e;
}
}
public static string EncryptByTDS(string privateKey, string publicKey, string data)
{
try
{
return new TDSEncryption().Encrypt(privateKey, publicKey, data);
}
catch (Exception e)
{
throw e;
}
}
public static string DecryptByTDS(string data)
{
try
{
return new TDSEncryption().Decrypt(Encryption.DefaultPrivateKey, Encryption.DefaultPublicKey, data);
}
catch (Exception e)
{
throw e;
}
}
public static string DecryptByTDS(string privateKey, string publicKey, string data)
{
try
{
return new TDSEncryption().Decrypt(privateKey, publicKey, data);
}
catch (Exception e)
{
throw e;
}
}
public static string EncryptByAES(string data)
{
try
{
return new AESEncryption().Encrypt(Encryption.DefaultPrivateKey, Encryption.DefaultPublicKey, data);
}
catch (Exception e)
{
throw e;
}
}
public static string EncryptByAES(string privateKey, string publicKey, string data)
{
try
{
return new AESEncryption().Encrypt(privateKey, publicKey, data);
}
catch (Exception e)
{
throw e;
}
}
public static string DecryptByAES(string data)
{
try
{
return new AESEncryption().Decrypt(Encryption.DefaultPrivateKey, Encryption.DefaultPublicKey, data);
}
catch (Exception e)
{
throw e;
}
}
public static string DecryptByAES(string privateKey, string publicKey, string data)
{
try
{
return new AESEncryption().Decrypt(privateKey, publicKey, data);
}
catch (Exception e)
{
throw e;
}
}
}
#endregion
//#region Mac Address
///// <summary>
///// Returns MAC Address from first Network Card in Computer
///// </summary>
///// <returns>MAC Address in string format</returns>
//public static string GetMacAddress()
//{
// string mcAddress = string.Empty;
// try
// {
// //Create out management class object using the Win32_NetworkAdapterConfiguration class to get the attributes af the network adapter
// ManagementClass mgmt = new ManagementClass("Win32_NetworkAdapterConfiguration");
// ManagementObjectCollection objCol = mgmt.GetInstances();
// foreach (ManagementObject obj in objCol)
// {
// if (mcAddress == String.Empty) // only return MAC Address from first card
// {
// //grab the value from the first network adapter we find you can change the string to an array and get all network adapters found as well
// if (Convert.ToBoolean(obj["IPEnabled"]) == true)
// {
// mcAddress = obj["MacAddress"].ToString();
// }
// }
// //dispose of our object
// obj.Dispose();
// }
// //replace the ":" with an empty space, this could also be removed if you wish
// mcAddress = mcAddress.Replace(":", "-");
// }
// catch
// {
// }
// return mcAddress;
//}
//#endregion
#region IP Address
static string getLocalIP()
{
string ipAddress = string.Empty;
try
{
IPAddress[] ipHost = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress item in ipHost)
{
if (item.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = item.ToString();
break;
}
}
if (string.IsNullOrEmpty(ipAddress) && ipHost.Length > 0)
ipAddress = ipHost[0].ToString();
}
catch
{
}
return ipAddress;
}
/// <summary>
/// For external address
/// </summary>
/// <returns>External IP address.</returns>
public static string GetIPAddress()
{
string ipAddress = string.Empty;
try
{
ipAddress = Global.GetIPAddress(false);
}
catch
{
}
return ipAddress;
}
/// <summary>
/// Find IP address of the machine
/// </summary>
/// <param name="localIP">True if want to find local IP.</param>
/// <returns>Return IP address. </returns>
public static string GetIPAddress(bool localIP)
{
string myIP = string.Empty;
try
{
myIP = getLocalIP();
string href = ""; //#### ConfigUtility.GetAppSettings("hrefIP");
if (!string.IsNullOrEmpty(href) && !localIP)
{
byte[] data = new WebClient().DownloadData(href);
string fIP = new System.Text.UTF8Encoding().GetString(data);
if (!string.IsNullOrEmpty(fIP))
myIP = fIP;
}
}
catch
{
}
return myIP;
}
#endregion
}
#endregion
}