private void btnSetStrCardNumber_Click(object sender, EventArgs e) { if (_connected == false) { MessageBox.Show("Please connect the device first!", "Error"); return; } if (String.IsNullOrEmpty(txtUserID.Text)) { MessageBox.Show("Please select employee to register", "Error"); return; } var sCardnumber = txtCardnumber.Text.Trim(); Cursor = Cursors.WaitCursor; _czkemClass.EnableDevice(_sdkMachineNumber, false); RegisterToMachine(sCardnumber, Convert.ToInt32(txtUserID.Text), txtName.Text); _czkemClass.RefreshData(_sdkMachineNumber);//the data in the device should be refreshed _czkemClass.EnableDevice(_sdkMachineNumber, true); Cursor = Cursors.Default; }
//Download the attendance records from the device(For both Black&White and TFT screen devices). public IList <TimeReportEntry> ReadTimeReports(DateTime from) { if (_bIsConnected == false) { throw new Exception("Please connect the att device first"); } if (!_axCZKEM1.EnableDevice(_iMachineNumber, false))//disable the device { throw new Exception("Unable to disable device"); } IList <TimeReportEntry> trrList; try { trrList = ReadTimeReportsInternal(from); } catch { throw; } finally { if (!_axCZKEM1.EnableDevice(_iMachineNumber, true))//enable the device { throw new Exception("Unable to enable device"); } } return(trrList); }
private void Conectar(Dispositivo disp) { File.AppendAllText(@"C:\logger.log", "Conectando... " + DateTime.Now + Environment.NewLine); //Intento conectarme al terminal de zk por tcp if (!Conectado) { Conectado = terminalZK.Connect_Net(disp.ip, Convert.ToInt32(disp.puerto)); } if (Conectado) { File.AppendAllText(@"C:\logger.log", "---------------CONECTADO---------------- " + DateTime.Now + Environment.NewLine); //asigno nuevo id de maquina idMaquina = disp.id; //Traigo los usuarios staff y comunes(clientes) con sus huellas del server listaUsuariosStaff = UsuarioController.Lista("staff"); listaUsuarios = UsuarioController.Lista($"dispositivos/id/{idMaquina}"); //deshabilito el terminal momentaneamente hasta que se completen las operaciones terminalZK.EnableDevice(idMaquina, false); GestionarAsistencias(); GestionarUsuarios(); terminalZK.EnableDevice(idMaquina, true); //Habilito el dispositivo } else { File.AppendAllText(@"C:\logger.log", DateTime.Now + " ERROR de Conexion al Dispositivo" + Environment.NewLine); timer1.Change(300000, Timeout.Infinite); //Re intento a los 5 minutos } }
public void GetUser() { //judge whether the device supports 9.0 fingerprint arithmetic string sOption = "~ZKFPVersion"; string sValue = ""; string idwEnrollNumber = ""; string sName = ""; string sPassword = ""; int iPrivilege = 0; bool bEnabled = false; int idwFigerIndex; string sTmpData = ""; int iTmpLength = 0; int iUpdateFlag = 1; sdk.EnableDevice(iMachineNumber, false); sdk.ReadAllUserID(iMachineNumber); //read all the user information to the memory // sdk.ReadAllTemplate(iMachineNumber);//read all the users' fingerprint templates to the memory sdk.ReadAllTemplate(iMachineNumber); var count = 0; while (sdk.SSR_GetAllUserInfo(iMachineNumber, out idwEnrollNumber, out sName, out sPassword, out iPrivilege, out bEnabled))//get all the users' information from the memory { var sb = sName.Split('\0'); users.Add(idwEnrollNumber.ToString(), sb[0]); count++; } sdk.EnableDevice(iMachineNumber, true); log._logger.Info($"得到{count}个用户"); }
private static int GetNumOfRecords(CZKEMClass axCZKEM1, int iMachineNumber, int idwErrorCode) { int num = 0; axCZKEM1.EnableDevice(iMachineNumber, false); if (!axCZKEM1.GetDeviceStatus(iMachineNumber, 6, ref num)) { axCZKEM1.GetLastError(ref idwErrorCode); Console.WriteLine(string.Concat("Operation failed,ErrorCode=", idwErrorCode.ToString()), "Error"); } else { Console.WriteLine(string.Concat("The count of the AttLogs in the device is ", num.ToString()), "Success"); } axCZKEM1.EnableDevice(iMachineNumber, true); return(idwErrorCode); }
private void Btn_Download_Click(object sender, EventArgs e) { result.AppendText(DateTime.Now.ToString() + " " + "Trying to download Log"); result.AppendText(Environment.NewLine); string sdwEnrollNumber = ""; int idwVerifyMode = 0; int idwInOutMode = 0; int idwYear = 0; int idwMonth = 0; int idwDay = 0; int idwHour = 0; int idwMinute = 0; int idwSecond = 0; int idwWorkcode = 0; int idwErrorCode = 0; int iGLCount = 0; try { myCZKEMClass.EnableDevice(iMachineNumber, false); //disable the device if (myCZKEMClass.ReadGeneralLogData(iMachineNumber)) //read all the attendance records to the memory { while (myCZKEMClass.SSR_GetGeneralLogData(iMachineNumber, out sdwEnrollNumber, out idwVerifyMode, out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour, out idwMinute, out idwSecond, ref idwWorkcode))//get records from the memory { string line; line = iGLCount.ToString() + " | " + sdwEnrollNumber + " | " + idwVerifyMode.ToString() + " | " + idwInOutMode.ToString() + " | " + idwYear.ToString() + "-" + idwMonth.ToString() + "-" + idwDay.ToString() + " " + idwHour.ToString() + ":" + idwMinute.ToString() + ":" + idwSecond.ToString() + " | " + idwWorkcode.ToString(); iGLCount++; result.AppendText(line); result.AppendText(Environment.NewLine); } } else { myCZKEMClass.GetLastError(ref idwErrorCode); if (idwErrorCode != 0) { result.AppendText("Reading data from terminal failed,ErrorCode: " + idwErrorCode.ToString()); result.AppendText(Environment.NewLine); } else { result.AppendText("No data from terminal returns!"); result.AppendText(Environment.NewLine); } } } catch (Exception ex) { result.AppendText("Error" + ex.ToString()); result.AppendText(Environment.NewLine); } finally { myCZKEMClass.EnableDevice(iMachineNumber, true); } }
//Download the attendance records from the device(For both Black&White and TFT screen devices). internal IList <TimeReportEntry> ReadTimeReports(DateTime from) { if (_bIsConnected == false) { throw new Exception("Please connect the att device first"); } if (!_axCZKEM1.EnableDevice(_iMachineNumber, false))//disable the device { throw new Exception("Unable to disable device"); } IList <TimeReportEntry> trrList; try { trrList = ReadTimeReportsInternal(from); Logger.LoggerInstance.log.Debug($"Retrived {trrList.Count} records from Date {from}"); } catch (Exception ex) { throw; } finally { if (!_axCZKEM1.EnableDevice(_iMachineNumber, true))//enable the device { throw new Exception("Unable to enable device"); } } if (trrList.Count == 0) { throw new Exception("No records to sync found in att"); } return(trrList); }
public void ReadUsers() { if (!_isConnected) { return; } _usersList.Clear(); Service.EnableDevice(MachineNumber, false); Service.ReadAllUserID(MachineNumber); String enrollNumber, name, password, tmpData; int privilege, flag, tmpLength; bool enabled; while (Service.SSR_GetAllUserInfo(MachineNumber, out enrollNumber, out name, out password, out privilege, out enabled)) { var user = new UserInfo { EnrollNumber = enrollNumber, Name = name, Password = password, Privilege = privilege, Enabled = enabled, FingerPrints = new List <FingerPrint>() }; _usersList.Add(user); for (var idwFingerIndex = 0; idwFingerIndex < 10; idwFingerIndex++) { if (Service.GetUserTmpExStr(MachineNumber, enrollNumber, idwFingerIndex, out flag, out tmpData, out tmpLength))//get the corresponding templates string and length from the memory { user.FingerPrints.Add(new FingerPrint { Finger = idwFingerIndex, Data = tmpData }); } } } Service.ReadAllUserID(MachineNumber); //read all the user information to the memory Service.ReadAllTemplate(MachineNumber); //read all the users' fingerprint templates to the memory Service.EnableDevice(MachineNumber, true); }
internal string getEmployeeFingerprintDetails(string EmployeeID) { string byTmpData = ""; if (IsConnect == true) { int FingerIndex = 0; int iFlag = 0; int iTmpLength = 0; ZkFingerprint.EnableDevice(iMachineNumber, false); ZkFingerprint.ReadAllTemplate(iMachineNumber); ZkFingerprint.GetUserTmpExStr(iMachineNumber, EmployeeID, FingerIndex, out iFlag, out byTmpData, out iTmpLength); ZkFingerprint.RefreshData(iMachineNumber);//the data in the device should be refreshed ZkFingerprint.EnableDevice(iMachineNumber, true); } return(byTmpData); }
private void btnHapus_Click(object sender, EventArgs e) { try { Cursor.Current = Cursors.WaitCursor; var pegawai = fp.pegawais.Where(x => x.pegawai_id == pegawai_id).FirstOrDefault(); if (pegawai != null) { if (MessageBox.Show(String.Format("Anda akan menghapus data pegawai\n\"{0} {1}\"", txtNIP.Text, txtNama.Text), "Konfirmasi", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { foreach (DataGridViewRow row in dgPegawai.SelectedRows) { Cursor.Current = Cursors.WaitCursor; if (sincron == true) { bool bIsConnected = false; int iMachineNumber = 1; int idwErrorCode = 0; var mesin = fp.mesins.ToList(); int no = 1; foreach (var msn in mesin) { bIsConnected = axCZKEM1.Connect_Net(msn.mesin_ip.Trim(), Convert.ToInt32(msn.mesin_key.Trim())); if (bIsConnected == true) { iMachineNumber = no; axCZKEM1.RegEvent(iMachineNumber, 65535); axCZKEM1.EnableDevice(iMachineNumber, false); if (axCZKEM1.SSR_DeleteEnrollData(iMachineNumber, pegawai_id, 12)) { axCZKEM1.RefreshData(iMachineNumber); fp.pegawais.Remove(pegawai); fp.SaveChanges(); GetData(); } else { if (axCZKEM1.SSR_DeleteEnrollData(iMachineNumber, pegawai_id, 11)) { axCZKEM1.RefreshData(iMachineNumber); fp.pegawais.Remove(pegawai); fp.SaveChanges(); GetData(); } else { if (axCZKEM1.SSR_DeleteEnrollData(iMachineNumber, pegawai_id, 10)) { axCZKEM1.RefreshData(iMachineNumber); fp.pegawais.Remove(pegawai); fp.SaveChanges(); GetData(); } else { if (axCZKEM1.SSR_DeleteEnrollData(iMachineNumber, pegawai_id, 6)) { axCZKEM1.RefreshData(iMachineNumber); fp.pegawais.Remove(pegawai); fp.SaveChanges(); GetData(); } else { axCZKEM1.GetLastError(ref idwErrorCode); MessageBox.Show("Operation failed,ErrorCode=" + idwErrorCode.ToString(), "Error"); } } } } } else { axCZKEM1.GetLastError(ref idwErrorCode); MessageBox.Show("Unable to connect the device,ErrorCode=" + idwErrorCode.ToString(), "Error"); } no += 1; axCZKEM1.EnableDevice(iMachineNumber, true); axCZKEM1.Disconnect(); } } else { fp.pegawais.Remove(pegawai); fp.SaveChanges(); GetData(); } } } } GroupAksi(true, ""); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void bwPosting_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { bool bIsConnected = false; int idwErrorCode = 0; lblProses.Invoke(new Action(() => lblProses.Text = "Mengambil data mesin")); var mesin = fp.mesins.ToList(); int no = 1; int jumlah = 0; foreach (var msn in mesin) { progressBar.Value = 0; bwDownload.ReportProgress(0); lblProses.Invoke(new Action(() => lblProses.Text = "Melakukan koneksi ke mesin " + msn.mesin_nama + ", IP " + msn.mesin_ip + ", port " + msn.mesin_key)); bIsConnected = axCZKEM1.Connect_Net(msn.mesin_ip.Trim(), Convert.ToInt32(msn.mesin_key.Trim())); if (bIsConnected == false) { axCZKEM1.GetLastError(ref idwErrorCode); lblProses.Invoke(new Action(() => lblProses.Text = "Koneksi ke mesin " + msn.mesin_nama + ", IP " + msn.mesin_ip + ", port " + msn.mesin_key + " GAGAL " + idwErrorCode.ToString())); gagal.Add("gagal"); } else { iMachineNumber = no; axCZKEM1.RegEvent(iMachineNumber, 65535); string sdwEnrollNumber = ""; int idwVerifyMode = 0; int idwInOutMode = 0; int idwYear = 0; int idwMonth = 0; int idwDay = 0; int idwHour = 0; int idwMinute = 0; int idwSecond = 0; int idwWorkcode = 0; int iValue = 400; axCZKEM1.EnableDevice(iMachineNumber, false); lblProses.Invoke(new Action(() => lblProses.Text = "Menghitung jumlah data absensi")); if (!axCZKEM1.GetDeviceStatus(iMachineNumber, 6, ref iValue)) { axCZKEM1.GetLastError(ref idwErrorCode); lblProses.Invoke(new Action(() => lblProses.Text = "Operation failed,ErrorCode=" + idwErrorCode.ToString())); e.Cancel = true; return; } lblProses.Invoke(new Action(() => lblProses.Text = "Mendownload " + iValue.ToString() + " data absensi")); if (axCZKEM1.ReadAllGLogData(iMachineNumber)) { var pegawai = fp.pegawais.ToList(); int nomor = 1; while (axCZKEM1.SSR_GetGeneralLogData(iMachineNumber, out sdwEnrollNumber, out idwVerifyMode, out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour, out idwMinute, out idwSecond, ref idwWorkcode)) { try { if (pegawai.Where(s => s.pegawai_id.Equals(sdwEnrollNumber)).Count() > 0) { log data = new log(); data.pegawai_id = sdwEnrollNumber; data.log_tanggal = DateTime.Parse(idwYear + "-" + idwMonth + "-" + idwDay); data.log_jam = TimeSpan.Parse(idwHour + ":" + idwMinute + ":" + idwSecond); data.log_kode = idwVerifyMode.ToString(); data.log_status = idwInOutMode.ToString(); fp.logs.Add(data); lblProses.Invoke(new Action(() => lblProses.Text = "Menyimpan data ke " + nomor + "/" + iValue + " ID " + sdwEnrollNumber + ", tanggal " + idwYear + "-" + idwMonth + "-" + idwDay + ", waktu " + idwHour + ":" + idwMinute + ":" + idwSecond + " status " + idwInOutMode.ToString() + ", BERHASIL")); jumlah += 1; } } catch (Exception ex) { gagal.Add("ID " + sdwEnrollNumber + ", tanggal " + idwYear + "-" + idwMonth + "-" + idwDay + ", waktu " + idwHour + ":" + idwMinute + ":" + idwSecond + " status " + idwInOutMode.ToString() + " ke " + nomor + "/" + iValue); lblProses.Invoke(new Action(() => lblProses.Text = "Menyimpan data ke " + nomor + "/" + iValue + " ID " + sdwEnrollNumber + ", tanggal " + idwYear + "-" + idwMonth + "-" + idwDay + ", waktu " + idwHour + ":" + idwMinute + ":" + idwSecond + " status " + idwInOutMode.ToString() + ", GAGAL " + ex.Message)); } fp.SaveChanges(); int percentage = nomor * 100 / iValue; nomor++; bwDownload.ReportProgress(percentage); } if (axCZKEM1.ClearGLog(iMachineNumber)) { axCZKEM1.RefreshData(iMachineNumber); lblProses.Invoke(new Action(() => lblProses.Text = "Menghapus Data absen di mesin")); } else { axCZKEM1.GetLastError(ref idwErrorCode); lblProses.Invoke(new Action(() => lblProses.Text = "Operation failed,ErrorCode=" + idwErrorCode.ToString())); } } else { Cursor = Cursors.Default; axCZKEM1.GetLastError(ref idwErrorCode); if (idwErrorCode != 0) { lblProses.Invoke(new Action(() => lblProses.Text = "Reading data from terminal failed,ErrorCode: " + idwErrorCode.ToString().ToString())); } else { lblProses.Invoke(new Action(() => lblProses.Text = "No data from terminal returns!")); } } no += 1; axCZKEM1.EnableDevice(iMachineNumber, true); axCZKEM1.Disconnect(); } } if (gagal.Count > 0) { lblProses.Invoke(new Action(() => lblProses.Text = "Gagal mendownload " + gagal.Count + " data absensi")); MessageBox.Show("Gagal mendownload " + gagal.Count + " data absensi"); e.Cancel = true; } else { lblProses.Invoke(new Action(() => lblProses.Text = "Berhasil mendownload " + jumlah.ToString() + " data absensi dari mesin")); MessageBox.Show("Berhasil mendownload " + jumlah.ToString() + " data absensi dari mesin"); } }
private void ImportRecords(CZKEMClass axCZKEM1, int iMachineNumber, string con) { string str = ""; int num = 0, num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, num6 = 0, num7 = 0, num8 = 0, num9 = 0, num10 = 0; List <linie> ListReccords = new List <linie>(); List <linie> ListReccordsImported = new List <linie>(); HashSet <ulong> HSetImportedKeys = new HashSet <ulong>(); SqlConnection sqlConnection0 = new SqlConnection(con); sqlConnection0.Open(); string str2 = string.Concat(new string[] { "select year(DATAORA),MONTH(DATAORA),DAY(DATAORA), DATEPART(Hh, DATAORA), DATEPART(n, DATAORA), DATEPART(s, DATAORA) FROM ATTLOG" }); SqlCommand sqlCommand1 = new SqlCommand(str2, sqlConnection0); SqlDataReader reader = sqlCommand1.ExecuteReader(); this.msg = string.Concat(msg, @"<br /> reader ok (already imported keys) "); bool hr = reader.HasRows; int year = 0, month = 0; if (hr) { while (reader.Read()) { linie ir = new linie(); ir.num2 = reader.GetInt32(0); ir.num3 = reader.GetInt32(1); ir.num4 = reader.GetInt32(2); ir.num5 = reader.GetInt32(3); ir.num6 = reader.GetInt32(4); ir.num7 = reader.GetInt32(5); ulong key = (ulong)(ir.num2 * 10000000000 + ir.num3 * 100000000 + ir.num4 * 1000000 + ir.num5 * 10000 + ir.num6 * 100 + ir.num7 * 1); if (year * 100 + month < ir.num2 * 100 + ir.num3) { year = ir.num2; month = ir.num3; } HSetImportedKeys.Add(key); } } this.msg = string.Concat(msg, @"<br /> Already imported keys loaded "); reader.Close(); //this.msg = string.Concat(msg, @"<br /> reader closed "); month -= 6; if (month < 1) { month = +12; year--; } sqlConnection0.Close(); int n1 = 0; bool ok; string strConn = ConfigurationManager.ConnectionStrings["IP"].ConnectionString; ok = conectToDevice(strConn, axCZKEM1, ref n1); if (ok) { axCZKEM1.EnableDevice(iMachineNumber, false); bool flag = axCZKEM1.ReadLastestLogData(iMachineNumber, 1, year, month, 1, 0, 0, 0); this.msg = string.Concat(msg, @"<br /> read finished"); axCZKEM1.EnableDevice(iMachineNumber, true); if (flag) { SqlConnection sqlConnection = new SqlConnection(con); try { while (axCZKEM1.SSR_GetGeneralLogData(iMachineNumber, out str, out num, out num1, out num2, out num3, out num4, out num5, out num6, out num7, ref num8)) { num9++; linie l = new linie(); l.str = str; l.num = num; l.num1 = num1; l.num2 = num2; l.num3 = num3; l.num4 = num4; l.num5 = num5; l.num6 = num6; l.num7 = num7; l.num8 = num8; l.num9 = num9; l.num10 = num10; num10++; ulong key = (ulong)(l.num2 * 10000000000 + l.num3 * 100000000 + l.num4 * 1000000 + l.num5 * 10000 + l.num6 * 100 + l.num7 * 1); bool ex = HSetImportedKeys.Contains(key); if (!ex) { ListReccords.Add(l); } } axCZKEM1.Disconnect(); this.msg = string.Concat(msg, @"<br /> New log list ready, device disconnected! "); if (!ListReccords.Any()) { this.msg = string.Concat(msg, @"<br /> Log list empty. Nothing to import! "); return; } sqlConnection.Open(); this.msg = string.Concat(msg, @"<br /> Connection Open ! (SQL) "); foreach (linie li in ListReccords) { str = li.str; num = li.num; num1 = li.num1; num2 = li.num2; num3 = li.num3; num4 = li.num4; num5 = li.num5; num6 = li.num6; num7 = li.num7; num8 = li.num8; num9 = li.num9; num10 = li.num10; string str1 = string.Concat(new string[] { "INSERT INTO ATTLOG (MARCA,DATAORA,TIP) VALUES (", str, ",'", num2.ToString(), "-", num3.ToString().PadLeft(2, '0'), "-", num4.ToString().PadLeft(2, '0'), " ", num5.ToString(), ":", num6.ToString(), ":", num7.ToString(), "',", num1.ToString(), ") " }); string strMsg = string.Concat(new string[] { @"<br /> -->", str, ",'", num2.ToString(), "-", num3.ToString().PadLeft(2, '0'), "-", num4.ToString().PadLeft(2, '0'), " ", num5.ToString(), ":", num6.ToString(), ":", num7.ToString(), "',", num1.ToString() }); SqlCommand sqlCommand = new SqlCommand(str1, sqlConnection); if (num2 * 10000 + num3 * 100 + num4 > 20161103) { Console.WriteLine(str1); try { sqlCommand.ExecuteNonQuery(); this.msg = string.Concat(msg, strMsg); } catch (Exception exception) { this.msg = string.Concat(msg, exception.Message.ToString()); } } } sqlConnection.Close(); msg = string.Concat(msg, @"<br /> Connection closed (SQL)"); } catch (Exception exception2) { Exception exception1 = exception2; this.msg = string.Concat(msg, @"<br />Can not open connection ! "); this.msg = string.Concat(msg, exception1.Message.ToString()); } } } }
protected void BtnDescargar_Click(object sender, EventArgs e) { log.Info(String.Format("El usuario [{0}] presiono el boton para descargar la plantilla del Control de Acceso con ID: [{1}]", UsuarioActual.Nombre, txtControlAcceso.SelectedValue)); // Validar si se selecciono un control de acceso if (!ValidarObjeto(txtControlAcceso.SelectedValue)) { MostrarAdvertencia(Constantes.MENSAJE_CAMPO_REQUERIDO_TITULO, "Por favor seleccione un control del listado"); return; } ControlAcceso control = null; try { control = controlAccesoDao.GetById(Int32.Parse(txtControlAcceso.SelectedValue)); } catch (Exception ex) { log.Error(String.Format("Error en el Proceso de Conexion con el control. Mensaje: [{0}]", ex.Message)); ManejarExcepcion(ex); } if (control == null) { MostrarAdvertencia("Control de Acceso No Encontrado", String.Format("No fue Posible encontrar el Control de Acceso con identificador [0]", txtControlAcceso.SelectedValue)); return; } // Variables de cajon int iMachineNumber = 1; string sdwEnrollNumber = Constantes.TEXTO_BLANCO; string sName = Constantes.TEXTO_BLANCO; string sPassword = Constantes.TEXTO_BLANCO; int iPrivilege = 0; bool bEnabled = false; int idwErrorCode = 0; int idwFingerIndex; string sTmpData = Constantes.TEXTO_BLANCO; int iTmpLength = 0; int iFlag = 0; try { log.Info(String.Format("Se Intentará conectar con el control de acceso con ID: [{0}]. El control tiene la direccion ip: [{1}] y el puerto: [{2}]", txtControlAcceso.SelectedValue, control.DireccionIp, control.Puerto)); CZKEMClass _control = new CZKEMClass(); if (_control.Connect_Net(control.DireccionIp, Int32.Parse(control.Puerto.Value.ToString()))) { log.Info(String.Format("Se logro correctamente la conexion con el control con direccion ip: [{0}] y el puerto: [{1}]", control.DireccionIp, control.Puerto)); _control.EnableDevice(iMachineNumber, false); _control.ReadAllUserID(iMachineNumber); //read all the user information to the memory _control.ReadAllTemplate(iMachineNumber); //read all the users' fingerprint templates to the memory while (_control.SSR_GetAllUserInfo(iMachineNumber, out sdwEnrollNumber, out sName, out sPassword, out iPrivilege, out bEnabled))//get all the users' information from the memory { log.Info(String.Format("Se obtienen los datos iMachineNumber: [{0}], sdwEnrollNumber: [{1}], sName: [{2}], sPassword: [{3}], iPrivilege: [{4}], bEnabled: [{5}]", iMachineNumber, sdwEnrollNumber, sName, sPassword, iPrivilege, bEnabled)); for (idwFingerIndex = 0; idwFingerIndex < 10; idwFingerIndex++) { if (_control.GetUserTmpExStr(iMachineNumber, sdwEnrollNumber, idwFingerIndex, out iFlag, out sTmpData, out iTmpLength))//get the corresponding templates string and length from the memory { log.Info(String.Format("Se obtienen los datos idwFingerIndex: [{0}], iFlag: [{1}], sTmpData: [{2}], iTmpLength: [{3}]", idwFingerIndex, iFlag, sTmpData, iTmpLength)); try { DbDominio.Plantilla planti = plantillaDao.GetByControlAccesoEnrollNumberFingerIndex(control, sdwEnrollNumber, idwFingerIndex); if (planti == null) { planti = new DbDominio.Plantilla(); planti.ControlAcceso = control; planti.Usuario_creado_por = UsuarioActual; log.Info("Se creará una plantilla nueva a partir de estos datos"); } else { log.Info("Esta es una plantilla nueva que se insertara"); } planti.FechaModificacion = DateTime.Now; planti.Usuario_modificado_por = UsuarioActual; planti.Enabled = bEnabled; planti.Enrollnumber = sdwEnrollNumber; planti.Fingerindex = idwFingerIndex; planti.Flag = iFlag; planti.IpControlTemplate = control.DireccionIp; planti.Nombre = sName; planti.Password = sPassword; planti.Privilege = iPrivilege; planti.Status = true; planti.Tmpdata = sTmpData; plantillaDao.SaveOrUpdate(planti); try { Empleado empleado = empleadoDao.GetByNumeroEmpleado(Int32.Parse(sdwEnrollNumber)); if (empleado != null && control != null) { EmpleadoControlAcceso eca = empleadoControlAccesoDao.GetByControlAcceso(control, empleado); if (eca == null) { eca = new EmpleadoControlAcceso(); } eca.CveEmpleado = empleado.CveEmpleado; eca.CveControlAcceso = control.CveControlAcceso; eca.ControlAcceso = control; eca.Empleado = empleado; empleadoControlAccesoDao.SaveOrUpdate(eca); } } catch (Exception ex) { log.Error(String.Format("Error en el Proceso Guardar Empleado Control de Acceso en la base de Datos. Mensaje: [{0}]", ex.Message)); log.Error(ex); } } catch (Exception ex) { log.Error(String.Format("Error en el Proceso Guardar Plantilla en la base de Datos. Mensaje: [{0}]", ex.Message)); log.Error(ex); } } } } _control.Disconnect(); MostrarExito("Proceso Completo", "Se completo el proceso exitosamente"); } else { _control.GetLastError(ref idwErrorCode); log.Error(String.Format("Error en el Proceso de Conexion al control con ID [{0}], Direccion IP [{1}] y Puerto [{2}]. Codigo de Error [{3}]", control.IdControl, control.DireccionIp, control.Puerto, idwErrorCode)); MostrarExcepcion("Conexion Invalida", String.Format("Error en el Proceso de Conexion con el Control con Direccion IP: {0} y Puerto {1}", control.DireccionIp, control.Puerto)); } } catch (Exception ex) { log.Error(String.Format("Error en el Proceso de Conexion con el control. Mensaje: [{0}]", ex.Message)); ManejarExcepcion(ex); } }
public List <Record> getAllLogData() { List <Record> records = new List <Record>(); if (!open()) { return(records); } int idwErrorCode = 0; string sdwEnrollNumber = ""; int idwVerifyMode = 0; int idwInOutMode = 0; int idwYear = 0; int idwMonth = 0; int idwDay = 0; int idwHour = 0; int idwMinute = 0; int idwSecond = 0; int idwWorkcode = 0; axCZKEM1.EnableDevice(iMachineNumber, false); //disable the device if (axCZKEM1.ReadGeneralLogData(iMachineNumber)) //read all the attendance records to the memory { while (axCZKEM1.SSR_GetGeneralLogData(iMachineNumber, out sdwEnrollNumber, out idwVerifyMode, out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour, out idwMinute, out idwSecond, ref idwWorkcode))//get records from the memory { string hour = idwHour.ToString(), min = idwMinute.ToString(); if (hour.Length == 1) { hour = "0" + hour; } if (min.Length == 1) { min = "0" + min; } Record record = new Record(int.Parse(sdwEnrollNumber), idwMonth.ToString() + "/" + idwDay.ToString() + "/" + idwYear.ToString(), hour + "." + min); records.Add(record); } axCZKEM1.EnableDevice(iMachineNumber, true);//enable the device axCZKEM1.Disconnect(); return(records); } else { axCZKEM1.GetLastError(ref idwErrorCode); if (idwErrorCode != 0) { NotificationHelper.CreateNotification("Reading data from terminal failed,ErrorCode: " + idwErrorCode.ToString()); FileHelper.writeToLog("Reading data from terminal failed,ErrorCode: " + idwErrorCode.ToString(), "Error"); } else { NotificationHelper.CreateNotification("No data from terminal returns!"); FileHelper.writeToLog("No data from terminal returns!", "Error"); } } return(null); }
public void EnableDevice(bool state) { CheckConnection(); ZApi.EnableDevice(MachineId, state); }
protected void BtnAceptar_Click(object sender, EventArgs e) { // Validamos que se haya seleccionado un control fuente if (!ValidarObjeto(txtPlantilla.SelectedValue)) { MostrarExcepcion(Constantes.MENSAJE_CAMPO_REQUERIDO_TITULO, "Es requerido Seleccionar la plantilla fuente"); return; } // Validamos que se haya seleccionado un control de destino if (!ValidarObjeto(txtControlDestino.SelectedValue)) { MostrarExcepcion(Constantes.MENSAJE_CAMPO_REQUERIDO_TITULO, "Es requerido Seleccionar el Control de Acceso de destino"); return; } // Validamos que el control de destino no sea el mismo que el seleccionado en la fuente if (txtControlDestino.SelectedValue.Equals(txtPlantilla.SelectedValue)) { MostrarExcepcion(Constantes.MENSAJE_CAMPO_CON_ERROR_TITULO, "El Control de Acceso de Destino es el Mismo que el de la fuente de Datos"); } // Obtenemos y validamos el control fuente ControlAcceso controlFuente = null; try { controlFuente = controlAccesoDao.GetById(Int32.Parse(txtPlantilla.SelectedValue)); } catch (Exception ex) { log.Error(String.Format("Error en el Proceso Obtener Control Fuente. Mensaje: [{0}]", ex.Message)); ManejarExcepcion(ex); } if (controlFuente == null) { MostrarExcepcion(Constantes.MENSAJE_CAMPO_CON_ERROR_TITULO, "El control fuente es nulo"); return; } // Obtenemos y validamos el control de destino ControlAcceso controlDestino = null; try { controlDestino = controlAccesoDao.GetById(Int32.Parse(txtControlDestino.SelectedValue)); } catch (Exception ex) { log.Error(String.Format("Error en el Proceso Obtener Control Destino. Mensaje: [{0}]", ex.Message)); ManejarExcepcion(ex); } if (controlDestino == null) { MostrarExcepcion(Constantes.MENSAJE_CAMPO_CON_ERROR_TITULO, "El control de destino es nulo"); return; } // Obtenemos y validamos la lista de plantillas a cargar List <DbDominio.Plantilla> listaPlantilla = null; try { listaPlantilla = plantillaDao.GetListado(null, controlFuente); } catch (Exception ex) { log.Error(String.Format("Error en el Proceso Obtener La plantilla desde el Control Fuente. Mensaje: [{0}]", ex.Message)); ManejarExcepcion(ex); } if (listaPlantilla == null || listaPlantilla.Count == 0) { MostrarExcepcion(Constantes.MENSAJE_CAMPO_CON_ERROR_TITULO, "La plantilla seleccionada es nula o vacia"); return; } // Al parecer todo va bien, iniciarmos el proceso int idwErrorCode = 0; string sdwEnrollNumber = Constantes.TEXTO_BLANCO; string sName = Constantes.TEXTO_BLANCO; int idwFingerIndex = 0; string sTmpData = Constantes.TEXTO_BLANCO; int iPrivilege = 0; string sPassword = Constantes.TEXTO_BLANCO; bool bEnabled = false; int iFlag = 1; int iUpdateFlag = 1; int iMachineNumber = 1; try { log.Info(String.Format("Se Intentará conectar con el control de acceso con ID: [{0}]. El control tiene la direccion ip: [{1}] y el puerto: [{2}]", txtControlDestino.SelectedValue, controlDestino.DireccionIp, controlDestino.Puerto)); CZKEMClass _control = new CZKEMClass(); // _control.PullMode = 1; if (_control.Connect_Net(controlDestino.DireccionIp, Int32.Parse(controlDestino.Puerto.Value.ToString()))) { log.Info(String.Format("Se logro correctamente la conexion con el control con direccion ip: [{0}] y el puerto: [{1}]", controlDestino.DireccionIp, controlDestino.Puerto)); _control.RegEvent(iMachineNumber, 65535); _control.EnableDevice(iMachineNumber, false); if (_control.BeginBatchUpdate(iMachineNumber, iUpdateFlag))//create memory space for batching data { log.Info(String.Format("Inicia el Proceso BeginBatchUpdate Con ImachineNumber : [{0}] iUpdateFlag: [{1}]", iMachineNumber, iUpdateFlag)); string sLastEnrollNumber = "";//the former enrollnumber you have upload(define original value as 0) foreach (DbDominio.Plantilla planti in listaPlantilla) { sdwEnrollNumber = planti.Enrollnumber; sName = planti.Nombre; idwFingerIndex = planti.Fingerindex != null ? planti.Fingerindex.Value : 0; sTmpData = planti.Tmpdata; iPrivilege = planti.Privilege != null ? planti.Privilege.Value : 0; sPassword = planti.Password; bEnabled = planti.Enabled != null ? planti.Enabled.Value : false; iFlag = planti.Flag != null ? planti.Flag.Value : 1; log.Info(String.Format("Se Carga la Siguiente sdwEnrollNumber: [{0}] sName: [{1}], idwFingerIndex: [{2}], sTmpData: [{3}], iPrivilege : [{4}], sPassword : [{5}], bEnabled : [{6}], iFlag: [{7}]", sdwEnrollNumber, sName, idwFingerIndex, sTmpData, iPrivilege, sPassword, bEnabled, iFlag)); if (sdwEnrollNumber != sLastEnrollNumber) //identify whether the user information(except fingerprint templates) has been uploaded { if (_control.SSR_SetUserInfo(iMachineNumber, sdwEnrollNumber, sName, sPassword, iPrivilege, bEnabled)) //upload user information to the memory { log.Info(String.Format("Se Completa El ProcesoS SR_SetUserInfo con la siguiente Informacion_ iMachineNumber [{0}] sdwEnrollNumber: [{1}] sName: [{2}], sPassword: [{3}], iPrivilege : [{4}], bEnabled: [{5}]", iMachineNumber, sdwEnrollNumber, sName, sPassword, iPrivilege, bEnabled)); _control.SetUserTmpExStr(iMachineNumber, sdwEnrollNumber, idwFingerIndex, iFlag, sTmpData);//upload templates information to the memory log.Info(String.Format("Se Completa El Proceso SetUserTmpExStr con la siguiente Informacion_ iMachineNumber [{0}] sdwEnrollNumber: [{1}] idwFingerIndex: [{2}], iFlag: [{3}], sTmpData : [{4}]", iMachineNumber, sdwEnrollNumber, idwFingerIndex, iFlag, sTmpData)); } else { _control.GetLastError(ref idwErrorCode); _control.EnableDevice(iMachineNumber, true); log.Error(String.Format("Error en el Proceso Distribuir La plantilla Al Control de Destino. Codigo de Error: [{0}]", idwErrorCode)); MostrarExcepcion("Error en el proceso", String.Format("Error en el Proceso Distribuir La plantilla Al Control de Destino. Codigo de Error: [{0}]", idwErrorCode)); return; } } else { _control.SetUserTmpExStr(iMachineNumber, sdwEnrollNumber, idwFingerIndex, iFlag, sTmpData); log.Info(String.Format("Se Completa El Proceso SetUserTmpExStr (sdwEnrollNumber != sLastEnrollNumber) con la siguiente Informacion_ iMachineNumber [{0}] sdwEnrollNumber: [{1}] idwFingerIndex: [{2}], iFlag: [{3}], sTmpData : [{4}]", iMachineNumber, sdwEnrollNumber, idwFingerIndex, iFlag, sTmpData)); } sLastEnrollNumber = sdwEnrollNumber; try { Empleado empleado = empleadoDao.GetByNumeroEmpleado(Int32.Parse(sdwEnrollNumber)); if (empleado != null && controlDestino != null) { EmpleadoControlAcceso eca = empleadoControlAccesoDao.GetByControlAcceso(controlDestino, empleado); if (eca == null) { eca = new EmpleadoControlAcceso(); } eca.ControlAcceso = controlDestino; eca.Empleado = empleado; empleadoControlAccesoDao.SaveOrUpdate(eca); } } catch (Exception ex) { log.Error(String.Format("Error en el Proceso Guardar Empleado Control de Acceso en la base de Datos. Mensaje: [{0}]", ex.Message)); log.Error(ex); } } } _control.BatchUpdate(iMachineNumber); //upload all the information in the memory _control.RefreshData(iMachineNumber); //the data in the device should be refreshed _control.EnableDevice(iMachineNumber, true); _control.Disconnect(); MostrarExito("Proceso Completo", "Se completo el proceso exitosamente"); } else { _control.GetLastError(ref idwErrorCode); log.Error(String.Format("Error en el Proceso de Conexion al control con ID [{0}], Direccion IP [{1}] y Puerto [{2}]. Codigo de Error [{3}]", controlDestino.IdControl, controlDestino.DireccionIp, controlDestino.Puerto, idwErrorCode)); MostrarExcepcion("Conexion Invalida", String.Format("Error en el Proceso de Conexion con el Control con Direccion IP: {0} y Puerto {1}", controlDestino.DireccionIp, controlDestino.Puerto)); } } catch (Exception ex) { log.Error(String.Format("Error en el Proceso de Conexion con el control. Mensaje: [{0}]", ex.Message)); ManejarExcepcion(ex); } }
private void bwPosting_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { try { bool bIsConnected = false; int idwErrorCode = 0; lblProses.Invoke(new Action(() => lblProses.Text = "Mengambil data mesin")); var mesin = fp.mesins.ToList(); int no = 1; int jumlah = 0; foreach (var msn in mesin) { progressBar.Value = 0; bwDownload.ReportProgress(0); lblProses.Invoke(new Action(() => lblProses.Text = "Melakukan koneksi ke mesin " + msn.mesin_nama + ", IP " + msn.mesin_ip + ", port " + msn.mesin_key)); bIsConnected = axCZKEM1.Connect_Net(msn.mesin_ip, Convert.ToInt32(msn.mesin_key)); if (bIsConnected == false) { axCZKEM1.GetLastError(ref idwErrorCode); lblProses.Invoke(new Action(() => lblProses.Text = "Koneksi ke mesin " + msn.mesin_nama + ", IP " + msn.mesin_ip + ", port " + msn.mesin_key + " GAGAL " + idwErrorCode.ToString())); gagal.Add("gagal"); } else { iMachineNumber = no; axCZKEM1.RegEvent(iMachineNumber, 65535); int iUpdateFlag = 1; axCZKEM1.EnableDevice(iMachineNumber, false); if (axCZKEM1.BeginBatchUpdate(iMachineNumber, iUpdateFlag))//create memory space for batching data { string sdwEnrollNumber = ""; string nip = ""; string sName = ""; int idwFingerIndex = 0; string sTmpData = ""; int iPrivilege = 0; string sPassword = ""; bool bEnabled = true; int iFlag = 1; lblProses.Invoke(new Action(() => lblProses.Text = "Mengambil data pegawai")); var pegawai = fp.pegawais.ToList(); string sLastEnrollNumber = "";//the former enrollnumber you have upload(define original value as 0) var nomor = 1; int iValue = pegawai.Count(); foreach (var row in pegawai) { sdwEnrollNumber = row.pegawai_id.ToString(); sName = row.pegawai_panggilan; nip = row.pegawai_nip; iPrivilege = row.pegawai_izin == "0" ? 3 : 0; sPassword = row.pegawai_sandi; if (axCZKEM1.SSR_SetUserInfo(iMachineNumber, sdwEnrollNumber, sName, sPassword, iPrivilege, bEnabled)) { lblProses.Invoke(new Action(() => lblProses.Text = "Mengupload data pegawai " + nip)); var data = fp.pegawais.Where(x => x.pegawai_id.Equals(sdwEnrollNumber)).FirstOrDefault(); data.upload = true; fp.SaveChanges(); jumlah += 1; } else { axCZKEM1.GetLastError(ref idwErrorCode); lblProses.Invoke(new Action(() => lblProses.Text = "Operation failed,ErrorCode=" + idwErrorCode.ToString())); gagal.Add("ID " + sdwEnrollNumber + ", nip " + nip); } int percentage = nomor * 100 / iValue; nomor++; bwDownload.ReportProgress(percentage); } } axCZKEM1.BatchUpdate(iMachineNumber); //upload all the information in the memory axCZKEM1.RefreshData(iMachineNumber); //the data in the device should be refreshed axCZKEM1.EnableDevice(iMachineNumber, true); } no += 1; axCZKEM1.EnableDevice(iMachineNumber, true); axCZKEM1.Disconnect(); } if (gagal.Count > 0) { lblProses.Invoke(new Action(() => lblProses.Text = "Gagal mengupload " + gagal.Count + " data pegawai")); MessageBox.Show("Gagal mendownload " + gagal.Count + " data pegawai"); e.Cancel = true; } else { lblProses.Invoke(new Action(() => lblProses.Text = "Berhasil mengupload " + jumlah.ToString() + " data pegawai ke mesin")); MessageBox.Show("Berhasil mengupload " + jumlah.ToString() + " data pegawai ke mesin"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void UpdateUsers() { GetUsersFromDb(); var n = 0; foreach (var device in Devices(DeviceType.Employee)) { Connect(device); _service.EnableDevice(MachineNumber, false); if (_service.ClearData(MachineNumber, 5)) { _service.RefreshData(MachineNumber); } foreach (var userInfo in UsersInfo) { if (_service.SSR_SetUserInfo(MachineNumber, userInfo.EnrollNumber, userInfo.Name, "", 0, true)) { if (_service.SSR_DeleteEnrollDataExt(MachineNumber, userInfo.EnrollNumber, 11)) { _service.RefreshData(MachineNumber); foreach (var fingerPrint in userInfo.FingerPrints) { if (_service.SetUserTmpExStr(MachineNumber, userInfo.EnrollNumber, fingerPrint.Finger, 1, fingerPrint.Data)) { n++; } } } } } _service.EnableDevice(MachineNumber, true); Disconnect(); } }
public static void iniciarColeccion() { // Variables de Cajon int iMachineNumber = 1; int idwErrorCode = 0; string sdwEnrollNumber = Constantes.TEXTO_BLANCO; int idwVerifyMode = 0; int idwInOutMode = 0; int idwYear = 0; int idwMonth = 0; int idwDay = 0; int idwHour = 0; int idwMinute = 0; int idwSecond = 0; int idwWorkcode = 0; // Variables de acceso a la base de datos IControlAccesoDao controlAccesoDao = daoFactory.GetControlAccesoDao(); IColectorMovimientoDao colectorMovimientoDao = daoFactory.GetColectorMovimientosDao(); IColectorMovimientoIncidenciaDao colectorMovimientoIncidenciaDao = daoFactory.GetColectorMovimientosIncidenciaDao(); IEmpleadoDao empleadoDao = daoFactory.GetEmpleadoDao(); IIncidenciaDao incidenciaDao = daoFactory.GetIncidenciaDao(); logger.Info("PROCESO COLECTOR: Ejecucion automatica de la tarea de coleccion"); List <ControlAcceso> lista = null; try { lista = controlAccesoDao.GetListado(true, null, DbDao.ControlAccesoDao.Ordenamiento.FechaUltimaConexion); } catch (Exception ex) { logger.Error(String.Format("Error al intentar obtener la lista de Controles de Acceso. Detalles: [{0}]", ex.Message), ex); } if (lista != null && lista.Count > 0) { foreach (ControlAcceso control in lista) { logger.Info(String.Format("Procesando control con Nombre: [{0}], Direccion IP: [{1}] y Puerto: [{2}]", control.Nombre, control.DireccionIp, control.Puerto)); try { CZKEMClass _control = new CZKEMClass(); if (_control.Connect_Net(control.DireccionIp, Int32.Parse(control.Puerto.Value.ToString()))) { // Deshabilitanos el control _control.EnableDevice(iMachineNumber, false); logger.Info(String.Format("Conectado al control con Nombre: [{0}], Direccion IP: [{1}] y Puerto: [{2}]", control.Nombre, control.DireccionIp, control.Puerto)); try { control.FechaUltimaConexion = DateTime.Now; controlAccesoDao.SaveOrUpdate(control); } catch (Exception ex) { logger.Warn(String.Format("Error al actualizar la Fecha de Ultima Conexionc del Control con Nombre: [{0}], Direccion IP: [{1}] y Puerto: [{2}]. Codigo de Error: [{3}]", control.Nombre, control.DireccionIp, control.Puerto, idwErrorCode)); logger.Warn(ex); } if (_control.ReadGeneralLogData(iMachineNumber)) { logger.Info(String.Format("Lectura de Datos Generales con EXITO control con Nombre: [{0}], Direccion IP: [{1}] y Puerto: [{2}]", control.Nombre, control.DireccionIp, control.Puerto)); while (_control.SSR_GetGeneralLogData(iMachineNumber, out sdwEnrollNumber, out idwVerifyMode, out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour, out idwMinute, out idwSecond, ref idwWorkcode)) { logger.Info(String.Format("Datos Obtenidos: CveControlAcceso: [{0}], sdwEnrollNumber: [{1}], idwVerifyMode: [{2}], idwInOutMode: [{3}], idwYear: [{4}], idwMonth: [{5}], idwDay: [{6}], idwHour: [{7}], idwMinute: [{8}], idwSecond: [{9}], idwWorkcode: [{10}]", control.CveControlAcceso, sdwEnrollNumber, idwVerifyMode, idwInOutMode, idwYear, idwMonth, idwDay, idwHour, idwMinute, idwSecond, idwWorkcode)); ColectorMovimiento colector = new ColectorMovimiento(control.IdControl, control.CveControlAcceso, sdwEnrollNumber, idwVerifyMode, idwInOutMode, idwYear, idwMonth, idwDay, idwHour, idwMinute, idwSecond, idwWorkcode); ColectorMovimiento up = colectorMovimientoDao.SaveOrUpdate(colector); colector = up; } } else { _control.GetLastError(ref idwErrorCode); if (idwErrorCode != 0) { String strError = String.Format("ERROR de conexion al control con Nombre: [{0}], Direccion IP: [{1}] y Puerto: [{2}]. Codigo de Error [{3}]", control.Nombre, control.DireccionIp, control.Puerto, idwErrorCode); logger.Error(strError); try { ColectorMovimientoIncidencia coleMovIncidencia = new ColectorMovimientoIncidencia(); coleMovIncidencia.ControlAcceso = control; coleMovIncidencia.Detalles = strError; colectorMovimientoIncidenciaDao.Save(coleMovIncidencia); } catch (Exception ex) { logger.Warn(String.Format("No se pudo guardar la incidencia de coleccion de movimientos. Mensaje: [{0}]", ex.Message)); } } else { logger.Info(String.Format("OK. El control Reporta que NO existen movimientos. Datos de conexion son Nombre: [{0}], Direccion IP: [{1}] y Puerto: [{2}]. Codigo de Mensaje: [{3}]", control.Nombre, control.DireccionIp, control.Puerto, idwErrorCode)); } } // Limpiamos el log if (_control.ClearGLog(iMachineNumber)) { _control.RefreshData(iMachineNumber); } else { _control.GetLastError(ref idwErrorCode); logger.Error(String.Format("Error en el Proceso de Limpiar el LOG del Control con Nombre: [{0}], Direccion IP: [{1}] y Puerto: [{2}]. Codigo de Error: [{3}]", control.Nombre, control.DireccionIp, control.Puerto, idwErrorCode)); } _control.EnableDevice(iMachineNumber, true); _control.Disconnect(); } else { _control.GetLastError(ref idwErrorCode); String strError = String.Format("Error en el Proceso de Conexion al control con Nombre: [{0}], Direccion IP: [{1}] y Puerto: [{2}]. Codigo de Error: [{3}]", control.Nombre, control.DireccionIp, control.Puerto, idwErrorCode); logger.Error(strError); try { ColectorMovimientoIncidencia coleMovIncidencia = new ColectorMovimientoIncidencia(); coleMovIncidencia.ControlAcceso = control; coleMovIncidencia.Detalles = strError; colectorMovimientoIncidenciaDao.Save(coleMovIncidencia); } catch (Exception ex) { logger.Warn(String.Format("No se pudo guardar la incidencia de coleccion de movimientos. Mensaje: [{0}]", ex.Message)); } } } catch (Exception ex) { String strError = String.Format("Error en el Proceso de Procesar Control con Nombre: [{0}], Direccion IP: [{1}] y Puerto: [{2}]. Codigo de Error: [{3}]", control.Nombre, control.DireccionIp, control.Puerto, idwErrorCode); logger.Error(strError); logger.Error(ex); try { ColectorMovimientoIncidencia coleMovIncidencia = new ColectorMovimientoIncidencia(); coleMovIncidencia.ControlAcceso = control; coleMovIncidencia.Detalles = strError; colectorMovimientoIncidenciaDao.Save(coleMovIncidencia); } catch (Exception except) { logger.Warn(String.Format("No se pudo guardar la incidencia de coleccion de movimientos. Mensaje: [{0}]", except.Message)); } } } // Se inicia el purrun de la tabla de inicidencias List <ColectorMovimiento> listaColector = colectorMovimientoDao.GetListado(); if (listaColector != null && listaColector.Count > 0) { foreach (ColectorMovimiento movimiento in listaColector) { try { Empleado empleado = empleadoDao.GetByNumeroEmpleado(Int32.Parse(movimiento.EnrollNumber)); ControlAcceso control = controlAccesoDao.GetById(movimiento.CveControlAcceso); DateTime fechaAlta = DateTime.Now; DateTime fechaIncidencia = new DateTime(movimiento.Year != null ? movimiento.Year.Value : fechaAlta.Year, movimiento.Month != null ? movimiento.Month.Value : fechaAlta.Month, movimiento.Day != null ? movimiento.Day.Value : fechaAlta.Day, movimiento.Hour != null ? movimiento.Hour.Value : fechaAlta.Hour, movimiento.Minute != null ? movimiento.Minute.Value : fechaAlta.Minute, movimiento.Second != null ? movimiento.Second.Value : fechaAlta.Second); if (empleado == null) { String strError = String.Format("ADVERTENCIA: El Empleado con clave [{0}] no fue encontrado en la base de datos. Esta incidencia no se guardara", movimiento.EnrollNumber); logger.Warn(strError); try { ColectorMovimientoIncidencia coleMovIncidencia = new ColectorMovimientoIncidencia(); coleMovIncidencia.ControlAcceso = control; coleMovIncidencia.Detalles = strError; coleMovIncidencia.CveEmpleado = movimiento.EnrollNumber; colectorMovimientoIncidenciaDao.Save(coleMovIncidencia); } catch (Exception except) { logger.Warn(String.Format("No se pudo guardar la incidencia de coleccion de movimientos. Mensaje: [{0}]", except.Message)); } } if (control == null) { logger.Warn(String.Format("ADVERTENCIA: El Control de Acceso con Clave: [{0}] no fue encontrado en la base de datos. Esta incidencia no se guardara", movimiento.CveControlAcceso)); } if (empleado != null && control != null) { try { Incidencia validacion = incidenciaDao.GetByEmpleadoControlFechaInOutMode(empleado, control, fechaIncidencia, movimiento.InOutMode.HasValue ? movimiento.InOutMode.Value : 0); if (empleado != null) { try { empleado.UltimaColeccion = String.Format("Fecha: [{0}] en el Control: [{1}]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), control.Nombre); empleadoDao.SaveOrUpdate(empleado); } catch { } } if (validacion == null) { Incidencia incidencia = new Incidencia(); incidencia.ControlAcceso = control; incidencia.Empleado = empleado; incidencia.EnviadoWs = 0; incidencia.FechaAlta = fechaAlta; incidencia.FechaHoraIncidencia = fechaIncidencia; incidencia.InOutMode = movimiento.InOutMode; Incidencia up = incidenciaDao.SaveOrUpdate(incidencia); incidencia = up; } else { logger.Warn(String.Format("ADVERTENCIA: Esta incidencia ya estaba dada de alta con la clave [{0}]", validacion.CveIncidencia)); } } catch (Exception ex) { logger.Error(String.Format("Error: Al intentar guardar la incidencia con Control: [{0}], Empleado: [{1}], Fecha Hora [{2}]. Mensaje: [{3}]", control.Nombre, empleado.Nombre, fechaIncidencia, ex.Message)); logger.Error(ex); } } } catch (Exception ex) { logger.Error(String.Format("Error al momento de intentar procesar los colectores de movimiento. Mensaje: [{0}] ", ex.Message)); logger.Error(ex); } } } // Se borra la tabla del colector de movimientos if (listaColector != null && listaColector.Count > 0) { foreach (ColectorMovimiento movimiento in listaColector) { try { colectorMovimientoDao.Delete(movimiento); } catch (Exception ex) { logger.Error(String.Format("Error al momento de intentar limpiar los colectores de movimiento. Mensaje: [{0}] ", ex.Message)); logger.Error(ex); } } } } else { logger.Info("La lista de controles de acceso a procesar está vacia o nula de controles de acceso activos en la base de datos."); } }
public List <LogData> TestESSLLogs(string ipAddress, int port, string fileName, int machineNumber) { if (axCZKEM.Connect_Net(ipAddress, port)) { Console.WriteLine("Device Connected Successfully"); axCZKEM.EnableDevice(machineNumber, bFlag: true); int dwYear = 0; int dwMonth = 0; int dwDay = 0; int dwHour = 0; int dwMinute = 0; int dwSecond = 0; axCZKEM.GetDeviceTime(machineNumber, ref dwYear, ref dwMonth, ref dwDay, ref dwHour, ref dwMinute, ref dwSecond); DateTime deviceDate = new DateTime(dwYear, dwMonth, dwDay, dwHour, dwMinute, dwSecond); double timeDifference = Math.Abs((deviceDate - DateTime.Now).TotalMinutes); if (timeDifference <= 1.0) { Console.WriteLine("Device date is upto date"); } else { Console.WriteLine($"Device date is not upto date.. Device Date : {deviceDate} - PC Date : {DateTime.Now} - Time Difference : {timeDifference} mins"); } string macAddress = ""; if (axCZKEM.GetDeviceMAC(machineNumber, ref macAddress)) { Console.WriteLine("macAddress = " + macAddress); } string firmware = ""; if (axCZKEM.GetFirmwareVersion(machineNumber, ref firmware)) { Console.WriteLine("Firmware version = " + firmware); } List <LogData> list = new List <LogData>(); try { Console.WriteLine($"requesting device for READ_PERMISSION... "); if (axCZKEM.ReadGeneralLogData(machineNumber)) { Console.WriteLine($"Device gave read permission... "); if (axCZKEM.IsTFTMachine(machineNumber)) { Console.WriteLine("TFT Machine"); string userId2 = ""; int verifyMode2 = 0; int inOutMode2 = 0; int year = 0; int month = 0; int day = 0; int hour = 0; int minute = 0; int second = 0; int workcode = 0; while (axCZKEM.SSR_GetGeneralLogData(machineNumber, out userId2, out verifyMode2, out inOutMode2, out year, out month, out day, out hour, out minute, out second, ref workcode)) { LogData logData2 = new LogData(); logData2.DeviceNumber = 1; logData2.DeviceUserId = userId2; logData2.Status = inOutMode2; logData2.TimeStamp = year.ToString() + "-" + month.ToString() + "-" + day.ToString() + " " + hour.ToString() + ":" + minute.ToString() + ":" + second.ToString(); list.Add(logData2); } string employeeNumber = string.Empty; string employeeName = string.Empty; string employeePassword = string.Empty; int previlege = 0; bool isEnabled = false; int totalUsers = 1; List <User> users = new List <User>(); while (axCZKEM.SSR_GetAllUserInfo(machineNumber, out employeeNumber, out employeeName, out employeePassword, out previlege, out isEnabled)) { if (employeeNumber.Length > 9) { Console.WriteLine("Employee number found " + employeeNumber); } users.Add(new User() { Index = totalUsers, Name = employeeName, EmployeeId = employeeNumber }); totalUsers++; employeeNumber = ""; employeeName = ""; } Console.WriteLine("Total Users " + totalUsers); File.AppendAllText(fileName, JsonConvert.SerializeObject(users)); } else { Console.WriteLine("Not a TFT Machine"); int userId = 0; int verifyMode = 0; int inOutMode = 0; string timeStamp = DateTime.Now.ToString(); int count = 0; while (axCZKEM.GetGeneralLogDataStr(machineNumber, ref userId, ref verifyMode, ref inOutMode, ref timeStamp)) { LogData logData = new LogData(); logData.DeviceNumber = 1; logData.DeviceUserId = userId.ToString(); logData.Status = inOutMode; logData.TimeStamp = timeStamp; list.Add(logData); Console.Out.Write(string.Format("Logs Downloaded: \r", count++)); } } } else { Console.Write($"Device not given read permission...\n returning back.."); } } catch (Exception ex) { Console.WriteLine("Exception occured : " + ex.Message + ex.InnerException); } finally { axCZKEM.EnableDevice(machineNumber, bFlag: true); } Console.WriteLine("Got " + list.Count + " logs.."); Console.ReadKey(); Console.WriteLine("Press any key to continue..."); return(list); } return(null); }
private void bwPosting_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { bool bIsConnected = false; int idwErrorCode = 0; lblProses.Invoke(new Action(() => lblProses.Text = "Mengambil data mesin")); var mesin = fp.mesins.ToList(); int no = 1; int jumlah = 0; foreach (var msn in mesin) { progressBar.Value = 0; bwDownload.ReportProgress(0); lblProses.Invoke(new Action(() => lblProses.Text = "Melakukan koneksi ke mesin " + msn.mesin_nama + ", IP " + msn.mesin_ip + ", port " + msn.mesin_key)); bIsConnected = axCZKEM1.Connect_Net(msn.mesin_ip.Trim(), Convert.ToInt32(msn.mesin_key.Trim())); if (bIsConnected == false) { axCZKEM1.GetLastError(ref idwErrorCode); lblProses.Invoke(new Action(() => lblProses.Text = "Koneksi ke mesin " + msn.mesin_nama + ", IP " + msn.mesin_ip + ", port " + msn.mesin_key + " GAGAL " + idwErrorCode.ToString())); gagal.Add("gagal"); } else { iMachineNumber = no; axCZKEM1.RegEvent(iMachineNumber, 65535); string sdwEnrollNumber = ""; string sName = ""; string sPassword = ""; int iPrivilege = 0; bool bEnabled = false; int iValue = 0; lblProses.Invoke(new Action(() => lblProses.Text = "Menghitung jumlah data pegawai")); axCZKEM1.EnableDevice(iMachineNumber, false); if (axCZKEM1.GetDeviceStatus(iMachineNumber, 2, ref iValue)) { int nomor = 1; axCZKEM1.ReadAllUserID(iMachineNumber); lblProses.Invoke(new Action(() => lblProses.Text = "Mendownload " + iValue.ToString() + " data pegawai")); while (axCZKEM1.SSR_GetAllUserInfo(iMachineNumber, out sdwEnrollNumber, out sName, out sPassword, out iPrivilege, out bEnabled)) { try { if (fp.pegawais.Where(x => x.pegawai_id.Equals(sdwEnrollNumber)).Count() == 0) { pegawai data = new pegawai(); data.pegawai_id = sdwEnrollNumber; data.pegawai_nip = ""; data.pegawai_nama = ""; data.pegawai_panggilan = sName; data.pegawai_golongan = ""; data.pegawai_jenis_kelamin = ""; data.pegawai_izin = iPrivilege == 3 ? "0" : "1"; data.pegawai_sandi = sPassword; data.upload = true; fp.pegawais.Add(data); fp.SaveChanges(); } else { var data = fp.pegawais.Where(x => x.pegawai_id.Equals(sdwEnrollNumber)).FirstOrDefault(); data.pegawai_id = sdwEnrollNumber; data.pegawai_panggilan = sName; data.pegawai_izin = iPrivilege == 3 ? "0" : "1"; data.pegawai_sandi = sPassword; data.upload = true; fp.SaveChanges(); } jumlah += 1; lblProses.Invoke(new Action(() => lblProses.Text = "Menyimpan data ID " + sdwEnrollNumber + ", nama " + sName + ", BERHASIL")); } catch { gagal.Add("ID " + sdwEnrollNumber + ", nama " + sName); lblProses.Invoke(new Action(() => lblProses.Text = "Menyimpan data ID " + sdwEnrollNumber + ", nama " + sName + ", GAGAL")); } int percentage = nomor * 100 / iValue; nomor++; bwDownload.ReportProgress(percentage); } axCZKEM1.EnableDevice(iMachineNumber, true); } else { axCZKEM1.GetLastError(ref idwErrorCode); lblProses.Invoke(new Action(() => lblProses.Text = "Operation failed,ErrorCode=" + idwErrorCode.ToString())); } no += 1; axCZKEM1.EnableDevice(iMachineNumber, true); axCZKEM1.Disconnect(); } } if (gagal.Count > 0) { lblProses.Invoke(new Action(() => lblProses.Text = "Gagal mendownload " + gagal.Count + " data pegawai")); MessageBox.Show("Gagal mendownload " + gagal.Count + " data pegawai"); e.Cancel = true; } else { lblProses.Invoke(new Action(() => lblProses.Text = "Berhasil mendownload " + jumlah.ToString() + " data pegawai dari mesin")); MessageBox.Show("Berhasil mendownload " + jumlah.ToString() + " data pegawai dari mesin"); } }