CEL_Payroll/Payroll.BO/Global/GlobalFunctions.cs

1385 lines
57 KiB
C#
Raw Normal View History

2024-09-17 14:30:13 +06:00
using System;
using System.Linq;
using System.Text;
using Ease.CoreV35.Model;
using System.Collections.Generic;
using Ease.CoreV35.Utility;
using System.IO;
using System.Drawing;
using System.Data;
using System.Reflection;
using ClosedXML.Excel;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Collections;
using DocumentFormat.OpenXml.Spreadsheet;
namespace Payroll.BO
{
//public class SearchParameter
//{
// public const
//}
public enum enumfractionCalculatinType
{
Monthly = 1,
Yearly = 2,
ThirtyDaysMonth = 3
}
[Serializable]
public class GlobalFunctions
{
private static int _roundofDigit;
private static string _workingPath;
public static bool bDataFound = false;
public static ID _setFormName = ID.FromInteger(0);
public static int SetProgressbarMaxValue = 0;
public static long TotalRocordCount = 0;
private GlobalFunctions()
{
_roundofDigit = -1;
}
#region Service Factory IGlobalFunctionService : IGlobalFunctionService
internal static IGlobalFunctionService Service
{
get { return Services.Factory.CreateService<IGlobalFunctionService>(typeof(IGlobalFunctionService)); }
}
#endregion
public static int RoundOfDigit
{
get
{
return _roundofDigit;
}
}
public static string workingPath
{
get
{
return _workingPath;
}
set
{
_workingPath = value;
}
}
public static string GetHardPasswordConditions()
{
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
StringBuilder sb3 = new StringBuilder();
HardPasswordSetup oHardPassword = new SystemInformation().GetPasswordSetup();
if (oHardPassword.MaxLength > 0)
sb.Append("Maximum Length= " + oHardPassword.MaxLength.ToString() + ",");
if (oHardPassword.MinLength > 0)
sb.Append("Minimum Length= " + oHardPassword.MinLength.ToString() + ",");
if (sb.ToString() != string.Empty)
sb3.Append("Password must have " + sb.ToString().Trim(','));
if (oHardPassword.ContainNumber)
sb2.Append("Number,");
if (oHardPassword.ContainLowercase)
sb2.Append("Lowercase,");
if (oHardPassword.ContainUppercase)
sb2.Append("Uppercase,");
if (oHardPassword.ContainSpecialCharacter)
sb2.Append("Special Character,");
if (oHardPassword.ContainLetter)
sb2.Append("Letter,");
if (sb.ToString() == string.Empty)
sb3.Append("Password must contains " + sb2.ToString().Trim(','));
else
sb3.Append(" and contains " + sb2.ToString().Trim(','));
if (sb3.ToString() == string.Empty)
sb3.Append("Username and Password cannot be same");
else
sb3.Append(" and Username and Password cannot be same");
return sb3.ToString();
}
public static bool IsHardPassword(string sUsername, string sPassword)
{
bool bValid = true;
HardPasswordSetup oHardPassword = new SystemInformation().GetPasswordSetup();
if (oHardPassword.ContainNumber)
{
if (!sPassword.ToCharArray().Any(char.IsDigit))
bValid = false;
}
if (oHardPassword.ContainLetter)
{
if (!sPassword.ToCharArray().Any(char.IsLetter))
bValid = false;
}
if (oHardPassword.ContainLowercase)
{
if (!sPassword.ToCharArray().Any(char.IsLower))
bValid = false;
}
if (oHardPassword.ContainUppercase)
{
if (!sPassword.ToCharArray().Any(char.IsUpper))
bValid = false;
}
if (oHardPassword.ContainSpecialCharacter)
{
Regex RgxUrl = new Regex("[^a-z0-9]");
if (!RgxUrl.IsMatch(sPassword))
bValid = false;
}
if (!oHardPassword.UserPasswordSame)
{
if (sUsername.ToLower().Trim() == sPassword.ToLower().Trim())
bValid = false;
}
if (oHardPassword.MaxLength > 0)
{
if (sPassword.Length > oHardPassword.MaxLength)
bValid = false;
}
if (oHardPassword.MinLength > 0)
{
if (sPassword.Length < oHardPassword.MinLength)
bValid = false;
}
return bValid;
}
public static void ExportToExcel(DataTable dt, string SFileName, string sSheetName)
{
string folderPath = SFileName;
using (ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook())
{
var ws = wb.Worksheets.Add(dt, sSheetName);
ws.Tables.FirstOrDefault().ShowAutoFilter = false;
wb.SaveAs(folderPath);
}
}
public static void ToCSV(DataTable dtDataTable, string strFilePath)
{
StreamWriter sw = new StreamWriter(strFilePath, false);
//headers
//for (int i = 0; i < dtDataTable.Columns.Count; i++)
//{
// sw.Write(dtDataTable.Columns[i]);
// if (i < dtDataTable.Columns.Count - 1)
// {
// sw.Write(",");
// }
//}
// sw.Write(sw.NewLine);
foreach (DataRow dr in dtDataTable.Rows)
{
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string value = dr[i].ToString();
if (value.Contains(','))
{
value = String.Format("\"{0}\"", value);
sw.Write(value);
}
else
{
sw.Write(dr[i].ToString());
}
}
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
public static string[] GetDFSL(DataTable dt, string nDepartmentID)
{
string sDes = "";
foreach (DataRow dr in dt.Rows)
{
if (dr[0].ToString() == nDepartmentID)
{
sDes = dr[3].ToString();
break;
}
}
string[] values = sDes.Split(',');
return values;
}
public static ID SetFormName
{
get
{
return _setFormName;
}
set
{
_setFormName = value;
}
}
private static int GetRoundOfDigit()
{
//int roundOfDigit = 0;
try
{
if (_roundofDigit != -1)
{
_roundofDigit = ConfigurationManager.GetIntValue("root", "roundofdegit", EnumConfigurationType.Logic);
if (_roundofDigit > 4 || _roundofDigit < 0)
{
_roundofDigit = -1;
throw new ServiceException("Round of digit not greater 4 digit. Location: "
+ "logic-Configuration; Node:Root, Child-Node:RoundOfDegit, Value:" + _roundofDigit.ToString());
}
}
}
catch (Exception ex)
{
throw new ServiceException(ex.InnerException.Message);
}
return _roundofDigit;
}
public static List<BudgetTempCollection> GetBudetPositions()
{
int nPos = 1;
List<BudgetTempCollection> oItems = new List<BudgetTempCollection>();
BudgetTempCollection item = new BudgetTempCollection();
item.enumBudgetCode = EnumBudgetCode.Basic_Salary;
item.position = nPos;
item.OriginID = 0;
nPos++;
oItems.Add(item);
ObjectsTemplate<AllowanceDeduction> oAllowances = AllowanceDeduction.GetAllowance(EnumStatus.Active);
foreach (AllowanceDeduction al in oAllowances)
{
item = new BudgetTempCollection();
item.enumBudgetCode = EnumBudgetCode.Allowance;
item.position = nPos;
item.OriginID = al.ID.Integer;
nPos++;
oItems.Add(item);
}
item = new BudgetTempCollection();
item.enumBudgetCode = EnumBudgetCode.PF;
item.position = nPos;
item.OriginID = 0;
nPos++;
oItems.Add(item);
ObjectsTemplate<Bonus> oBonus = Bonus.Get(EnumStatus.Active);
foreach (Bonus al in oBonus)
{
item = new BudgetTempCollection();
item.enumBudgetCode = EnumBudgetCode.Bonus;
item.position = nPos;
item.OriginID = al.ID.Integer;
nPos++;
oItems.Add(item);
}
ObjectsTemplate<OpiItem> oOPIs = OpiItem.Get();
foreach (OpiItem al in oOPIs)
{
item = new BudgetTempCollection();
item.enumBudgetCode = EnumBudgetCode.OPI;
item.position = nPos;
item.OriginID = al.ID.Integer;
nPos++;
oItems.Add(item);
}
ObjectsTemplate<AllowanceDeduction> oDeducts = AllowanceDeduction.GetDeduction(EnumStatus.Active);
foreach (AllowanceDeduction al in oDeducts)
{
item = new BudgetTempCollection();
item.enumBudgetCode = EnumBudgetCode.Deduction;
item.position = nPos;
item.OriginID = al.ID.Integer;
nPos++;
oItems.Add(item);
}
item = new BudgetTempCollection();
item.enumBudgetCode = EnumBudgetCode.IncomeTax;
item.position = nPos;
item.OriginID = 0;
nPos++;
oItems.Add(item);
item = new BudgetTempCollection();
item.enumBudgetCode = EnumBudgetCode.CTC;
item.position = nPos;
item.OriginID = 0;
nPos++;
oItems.Add(item);
return oItems;
}
public static string FindRCCode2(Department department, ObjectsTemplate<Department> oDepartments)
{
string rccode = "";
if (department != null && (department.Tier == 2||department.Tier == 1))
return rccode = department.RCCode;
else
department = oDepartments.Find(x => x.ID == department.ParentID);
if (department != null && (department.Tier == 2 || department.Tier == 1))
return rccode = department.RCCode;
else
department = oDepartments.Find(x => x.ID == department.ParentID);
if (department != null && (department.Tier == 2 || department.Tier == 1))
return rccode = department.RCCode;
else
department = oDepartments.Find(x => x.ID == department.ParentID);
if (department != null && (department.Tier == 2 || department.Tier == 1))
return rccode = department.RCCode;
else
department = oDepartments.Find(x => x.ID == department.ParentID);
if (department != null && (department.Tier == 2 || department.Tier == 1))
return rccode = department.RCCode;
else
department = oDepartments.Find(x => x.ID == department.ParentID);
if (department != null && (department.Tier == 2 || department.Tier == 1))
return rccode = department.RCCode;
return rccode;
}
public static string FindRCCode(Department department, ObjectsTemplate<Department> oDepartments)
{
string rccode = "";
if (department != null)
{
Department oItem = new Department();
if (department.Tier == 6)
{
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == department.ParentID; });
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
rccode = oItem == null ? "" : oItem.RCCode;
}
else if (department.Tier == 5)
{
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == department.ParentID; });
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
rccode =oItem==null?"": oItem.RCCode;
}
else if (department.Tier == 4)
{
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == department.ParentID; });
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
rccode = oItem == null ? "" : oItem.RCCode;
}
else if (department.Tier == 3)
{
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == department.ParentID; });
rccode = oItem == null ? "" : oItem.RCCode;
}
else if (department.Tier == 2)
{
rccode = department.RCCode;
}
}
return rccode;
}
public static string[] FindDivisionDeparmentUnit(Department department, ObjectsTemplate<Department> oDepartments)
{
string[] aDescription = new string[6];
Department oItem = new Department();
if (department != null)
{
if (department.Tier == 6)
{
aDescription[5] = department.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == department.ParentID; });
if (oItem != null)
{
aDescription[4] = oItem.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
if (oItem != null)
{
aDescription[3] = oItem.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
if (oItem != null)
{
aDescription[2] = oItem.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
if (oItem != null)
{
aDescription[1] = oItem.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
if (oItem != null)
{
aDescription[0] = oItem.Name;
}
//else
// aDescription[0] = aDescription[1];
}
}
}
}
}
else if (department.Tier == 5)
{
aDescription[5] = "";
aDescription[4] = department.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == department.ParentID; });
if (oItem != null)
{
aDescription[3] = oItem.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
if (oItem != null)
{
aDescription[2] = oItem.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
if (oItem != null)
{
aDescription[1] = oItem.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
if (oItem != null)
{
aDescription[0] = oItem.Name;
}
//else
// aDescription[0] = aDescription[1];
}
}
}
}
else if (department.Tier == 4)
{
aDescription[5] = "";
aDescription[4] = "";
aDescription[3] = department.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == department.ParentID; });
if (oItem != null)
{
aDescription[2] = oItem.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
if (oItem != null)
{
aDescription[1] = oItem.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
if (oItem != null)
{
aDescription[0] = oItem.Name;
}
//else
// aDescription[0] = aDescription[1];
}
}
}
else if (department.Tier == 3)
{
aDescription[5] = "";
aDescription[4] = "";
aDescription[3] = "";
aDescription[2] = department.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == department.ParentID; });
if (oItem != null)
{
aDescription[1] = oItem.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == oItem.ParentID; });
if (oItem != null)
{
aDescription[0] = oItem.Name;
}
//else
// aDescription[0] = aDescription[1];
}
}
else if (department.Tier == 2)
{
aDescription[5] = "";
aDescription[4] = "";
aDescription[3] = "";
aDescription[2] = "";
aDescription[1] = department.Name;
oItem = oDepartments.Find(delegate(Department dept) { return dept.ID == department.ParentID; });
if (oItem != null)
{
aDescription[0] = oItem.Name;
}
//else
// aDescription[0] = aDescription[1];
}
else if (department.Tier == 1)
{
aDescription[5] = "";
aDescription[4] = "";
aDescription[3] = "";
aDescription[2] = "";
aDescription[1] = "";
aDescription[0] = department.Name;
}
}
return aDescription;
}
public static string GetFriendlyName(EnumStatus eStatus)
{
string sName = "";
if (eStatus == EnumStatus.Active)
sName = "Active";
else if (eStatus == EnumStatus.Archieved)
sName = "Archieved";
else if (eStatus == EnumStatus.Inactive)
sName = "Inactive";
else if (eStatus == EnumStatus.Regardless)
sName = "Regardless";
else if (eStatus == EnumStatus.Role_Approved_and_Menu_Assigned)
sName = "Role Approved and Menu Assigned";
else if (eStatus == EnumStatus.Role_Approved_and_Menu_Not_Yet_Assigned)
sName = "Role Approved and Menu Not Yet Assigned";
else if (eStatus == EnumStatus.Role_Assigned_To_User_And_Waiting_For_Approve)
sName = "Role Assigned To User And Waiting For Approve";
else if (eStatus == EnumStatus.Role_Created_And_Waiting_For_Approve)
sName = "Role Created And Waiting For Approve";
else if (eStatus == EnumStatus.Role_Menu_Assigned_And_Waiting_For_Approve)
sName = "Role Menu Assigned And Waiting For Approve";
else if (eStatus == EnumStatus.Role_Menu_Modified_And_Waiting_For_Approve)
sName = "Role Menu Modified And Waiting For Approve";
else if (eStatus == EnumStatus.Role_Modified_And_Waiting_For_Approve)
sName = "Role Modified And Waiting For Approve";
else if (eStatus == EnumStatus.User_Active_And_Waiting_For_Approve)
sName = "User Active And Waiting For Approve";
else if (eStatus == EnumStatus.User_Created_And_Waiting_For_Approve || eStatus == EnumStatus.User_Modified_And_Waiting_For_Approve)
sName = "User Created And Waiting For Approve";
else if (eStatus == EnumStatus.User_Inactive_And_Waiting_For_Approve)
sName = "User Inactive And Waiting For Approve";
return sName;
}
public static bool IsSingleSingnOn()
{
try
{
bool bvalid = ConfigurationManager.GetBoolValue("weblogin", "singlesignon", EnumConfigurationType.Logic);
if (bvalid == true) return true;
else return false;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static double ConevrtToDlyRateofMonth(double nAmount, DateTime dMonthDate)
{
int nDays = Global.DateFunctions.DateDiff("d", GlobalFunctions.FirstDateOfMonth(dMonthDate),
GlobalFunctions.LastDateOfMonth(dMonthDate)) + 1;
return nAmount / nDays;
}
public static double ConevrtToDlyRate(double nAmount, DateTime dMonthDate)
{
bool isYearly = ConfigurationManager.GetBoolValue("root", "fractionalcalculationyearly", EnumConfigurationType.Logic);
if (isYearly == false)
{
return ConevrtToDlyRateofMonth(nAmount, dMonthDate);
}
else
{
return (nAmount * 12) / 365;
}
}
public static DateTime FirstDateOfMonth(DateTime date)
{
return Ease.CoreV35.Utility.Global.DateFunctions.FirstDateOfMonth(date);
}
public static DateTime LastDateOfMonth(DateTime date)
{
return Ease.CoreV35.Utility.Global.DateFunctions.LastDateOfMonth(date);
}
public static DateTime LastDateOfYear(DateTime date)
{
return new DateTime(date.Year, 12, 31);
}
public static DateTime FirstDateOfYear(DateTime date)
{
return new DateTime(date.Year, 1, 1);
}
public static double Round(double value)
{
double roundedValue = 0.00;
try
{
//roundedValue = Ease.CoreV35.Utility.Global.NumericFunctions.RoundOff(value, GetRoundOfDigit());
roundedValue = Math.Round(value, GetRoundOfDigit(), MidpointRounding.AwayFromZero);
}
catch (Exception ex)
{
throw new ServiceException(ex.InnerException.Message);
}
return roundedValue;
}
public static void ResetStatus()
{
Global.Status.ResetStatus();
}
public static void SetStatus(string statusString)
{
Global.Status.SetStatus(statusString);
}
public static void UpdateStatus(string statusString)
{
Global.Status.UpdateStatus(statusString);
}
public static string MillionToInWords(int no)
{
if (no == 0)
return "zero";
if (no < 0)
return "minus " + MillionToInWords(Math.Abs(no));
string stringValue = "";
if ((no / 1000000) > 0)
{
stringValue += MillionToInWords(no / 1000000) + " million ";
no %= 1000000;
}
if ((no / 1000) > 0)
{
stringValue += MillionToInWords(no / 1000) + " thousand ";
no %= 1000;
}
if ((no / 100) > 0)
{
stringValue += MillionToInWords(no / 100) + " hundred ";
no %= 100;
}
if (no > 0)
{
if (stringValue != "")
stringValue += "and ";
var units = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
var tens = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
if (no < 20)
stringValue += units[no];
else
{
stringValue += tens[no / 10];
if ((no % 10) > 0)
stringValue += "-" + units[no % 10];
}
}
return stringValue;
}
public static string TakaFormat(double value)
{
double roundedValue = 0.00;
string TakaFormat = "";
try
{
roundedValue = Math.Round(value, GetRoundOfDigit(), MidpointRounding.AwayFromZero);
//roundedValue = Ease.CoreV35.Utility.Global.NumericFunctions.RoundOff(value, GetRoundOfDigit());
//TakaFormat = Ease.CoreV35.Utility.Global.NumericFunctions.TakaFormat(roundedValue);
System.Globalization.CultureInfo vNewCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
//TakaFormat = string.Format(vNewCulture, "{0:N}",(int) roundedValue);
TakaFormat = ((int)roundedValue).ToString();
}
catch (Exception ex)
{
throw new ServiceException(ex.InnerException.Message);
}
return TakaFormat;
}
public static string TakaFormat(int value)
{
double roundedValue = 0.00;
string TakaFormat = "";
try
{
//roundedValue = Ease.CoreV35.Utility.Global.NumericFunctions.RoundOff(Convert.ToDouble(value), GetRoundOfDigit());
roundedValue = Math.Round(Convert.ToDouble(value), GetRoundOfDigit(), MidpointRounding.AwayFromZero);
TakaFormat = Ease.CoreV35.Utility.Global.NumericFunctions.TakaFormat(roundedValue);
}
catch (Exception ex)
{
throw new ServiceException(ex.InnerException.Message);
}
return TakaFormat;
}
public static DateTime GetOperationDate()
{
try
{
return Service.GetOperationDate();
}
catch (ServiceException e)
{
throw new Exception(e.Message, e);
}
}
public static DataSet GetSalarySummary(DateTime fromDate, DateTime toDate)
{
try
{
return Service.GetSalarySummary(fromDate, toDate);
}
catch (ServiceException e)
{
throw new Exception(e.Message, e);
}
}
public static enumfractionCalculatinType getFractionateCalType()
{
enumfractionCalculatinType type = enumfractionCalculatinType.Monthly;
string caltype = ConfigurationManager.GetStringValue("root", "monthfraction", EnumConfigurationType.Logic);
if (caltype.ToUpper() == "THIRTYDAYS")
type = enumfractionCalculatinType.ThirtyDaysMonth;
else if (caltype.ToUpper() == "YEARLY")
type = enumfractionCalculatinType.Yearly;
else
type = enumfractionCalculatinType.Monthly;
return type;
}
public static double GetFractinalOfMonth(DateTime dDate)
{
double WorkDays;
double TotalDays;
double nFraction = 1;
WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", dDate,
GlobalFunctions.LastDateOfMonth(dDate)) + 1;
// bool isYearly = ConfigurationManager.GetBoolValue("root", "fractionalcalculationyearly", EnumConfigurationType.Logic);
enumfractionCalculatinType ntype = getFractionateCalType();
switch (ntype)
{
case enumfractionCalculatinType.Monthly:
TotalDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
GlobalFunctions.FirstDateOfMonth(dDate), GlobalFunctions.LastDateOfMonth(dDate)) + 1;
nFraction = (WorkDays / TotalDays);
break;
case enumfractionCalculatinType.Yearly:
double yearlyFraction = 0.0328767123; // which mean 12/365
if (WorkDays == dDate.Day)
nFraction = 1;
//else if (dDate.Day ==1) // if date is first of month, fractionate should be 1
// nFraction = 1;
else
nFraction = yearlyFraction * WorkDays;
if (nFraction > 1) nFraction = 1; // monthly fraction can't greater 1,
break;
case enumfractionCalculatinType.ThirtyDaysMonth:
if (dDate == LastDateOfMonth(dDate))
return 1;
else
{
WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", dDate,
GlobalFunctions.LastDateOfMonth(dDate)) + 1;
int tempDaya = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", FirstDateOfMonth(dDate),
GlobalFunctions.LastDateOfMonth(dDate)) + 1;
if (tempDaya == 31) WorkDays = WorkDays - 1;
else if (tempDaya < 30)
if (tempDaya == 28) WorkDays = WorkDays + 2;
else WorkDays = WorkDays + 1;
TotalDays = 30;
// TotalDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
// GlobalFunctions.FirstDateOfMonth(dDate), GlobalFunctions.LastDateOfMonth(dDate));
nFraction = (WorkDays / TotalDays);
}
break;
default:
break;
}
return nFraction;
}
public static double GetFractinalOfTillDate(DateTime dDate)
{
double WorkDays;
double TotalDays;
double nFraction = 1;
WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
GlobalFunctions.FirstDateOfMonth(dDate), dDate) + 1;
enumfractionCalculatinType ntype = getFractionateCalType();
switch (ntype)
{
case enumfractionCalculatinType.Monthly:
TotalDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
GlobalFunctions.FirstDateOfMonth(dDate), GlobalFunctions.LastDateOfMonth(dDate)) + 1;
nFraction = (WorkDays / TotalDays);
break;
case enumfractionCalculatinType.Yearly:
double yearlyFraction = 0.0328767123; // which mean 12/365
if (WorkDays == dDate.Day)
nFraction = 1;
else
nFraction = yearlyFraction * WorkDays;
break;
case enumfractionCalculatinType.ThirtyDaysMonth:
if (dDate == FirstDateOfMonth(dDate))
return 1;
else
{
WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
GlobalFunctions.FirstDateOfMonth(dDate), dDate) + 1;
int tempDaya = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", FirstDateOfMonth(dDate),
GlobalFunctions.LastDateOfMonth(dDate)) + 1;
if (tempDaya == 31) WorkDays = WorkDays - 1;
else if (tempDaya < 30)
if (tempDaya == 28) WorkDays = WorkDays + 2;
else WorkDays = WorkDays + 1;
TotalDays = 30;
// TotalDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
// GlobalFunctions.FirstDateOfMonth(dDate), GlobalFunctions.LastDateOfMonth(dDate));
nFraction = (WorkDays / TotalDays);
}
break;
default:
break;
}
return nFraction;
}
public static double GetFraction(DateTime StartDate, DateTime EndDate)
{
double WorkDays;
double MonDays;
double TotFract;
double nFraction = 1;
TotFract = 0;
// bool isYearly = ConfigurationManager.GetBoolValue("root", "fractionalcalculationyearly", EnumConfigurationType.Logic);
//bool isYearly = ConfigurationManager.GetBoolValue("root", "fractionalcalculation", EnumConfigurationType.Logic);
enumfractionCalculatinType ntype = getFractionateCalType();
WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", StartDate,
GlobalFunctions.LastDateOfMonth(StartDate)) + 1;
switch (ntype)
{
case enumfractionCalculatinType.Monthly:
while (StartDate <= EndDate)
{
WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", StartDate,
GlobalFunctions.LastDateOfMonth(StartDate)) + 1;
MonDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
GlobalFunctions.FirstDateOfMonth(StartDate),
GlobalFunctions.LastDateOfMonth(StartDate)) + 1;
if (StartDate.Month == EndDate.Month && EndDate != GlobalFunctions.LastDateOfMonth(EndDate))
{
WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
GlobalFunctions.FirstDateOfMonth(EndDate), EndDate) + 1;
}
TotFract = TotFract + WorkDays / MonDays;
StartDate = GlobalFunctions.LastDateOfMonth(StartDate).AddDays(1);
}
nFraction = TotFract;
break;
case enumfractionCalculatinType.Yearly:
//0.032876712328767123287671232876712
//0.0328767123
//if (StartDate == GlobalFunctions.FirstDateOfMonth(StartDate) && EndDate == GlobalFunctions.LastDateOfMonth(EndDate))
//{
// WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("m", StartDate, EndDate) + 1;
// nFraction = WorkDays;
//}
//else
//{
// WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", StartDate, EndDate) + 1;
// double yearlyFraction = 0.0328767123; // which mean 12/365
// nFraction = yearlyFraction * WorkDays;
//}
nFraction = 0;
if (Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("m", GlobalFunctions.FirstDateOfMonth(StartDate),
GlobalFunctions.LastDateOfMonth(EndDate)) > 2)
{
nFraction = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("m", GlobalFunctions.FirstDateOfMonth(StartDate.AddMonths(1)),
GlobalFunctions.LastDateOfMonth(EndDate.AddMonths(-1)));
nFraction = nFraction + (Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", StartDate,
GlobalFunctions.LastDateOfMonth(StartDate)) + 1) * 0.0328767123;
nFraction = nFraction + (Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", GlobalFunctions.FirstDateOfMonth(EndDate),
EndDate) + 1) * 0.0328767123;
}
else
{
if (StartDate.Month == EndDate.Month && StartDate.Year == EndDate.Year) // if cross two month
{
if (StartDate == FirstDateOfMonth(StartDate) && EndDate == LastDateOfMonth(EndDate))
nFraction = 1;
else
nFraction = nFraction + (Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", StartDate,
EndDate) + 1) * 0.0328767123;
}
else
{
if (StartDate == FirstDateOfMonth(StartDate) && EndDate == LastDateOfMonth(EndDate))
nFraction = 1;
else
nFraction = nFraction + (Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", StartDate,
GlobalFunctions.LastDateOfMonth(StartDate)) + 1) * 0.0328767123;
if (EndDate == LastDateOfMonth(EndDate))
nFraction = nFraction + 1;
else nFraction = nFraction + (Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", GlobalFunctions.FirstDateOfMonth(EndDate),
EndDate) + 1) * 0.0328767123;
}
}
//while (StartDate <= EndDate)
//{
// if (StartDate.Day != 1 )
// {
// nFraction = nFraction + ((double)(Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
// GlobalFunctions.FirstDateOfMonth(EndDate), EndDate) + 1)) * 0.0328767123;
// }
// WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", StartDate,
// GlobalFunctions.LastDateOfMonth(StartDate)) + 1;
// MonDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
// GlobalFunctions.FirstDateOfMonth(StartDate),
// GlobalFunctions.LastDateOfMonth(StartDate)) + 1;
// if (StartDate.Month == EndDate.Month && EndDate != GlobalFunctions.LastDateOfMonth(EndDate))
// {
// nFraction = nFraction + ((double) (Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
// GlobalFunctions.FirstDateOfMonth(EndDate), EndDate) + 1)) * 0.0328767123;
// }
// TotFract = TotFract + WorkDays / MonDays;
// StartDate = GlobalFunctions.LastDateOfMonth(StartDate).AddDays(1);
//}
break;
case enumfractionCalculatinType.ThirtyDaysMonth:
WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", StartDate,
GlobalFunctions.LastDateOfMonth(StartDate)) + 1;
while (StartDate <= EndDate)
{
WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", StartDate,
GlobalFunctions.LastDateOfMonth(StartDate)) + 1;
MonDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
GlobalFunctions.FirstDateOfMonth(StartDate), GlobalFunctions.LastDateOfMonth(StartDate)) + 1;
int tempDaya = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d", FirstDateOfMonth(StartDate),
GlobalFunctions.LastDateOfMonth(StartDate)) + 1;
if (tempDaya == 31) WorkDays = WorkDays - 1;
else if (tempDaya < 30)
if (tempDaya == 28) WorkDays = WorkDays + 2;
else WorkDays = WorkDays + 1;
MonDays = 30;
if (StartDate.Month == EndDate.Month && EndDate != GlobalFunctions.LastDateOfMonth(EndDate))
{
WorkDays = Ease.CoreV35.Utility.Global.DateFunctions.DateDiff("d",
GlobalFunctions.FirstDateOfMonth(EndDate), EndDate) + 1;
MonDays = 30;
}
TotFract = TotFract + WorkDays / MonDays;
StartDate = GlobalFunctions.LastDateOfMonth(StartDate).AddDays(1);
}
nFraction = TotFract;
break;
default:
break;
}
return nFraction;
}
//return Total Hour and Minutes In string Format(Hour.Minutes)
public static string GetHourMinutes(List<String> hours)
{
string HoursMinutes = string.Empty;
double hour = 0;
double minutes = 0;
foreach (String hr in hours)
{
//string[] x = hr.ToString("f").Split('.');
//string xx = hr.ToString();
hour = hour + Convert.ToDouble(hr.Split(':')[0]);
minutes = minutes + Convert.ToDouble(hr.Split(':')[1]);
}
if (minutes > 60)
{
int hr = Convert.ToInt32(minutes) / 60;
hour = hour + Convert.ToDouble(hr);
minutes = minutes % 60;
}
return HoursMinutes = Convert.ToString(hour) + ":" + minutes.ToString("00");
}
public static string SaveDirectoryImages(string sDirectoryPath, bool needEmployeeCheck, EnumPhotoType ePhotoType)
{
string sMsg = "";
ObjectsTemplate<Employee> oEmployees = new ObjectsTemplate<Employee>();
int nFolderLevel = 0;
string sFolderLevel = ConfigurationManager.GetStringValue("root", "folderlevel", EnumConfigurationType.Logic);
if (sFolderLevel != null)
nFolderLevel = Convert.ToInt16(sFolderLevel);
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
int nCount = 0;
DirectoryInfo di = new DirectoryInfo(sDirectoryPath);
FileInfo[] smFiles = di.GetFiles();
if (needEmployeeCheck)
{
oEmployees = Employee.GetAllEmps();
foreach (FileInfo fi in smFiles)
{
Employee oEmp = oEmployees.Find(delegate(Employee em) { return em.EmployeeNo == Path.GetFileNameWithoutExtension(fi.Name); });
if (oEmp == null)
{
sb.AppendLine("\t" + Path.GetFileNameWithoutExtension(fi.Name));
}
}
if (sb.ToString() != "")
sMsg += "The following employee not found\n-----------------------------------------------------------------------------------------------------------------------------------\n\n" + sb.ToString();
}
if (sMsg == "")
{
foreach (FileInfo fi in smFiles)
{
if (nFolderLevel > Path.GetFileNameWithoutExtension(fi.Name).Length)
{
sb2.AppendLine("\t" + "File Name= " + fi.Name + " Length= " + Path.GetFileNameWithoutExtension(fi.Name).Length.ToString());
continue;
}
if (fi.Extension.ToLower() == ".jpg" ||
fi.Extension.ToLower() == ".jpeg" ||
fi.Extension.ToLower() == ".png" ||
fi.Extension.ToLower() == ".gif" ||
fi.Extension.ToLower() == ".tif" ||
fi.Extension.ToLower() == ".tiff" ||
fi.Extension.ToLower() == ".bmp")
{
SaveImage(fi.FullName, EnumPhotoType.EmployeePicture);
}
}
if (sb2.ToString() != "")
{
if (sb2.ToString() != "")
sMsg += "\n\n Invalid Image Length. Original Folder Level Length= " + nFolderLevel.ToString() + "\n-----------------------------------------------------------------------------------------------------------------------------------\n\n" + sb2.ToString();
}
}
return sMsg;
}
//catch (Exception exp)
//{
// MessageBox.Show(exp.Message, "Upload Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
//}
public static void SaveImage(string sImageLocation, EnumPhotoType ePhotoType)
{
int nFolderLevel = 0;
string sFolderLevel = ConfigurationManager.GetStringValue("root", "folderlevel", EnumConfigurationType.Logic);
if (sFolderLevel != null && sFolderLevel != "")
nFolderLevel = Convert.ToInt16(sFolderLevel);
FileInfo fInfo = new FileInfo(sImageLocation.Trim());
string sImageName = fInfo.Name;
List<PhotoPath> oPhotoPaths = PhotoPath.Get();
if (oPhotoPaths.Count == 0)
throw new Exception("Photo path is not defined.");
string sRootPath = "";
switch (ePhotoType)
{
case EnumPhotoType.EmployeePicture:
sRootPath = oPhotoPaths[0].EmployeePhoto;
break;
case EnumPhotoType.EmployeeSignature:
sRootPath = oPhotoPaths[0].EmployeeSignature;
break;
case EnumPhotoType.NomineePicture:
sRootPath = oPhotoPaths[0].NomineePhoto;
break;
case EnumPhotoType.NomineeSignature:
sRootPath = oPhotoPaths[0].NomineeSignature;
break;
case EnumPhotoType.HospitalizationPicture:
sRootPath = oPhotoPaths[0].HospitalizationPhoto;
break;
}
string sSubFolderName = sRootPath;
if (nFolderLevel == 0)
{
if (sImageLocation.Trim() != (sSubFolderName + "\\" + sImageName).Trim())
{
bool exists = System.IO.Directory.Exists(sSubFolderName);
if (!exists)
System.IO.Directory.CreateDirectory(sSubFolderName);
File.Copy(sImageLocation, sSubFolderName + "\\" + sImageName, true);
}
return;
}
string sFileNameUptoLevel = sImageName.Substring(0, nFolderLevel);
char[] sFileNameArray = sFileNameUptoLevel.ToCharArray();
foreach (char cChar in sFileNameArray)
{
if (cChar == '.')
continue;
sSubFolderName += "\\" + cChar;
bool exists = System.IO.Directory.Exists(sSubFolderName);
if (!exists)
System.IO.Directory.CreateDirectory(sSubFolderName);
}
if (fInfo.IsReadOnly)
fInfo.IsReadOnly = false;
if (sImageLocation.Trim() != (sSubFolderName + "\\" + sImageName).Trim())
File.Copy(sImageLocation, sSubFolderName + "\\" + sImageName, true);
}
public static string GetImage(string sFilename, EnumPhotoType ePhotoType)
{
if (sFilename == "")
throw new Exception("Invalid file name."); ;
string sFilePath = "";
int nFolderLevel = 0;
string sFolderLevel = ConfigurationManager.GetStringValue("root", "folderlevel", EnumConfigurationType.Logic);
if (sFolderLevel != null && sFolderLevel != "")
nFolderLevel = Convert.ToInt16(sFolderLevel);
//else
// throw new Exception("Folder level is not defined in config file.");
List<PhotoPath> oPhotoPaths = PhotoPath.Get();
if (oPhotoPaths.Count == 0)
throw new Exception("Photo path is not defined.");
string sRootPath = "";
switch (ePhotoType)
{
case EnumPhotoType.EmployeePicture:
sRootPath = oPhotoPaths[0].EmployeePhoto;
break;
case EnumPhotoType.EmployeeSignature:
sRootPath = oPhotoPaths[0].EmployeeSignature;
break;
case EnumPhotoType.NomineePicture:
sRootPath = oPhotoPaths[0].NomineePhoto;
break;
case EnumPhotoType.NomineeSignature:
sRootPath = oPhotoPaths[0].NomineeSignature;
break;
case EnumPhotoType.HospitalizationPicture:
sRootPath = oPhotoPaths[0].HospitalizationPhoto;
break;
}
string sSubFolderName = sRootPath;
string sFileNameUptoLevel = sFilename.Substring(0, nFolderLevel);
char[] sFileNameArray = sFileNameUptoLevel.ToCharArray();
foreach (char cChar in sFileNameArray)
{
if (cChar == '.')
continue;
sSubFolderName += "\\" + cChar;
}
DirectoryInfo di = new DirectoryInfo(sSubFolderName);
FileInfo[] smFiles = di.GetFiles();
foreach (FileInfo fi in smFiles)
{
if (fi.Name == sFilename)
{
sFilePath = fi.FullName;
break;
}
}
return sFilePath;
}
public static void BackupDatabase(string sPath)
{
try
{
GlobalFunctions.Service.BackupDatabase(sPath);
}
catch (Exception ex)
{
throw ex;
}
}
}
public static class GlobalExtensions
{
public static string CommaSeparatedIDs<T>(this ObjectsTemplate<T> objCollections) where T : ObjectTemplate
{
return objCollections.Aggregate(new StringBuilder(), (acc, x) => acc.Append(x.ID.Integer + ","),
acc => acc.ToString().Trim(','));
}
public static ObjectsTemplate<T> ToObjectsTemplate<T>(this IEnumerable<T> objCollections) where T : ObjectTemplate
{
ObjectsTemplate<T> objects = new ObjectsTemplate<T>();
foreach (var item in objCollections)
{
objects.Add(item);
}
return objects;
}
public static DateTime RemoveSecondsAndMiliseconds(this DateTime dt)
{
return dt.AddSeconds(-dt.Second).AddMilliseconds(-dt.Millisecond);
}
public static DateTime FirstDateOfMonth(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, 1);
}
public static DateTime LastDateOfMonth(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, 1).AddMonths(1).AddDays(-1);
}
public static int TotalDaysInMonth(this DateTime dt)
{
return (int)(dt.LastDateOfMonth().Subtract(dt.FirstDateOfMonth()).TotalDays + 1);
}
public static string ToColorCode(this System.Drawing.Color clr)
{
return System.Drawing.ColorTranslator.ToHtml(clr);
}
public static System.Drawing.Color ColorCodeToColor(this string hex)
{
try
{
System.Drawing.Color clr = System.Drawing.ColorTranslator.FromHtml(hex);
return clr;
}
catch (Exception gEx)
{
if (gEx.InnerException != null && gEx.InnerException is FormatException)
{
throw new Exception("ColorCode String could not be converted to color\n\r This may happen due to invalid HTML Color code or Hex code", gEx.InnerException);
}
throw new Exception("An Error Occurred", gEx);
}
}
public static DataTable ToDataTable<TSource>(this IList<TSource> data)
{
DataTable dataTable = new DataTable(typeof(TSource).Name);
PropertyInfo[] props = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ??
prop.PropertyType);
}
foreach (TSource item in data)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
}
public class ItemComparer : IComparer
{
public int Column { get; set; }
public SortOrder Order { get; set; }
public ItemComparer(int colIndex)
{
Column = colIndex;
Order = SortOrder.None;
}
public int Compare(object a, object b)
{
int result;
ListViewItem itemA = a as ListViewItem;
ListViewItem itemB = b as ListViewItem;
result = String.Compare(itemA.SubItems[Column].Text, itemB.SubItems[Column].Text);
if (Order == SortOrder.Descending)
{
result *= -1;
}
else
{
return -1;
}
return result;
}
}
public class CustomComparer : IComparer<string>
{
public int Compare(string x, string y)
{
var regex = new Regex("^(d+)");
// run the regex on both strings
var xRegexResult = regex.Match(x);
var yRegexResult = regex.Match(y);
// check if they are both numbers
if (xRegexResult.Success && yRegexResult.Success)
{
return int.Parse(xRegexResult.Groups[1].Value).CompareTo(int.Parse(yRegexResult.Groups[1].Value));
}
// otherwise return as string comparison
return x.CompareTo(y);
}
}
#region Interface IThisSystemService
public interface IGlobalFunctionService
{
DateTime GetOperationDate();
void BackupDatabase(string sPath);
DataSet GetSalarySummary(DateTime fromDate, DateTime toDate);
}
#endregion
}