using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Security.Cryptography;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Configuration;
using System.Drawing;
namespace ManagementSystem.Utility
{
public static class UtilityClass
{
#region 加解密相關
///
/// 進行DES加密
///
/// 要加密的字串
/// 金鑰,必須為8位
/// 以Base64格式返回的加密字串
public static string EncryptDES(string pToEncrypt, string sKey)
{
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Convert.ToBase64String(ms.ToArray());
ms.Close();
return str;
}
}
public static string DecryptDES(string pToDecrypt, string sKey)
{
try
{
//判斷是否為空值
if (pToDecrypt == "")
{
return "";
}
byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return str;
}
}
catch (Exception ex)
{
return "";
}
}
public static string EncryptDES(int pToEncrypt, string sKey)
{
return EncryptDES(pToEncrypt.ToString(), sKey);
}
#endregion
#region 取得系統參數資料
public static DataSet GetSystemArgument(string strSysArgumentClassID, string strLanguageID)
{
DataSet dsData = new DataSet();
try
{
string strCommand = string.Format("Select ArgumentID,ArgumentValue,LanguageID,OrderByValue From OTB_SYS_Arguments Where ArgumentClassID='{0}'", strSysArgumentClassID);
if (strLanguageID != "")
{
strCommand += string.Format(" And LanguageID = '{0}'", strLanguageID);
}
using (SqlConnection sqlConn = GetConn(MainForm.strAccountingBookID))
{
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(strCommand, sqlConn))
{
if (sqlConn.State == ConnectionState.Closed) //判斷連線狀態
{
sqlConn.Open();
}
sqlAdapter.Fill(dsData, "Arguments");
//增加空白選項
DataRow drData = dsData.Tables["Arguments"].NewRow();
drData["ArgumentID"] = " ";
drData["ArgumentValue"] = "請選擇";
drData["OrderByValue"] = 0;
dsData.Tables["Arguments"].Rows.Add(drData);
//資料進行排序
dsData.Tables["Arguments"].DefaultView.Sort = "OrderByValue ASC";
}
}
return dsData;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region 取得組織結構
public static DataSet GetOrgList()
{
DataSet dsData = new DataSet();
try
{
string strCommand = string.Format("Select OrganizationID,OrganizationName From OTB_SYS_Organization Where Effective='Y'");
using (SqlConnection sqlConn = GetConn(MainForm.strAccountingBookID))
{
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(strCommand, sqlConn))
{
if (sqlConn.State == ConnectionState.Closed) //判斷連線狀態
{
sqlConn.Open();
}
sqlAdapter.Fill(dsData, "Organizations");
//增加空白選項
DataRow drData = dsData.Tables["Organizations"].NewRow();
drData["OrganizationID"] = " ";
drData["OrganizationName"] = "請選擇";
dsData.Tables["Organizations"].Rows.Add(drData);
//資料進行排序
dsData.Tables["Organizations"].DefaultView.Sort = "OrganizationID ASC";
}
}
return dsData;
}
catch (Exception ex)
{
throw ex;
}
}
public static DataSet GetOrganization()
{
DataSet dsData = new DataSet();
try
{
string strCommand = string.Format("Select DepartmentID,DepartmentName,DepartmentShortName,ParentDepartmentID,LevelOfDepartment,OrderByValue From OTB_SYS_Departments Where Effective='Y'");
using (SqlConnection sqlConn = GetConn(MainForm.strAccountingBookID))
{
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(strCommand, sqlConn))
{
if (sqlConn.State == ConnectionState.Closed) //判斷連線狀態
{
sqlConn.Open();
}
sqlAdapter.Fill(dsData, "Departments");
//增加資料
foreach (DataRow drDatas in dsData.Tables["Departments"].Rows)
{
drDatas["DepartmentName"] = GetOrgTree(drDatas["DepartmentID"].ToString());
}
//增加空白選項
DataRow drData = dsData.Tables["Departments"].NewRow();
drData["DepartmentID"] = " ";
drData["DepartmentName"] = "請選擇";
drData["OrderByValue"] = 0;
dsData.Tables["Departments"].Rows.Add(drData);
//資料進行排序
dsData.Tables["Departments"].DefaultView.Sort = "LevelOfDepartment ASC, OrderByValue ASC";
}
}
return dsData;
}
catch (Exception ex)
{
throw ex;
}
}
public static string GetOrgTree(string strOrgID)
{
try
{
DataSet dsData = new DataSet();
string strCommand = string.Format("Select DepartmentName,DepartmentShortName,ParentDepartmentID From OTB_SYS_Departments Where DepartmentID = '{0}'", strOrgID);
using (SqlConnection sqlConn = GetConn(MainForm.strAccountingBookID))
{
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(strCommand, sqlConn))
{
if (sqlConn.State == ConnectionState.Closed) //判斷連線狀態
{
sqlConn.Open();
}
sqlAdapter.Fill(dsData, "Departments");
if (dsData.Tables["Departments"].Rows[0]["ParentDepartmentID"].ToString().Trim() == "")
{
return dsData.Tables["Departments"].Rows[0]["DepartmentName"].ToString().Trim();
}
else
{
return GetOrgTree(dsData.Tables["Departments"].Rows[0]["ParentDepartmentID"].ToString().Trim()) + "-" + dsData.Tables["Departments"].Rows[0]["DepartmentName"].ToString().Trim();
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region 取得指定Table資料
public static DataSet GetTable(string strTableName, string[] strColumnList , string strWhere, string strOrderBy)
{
DataSet dsData = new DataSet();
try
{
string strColumns = "";
foreach (string strColumn in strColumnList) //取得欄位陣列
{
if (strColumns != "")
{
strColumns += "," + strColumn.Trim();
}
else
{
strColumns = strColumn;
}
}
string strCommand = string.Format("Select {0} From {1} ",strColumns, strTableName);
if (strWhere != "") //設定過濾條件
{
strCommand += " Where " + strWhere;
}
if (strOrderBy != "") //取得排序欄位
{
strCommand += " Order By " + strOrderBy;
}
using (SqlConnection sqlConn = GetConn(MainForm.strAccountingBookID))
{
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(strCommand, sqlConn))
{
if (sqlConn.State == ConnectionState.Closed) //判斷連線狀態
{
sqlConn.Open();
}
sqlAdapter.Fill(dsData, "Result");
}
}
return dsData;
}
catch (Exception ex)
{
throw ex;
}
}
public static DataSet GetTable(string strTableName, string[] strColumnList, string strWhere)
{
return GetTable(strTableName, strColumnList, strWhere, "");
}
public static DataSet GetTable(string strTableName, string[] strColumnList)
{
return GetTable(strTableName, strColumnList,"","");
}
public static DataSet GetTable(string strTableName)
{
return GetTable(strTableName,new string[] {"*"}, "", "");
}
#endregion
#region SQL命令相關程式集
public static SqlConnection GetConn(string strOrg)
{
string strConn = "";
SqlConnection sqlConn = null;
switch(strOrg)
{
case "":
strConn = System.Configuration.ConfigurationManager.ConnectionStrings["OrigtekSQLConn"].ToString();
sqlConn = new SqlConnection(strConn);
break;
case "Origtek":
strConn = System.Configuration.ConfigurationManager.ConnectionStrings["OrigtekSQLConn"].ToString();
sqlConn = new SqlConnection(strConn);
break;
case "OrigtekEnergy":
strConn = System.Configuration.ConfigurationManager.ConnectionStrings["OEnergySQLConn"].ToString();
sqlConn = new SqlConnection(strConn);
break;
}
return sqlConn;
}
public static SqlConnection GetConn()
{
return GetConn("");
}
public static DataSet GetSQLResult(string strSQL)
{
DataSet dsData = new DataSet();
try
{
using (SqlConnection sqlConn = GetConn(MainForm.strAccountingBookID))
{
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(strSQL, sqlConn))
{
if (sqlConn.State == ConnectionState.Closed) //判斷連線狀態
{
sqlConn.Open();
}
sqlAdapter.Fill(dsData, "Result");
}
}
return dsData;
}
catch(Exception ex)
{
throw ex;
}
}
public static bool IsExist(string strSQL)
{
try
{
DataSet sdResult = GetSQLResult(strSQL);
DataTable dtResult = sdResult.Tables[0];
if (dtResult.Rows.Count > 0)
{ return true; }
else
{ return false; }
}
catch (Exception ex)
{
throw ex;
}
}
public static bool RunSQLNonReturn(string strSQL)
{
try
{
SqlConnection sqlConn = GetConn(MainForm.strAccountingBookID);
SqlCommand sqlCmd = new SqlCommand(strSQL, sqlConn);
if (sqlConn.State == ConnectionState.Closed) //判斷連線狀態
{
sqlConn.Open();
}
sqlCmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
return false;
}
}
public static string GetSQLCount(string strSQL)
{
string strCount = "";
DataSet dsTemp = GetSQLResult(strSQL);
strCount = dsTemp.Tables[0].Rows.Count.ToString();
//回傳查詢結果
if(strCount == "")
{ return "0"; }
else
{ return strCount; }
}
#endregion
#region 其它共用程式
public static bool IsNumber(string strSource)
{
float output;
return float.TryParse(strSource, out output);
} //確認是否為數字
public static bool IsDate(string strSource)
{
try
{
//System.Globalization.DateTimeFormatInfo dtInfo = new System.Globalization.DateTimeFormatInfo();
//dtInfo.FullDateTimePattern = "yyyy/MM/dd";
//DateTime dtOutput = DateTime.ParseExact(strSource, "F", dtInfo);
DateTime dtOutput;
if (DateTime.TryParse(strSource, out dtOutput))
{
return true;
}
else
{
return false;
}
}
catch(Exception ex)
{
return false;
}
}
public static string MarkNumber(double dbNumber,int intPoint) //將資料加上三位一撇
{
return string.Format("{0:N" + intPoint + "}", dbNumber);
}
public static string MarkNumber(int intNumber, int intPoint) //將資料加上三位一撇
{
return string.Format("{0:N" + intPoint + "}", intNumber);
}
public static string MarkNumber(string strNumber, int intPoint) //將資料加上三位一撇
{
if (strNumber.IndexOf("%") != -1)
{
return strNumber;
}
if (!string.IsNullOrEmpty(strNumber))
{
if (IsNumber(strNumber))
{
return MarkNumber(Convert.ToDouble(strNumber), intPoint);
}
}
return "";
}
public static string MarkNumber(double dbNumber) //將資料加上三位一撇
{
return string.Format("{0:N0}", dbNumber);
}
public static string MarkNumber(int intNumber) //將資料加上三位一撇
{
return string.Format("{0:N0}", intNumber);
}
public static string MarkNumber(string strNumber) //將資料加上三位一撇
{
if (!string.IsNullOrEmpty(strNumber))
{
if (strNumber.IndexOf("%") != -1)
{
return strNumber;
}
if (IsNumber(strNumber))
{
return MarkNumber(Math.Round(Convert.ToDouble(strNumber)));
}
}
return "";
}
public static DataTable GetAccountingSubjectByID(string strAccountingSubID, string strAccountingBookID)
{
try
{
DataTable dtTemp = new DataTable();
if (strAccountingSubID.Trim() != "")
{
//宣告物件
string strSQL = string.Format("Select AccountingSubID, AccountingClass, DCClass, AccountingSubName From OTB_FNC_AccountingSubjects Where AccountingSubID = '{0}' And AccountingBookID = '{1}'", strAccountingSubID, strAccountingBookID);
using (SqlConnection sqlConn = GetConn(MainForm.strAccountingBookID))
{
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter())
{
//添加參數
sqlAdapter.SelectCommand = new SqlCommand();
sqlAdapter.SelectCommand.Connection = sqlConn;
sqlAdapter.SelectCommand.CommandText = strSQL;
if (sqlConn.State == ConnectionState.Closed) //判斷連線狀態
{
sqlConn.Open();
}
//進行查詢
dtTemp = UtilityClass.GetSQLResult(strSQL).Tables["Result"];
}
}
}
return dtTemp;
}
catch (Exception ex)
{
ErrorHandler.WriteErrorLog("UtilityClass.cs", ex);
return null;
}
}
public static DataTable GetAccountingSubjectByName(string strAccountingSubName)
{
try
{
DataTable dtTemp = new DataTable();
if (strAccountingSubName.Trim() != "")
{
//宣告物件
string strSQL = string.Format("Select AccountingSubID, AccountingClass, DCClass, AccountingSubName From OTB_FNC_AccountingSubjects Where AccountingSubName = '{0}'", strAccountingSubName);
using (SqlConnection sqlConn = GetConn(MainForm.strAccountingBookID))
{
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter())
{
//添加參數
sqlAdapter.SelectCommand = new SqlCommand();
sqlAdapter.SelectCommand.Connection = sqlConn;
sqlAdapter.SelectCommand.CommandText = strSQL;
if (sqlConn.State == ConnectionState.Closed) //判斷連線狀態
{
sqlConn.Open();
}
//進行查詢
dtTemp = UtilityClass.GetSQLResult(strSQL).Tables["Result"];
}
}
}
return dtTemp;
}
catch (Exception ex)
{
ErrorHandler.WriteErrorLog("AccountingEntries.cs", ex);
return null;
}
}
public static string[] GetInsurance(string InsuranceAmount) //取得勞健保資料
{
string strSQL = "Select * From OTB_HR_Insurance Where InsuranceAmountStart <= " + InsuranceAmount + " And InsuranceAmountEnd > " + InsuranceAmount;
string[] intInsurance = new string[6];
DataSet dsData = new DataSet();
try
{
using (SqlConnection sqlConn = GetConn(MainForm.strAccountingBookID))
{
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(strSQL, sqlConn))
{
if (sqlConn.State == ConnectionState.Closed) //判斷連線狀態
{
sqlConn.Open();
}
sqlAdapter.Fill(dsData, "Result");
intInsurance[0] = dsData.Tables["Result"].Rows[0]["InsuranceLevel"].ToString(); //級距
intInsurance[1] = dsData.Tables["Result"].Rows[0]["C_LaborProtection"].ToString(); //公司提列勞保
intInsurance[2] = dsData.Tables["Result"].Rows[0]["S_LaborProtection"].ToString(); //自行提列勞保
intInsurance[3] = dsData.Tables["Result"].Rows[0]["C_HealthInsuranceAmount"].ToString(); //公司提列健保
intInsurance[4] = dsData.Tables["Result"].Rows[0]["S_HealthInsuranceAmount"].ToString(); //自行提列健保
intInsurance[5] = dsData.Tables["Result"].Rows[0]["RetirementAmount"].ToString(); //勞退金
}
}
return intInsurance;
}
catch (Exception ex)
{
return intInsurance;
}
}
public static string[] GetInsuranceByLevel(string InsuranceLevel) //取得勞健保資料
{
string strSQL = "Select * From OTB_HR_Insurance Where InsuranceLevel = " + InsuranceLevel;
string[] intInsurance = new string[6];
DataSet dsData = new DataSet();
try
{
using (SqlConnection sqlConn = GetConn(MainForm.strAccountingBookID))
{
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(strSQL, sqlConn))
{
if (sqlConn.State == ConnectionState.Closed) //判斷連線狀態
{
sqlConn.Open();
}
sqlAdapter.Fill(dsData, "Result");
intInsurance[0] = dsData.Tables["Result"].Rows[0]["InsuranceLevel"].ToString(); //級距
intInsurance[1] = dsData.Tables["Result"].Rows[0]["C_LaborProtection"].ToString(); //公司提列勞保
intInsurance[2] = dsData.Tables["Result"].Rows[0]["S_LaborProtection"].ToString(); //自行提列勞保
intInsurance[3] = dsData.Tables["Result"].Rows[0]["C_HealthInsuranceAmount"].ToString(); //公司提列健保
intInsurance[4] = dsData.Tables["Result"].Rows[0]["S_HealthInsuranceAmount"].ToString(); //自行提列健保
intInsurance[5] = dsData.Tables["Result"].Rows[0]["RetirementAmount"].ToString(); //勞退金
}
}
return intInsurance;
}
catch (Exception ex)
{
return intInsurance;
}
}
public static string[] GetAccountingYears(int intAmount) //取得會計年度選單
{
try
{
string[] strYears = new string[intAmount];
DateTime dtNow = DateTime.Now;
for (int intCount = 0; intCount < intAmount; intCount++)
{
strYears[intCount] = (dtNow.Year - intCount).ToString();
}
return strYears;
}
catch (Exception ex)
{
return null;
}
}
public static void CreateDir(string strDirPath) //建立資料夾
{
string[] strDir = strDirPath.Split('\\');
string strCreatePath = "";
foreach (string strPath in strDir)
{
if(strPath != "")
{
strCreatePath += strPath + "\\";
if (!Directory.Exists(strCreatePath))
{
Directory.CreateDirectory(strCreatePath);
}
}
}
}
public static void WriteFile(string strFilePath ,string strContent) //撰寫檔案文字內容
{
using (StreamWriter swFile = new StreamWriter(strFilePath, true))
{
swFile.WriteLine(strContent);
}
}
public static void WriteFile(string strFilePath, string[] strContent) //撰寫檔案文字內容
{
//判斷檔案是否存在
string[] strPathArray = strFilePath.Split('\\');
string strCHKPath = "";
for (int intPath = 0; intPath < strPathArray.Length - 1; intPath ++ )
{
strCHKPath += strPathArray[intPath] + "\\";
}
//檢查資料夾是否存在
if (!File.Exists(strCHKPath))
{
CreateDir(strCHKPath);
}
using (StreamWriter swFile = new StreamWriter(strFilePath, true))
{
foreach(string strContentText in strContent)
{
swFile.WriteLine(strContentText);
}
}
}
public static void SetGridColor(DataGridView dgvGrid) //處理欄位間隔顏色的改變
{
foreach (DataGridViewRow drColor in dgvGrid.Rows)
{
if (drColor.Index % 2 == 0)
{
drColor.DefaultCellStyle.BackColor = Color.LightGray;
}
else
{
drColor.DefaultCellStyle.BackColor = Color.White;
}
}
}
#endregion
#region 計算財務相關公式
#endregion
}
}