using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using UtopiaAttService; namespace FaceTransfer { public partial class Form1 : Form { public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass(); private bool bIsConnected = false;//the boolean value identifies whether the device is connected public static string filePath = "credentials.txt"; private CheckBox headerCheckBox; private CheckBox headerCheckBox2; private CheckBox headerCheckBox3; string machineid1From; string machineid2To; private int count = 0; int totalrecord = 0; static string devInfo2; static string devInfo; static string machineid2; static string timePart; static string datePart; bool checkadmin = false; string machineType; static ConnectionClass ObjConnectionClass = new ConnectionClass(); static MachineConnectivity machineConnectivity = new MachineConnectivity(); RegisteredUsers RegisteredUsers = new RegisteredUsers(); AttendanceMachineDAO attendanceMachineDAO = new AttendanceMachineDAO(); static MySqlConnection connection; private AttendanceMachine Machine; private BackgroundWorker backgroundWorker; StringBuilder responseStringBuilder = new StringBuilder(); List MachineEmployeeList = new List(); CallBack myCallBack = new CallBack(machineConnectivity.BeCalled); List selectedValues = new List(); public Form1() { InitializeComponent(); SetGridView1(); SetGridView2(); SetGridView3(); SetBackgroundWorker(); //addColumnMachineGrid(); dateTimePicker1.Format = DateTimePickerFormat.Custom; dateTimePicker1.CustomFormat = "yyyy-MM-dd"; // bindDropDownMachineIp(); } private void Form1_Load(object sender, EventArgs e) { // Enable auto-scrolling for the form this.AutoScroll = true; this.HorizontalScroll.Enabled = false; this.VerticalScroll.Enabled = false; } private void addColumnMachineGrid() { DataGridViewTextBoxColumn idColumn = new DataGridViewTextBoxColumn(); idColumn.HeaderText = "Employee ID"; // Set the header text for the column // Add the column to the DataGridView DataGvMachine.Columns.Add(idColumn); } private void SetBackgroundWorker() { backgroundWorker = new BackgroundWorker(); backgroundWorker.WorkerReportsProgress = true; backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundWorker_DoWork); backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted); backgroundWorker.ProgressChanged += Bg_ProgressChanged; } private void Bg_ProgressChanged(object sender, ProgressChangedEventArgs e) { if (backgroundWorker.CancellationPending) { // Handle the progress update only if the background worker is not canceled return; } if (e.ProgressPercentage == 0) { UpdateUITask(machineid1From, machineid2To); } if (e.ProgressPercentage == 1) { lblTotalEmp.Text = "Total emp : " + e.UserState.ToString(); } if (e.ProgressPercentage == 2) { lblResult.Text = "Emp: " + e.UserState + " ---> transferred"; } if (e.ProgressPercentage == 3) { lblResult.Text = "Emp: " + e.UserState + " ---> transferred"; } } private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { } private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { if (backgroundWorker.CancellationPending) { e.Cancel = true; return; } RunFaceTransfer(); } /// ////////////////////////////////////--------------- BACKGROUND WORKER COMPLETE --------------------///////////////////////// private void btn_sync_Click(object sender, EventArgs e) { if (dateTimePicker1.Text.Length > 0 && cb_machineFrom.SelectedIndex > 0) { List response = syncAttendance(); if (response.Count != 0 && !response[0].Contains("not connected")) { MessageBox.Show("Completed"); } else { MessageBox.Show("Sync not completed"); } } else { MessageBox.Show("Please provide proper data"); } } public List syncAttendance() { List responses = new List(); connection = ObjConnectionClass.Connection(); if (ObjConnectionClass.OpenConnection() == true) { AttendanceMachineDAO attendanceMachineDAO = new AttendanceMachineDAO(); string machineIp = cb_machineFrom.SelectedValue.ToString(); List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", machineIp); foreach (var machine in machines) { responses.Add(PostAttendance(machine)); } } ObjConnectionClass.CloseConnection(); return responses; } public string PostAttendance(AttendanceMachine machine) { string response = ""; DateTime now = DateTime.Now.AddMinutes(-5); string devInfo = machine.GetDeviceInfo(); //string str4 = "GetRecord(start_time=\"" + machine.LastSyncDate.ToString("yyyy-MM-dd HH:mm:ss") + "\")"; string date = dateTimePicker1.Text.ToString(); date = date + " 00:00:00"; string str4 = "GetRecord(start_time=\"" + date + "\")"; string str5 = ""; uint num2 = 0; if (machineConnectivity.ExecuteCommad(devInfo, devInfo.Length, str4, str4.Length, ref str5, ref num2, myCallBack) != 0) { Console.WriteLine("Not Connected"); response = machine.MachineId + " is not connected !"; } else { Console.WriteLine("Connected"); // response = machine.MachineId + " has " + GetLoopCnt(str5) + " records !"; Console.WriteLine(response); machine.LastSyncDate = now; SaveRows(str5, machine); } return response; } public void SaveRows(string response, AttendanceMachine machine) { AttendanceMachineDAO attendanceMachineDAO = new AttendanceMachineDAO(); AttendanceDAO attendanceDAO = new AttendanceDAO(); string[] allObj = response.Split(new string[] { "time" }, StringSplitOptions.None); totalrecord = GetTotal(allObj[0]); // Set ProgressBar properties lb_total.Text = "Total 0/" + totalrecord + ""; progressBar1.Minimum = 0; progressBar1.Maximum = totalrecord; int count = 0; for (int i = 0; i < allObj.Length; i++) { string s = allObj[i]; if (!s.Contains("Return")) { string[] objDetail = s.Split(new string[] { "\"" }, StringSplitOptions.None); Attendance log = new Attendance(objDetail[3], Convert.ToDateTime(objDetail[1]), false, machine.MachineId, "1", machine.MachineIp, Convert.ToDateTime(objDetail[1])); count++; lb_total.Text = "Total " + count + "/" + totalrecord + ""; Console.WriteLine("{Total " + count + " / " + totalrecord + " }"); attendanceDAO.Add(log, connection); progressBar1.Value = count; } } } public int GetTotal(string str5String) { // Regular expression pattern to match "total" attribute string pattern = @"total=""(\d+)"""; // Use Regex.Match to find the match in the str5String Match match = Regex.Match(str5String, pattern); if (match.Success) { // Extract the "total" value from the match totalrecord = Convert.ToInt32(match.Groups[1].Value); } return totalrecord; } /// ////////////////////////////////////--------------- SYNC ATTENDANCE COMPLETE --------------------///////////////////////// private void UpdateUITask(string machineid, string machineid2) { // Use Invoke to safely update the UI controls from the main UI thread lblFrom.Text = "From - " + machineid.ToLower(); lblTo.Text = "To - " + machineid2.ToLower(); } int port; int Tomachineid; public void RunFaceTransferNedoToZkteco() { string fromip = cb_from.SelectedValue.ToString(); string Toip = cb_to.SelectedValue.ToString(); ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; List responses = new List(); // Initialize(); connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { AttendanceMachineDAO attendanceMachineDAO = new AttendanceMachineDAO(); //List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", fromip); //foreach (var machine in machines) //{ // machineid1From = machine.MachineId; List machineFrom = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", fromip); foreach (var machine in machineFrom) { //devInfo2 = GetDeviceInfo(machine.MachineIp, machine.PortNumber); List machinTo = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", Toip); foreach (var machineTo in machinTo) { port = machineTo.PortNumber; int.TryParse(machineTo.MachineId, out Tomachineid); } List selectedValues = new List(); // Loop through each row in the DataGridView foreach (DataGridViewRow row in gv.Rows) { // Check if the CheckBox in the first column is checked for the current row DataGridViewCheckBoxCell checkBoxCell = row.Cells["checkBoxColumn"] as DataGridViewCheckBoxCell; if (checkBoxCell.Value != null && (bool)checkBoxCell.Value) { // If the CheckBox is checked, get the value of the "AcNo" column (Employee ID) string employeeId = row.Cells["AcNo"].Value.ToString(); selectedValues.Add(employeeId); } } // Now, the selectedValues list contains the Employee IDs of the selected rows // You can process this list as needed foreach (string employeeId in selectedValues) { Console.WriteLine("Selected Employee ID: " + employeeId); responses.AddRange(get_set_EmpFaceTemplateZkteco(employeeId, fromip, Convert.ToInt32(machine.MachineId), Toip, Tomachineid, port)); } if (selectedValues.Count == 0) { get_set_EmpFaceTemplateZkteco(employeeId, fromip, Convert.ToInt32(machine.MachineId), Toip, Tomachineid, port); //MessageBox.Show("Completed"); } } ObjConnectionClass.CloseConnection(); MessageBox.Show("Completed"); } btnReset_Click(null, null); } public void RunFaceTransfer() { string fromip = cb_fromMachine.SelectedValue.ToString(); string Toip = cb_ToMachine.SelectedValue.ToString(); ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; List responses = new List(); // Initialize(); connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { AttendanceMachineDAO attendanceMachineDAO = new AttendanceMachineDAO(); //List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", fromip); //foreach (var machine in machines) //{ // machineid1From = machine.MachineId; List machines2 = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", Toip); foreach (var machine2 in machines2) { devInfo2 = GetDeviceInfo(Toip, machine2.PortNumber); machineid2 = machine2.MachineId; machineid2To = machineid2; //backgroundWorker.ReportProgress(0); // } List selectedValues = new List(); // Loop through each row in the DataGridView foreach (DataGridViewRow row in GvEmpData.Rows) { // Check if the CheckBox in the first column is checked for the current row DataGridViewCheckBoxCell checkBoxCell = row.Cells["checkBoxColumn"] as DataGridViewCheckBoxCell; if (checkBoxCell.Value != null && (bool)checkBoxCell.Value) { // If the CheckBox is checked, get the value of the "AcNo" column (Employee ID) string employeeId = row.Cells["AcNo"].Value.ToString(); selectedValues.Add(employeeId); } } // Now, the selectedValues list contains the Employee IDs of the selected rows // You can process this list as needed foreach (string employeeId in selectedValues) { Console.WriteLine("Selected Employee ID: " + employeeId); getEmpFaceTemplate(employeeId, Machine.MachineIp, Machine.PortNumber, Machine.MachineId, Toip, devInfo2, machineid2); } } MessageBox.Show("Completed"); ObjConnectionClass.CloseConnection(); } btnReset_Click(null, null); } public void getEmpFaceTemplate(string empid, string machineip, int portno, string machineID, string FaceSetInIP, string devInfo2, string machineid2) { string devInfo = GetDeviceInfo(machineip, portno); string str4 = "GetEmployee(id=\"" + empid + "\")"; string str5 = ""; uint num2 = 0; if (machineConnectivity.ExecuteCommad(devInfo, devInfo.Length, str4, str4.Length, ref str5, ref num2, myCallBack) != 0) { Console.WriteLine("Not Connected"); MessageBox.Show("Machine not connected"); return; } else { if (str5.Contains("success")) { SetEmployeeInfo(myCallBack, str5, empid, devInfo2, machineid2); count++; } else { Console.WriteLine("Emp: " + empid + "---> Not transferred in " + machineID + ""); MessageBox.Show("Emp: " + empid + "---> Not transferred in " + machineID + ""); } } } bool Bconnect = false; int lenght = 0; string template; public List get_set_EmpFaceTemplateZkteco(string empid, string fromIP, int fromID, string ToIP, int ToID, int port) { List responses = new List(); Bconnect = axCZKEM1.Connect_Net(fromIP, port); axCZKEM1.EnableDevice(fromID, false); //disable the device if (Bconnect == true) { if (empid == "") { //while (axCZKEM1.SSR_GetAllUserInfo(machineNumber, out sdwEnrollNumber, out sName, out sPassword, out iPrivilege, out bEnabled)) //{ //} } else { if (axCZKEM1.GetUserFaceStr(fromID, empid, 50, ref template, ref lenght)) { Bconnect = false; Bconnect = axCZKEM1.Connect_Net(ToIP, port); axCZKEM1.EnableDevice(ToID, false); //disable the device if (Bconnect == true) { int prvlg = 0; if (checkadmin == true) { prvlg = 1; } else { prvlg = 0; } if (axCZKEM1.SSR_SetUserInfo(ToID, empid, "", "", prvlg, true))//upload user information to the memory { bool getUserTmpExSuccess = axCZKEM1.SetUserFaceStr(ToID, (empid), 50, template, 0); // upload templates information to the device if (getUserTmpExSuccess) { responses.Add($"Emp : {empid} transferred"); Console.WriteLine(""); } } axCZKEM1.EnableDevice(ToID, true); axCZKEM1.RefreshData(ToID);//the data in the device should be refreshed axCZKEM1.Disconnect(); } else { responses.Add($"Machine {ToIP} not connected."); Console.WriteLine($"Machine {ToIP} not connected."); } axCZKEM1.EnableDevice(fromID, true); axCZKEM1.Disconnect(); } else { // Handle failure to connect to the device responses.Add($"Face template not availabel in {fromIP}."); } } } else { responses.Add($"Machine {fromIP} not connected."); Console.WriteLine($"Machine {fromIP} not connected."); } return responses; } public List SetEmployeeInfo(CallBack myCallBack, string str5, string empid, string devInfo2, string machineid) { string str4 = ""; List responses = new List(); string[] splitData = str5.Split('('); for (int i = 0; i < splitData.Length; i++) { string s = splitData[i]; if (!s.Contains("Return")) { string updatedData = s.Replace("result=\"success\" ", ""); string[] updatedResult = updatedData.Split(')'); str4 = "SetEmployee(" + updatedResult[0] + ")"; //str4 = str4.Substring(0, str4.Length - 1); //str4 += str4 + " overwrite=\"true\")"; } } str5 = ""; uint num2 = 0; if (machineConnectivity.ExecuteCommad(devInfo2, devInfo2.Length, str4, str4.Length, ref str5, ref num2, myCallBack) != 0) { Console.WriteLine(str5); responses.Add("Machine not connected"); MessageBox.Show("Machine not connected"); } else { Console.WriteLine(str5); if (!str5.Contains("fail")) { Console.WriteLine("Emp: " + empid + "---> transferred in " + machineid + ""); responses.Add("Emp: " + empid + "---> transferred in " + machineid + ""); backgroundWorker.ReportProgress(2, empid); //MessageBox.Show("Emp transferred"); } else { Console.WriteLine("Emp: " + empid + "---> Not transferred in " + machineid + ""); responses.Add("Emp: " + empid + "---> Not transferred in " + machineid + ""); //MessageBox.Show("Emp not transferred"); } } return responses; } public static string GetDeviceInfo(string machineIp, int portNumber) { return "DeviceInfo( dev_id = \"1\" dev_type = \"HW_HDCP\" comm_type = \"ip\" ip_address = \"" + machineIp + "\", password = \"\", port_number = \"" + portNumber + "\")"; } private void BindSearchData(string searchText, int GridNo) { if (GridNo == 1) { GvEmpData.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // Ensure that the search text is not empty if (string.IsNullOrWhiteSpace(searchText)) { // Reset the selection if the search text is empty GvEmpData.ClearSelection(); return; } // Search for the row that matches the search text (case-insensitive) foreach (DataGridViewRow row in GvEmpData.Rows) { // Ensure that the cell value is not null before comparing if (row.Cells[1].Value != null && row.Cells[1].Value.ToString().Equals(searchText, StringComparison.OrdinalIgnoreCase)) { row.Selected = true; // Scroll to the selected row if needed GvEmpData.FirstDisplayedScrollingRowIndex = row.Index; return; } } // If the search text is not found, clear the selection GvEmpData.ClearSelection(); } if (GridNo == 2) { gv.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // Ensure that the search text is not empty if (string.IsNullOrWhiteSpace(searchText)) { // Reset the selection if the search text is empty gv.ClearSelection(); return; } // Search for the row that matches the search text (case-insensitive) foreach (DataGridViewRow row in gv.Rows) { // Ensure that the cell value is not null before comparing if (row.Cells[1].Value != null && row.Cells[1].Value.ToString().Equals(searchText, StringComparison.OrdinalIgnoreCase)) { row.Selected = true; // Scroll to the selected row if needed gv.FirstDisplayedScrollingRowIndex = row.Index; return; } } // If the search text is not found, clear the selection gv.ClearSelection(); } if (GridNo == 3) { gvZktecoData.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // Ensure that the search text is not empty if (string.IsNullOrWhiteSpace(searchText)) { // Reset the selection if the search text is empty gvZktecoData.ClearSelection(); return; } // Search for the row that matches the search text (case-insensitive) foreach (DataGridViewRow row in gvZktecoData.Rows) { // Ensure that the cell value is not null before comparing if (row.Cells[0].Value != null && row.Cells[0].Value.ToString().Equals(searchText, StringComparison.OrdinalIgnoreCase)) { row.Selected = true; // Scroll to the selected row if needed gvZktecoData.FirstDisplayedScrollingRowIndex = row.Index; return; } } // If the search text is not found, clear the selection gvZktecoData.ClearSelection(); } else { DataGvMachine.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // Ensure that the search text is not empty if (string.IsNullOrWhiteSpace(searchText)) { // Reset the selection if the search text is empty DataGvMachine.ClearSelection(); return; } // Search for the row that matches the search text (case-insensitive) foreach (DataGridViewRow row in DataGvMachine.Rows) { // Ensure that the cell value is not null before comparing if (row.Cells[1].Value != null && row.Cells[1].Value.ToString().Equals(searchText.ToString(), StringComparison.OrdinalIgnoreCase)) { row.Selected = true; // Scroll to the selected row if needed DataGvMachine.FirstDisplayedScrollingRowIndex = row.Index; return; } } // If the search text is not found, clear the selection DataGvMachine.ClearSelection(); } } private void bindDropDownMachineIp(string type) { ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection = ObjConnectionClass.Connection(); bool OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection) { string query = "SELECT a.machine_ip, a.machine_name, CONCAT(a.machine_name, '-', a.machine_ip) AS concatColumn " + "FROM attendance_machine a WHERE a.machine_status = 1 " + type + " " + " ORDER BY machine_name"; MySqlCommand cmd = new MySqlCommand(query, connection); DataTable dataTable = new DataTable(); MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(cmd); mySqlDataAdapter.Fill(dataTable); if (dataTable.Rows.Count > 0) { // Create a new row with Id = 0 DataRow newRow = dataTable.NewRow(); newRow["concatColumn"] = "SELECT"; dataTable.Rows.InsertAt(newRow, 0); // Bind DataTable to ComboBoxes BindComboBox(cb_fromMachine, dataTable); BindComboBox(cb_ToMachine, dataTable); BindComboBox(cb_machineFrom, dataTable); BindComboBox(cbMachineIp, dataTable); BindComboBoxList(cbListMachIp, dataTable); BindComboBox(cbMachIp, dataTable); BindComboBox(cb_machineIpTurnstile, dataTable); BindComboBox(cb_from, dataTable); BindComboBox(cb_to, dataTable); BindComboBox(cb_zkteco, dataTable); BindComboBox(comboBox1, dataTable); BindComboBox(cb_syncMachineip, dataTable); } } } private void BindComboBox(ComboBox comboBox, DataTable dataTable) { comboBox.DataSource = dataTable.Copy(); comboBox.ValueMember = "machine_ip"; comboBox.DisplayMember = "concatColumn"; } private void BindComboBoxList(ListBox comboBox, DataTable dataTable) { comboBox.DataSource = dataTable.Copy(); comboBox.ValueMember = "machine_ip"; comboBox.DisplayMember = "concatColumn"; } private void SetGridView2() { DataGvMachine.BackgroundColor = Color.White; DataGvMachine.RowHeadersVisible = false; DataGvMachine.AutoGenerateColumns = false; // Add a CheckBox Column to the DataGridView at the first position. DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn(); checkBoxColumn.HeaderText = ""; // Set the header text for the CheckBox column checkBoxColumn.Width = 30; checkBoxColumn.Name = "checkBoxColumn"; // Set the custom header cell to display the desired text and center align the text DataGridViewColumnHeaderCell headerCell = new DataGridViewColumnHeaderCell(); headerCell.Value = ""; headerCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; checkBoxColumn.HeaderCell = headerCell; DataGvMachine.Columns.Insert(0, checkBoxColumn); // Find the Location of Header Cell (using index 0). Point headerCellLocation = this.DataGvMachine.GetCellDisplayRectangle(0, -1, true).Location; // Initialize the header checkbox headerCheckBox2 = new CheckBox(); headerCheckBox2.Size = new Size(15, 15); headerCheckBox2.BackColor = Color.Transparent; // Place the Header CheckBox in the Location of the Header Cell. headerCheckBox2.Location = new Point(headerCellLocation.X + (checkBoxColumn.Width / 2) - (headerCheckBox2.Width / 2), headerCellLocation.Y + 2); // Assign Click event to the Header CheckBox. headerCheckBox2.Click += new EventHandler(HeaderCheckBox_Clicked1); DataGvMachine.Controls.Add(headerCheckBox2); // Assign Click event to the DataGridView Cell. DataGvMachine.CellContentClick += new DataGridViewCellEventHandler(DataGvMachine_CellClick); // Add a new DataGridViewTextBoxColumn DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn(); column.DataPropertyName = "AcNo"; // Set DataPropertyName to "AcNo" column.HeaderText = "Employee ID"; // Set the header text for the column column.Name = "AcNo"; // Add the column to the DataGridView DataGvMachine.Columns.Add(column); DataGvMachine.Visible = false; } private void SetGridView1() { GvEmpData.BackgroundColor = Color.White; GvEmpData.RowHeadersVisible = false; GvEmpData.AutoGenerateColumns = false; // Add a CheckBox Column to the DataGridView at the first position. DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn(); checkBoxColumn.HeaderText = ""; // Set the header text for the CheckBox column checkBoxColumn.Width = 30; checkBoxColumn.Name = "checkBoxColumn"; // Set the custom header cell to display the desired text and center align the text DataGridViewColumnHeaderCell headerCell = new DataGridViewColumnHeaderCell(); headerCell.Value = ""; headerCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; checkBoxColumn.HeaderCell = headerCell; GvEmpData.Columns.Insert(0, checkBoxColumn); // Find the Location of Header Cell (using index 0). Point headerCellLocation = this.GvEmpData.GetCellDisplayRectangle(0, -1, true).Location; // Initialize the header checkbox headerCheckBox3 = new CheckBox(); headerCheckBox3.Size = new Size(15, 15); headerCheckBox3.BackColor = Color.Transparent; // Place the Header CheckBox in the Location of the Header Cell. headerCheckBox3.Location = new Point(headerCellLocation.X + (checkBoxColumn.Width / 2) - (headerCheckBox3.Width / 2), headerCellLocation.Y + 2); // Assign Click event to the Header CheckBox. headerCheckBox3.Click += new EventHandler(HeaderCheckBox_Clicked); GvEmpData.Controls.Add(headerCheckBox3); // Assign Click event to the DataGridView Cell. GvEmpData.CellContentClick += new DataGridViewCellEventHandler(GvEmpData_CellClick); // Add a new DataGridViewTextBoxColumn DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn(); column.DataPropertyName = "AcNo"; // Set DataPropertyName to "AcNo" column.HeaderText = "Employee ID"; // Set the header text for the column column.Name = "AcNo"; // Add the column to the DataGridView GvEmpData.Columns.Add(column); GvEmpData.Visible = false; } private void SetGridView3() { gv.BackgroundColor = Color.White; gv.RowHeadersVisible = false; gv.AutoGenerateColumns = false; // Add a CheckBox Column to the DataGridView at the first position. DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn(); checkBoxColumn.HeaderText = ""; // Set the header text for the CheckBox column checkBoxColumn.Width = 30; checkBoxColumn.Name = "checkBoxColumn"; // Set the custom header cell to display the desired text and center align the text DataGridViewColumnHeaderCell headerCell = new DataGridViewColumnHeaderCell(); headerCell.Value = ""; headerCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; checkBoxColumn.HeaderCell = headerCell; gv.Columns.Insert(0, checkBoxColumn); // Find the Location of Header Cell (using index 0). Point headerCellLocation = this.gv.GetCellDisplayRectangle(0, -1, true).Location; // Initialize the header checkbox headerCheckBox = new CheckBox(); headerCheckBox.Size = new Size(15, 15); headerCheckBox.BackColor = Color.Transparent; // Place the Header CheckBox in the Location of the Header Cell. headerCheckBox.Location = new Point(headerCellLocation.X + (checkBoxColumn.Width / 2) - (headerCheckBox.Width / 2), headerCellLocation.Y + 2); // Assign Click event to the Header CheckBox. headerCheckBox.Click += new EventHandler(GvHeaderCheckBox_Clicked); gv.Controls.Add(headerCheckBox); // Assign Click event to the DataGridView Cell. gv.CellContentClick += new DataGridViewCellEventHandler(gv_CellClick); // Add a new DataGridViewTextBoxColumn DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn(); column.DataPropertyName = "AcNo"; // Set DataPropertyName to "AcNo" column.HeaderText = "Employee ID"; // Set the header text for the column column.Name = "AcNo"; // Add the column to the DataGridView gv.Columns.Add(column); } private void showControls() { lblSearch.Visible = true; txtSearch.Visible = true; lbl_ip_to.Visible = true; cb_ToMachine.Visible = true; GvEmpData.Visible = true; } /////////////////////////////////////----------- BUTTONS & EVENTS -----------------------////////////////////////////////////////// private void btnGet_Click(object sender, EventArgs e) { showControls(); if (cb_fromMachine.SelectedIndex > 0) { ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", cb_fromMachine.SelectedValue.ToString()); machineid1From = machines[0].MachineId; Machine = new AttendanceMachine(machines[0].MachineId, cb_fromMachine.SelectedValue.ToString(), machines[0].PortNumber); (List EmployeeList, int TotalCount) = attendanceMachineDAO.GetEmployees(connection, machineid1From); backgroundWorker.ReportProgress(1, TotalCount); // Set the EmployeeList as the DataSource GvEmpData.DataSource = EmployeeList; ObjConnectionClass.CloseConnection(); } } else { MessageBox.Show("Please provide proper machine ip's"); } } private void txtSearch_TextChanged(object sender, EventArgs e) { string searchText = txtSearch.Text.Trim(); BindSearchData(searchText, 1); } private void btnReset_Click(object sender, EventArgs e) { cb_machineFrom.SelectedIndex = 0; lb_total.Text = "Total"; progressBar1.Value = 0; progressBar1.Minimum = 0; progressBar1.Maximum = 0; count = 0; backgroundWorker.WorkerSupportsCancellation = true; if (backgroundWorker.IsBusy) { // Request cancellation of the task backgroundWorker.CancelAsync(); } cb_fromMachine.SelectedIndex = 0; cb_ToMachine.SelectedIndex = 0; lblFrom.Text = "From:"; lblTo.Text = "To:"; lblResult.Text = "Emp no :"; lblTotalEmp.Text = "Total Emp :"; GvEmpData.DataSource = null; GvEmpData.Visible = false; lbl_ip_to.Visible = false; cb_ToMachine.Visible = false; lblSearch.Visible = false; txtSearch.Visible = false; cb_machineFrom.SelectedIndex = 0; txtSearch.Text = ""; tb_emp.Text = ""; GvRegisteredUsers.DataSource = null; DataGvMachine.DataSource = null; GvFaceTemplate.DataSource = null; txtEmpoyeeCd.Text = null; cbMachIp.SelectedIndex = 0; } private void Btn_Transfer_Click(object sender, EventArgs e) { if (cb_fromMachine.SelectedIndex > 0 && cb_ToMachine.SelectedIndex > 0) { //backgroundWorker.RunWorkerAsync(); RunFaceTransfer(); } else { MessageBox.Show("Please provide proper machine ip's"); } } private void btnGetRecord_Click(object sender, EventArgs e) { DataGvMachine.Visible = true; if (comboBox1.SelectedIndex > 0) { //DataGvMachine.Rows.Clear(); lbl_totalemp.Text = ""; ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { AttendanceMachineDAO attendanceMachineDAO = new AttendanceMachineDAO(); List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", comboBox1.SelectedValue.ToString()); Machine = new AttendanceMachine(machines[0].MachineId, comboBox1.SelectedValue.ToString(), machines[0].PortNumber); // backgroundWorker.ReportProgress(1, TotalCount); string devInfo = GetDeviceInfo(machines[0].MachineIp, machines[0].PortNumber); string str4 = "GetEmployeeID()"; string str5 = ""; uint num2 = 0; if (machineConnectivity.ExecuteCommad(devInfo, devInfo.Length, str4, str4.Length, ref str5, ref num2, myCallBack) != 0) { Console.WriteLine("Not Connected"); MessageBox.Show("Machine not connected"); } else { if (!str5.Contains("fail")) { ConvertData(str5); } else { } } ObjConnectionClass.CloseConnection(); } } else { MessageBox.Show("Please provide proper machine ip's"); } } private void ConvertData(string str5) { DataTable dt = new DataTable(); dt.Columns.Add("AcNo", typeof(string)); string[] keyValuePairs = str5.Split(new char[] { ',', '=' }, StringSplitOptions.RemoveEmptyEntries); // Create a list to store the extracted values List values = new List(); foreach (string keyValue in keyValuePairs) { // Find the index of the first occurrence of '"' int startIdx = keyValue.IndexOf('"'); // Find the index of the last occurrence of '"' int endIdx = keyValue.LastIndexOf('"'); // Extract the value between the '"' characters if (startIdx != -1 && endIdx != -1 && startIdx < endIdx) { string value = keyValue.Substring(startIdx + 1, endIdx - startIdx - 1); values.Add(value); } } if (values.Count > 0) { // The first value is the total employee count lbl_totalemp.Text = "Total Emp: " + values[1].ToString(); foreach (string value in values) { if (value != "success" && value != values[1]) { //DataGvMachine.Rows.Add(value); dt.Rows.Add(value); } } } SortDataGridView(dt); //DataGvMachine.DataSource = dt; } private void SortDataGridView(DataTable dt) { // Assuming you have populated the data source for DataGvMachine // and the data source is a DataTable named "dataSourceTable" // Assuming "serial_number" column is in the first position (index 0) if (dt.Rows.Count > 0) { // Custom sorting by converting "serial_number" to unsigned integer var sortedRows = dt.AsEnumerable() .OrderBy(row => Convert.ToUInt64(row["AcNo"])) .CopyToDataTable(); // Bind the sorted data to the DataGridView DataGvMachine.DataSource = sortedRows; } } string employeeId; private void GetTemplateSaveInMachine() { SaveTemplate saveTemplate = new SaveTemplate(); string fromip = comboBox1.SelectedValue.ToString(); ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; List responses = new List(); // Initialize(); connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { string devInfo = GetDeviceInfo(fromip, Machine.PortNumber); foreach (DataGridViewRow row in DataGvMachine.Rows) { // Check if the CheckBox in the first column is checked for the current row DataGridViewCheckBoxCell checkBoxCell = row.Cells["checkBoxColumn"] as DataGridViewCheckBoxCell; if (checkBoxCell.Value != null && (bool)checkBoxCell.Value) { // If the CheckBox is checked, get the value of the "AcNo" column (Employee ID) employeeId = row.Cells["AcNo"].Value.ToString(); string str4 = "GetEmployee(id=\"" + employeeId + "\")"; string machineResponse = ""; uint num2 = 0; if (machineConnectivity.ExecuteCommad(devInfo, devInfo.Length, str4, str4.Length, ref machineResponse, ref num2, myCallBack) != 0) { Console.WriteLine("Not Connected"); return; } else { if (machineResponse.Contains("success")) { str4 = removeReturn(machineResponse); saveTemplate.CheckInDb(connection, employeeId, str4); } else { Console.WriteLine("Template not saved"); } } } } } } private string removeReturn(string str5) { string str4 = null; string[] splitData = str5.Split('('); for (int i = 0; i < splitData.Length; i++) { string s = splitData[i]; if (!s.Contains("Return")) { string updatedData = s.Replace("result=\"success\" ", ""); string[] updatedResult = updatedData.Split(')'); str4 = updatedResult[0]; } } return str4; } private void SepratetemplateFromStr5() { //string searchStr = "face_data=\""; //int currentIndex = 0; //while (true) //{ // int startIndex = str5.IndexOf(searchStr, currentIndex); // if (startIndex == -1) // { // break; // } // startIndex += searchStr.Length; // int endIndex = str5.IndexOf("\"", startIndex); // if (endIndex == -1) // { // break; // } // string faceData = str5.Substring(startIndex, endIndex - startIndex); // Console.WriteLine(faceData); // currentIndex = endIndex + 1; //} } private string GetBlobValue(String empid) { string stringValue = null; ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { string query = "SELECT template FROM attendance_machine_face_templates WHERE serial_no = @RecordId"; using (MySqlCommand command = new MySqlCommand(query, connection)) { command.Parameters.AddWithValue("@RecordId", empid); using (MySqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { // Assuming blob_data is of type varbinary(max) byte[] blobValue = (byte[])reader["template"]; stringValue = Encoding.UTF8.GetString(blobValue); // Use the blobValue byte array as needed //Console.WriteLine($"Retrieved BLOB value of length: {stringValue}"); } else { Console.WriteLine("No matching record found."); } } } } return stringValue; } private void btn_result_Click(object sender, EventArgs e) { DataTable dataTable = new DataTable(); if (tb_emp.Text.Length > 0) { ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { RegisteredUsers registeredUsers = new RegisteredUsers(); dataTable = registeredUsers.Registered_Users(tb_emp.Text, connection); GvRegisteredUsers.DataSource = dataTable; } } } private void btnSaveDb_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex > 0) { GetTemplateSaveInMachine(); MessageBox.Show("DONE"); } else { MessageBox.Show("Please provide proper machine ip's"); } } private void DataGvMachine_CellClick(object sender, DataGridViewCellEventArgs e) { //Check to ensure that the row CheckBox is clicked. if (e.RowIndex >= 0 && e.ColumnIndex == 0) { //Loop to verify whether all row CheckBoxes are checked or not. bool isChecked = true; foreach (DataGridViewRow row in DataGvMachine.Rows) { if (Convert.ToBoolean(row.Cells["checkBoxColumn"].EditedFormattedValue) == false) { isChecked = false; break; } } headerCheckBox2.Checked = isChecked; } } private void HeaderCheckBox_Clicked1(object sender, EventArgs e) { //Necessary to end the edit mode of the Cell. DataGvMachine.EndEdit(); //Loop and check and uncheck all row CheckBoxes based on Header Cell CheckBox. foreach (DataGridViewRow row in DataGvMachine.Rows) { DataGridViewCheckBoxCell checkBox = (row.Cells["checkBoxColumn"] as DataGridViewCheckBoxCell); checkBox.Value = headerCheckBox2.Checked; } } private void GvEmpData_CellClick(object sender, DataGridViewCellEventArgs e) { //Check to ensure that the row CheckBox is clicked. if (e.RowIndex >= 0 && e.ColumnIndex == 0) { //Loop to verify whether all row CheckBoxes are checked or not. bool isChecked = true; foreach (DataGridViewRow row in GvEmpData.Rows) { if (Convert.ToBoolean(row.Cells["checkBoxColumn"].EditedFormattedValue) == false) { isChecked = false; break; } } headerCheckBox.Checked = isChecked; } } private void gv_CellClick(object sender, DataGridViewCellEventArgs e) { //Check to ensure that the row CheckBox is clicked. if (e.RowIndex >= 0 && e.ColumnIndex == 0) { //Loop to verify whether all row CheckBoxes are checked or not. bool isChecked = true; foreach (DataGridViewRow row in GvEmpData.Rows) { if (Convert.ToBoolean(row.Cells["checkBoxColumn"].EditedFormattedValue) == false) { isChecked = false; break; } } headerCheckBox.Checked = isChecked; } } private void GvHeaderCheckBox_Clicked(object sender, EventArgs e) { //Necessary to end the edit mode of the Cell. gv.EndEdit(); //Loop and check and uncheck all row CheckBoxes based on Header Cell CheckBox. foreach (DataGridViewRow row in gv.Rows) { DataGridViewCheckBoxCell checkBox = (row.Cells["checkBoxColumn"] as DataGridViewCheckBoxCell); checkBox.Value = headerCheckBox.Checked; } } private void HeaderCheckBox_Clicked(object sender, EventArgs e) { //Necessary to end the edit mode of the Cell. GvEmpData.EndEdit(); //Loop and check and uncheck all row CheckBoxes based on Header Cell CheckBox. foreach (DataGridViewRow row in GvEmpData.Rows) { DataGridViewCheckBoxCell checkBox = (row.Cells["checkBoxColumn"] as DataGridViewCheckBoxCell); checkBox.Value = headerCheckBox3.Checked; } } private void btmGetTemplate_Click(object sender, EventArgs e) { try { List Response = new List(); if (txtEmpoyeeCd.Text.Length == 0) { MessageBox.Show("Please provide employee code"); return; } if (cbListMachIp.SelectedIndex == 0) { MessageBox.Show("Please provide machine"); return; } if (dataTableFaceTemplates.Rows.Count > 0) { ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { // Loop through each selected value foreach (string selectedValue in selectedValues) { // Assuming that the selectedValue is used in the following operations List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", selectedValue); Machine = new AttendanceMachine(machines[0].MachineId, selectedValue, machines[0].PortNumber); devInfo2 = GetDeviceInfo(Machine.MachineIp, Machine.PortNumber); if (dataTableFaceTemplates.Rows.Count > 0) { // Fetch and populate the blob data into the "BlobDataBytes" column foreach (DataRow row in dataTableFaceTemplates.Rows) { byte[] blobValue = (byte[])row["template"]; string stringValue = Encoding.UTF8.GetString(blobValue); string emp = row["serial_no"].ToString(); Response.AddRange(SetEmployeeInfo(myCallBack, stringValue, emp, devInfo2, Machine.MachineId)); } // Add each response to the StringBuilder foreach (string response in Response) { responseStringBuilder.AppendLine(response); } string allResponses = responseStringBuilder.ToString(); // Display all responses in a message box MessageBox.Show(allResponses); responseStringBuilder.Clear(); } else { GvFaceTemplate.DataSource = null; txtEmpoyeeCd.Text = null; cbMachIp.SelectedIndex = 0; MessageBox.Show("Template of - " + txtEmpoyeeCd.Text + " - not found in db"); } } } } else { MessageBox.Show("No face found/Invalid employee code"); } } catch (Exception ex) { // Log or handle exception } } private void btnAllow_Click(object sender, EventArgs e) { if (DataGvMachine.Rows.Count > 1) { string fromip = cbMachineIp.SelectedValue.ToString(); ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; List responses = new List(); // Initialize(); connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", fromip); Machine = new AttendanceMachine(machines[0].MachineId, cbMachIp.SelectedValue.ToString(), machines[0].PortNumber); string devInfo = GetDeviceInfo(fromip, Machine.PortNumber); foreach (DataGridViewRow row in DataGvMachine.Rows) { // Check if the CheckBox in the first column is checked for the current row DataGridViewCheckBoxCell checkBoxCell = row.Cells["checkBoxColumn"] as DataGridViewCheckBoxCell; if (checkBoxCell.Value != null && (bool)checkBoxCell.Value) { // If the CheckBox is checked, get the value of the "AcNo" column (Employee ID) employeeId = row.Cells["AcNo"].Value?.ToString(); string str4 = "GetEmployee(id=\"" + employeeId + "\")"; string machineResponse = ""; uint num2 = 0; if (machineConnectivity.ExecuteCommad(devInfo, devInfo.Length, str4, str4.Length, ref machineResponse, ref num2, myCallBack) != 0) { Console.WriteLine("Not Connected"); return; } else { if (!machineResponse.Contains("fail")) { str4 = removeReturn(machineResponse); //Check turnstile is allow or not AllowturnstileAccess(str4, employeeId, devInfo, Machine.MachineId); //saveTemplate.CheckInDb(connection, employeeId, str4); } else { Console.WriteLine("Template not saved"); } } } } } } else { MessageBox.Show("Please get machine data first"); } } private void AllowturnstileAccess(string value, string empid, string devInfo, string machineid) { if (!value.Contains("authority=\"0X11\"")) { string pattern = @"authority\s*=\s*""0X55"""; // Define the replacement value string replacement = "authority=\"0X11\""; // Use Regex.Replace to perform the replacement string modifiedValue = Regex.Replace(value, pattern, replacement); SetEmployeeInfo(myCallBack, modifiedValue, empid, devInfo, machineid); } else { Console.WriteLine("Turnstile access already allowed"); } } private void btn_logout_Click(object sender, EventArgs e) { this.Hide(); LoginForm loginForm = new LoginForm(); loginForm.Show(); File.Delete(filePath); } DataTable dataTableFaceTemplates = new DataTable(); private void btn_getFaceTemplates_Click(object sender, EventArgs e) { //GetBlobValue(txtEmpoyeeCd.Text); if (txtEmpoyeeCd.Text.Length > 0) { ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { RegisteredUsers registeredUsers = new RegisteredUsers(); dataTableFaceTemplates = registeredUsers.GetFaceTemplates(connection, txtEmpoyeeCd.Text); dataTableFaceTemplates.Columns.Add("Face", typeof(string)); // Set the DataGridView's DataSource to the modified dataTableFaceTemplates GvFaceTemplate.DataSource = dataTableFaceTemplates; GvFaceTemplate.Columns["template"].Visible = false; foreach (DataRow row in dataTableFaceTemplates.Rows) { row["Face"] = "Yes"; } } } else { MessageBox.Show("PLease provide emp code"); // Handle the case where txtEmpoyeeCd.Text is empty } } private void btn_get_face_Click(object sender, EventArgs e) { if (cb_from.SelectedIndex > 0) { ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", cb_from.SelectedValue.ToString()); machineid1From = machines[0].MachineId; Machine = new AttendanceMachine(machines[0].MachineId, cb_fromMachine.SelectedValue.ToString(), machines[0].PortNumber); (List EmployeeList, int TotalCount) = attendanceMachineDAO.GetEmployees(connection, machineid1From); // Set the EmployeeList as the DataSource gv.DataSource = EmployeeList; ObjConnectionClass.CloseConnection(); } } else { MessageBox.Show("Please provide proper machine ip's"); } } private void txtSearchNew_TextChanged(object sender, EventArgs e) { string searchText = txtSearchNew.Text.Trim(); BindSearchData(searchText, 2); } private void btn_transferNew_Click(object sender, EventArgs e) { if (cb_to.SelectedIndex > 0 && cb_from.SelectedIndex > 0) { //backgroundWorker.RunWorkerAsync(); RunFaceTransferNedoToZkteco(); } else { MessageBox.Show("Please provide proper machine ip's"); } } private void btn_livedata_get_Click(object sender, EventArgs e) { if (cb_zkteco.SelectedIndex > 0) { //DataGvMachine.Rows.Clear(); lbl_totalemp.Text = ""; ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { AttendanceMachineDAO attendanceMachineDAO = new AttendanceMachineDAO(); DataTable dataTable = new DataTable(); dataTable.Columns.Add("Serial_no", typeof(string)); List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", cb_zkteco.SelectedValue.ToString()); Machine = new AttendanceMachine(machines[0].MachineId, cb_zkteco.SelectedValue.ToString(), machines[0].PortNumber); // backgroundWorker.ReportProgress(1, TotalCount); Bconnect = axCZKEM1.Connect_Net(Machine.MachineIp, Machine.PortNumber); axCZKEM1.EnableDevice(Convert.ToInt32(Machine.MachineId), false); //disable the device if (Bconnect == true) { string sdwEnrollNumber = string.Empty, sName = string.Empty, sPassword = string.Empty; int iPrivilege = 0, iFaceIndex = 0, iFlag = 0, iTmpLength = 0; bool bEnabled = false; axCZKEM1.ReadAllTemplate(Convert.ToInt32(Machine.MachineId)); while (axCZKEM1.SSR_GetAllUserInfo(Convert.ToInt32(Machine.MachineId), out sdwEnrollNumber, out sName, out sPassword, out iPrivilege, out bEnabled)) { // Create a new DataRow DataRow newRow = dataTable.NewRow(); // Set the value of the "EnrollNumber" column newRow["Serial_no"] = sdwEnrollNumber; // Add the new row to the DataTable dataTable.Rows.Add(newRow); } txt_total.Text = "Total Emp:" + dataTable.Rows.Count; } axCZKEM1.EnableDevice(Convert.ToInt32(Machine.MachineId), true); axCZKEM1.Disconnect(); //gvZktecoData.DataSource = dataTable; if (dataTable.Rows.Count > 0) { SortDataGridViewZKTECO(dataTable); } ObjConnectionClass.CloseConnection(); } } else { MessageBox.Show("Please provide proper machine ip's"); } } private void SortDataGridViewZKTECO(DataTable dt) { // Assuming you have populated the data source for DataGvMachine // and the data source is a DataTable named "dataSourceTable" // Assuming "serial_number" column is in the first position (index 0) if (dt.Rows.Count > 0) { // Custom sorting by converting "serial_number" to unsigned integer var sortedRows = dt.AsEnumerable() .OrderBy(row => Convert.ToUInt64(row["Serial_no"])) .CopyToDataTable(); // Bind the sorted data to the DataGridView gvZktecoData.DataSource = sortedRows; } } private void txt_searchZkteco_TextChanged(object sender, EventArgs e) { string searchText = txt_searchZkteco.Text.Trim(); BindSearchData(searchText, 3); } private void btn_sync_time_Click(object sender, EventArgs e) { if (cb_1.Checked == true || cb_2.Checked == true) { if (cb_syncMachineip.SelectedIndex > 0) { if (cb_1.Checked == true) { SyncTimeZkteco(); } if (cb_2.Checked == true) { SyncTimeNedo(); } } else { MessageBox.Show("Please select machine ip"); } } else { MessageBox.Show("Please check machine type"); } } public void SyncTimeZkteco() { ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", cb_syncMachineip.SelectedValue.ToString()); Machine = new AttendanceMachine(machines[0].MachineId, cb_syncMachineip.SelectedValue.ToString(), machines[0].PortNumber); ObjConnectionClass.CloseConnection(); Bconnect = axCZKEM1.Connect_Net(Machine.MachineIp, Machine.PortNumber); axCZKEM1.EnableDevice(Convert.ToInt32(Machine.MachineId), false); //disable the device if (Bconnect == true) { int machineNumber = int.Parse(Machine.MachineId); int dwYear = 0; int dwMonth = 0; int dwDay = 0; int dwHour = 0; int dwSecond = 0; bool result = axCZKEM1.SetDeviceTime(machineNumber); if (result == true) { txt_showTime.Text = System.DateTime.Now.ToShortTimeString(); //string deviceTime = new DateTime(dwYear, dwMonth, dwDay, dwHour, dwMinute, dwSecond).ToString(); MessageBox.Show("Machine Time Updated"); } else { MessageBox.Show("Error"); } } else { MessageBox.Show("Machine not connected"); } } } public void SyncTimeNedo() { ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", cb_syncMachineip.SelectedValue.ToString()); Machine = new AttendanceMachine(machines[0].MachineId, cb_syncMachineip.SelectedValue.ToString(), machines[0].PortNumber); ObjConnectionClass.CloseConnection(); devInfo = GetDeviceInfo(Machine.MachineIp, Machine.PortNumber); DateTime datetime = System.DateTime.Now; string command = "SetDeviceInfo(time=\"" + datetime.ToString("yyyy-MM-dd HH:mm:ss") + "\" memory_alarm=\"90%\" language=\"chs\" volume=\"low/mid/high\")"; string str5 = ""; uint num2 = 0; if (machineConnectivity.ExecuteCommad(devInfo, devInfo.Length, command, command.Length, ref str5, ref num2, myCallBack) != 0) { MessageBox.Show("Machine not connected"); return; } else { if (str5.Contains("result=\"fail\"")) { MessageBox.Show("Error"); } else { txt_showTime.Text = datetime.ToShortTimeString(); MessageBox.Show("Machine Time Updated"); } } } } private void cb_1_CheckedChanged(object sender, EventArgs e) { cb_2.Checked = false; string machineType = " AND (a.machine_type = 'ZKTECO')"; bindDropDownMachineIp(machineType); } private void cb_2_CheckedChanged(object sender, EventArgs e) { cb_1.Checked = false; string machineType = " AND (a.machine_type IS NULL)"; bindDropDownMachineIp(machineType); } private void btn_getTime_Click(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { string searchText = textBox2.Text.Trim(); BindSearchData(searchText, 0); } private void GetDeviceTimeNedo() { string devInfo = GetDeviceInfo(cb_syncMachineip.SelectedValue.ToString(), 9922); string str4 = "GetDeviceInfo()"; string str5 = ""; uint num2 = 0; if (machineConnectivity.ExecuteCommad(devInfo, devInfo.Length, str4, str4.Length, ref str5, ref num2, myCallBack) != 0) { MessageBox.Show("Machine not Connected"); } else { if (!str5.Contains("fail")) { (datePart, timePart) = SeprateTime(str5); txt_showTime.Text = timePart; } } } private static (string, string) SeprateTime(string str5) { string pattern = @"time=""([^""]+)"""; // Use Regex.Match to find the first match in the input string Match match = Regex.Match(str5, pattern); if (match.Success) { // Extract the time value from the captured group string timeValue = match.Groups[1].Value; if (DateTime.TryParse(timeValue, out DateTime parsedTime)) { // Format the parsed time in 12-hour format with AM/PM datePart = parsedTime.ToString("yyyy-MM-dd"); timePart = parsedTime.ToString("hh:mm:ss tt"); } return (datePart, timePart); } else { return (null, null); } } private void GetDeviceTimeZkteco() { try { ConnectionClass ObjConnectionClass = new ConnectionClass(); MySqlConnection connection; bool OpenConnection; connection = ObjConnectionClass.Connection(); OpenConnection = ObjConnectionClass.OpenConnection(); if (OpenConnection == true) { List machines = attendanceMachineDAO.getAttendanceMachineDetails(connection, "0", cb_syncMachineip.SelectedValue.ToString()); Machine = new AttendanceMachine(machines[0].MachineId, cb_syncMachineip.SelectedValue.ToString(), machines[0].PortNumber); ObjConnectionClass.CloseConnection(); int dwYear = 0; int dwMonth = 0; int dwDay = 0; int dwHour = 0; int dwMinute = 0; int dwSecond = 0; Bconnect = axCZKEM1.Connect_Net(cb_syncMachineip.SelectedValue.ToString(), 4370); axCZKEM1.EnableDevice(Convert.ToInt32(Machine.MachineId), false); //disable the device if (Bconnect == true) { bool result = axCZKEM1.GetDeviceTime(Convert.ToInt32(Machine.MachineId), ref dwYear, ref dwMonth, ref dwDay, ref dwHour, ref dwMinute, ref dwSecond); DateTime date = new DateTime(dwYear, dwMonth, dwDay, dwHour, dwMinute, dwSecond); DateTime parsedTime; if (DateTime.TryParseExact(date.ToString(), "M/d/yyyy h:mm:ss tt", null, System.Globalization.DateTimeStyles.None, out parsedTime)) { datePart = parsedTime.ToString("yyyy-MM-dd"); timePart = parsedTime.ToString("hh:mm:ss tt"); txt_showTime.Text = timePart; } } else { MessageBox.Show("Machine not connected"); } } else { MessageBox.Show("Database connection error"); } } catch (Exception ex) { MessageBox.Show("Error in connecting machine"); } } private void btn_getTime_Click_1(object sender, EventArgs e) { if (cb_1.Checked == true || cb_2.Checked == true) { if (cb_syncMachineip.SelectedIndex > 0) { if (cb_1.Checked == true) { GetDeviceTimeZkteco(); } if (cb_2.Checked == true) { //GetTimeNedo(); GetDeviceTimeNedo(); } } else { MessageBox.Show("Please select machine ip"); } } else { MessageBox.Show("Please check machine type"); } } private void isAdmin_CheckedChanged(object sender, EventArgs e) { checkadmin = isAdmin.Checked; } private void cbListMachIp_SelectedIndexChanged(object sender, EventArgs e) { foreach (DataRowView item in cbListMachIp.CheckedItems) { string selectedValue = item.Row[0].ToString(); // Check if the selected value is already in the list if (!selectedValues.Contains(selectedValue)) { selectedValues.Add(selectedValue); } } } private void tabControl_SelectedIndexChanged(object sender, EventArgs e) { string tabControlInder = tabControl.SelectedIndex.ToString(); if (Convert.ToInt32(tabControlInder) <= 4) { machineType = " AND (a.machine_type IS NULL)"; bindDropDownMachineIp(machineType); } else { if (tabControlInder == "8") { // machineType = "AND (a.machine_type = 'ZKTECO' OR a.machine_type IS NULL) "; return; } else { machineType = "AND(a.machine_type = 'ZKTECO')"; } bindDropDownMachineIp(machineType); } } } }