using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Globalization; using System.Data.SqlClient; using System.IO; using System.Data.OleDb; using HRM.BO; using Ease.Core.Model; using Ease.Core.DataAccess; using Ease.Core.Utility; using Microsoft.Data.SqlClient; namespace HRM.DA { #region AttnRawData Service [Serializable] public class AttnRawDataService : ServiceTemplate, IAttnRawDataService { #region Object Mapping private void MapObject(AttnRawData oAttnRawData, DataReader oReader) { oAttnRawData.CardID = oReader.GetInt32("CardID", 0); oAttnRawData.EmployeeID = oReader.GetInt32("EmployeeID", 0); oAttnRawData.CardNo = oReader.GetString("CardNo"); oAttnRawData.PunchTime = oReader.GetDateTime("PunchTime").Value; oAttnRawData.EntryMode = (EnumEntryMode)oReader.GetInt32("EntryMode").Value; oAttnRawData.DeviceIPAddress = oReader.GetString("DeviceIPAddress"); oAttnRawData.DeviceNo = oReader.GetString("DeviceNo"); } protected override T CreateObject(DataReader oReader) { AttnRawData oAttnRawData = new AttnRawData(); MapObject(oAttnRawData, oReader); return oAttnRawData as T; } #endregion #region Private Functions private DataTable GetDataFromDB(DateTime maxPunchTime) { DataTable dTable = new DataTable(); EnumAttendanceDB enumAttnDB = GetAttendanceDBType(); switch (enumAttnDB) { case EnumAttendanceDB.Access: dTable = GetDataFromAccessDB(maxPunchTime); break; case EnumAttendanceDB.Text: dTable = GetDataFromTextFile(maxPunchTime); break; case EnumAttendanceDB.SQLServer: case EnumAttendanceDB.Oracle: dTable = GetDataFromRelationalDB(maxPunchTime); break; case EnumAttendanceDB.None: default: throw new ServiceException("No Attendance Raw data source defined in config"); break; } return dTable; } public DataTable GetInOutData(DateTime startDate, DateTime endDate, int employeeID) { DataSet attenDataset = null; TransactionContext tc = null; try { tc = TransactionContext.Begin(); attenDataset = AttnRawDataDA.GetInOutData(tc, startDate, endDate, employeeID); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return attenDataset.Tables[0]; } private DataTable GetDataFromRelationalDB(DateTime maxPunchTime) { DataSet attenDataset = null; TransactionContext tc = null; try { ConnectionContext connContext = new ConnectionContext("serviceHandlerAttn"); tc = TransactionContext.Begin(true, connContext); attenDataset = AttnRawDataDA.GetDataFromClientSqlDB(tc, maxPunchTime); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return attenDataset.Tables[0]; } private DataTable GetDataFromAccessDB(DateTime maxPunchTime) { //string sourceFNHeadOffice = string.Empty; string sourceFNAnwarCement = string.Empty; string sourceFNAnwarIspat = string.Empty; string mPunchTime = string.Empty; string sql = string.Empty; string fileLocation = ""; string clause = string.Empty; var dTable = new DataTable(); fileLocation = "C:\\Local\\"; //Ease.Core.Utility.ConfigUtility.GetAppSettings("AttendanceDataLocation"); string password = ""; // Ease.Core.Utility.ConfigUtility.GetAppSettings("AttendanceDataPassword"); if (!string.IsNullOrEmpty(fileLocation)) { string connectionString = string.Empty; if (string.IsNullOrEmpty(password)) { connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};Persist Security Info=False;", fileLocation); } else { password = Ease.Core.Utility.Global.CipherFunctions.Decrypt("Cel.Admin", password); connectionString = String.Format( "Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};Jet OLEDB:Database Password={1};", fileLocation, password); } OleDbConnection connHO = new OleDbConnection(connectionString); //sql = String.Format("SELECT * FROM Employee_Attendance where PunchTime > '{0}'", maxPunchTime.ToString("dd MMM yyyy")); sql = String.Format( "select ui.BadgeNumber as EmployeeID,cio.CheckTime as PunchTime,0 as MachineNo,0 as EntryMode from UserInfo ui, CheckInOut cio where ui.UserID = cio.UserID and cio.CheckTime > #{0}#", maxPunchTime.ToString("dd MMM yyyy")); OleDbCommand cmdHO = new OleDbCommand(sql, connHO); connHO.Open(); using (DataTable dt = new DataTable()) { using (OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connHO)) { adapter.Fill(dt); dTable = dt; } } connHO.Close(); } return dTable; } private DataTable GetDataFromTextFile(DateTime maxPunchTime) { CultureInfo provider = CultureInfo.InvariantCulture; var dTable = new DataTable(); dTable.Columns.Add("EmployeeID", typeof(string)); dTable.Columns.Add("PunchTime", typeof(string)); dTable.Columns.Add("MachineNo", typeof(string)); dTable.Columns.Add("EntryMode", typeof(int)); int devciceNoStart = ConfigurationManager.GetIntValue("carddata", "devicenostart", EnumConfigurationType.Logic); int devciceNoEnd = ConfigurationManager.GetIntValue("carddata", "devicenoend", EnumConfigurationType.Logic); int devciceNoLength = devciceNoEnd - devciceNoStart + 1; string dateFormat = ConfigurationManager.GetStringValue("carddata", "dateformat", EnumConfigurationType.Logic); string timeFormat = ConfigurationManager.GetStringValue("carddata", "timeformat", EnumConfigurationType.Logic); int dateStart = ConfigurationManager.GetIntValue("carddata", "datestart", EnumConfigurationType.Logic); int dateEnd = ConfigurationManager.GetIntValue("carddata", "dateend", EnumConfigurationType.Logic); int dateLength = dateEnd - dateStart + 1; int timeStart = ConfigurationManager.GetIntValue("carddata", "timestart", EnumConfigurationType.Logic); int timeEnd = ConfigurationManager.GetIntValue("carddata", "timeend", EnumConfigurationType.Logic); int timeLength = timeEnd - timeStart + 1; int identifierStart = ConfigurationManager.GetIntValue("carddata", "identifierstart", EnumConfigurationType.Logic); int identifierEnd = ConfigurationManager.GetIntValue("carddata", "identifierend", EnumConfigurationType.Logic); int identifierLength = identifierEnd - identifierStart + 1; string fileLocation = ""; // Ease.Core.Utility.ConfigUtility.GetAppSettings("AttendanceDataLocation"); string[] files = Directory.GetFiles(fileLocation).Where(x => Path.GetExtension(x).ToLower() == ".txt") .ToArray(); StreamReader streamReader = null; foreach (var file in files) { using (streamReader = new StreamReader(file)) { var lineData = string.Empty; var lineNo = 1; DataRow dRow = null; lineData = streamReader.ReadLine(); while (lineData != null) { dRow = dTable.NewRow(); try { string devicedNo = Global.StringFuncions.Mid(lineData, devciceNoStart, devciceNoLength); DateTime date = DateTime.ParseExact( Global.StringFuncions.Mid(lineData, dateStart, dateLength), dateFormat, provider); DateTime time = DateTime.ParseExact( Global.StringFuncions.Mid(lineData, timeStart, timeLength), timeFormat, provider); string identifier = Global.StringFuncions.Mid(lineData, identifierStart, identifierLength); if (date < maxPunchTime.Date) { lineNo++; lineData = streamReader.ReadLine(); continue; } dRow["EmployeeID"] = identifier; dRow["PunchTime"] = string.Format("{0} {1}", date.ToString("dd MMM yyyy"), time.ToString("HH:mm:ss")); dRow["MachineNo"] = devicedNo; dRow["EntryMode"] = 0; } catch (Exception) { throw new Exception( string.Format("Invalid Data. File: {0}, Line Number: {1}", file, lineNo)); } lineNo++; lineData = streamReader.ReadLine(); dTable.Rows.Add(dRow); } } } return dTable; } #endregion #region Service implementation public EnumAttendanceDB GetAttendanceDBType() { EnumAttendanceDB enumAttnDB = EnumAttendanceDB.None; var attnCollectionTypeString = ""; // Ease.Core.Utility.ConfigUtility.GetAppSettings("AttendanceCollectionType"); try { enumAttnDB = (EnumAttendanceDB)Enum.Parse(typeof(EnumAttendanceDB), attnCollectionTypeString, true); if (!Enum.IsDefined(typeof(EnumAttendanceDB), enumAttnDB)) { enumAttnDB = EnumAttendanceDB.None; } } catch (Exception) { enumAttnDB = EnumAttendanceDB.None; } return enumAttnDB; } public List Get(DateTime fromDate, DateTime toDate, int payrollTypeID) { TransactionContext tc = null; try { tc = TransactionContext.Begin(); DataReader dr = new DataReader(AttnRawDataDA.Get(tc, fromDate, toDate, payrollTypeID)); var attnRawDatas = this.CreateObjects(dr); dr.Close(); tc.End(); return attnRawDatas; } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } } public List GetWithoutMobileRawData(DateTime fromDate, DateTime toDate, int payrollTypeID) { TransactionContext tc = null; try { tc = TransactionContext.Begin(); DataReader dr = new DataReader(AttnRawDataDA.GetWithoutMobileRawData(tc, fromDate, toDate, payrollTypeID)); var attnRawDatas = this.CreateObjects(dr); dr.Close(); tc.End(); return attnRawDatas; } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } } public List Get(DateTime fromDate, DateTime toDate, string empIDs, int payrollTypeID) { List attnRawDatas = new List(); TransactionContext tc = null; try { tc = TransactionContext.Begin(); DataReader dr = new DataReader(AttnRawDataDA.Get(tc, fromDate, toDate, empIDs, payrollTypeID)); attnRawDatas = this.CreateObjects(dr); dr.Close(); tc.End(); } catch (Exception e) { if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); } return attnRawDatas; } public void SaveAuto(List attnRawDatas) { TransactionContext tc = null; try { tc = TransactionContext.Begin(true); int nAttnRawDataID = tc.GenerateID("AttnRawData", "ATTNRAWDATAID"); if (attnRawDatas != null && attnRawDatas.Count > 0) { foreach (AttnRawData item in attnRawDatas) { item.PunchTime = DateTime.ParseExact(item.PunchTimeDateString.Trim(), "M/d/yyyy H:mm", null); } DateTime dMinValue = attnRawDatas.Min(x => x.PunchTime); string empIDs = attnRawDatas.Aggregate(new StringBuilder(), (sb, rData) => sb.AppendFormat("{0},", rData.EmployeeID), sb => sb.ToString().Trim(',')); AttnRawDataDA.Delete(tc, dMinValue, empIDs); DataTable _dtRawData = null; _dtRawData = new DataTable("AttnRawData"); _dtRawData.Columns.Add("ATTNRAWDATAID", typeof(int)); _dtRawData.Columns.Add("CARDID", typeof(int)); _dtRawData.Columns.Add("EMPLOYEEID", typeof(int)); _dtRawData.Columns.Add("CARDNO", typeof(string)); _dtRawData.Columns.Add("PUNCHTIME", typeof(DateTime)); _dtRawData.Columns.Add("ENTRYMODE", typeof(int)); _dtRawData.Columns.Add("DEVICEIPADDRESS", typeof(string)); _dtRawData.Columns.Add("DEVICENO", typeof(string)); _dtRawData.Columns.Add("PUNCHDATE", typeof(DateTime)); foreach (AttnRawData item in attnRawDatas) { _dtRawData.Rows.Add(nAttnRawDataID++, null, item.EmployeeID, item.CardNo.Trim(), item.PunchTime, (int)item.EntryMode, item.DeviceIPAddress, item.DeviceNo, item.PunchTime); } using (SqlBulkCopy bulkCopy = new SqlBulkCopy((SqlConnection)tc.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)tc.Transaction)) { bulkCopy.BulkCopyTimeout = 600; // in seconds bulkCopy.BatchSize = 5000; bulkCopy.ColumnMappings.Add("ATTNRAWDATAID", "ATTNRAWDATAID"); bulkCopy.ColumnMappings.Add("CARDID", "CARDID"); bulkCopy.ColumnMappings.Add("EMPLOYEEID", "EMPLOYEEID"); bulkCopy.ColumnMappings.Add("CARDNO", "CARDNO"); bulkCopy.ColumnMappings.Add("PUNCHTIME", "PUNCHTIME"); bulkCopy.ColumnMappings.Add("ENTRYMODE", "ENTRYMODE"); bulkCopy.ColumnMappings.Add("DEVICEIPADDRESS", "DEVICEIPADDRESS"); bulkCopy.ColumnMappings.Add("DEVICENO", "DEVICENO"); bulkCopy.ColumnMappings.Add("PUNCHDATE", "PUNCHDATE"); bulkCopy.DestinationTableName = "AttnRawData"; bulkCopy.WriteToServer(_dtRawData); } } tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } } #endregion public void RunScriptCollectRawData(DateTime attnDate) { TransactionContext tc = null; try { tc = TransactionContext.Begin(); tc.CommandTimeOut = 48000; tc.ExecuteNonQuery(CommandType.StoredProcedure, "spCollectRawDataByDate", attnDate.Date.AddDays(-1)); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } } } #endregion }