예제 #1
0
 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
     }
 }
예제 #2
0
 private void RetryTimer_Elapsed(object sender, ElapsedEventArgs e)
 {
     try {
         RetryTimer.Stop();
         if (Ping3Times() && RetryCount < MaxTime)
         {
             IsConnected = iClockClient.Connect_Net(ConnectionConfig.IP, Convert.ToInt32(ConnectionConfig.Port));
             if (IsConnected)
             {
                 UnregisterEvents();
                 RegisterEvents();
                 Status = STATUS_CONNECTED;
                 UpdateFingerPrintStatus(STATUS_CONNECTED);
                 RetryTimer.Dispose();
                 RetryTimer = null;
                 RetryCount = 0;
             }
         }
         else
         {
             RetryCount++;
             RetryTimer.Start();
         }
     } catch (Exception ex) {
         logger.Error(ex.Message, ex);
         RetryCount++;
         RetryTimer.Start();
     }
 }
예제 #3
0
 private void btnReset_Click(object sender, EventArgs e)
 {
     if (ltReloj.Count > 0)
     {
         foreach (Reloj obj in ltReloj)
         {
             bool bConexion = objCZKEM.Connect_Net(obj.IpReloj, 4370);
             pnlMensaje.Enabled = true;
             Utilerias.ControlNotificaciones(panelTag, lbMensaje, 1, "Comenzando el procezo ");
             if (bConexion)
             {
                 //Reiniciando dispositivo...
                 objCZKEM.RestartDevice(1);
                 pnlMensaje.Enabled = true;
                 Utilerias.ControlNotificaciones(panelTag, lbMensaje, 2, "Reiniciando el dispositivo");
                 pnlMensaje.Enabled = false;
                 System.Threading.Thread.Sleep(60000);
             }
             pnlMensaje.Enabled = true;
             Utilerias.ControlNotificaciones(panelTag, lbMensaje, 1, "El Reloj " + obj.Descripcion + " se ha reiniciado exitosamente");
         }
     }
     else
     {
         pnlMensaje.Enabled = true;
         Utilerias.ControlNotificaciones(panelTag, lbMensaje, 3, "No se ha Seleccionado algún Registro.");
         pnlMensaje.Enabled = false;
     }
 }
예제 #4
0
 public bool Connect_Net(string IPAdd, int Port)
 {
     try
     {
         if (objCZKEM.Connect_Net(IPAdd, Port))
         {
             if (objCZKEM.RegEvent(1, 65535))
             {
                 //objCZKEM.OnConnected += ObjCZKEM_OnConnected;
                 //objCZKEM.OnDisConnected += objCZKEM_OnDisConnected;
                 //objCZKEM.OnEnrollFinger += ObjCZKEM_OnEnrollFinger;
                 //objCZKEM.OnFinger += ObjCZKEM_OnFinger;
                 //objCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(zkemClient_OnAttTransactionEx);
                 objCZKEM.RegEvent(1, 32767);
             }
             return(true);
         }
         return(false);
     }
     catch {
         Utilerias.ControlNotificaciones(panelTag, lbMensaje, 3, "No fue Posible conectar con el Dispositivo.");
         timer1.Start();
         return(false);
     }
 }
예제 #5
0
        public bool Connect(int port = 4370)
        {
            if (IsConnected)
            {
                ZApi.Disconnect();
            }

            int errorCode = 0;



            ZApi.MachineNumber = MachineId;

            IsConnected = ZApi.Connect_Net(IpAddress, port);

            if (!IsConnected)
            {
                ZApi.GetLastError(ref errorCode);
                throw new Exception("Error " + errorCode);
            }

            RegisterEvent();

            FireEvent(ref Connected);



            return(IsConnected);
        }
예제 #6
0
        public override bool Connect(int Terminal)
        {
            base.Connect(Terminal);
            log.AddLog(Consts.SERVIDOR_INICIALIZANDO);
            int i = 0;

            do
            {
                bIsConnected = bioRep.Connect_Net(TerminalDados.IP, TerminalDados.Porta);
                if (!bIsConnected)
                {
                    bioRep.Disconnect();
                }
                i++;
            } while (!bIsConnected && i <= 10);

            if (bIsConnected)
            {
                log.AddLog(Consts.SERVIDOR_ONLINE);
                numeroRep = 1;
            }
            else
            {
                log.AddLog(Consts.SERVIDOR_OFFLINE);
            }

            return(bIsConnected);
        }
예제 #7
0
        private void btnGuardar_Click(object sender, EventArgs e)
        {
            if (ltReloj.Count > 0)
            {
                panelMensaje.Visible = true;
                int iCont = 0;
                prgb1.Value = 20;
                bool bBandera = false;
                foreach (Reloj obj in ltReloj)
                {
                    iCont += 1;
                    panelMensaje.Enabled = true;
                    Utilerias.ControlNotificaciones(panelTag, lbMensaje, 2, "Conectando con Dispositivo " + iCont + " de " + ltReloj.Count);
                    prgb1.Value          = 40;
                    panelMensaje.Enabled = false;
                    bool bConect = objCZKEM.Connect_Net(obj.IpReloj, 4370);

                    if (bConect != false)
                    {
                        prgb1.Value = prgb1.Value + (10 / ltReloj.Count);
                        switch (iOpcionAdmin)
                        {
                        case 0:
                            int iAnio   = Convert.ToInt32(cbAnio.SelectedItem.ToString());
                            int iMes    = cbMes.SelectedIndex + 1;
                            int iDia    = cbdia.SelectedIndex + 1;
                            int iHora   = cbHora.SelectedIndex;
                            int iMinuto = cbMinutos.SelectedIndex;
                            if (!objCZKEM.SetDeviceTime2(1, iAnio, iMes, iDia, iHora, iMinuto, 0))
                            {
                                bBandera = true;
                            }
                            break;

                        case 1:
                            if (!objCZKEM.SetDeviceTime(1))
                            {
                                bBandera = true;
                            }
                            break;
                        }

                        prgb1.Value = 90;
                    }
                }
                panelMensaje.Enabled = true;

                if (bBandera == true)
                {
                    Utilerias.ControlNotificaciones(panelTag, lbMensaje, 3, "Uno o más registros no pudieron ser Enviados. Repetir el proceso");
                }
                else
                {
                    Utilerias.ControlNotificaciones(panelTag, lbMensaje, 1, "Hora Asignada Correctamente.");
                }
                prgb1.Value = 100;
            }
            timer1.Start();
        }
        private bool Connect(Device device)
        {
            IsConnected = _service.Connect_Net(device.ip, device.port);

            if (!IsConnected)
            {
                ViewError();
                return(false);
            }
            return(true);
        }
예제 #9
0
 public bool Connect_Net(string IPAdd, int Port)
 {
     if (objCZKEM.Connect_Net(IPAdd, Port))
     {
         if (objCZKEM.RegEvent(1, 65535))
         {
         }
         return(true);
     }
     return(false);
 }
예제 #10
0
        public void Connect(bool force, Func <CZKEMClass, bool, bool> onConnected)
        {
            try {
                if (string.IsNullOrEmpty(ConnectionConfig.IP) || ConnectionConfig.Port == 0)
                {
                    throw new Exception("IP and Port cannot be null or empty");
                }
                logger       = LogManager.GetLogger(ToString());
                iClockClient = iClockClient ?? new CZKEMClass();
                if (IsConnected == true && force)
                {
                    iClockClient.Disconnect();
                    iClockClient.OnConnected    += IClockClient_OnConnected;
                    iClockClient.OnDisConnected += IClockClient_OnDisConnected;
                    IsConnected = iClockClient.Connect_Net(ConnectionConfig.IP, ConnectionConfig.Port);
                }

                if (IsConnected == false)
                {
                    iClockClient.OnConnected    += IClockClient_OnConnected;
                    iClockClient.OnDisConnected += IClockClient_OnDisConnected;
                    IsConnected = iClockClient.Connect_Net(ConnectionConfig.IP, ConnectionConfig.Port);
                }

                if (IsConnected == true)
                {
                    RegisterEvents();
                    Status = STATUS_CONNECTED;
                }
                else
                {
                    int idwErrorCode = 0;
                    iClockClient.GetLastError(ref idwErrorCode);
                    throw new Exception(idwErrorCode.ToString());
                }
                onConnected(iClockClient, IsConnected);
            } catch (Exception ex) {
                logger.Error(ex.Message, ex);
            }
        }
예제 #11
0
파일: Form1.cs 프로젝트: saurabh18n/Alog
        //public zkemkeeper.CZKEM deviceConnection = new zkemkeeper.CZKEM();
        private void Connect_Click(object sender, EventArgs e)
        {
            result.AppendText(DateTime.Now.ToString() + "   " + "Application Started.");
            result.AppendText(Environment.NewLine);
            myCZKEMClass = new CZKEMClass();
            try
            {
                bIsConnected = myCZKEMClass.Connect_Net(ipTextbox.Text.Trim(), Convert.ToInt32(portText.Text));   // 4370 is port no of attendance machine
                if (bIsConnected == true)
                {
                    Connect.Enabled      = false;
                    DisconnetBtn.Enabled = true;
                    StatusText.Text      = "Connected";
                    result.AppendText(DateTime.Now.ToString() + "   " + "Device Connected Successfully");
                    result.AppendText(Environment.NewLine);
                    //Download and display data =========================================================================================================

                    //result.AppendText(DateTime.Now.ToString() + "   " + "Data Download End");
                    //result.AppendText(Environment.NewLine);
                    //register realtime event handler ====================================================================================================
                    result.AppendText(DateTime.Now.ToString() + "   " + "Registerinig for realtime In/Out update");
                    result.AppendText(Environment.NewLine);
                    //if (myCZKEMClass.RegEvent(1, 65535))
                    //{
                    //    myCZKEMClass.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(handleAtt);
                    //    myCZKEMClass.OnConnected += new zkemkeeper._IZKEMEvents_OnConnectedEventHandler(HandleConnect);
                    //    myCZKEMClass.OnDisConnected += new zkemkeeper._IZKEMEvents_OnDisConnectedEventHandler(HandleConnect);
                    //    result.AppendText(DateTime.Now.ToString() + "   " + "Registration Successfull");
                    //    result.AppendText(Environment.NewLine);
                    //    result.AppendText(DateTime.Now.ToString() + "   " + "Please try test finger to realtime test");
                    //    result.AppendText(Environment.NewLine);
                    //}
                    //else
                    //{
                    //    result.AppendText(DateTime.Now.ToString() + "   " + "Registration Not Successfull");
                    //    result.AppendText(Environment.NewLine);
                    //}
                }
                else
                {
                    result.AppendText(DateTime.Now.ToString() + "   " + "Device Not Conneted");
                    result.AppendText(Environment.NewLine);
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
예제 #12
0
 private bool open()
 {
     bIsConnected = axCZKEM1.Connect_Net(netDet.IP_AM, Convert.ToInt32(netDet.PORT_AM));
     if (bIsConnected == true)
     {
         return(true);
     }
     else
     {
         NotificationHelper.CreateNotification("Unable to connect to Machine");
         FileHelper.writeToLog("Unable to connect to Machine");
         return(false);
     }
 }
예제 #13
0
            public bool Connect()
            {
                bool bResult = sdk.Connect_Net(sIP, iPort);

                if (bResult)
                {
                    sdk.RegEvent(iMachineNumber, 65535);
                    log._logger.Info("Successfully Connect " + sIP);
                }
                else
                {
                    log._logger.Info("Connecting " + sIP + " Failed......Current Time:" + DateTime.Now.ToLongTimeString());
                }
                return(bResult);
            }
예제 #14
0
        public void Start()
        {
            _log.Debug("Iniciando el servicio");

            if (controller == null)
            {
                controller = new CZKEMClass();

                controller.Connect_Net(ConfigManager.ServiceBiometricIPDevice, int.Parse(ConfigManager.ServiceBiometricPortDevice));
            }

            // Activa la recepción de los eventos del dispositivo biométrico
            controller.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(controller_OnAttTransactionEx);

            _log.Debug("El servicio inició de manera satisfactoria");
        }
예제 #15
0
        async void Save_Clicked(object sender, EventArgs e)
        {
            Item Attempt = (Item)sender;

            Client = new CZKEMClass();
            bool connected = Client.Connect_Net(Attempt.IP, int.Parse(Attempt.Port));

            if (connected)
            {
                await Navigation.PushAsync(new NewItemPage(Client));
            }
            else
            {
                await DisplayAlert("Not Connected", "We were unable to connect to the door lock", "Ok");
            }
        }
예제 #16
0
        public Program()
        {
            _usersList      = new List <UserInfo>();
            _attendanceLogs = new List <AttendanceLog>();

            _isConnected = false;

            var ip   = "192.168.1.111";
            int port = 4370;

            _isConnected = Service.Connect_Net(ip, port);

            if (!_isConnected)
            {
                ViewError();
            }
        }
예제 #17
0
        private bool conectToDevice(string str, CZKEMClass cZKEMClass, ref int num1)
        {
            bool ok;

            if (!cZKEMClass.Connect_Net(str.ToString(), 4370))
            {
                cZKEMClass.GetLastError(ref num1);
                this.msg = string.Concat(msg, @"<br />Unable to connect the device,ErrorCode=", num1.ToString());
                ok       = false;
            }
            else
            {
                this.msg = string.Concat(msg, @"<br />Connected to device!");
                cZKEMClass.RegEvent(1, 65535);
                ok = true;
            }
            return(ok);
        }
예제 #18
0
        private void btnConnect_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (cboDeivice.EditValue != null)
            {
                Waiting.ShowWaitForm();
                Waiting.SetWaitFormDescription("Đang kết nối thiết bị");
                try
                {
                    Class.DanhMuc_ThietBiChamCong dm = new Class.DanhMuc_ThietBiChamCong();
                    DataTable dt = dm.GetMachineByCode(cboDeivice.EditValue.ToString());
                    id   = int.Parse(dt.Rows[0]["MachineCode"].ToString());
                    ip   = dt.Rows[0]["IP"].ToString();
                    port = int.Parse(dt.Rows[0]["PortID"].ToString());
                    string MachineName = dt.Rows[0]["MachineName"].ToString();
                    if (MachineName.IndexOf("TFT") > 0)
                    {
                        product = "1";
                    }
                    else
                    {
                        product = "0";
                    }
                    bIsConnected = axczkem1.Connect_Net(ip, port);


                    if (bIsConnected)
                    {
                        btnConnect.Enabled    = false;
                        btnDisconnect.Enabled = true;
                        btnLoadData.Enabled   = true;
                        cboDeivice.Enabled    = false;
                        lblStatus.Text        = "<image=State_Validation_Valid_48x48.png>  Đang kết nối";
                    }
                    Class.S_Log.Insert("Chấm công", "Kết nối thiết bị chấm công");
                }
                catch { }

                Waiting.CloseWaitForm();
            }
            else
            {
                MessageBox.Show("Bạn chưa chọn thết bị");
            }
        }
예제 #19
0
        private static bool conectToDevice(string str, CZKEMClass cZKEMClass, ref int num1)
        {
            bool ok;

            if (!cZKEMClass.Connect_Net(str.ToString(), 4370))
            {
                cZKEMClass.GetLastError(ref num1);
                Console.WriteLine(string.Concat("Unable to connect the device,ErrorCode=", num1.ToString()));
                ok = false;
            }
            else
            {
                Console.WriteLine("Current State:Connected");
                cZKEMClass.RegEvent(1, 65535);
                ok = true;
            }

            return(ok);
        }
예제 #20
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (_ipAddress.Trim() == "" || _ipAddress.Trim() == "")
            {
                MessageBox.Show("IP and Port cannot be null", "Error");
                return;
            }

            int idwErrorCode = 0;

            Cursor = Cursors.WaitCursor;
            if (_connected)
            {
                Disconnect();
                Cursor = Cursors.Default;
                return;
            }

            _connected = _czkemClass.Connect_Net(_ipAddress, Program._port);
            if (_connected)
            {
                btnConnect.Text = "Disconnect";
                btnConnect.Refresh();
                lblState.Text     = "Connected";
                _sdkMachineNumber = 1;                              //In fact,when you are using the tcp/ip communication,this parameter will be ignored,that is any integer will all right.Here we use 1.

                if (_czkemClass.RegEvent(_sdkMachineNumber, 65535)) //Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
                {
                    _czkemClass.OnVerify           += new zkemkeeper._IZKEMEvents_OnVerifyEventHandler(axCZKEM1_OnVerify);
                    _czkemClass.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
                    _czkemClass.OnHIDNum           += new zkemkeeper._IZKEMEvents_OnHIDNumEventHandler(axCZKEM1_OnHIDNum);
                }

                _connected = true;
            }
            else
            {
                _czkemClass.GetLastError(ref idwErrorCode);
                MessageBox.Show("Unable to connect the device,ErrorCode=" + idwErrorCode, "Error");
            }
            Cursor = Cursors.Default;
        }
예제 #21
0
        private void btnKoneksi_Click(object sender, EventArgs e)
        {
            bool bIsConnected = false;
            int  idwErrorCode = 0;

            foreach (DataGridViewRow row in dgMesin.SelectedRows)
            {
                Cursor.Current = Cursors.WaitCursor;
                bIsConnected   = axCZKEM1.Connect_Net(row.Cells[2].Value.ToString(), Convert.ToInt32(row.Cells[3].Value.ToString()));
                if (bIsConnected == true)
                {
                    MessageBox.Show("Koneksi ke mesin absensi berhasil");
                }
                else
                {
                    axCZKEM1.GetLastError(ref idwErrorCode);
                    MessageBox.Show("Unable to connect the device,ErrorCode=" + idwErrorCode.ToString(), "Error");
                }
                axCZKEM1.Disconnect();
            }
        }
        public bool connectViaIP(string ipAddress, int port)
        {
            if (!IsConnect)
            {
                ZkFingerprint.Disconnect();
                int errorcode = 0;
                IsConnect = ZkFingerprint.Connect_Net(ipAddress, port);
                if (IsConnect == true)
                {
                    bool val = ZkFingerprint.RegEvent(iMachineNumber, 65535);
                    return(true);
                }
                else
                {
                    ZkFingerprint.GetLastError(ref errorcode);
                    bool isReturnError = false;
                    foreach (KeyValuePair <int, string> error in errorCodes)
                    {
                        if (error.Key == errorcode)
                        {
                            attendance.MessageDisplayer("Unable to connect the device,\nDevice returns an error:" + error.Value.ToString(), 0);
                            // MessageBox.Show("Unable to connect the device,\nDevice returns an error:" + error.Value.ToString(), "Connection Failure", MessageBoxButtons.OK,MessageBoxIcon.Warning);
                            isReturnError = true;
                            break;
                        }
                    }

                    if (!isReturnError)
                    {
                        attendance.MessageDisplayer("Unable to connect the device, Device returns an error.\nPlease restart the device and try again", 0);
                    }

                    return(false);
                }
            }
            else
            {
                return(true);// already connected
            }
        }
예제 #23
0
        //If your device supports the TCP/IP communications, you can refer to this.
        //when you are using the tcp/ip communication,you can distinguish different devices by their IP address.
        public void Connect()
        {
            int idwErrorCode = 0;

            _axCZKEM1     = new CZKEMClass();
            _bIsConnected = _axCZKEM1.Connect_Net(ApplicationSettings.ATT_IP, ApplicationSettings.ATT_Port);
            if (_bIsConnected == true)
            {
                _iMachineNumber = 1;
                if (!_axCZKEM1.RegEvent(_iMachineNumber, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
                {
                    _axCZKEM1.GetLastError(ref idwErrorCode);
                    Disconnect();
                    throw new Exception("Unable to register to evetns, ErrorCode=" + idwErrorCode.ToString());
                }
            }
            else
            {
                _axCZKEM1.GetLastError(ref idwErrorCode);
                throw new Exception("Unable to connect the device, ErrorCode=" + idwErrorCode.ToString());
            }
        }
예제 #24
0
        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);
            }
        }
예제 #25
0
        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.");
            }
        }
예제 #26
0
        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);
            }
        }
예제 #27
0
        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);
            }
        }
        protected void BtnActualizar_Click(object sender, EventArgs e)
        {
            log.Info(String.Format("El usuario [{0}] presiono el boton para actualizar la fecha en los controles. La nueva fecha es [{1}], la nueva hora es [{2}]", UsuarioActual.Nombre, txtFecha.Text, txtHora.Text));


            if (!ValidarObjeto(txtFecha.Text))
            {
                MostrarAdvertencia(Constantes.MENSAJE_CAMPO_REQUERIDO_TITULO, "Es requerido capturar una fecha");
            }
            if (!ValidarObjeto(txtHora.Text))
            {
                MostrarAdvertencia(Constantes.MENSAJE_CAMPO_REQUERIDO_TITULO, "Es requerido capturar una hora");
            }

            if (Repeticion == null || Repeticion.Items == null || Repeticion.Items.Count == 0)
            {
                MostrarAdvertencia(Constantes.MENSAJE_CAMPO_REQUERIDO_TITULO, "Es requerido seleccionar controles de acceso para actualizar las fechas");
            }

            foreach (RepeaterItem i in Repeticion.Items)
            {
                //Retrieve the state of the CheckBox
                CheckBox cb = (CheckBox)i.FindControl("CheckControlAcceso");
                if (cb.Checked)
                {
                    //Retrieve the value associated with that CheckBox
                    HiddenField identificador = (HiddenField)i.FindControl("identificador");

                    if (ValidarObjeto(identificador.Value))
                    {
                        log.Info(String.Format("El usuario: [{0}] ha seleccionado el control de acceso con identificador: [{1}] para actualizar su fecha y hora", UsuarioActual.Nombre, identificador));
                        try
                        {
                            int idwErrorCode = 0;

                            String[] DatosFecha = txtFecha.Text.Split('/');
                            String[] DatosHora  = txtHora.Text.Split(':');

                            int idwYear   = Convert.ToInt32(DatosFecha[0]);
                            int idwMonth  = Convert.ToInt32(DatosFecha[1]);
                            int idwDay    = Convert.ToInt32(DatosFecha[2]);
                            int idwHour   = Convert.ToInt32(DatosHora[0]);
                            int idwMinute = Convert.ToInt32(DatosHora[1]);
                            int idwSecond = Convert.ToInt32(DatosHora[2]);

                            ControlAcceso control = controlAccesoDao.GetById(Int32.Parse(identificador.Value));
                            if (control != null)
                            {
                                log.Info(String.Format("El control de acceso tiene la direccion ip: [{0}] y el puerto [{1}]", 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 de acceso con direccion ip: [{0}] y el puerto [{1}]", control.DireccionIp, control.Puerto));

                                    if (_control.SetDeviceTime2(1, idwYear, idwMonth, idwDay, idwHour, idwMinute, idwSecond))
                                    {
                                        log.Info(String.Format("Se logro correctamente la actualización de fecha y hora al control de acceso con direccion ip: [{0}] y el puerto [{1}]", control.DireccionIp, control.Puerto));
                                        _control.RefreshData(1);
                                        MostrarExito("Proceso Correcto", "Se actualizo correctamente el control " + control.Nombre);
                                    }
                                    else
                                    {
                                        _control.GetLastError(ref idwErrorCode);
                                        log.Error(String.Format("Error en el Proceso Actualizar Fecha En Control con Direccion ip: [{0}] y puerto [{1}], Codigo de Error [{2}]", control.DireccionIp, control.Puerto, idwErrorCode));
                                    }

                                    _control.Disconnect();
                                }
                                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 actualizacion de fecha en el control de Acceso. Mensaje [{0}]", ex.Message));
                            ManejarExcepcion(ex);
                        }
                    }
                }
            }
        }
예제 #29
0
 private void Form1_Load(object sender, EventArgs e)
 {
     Thread createComAndMessagePumpThread = new Thread(() =>
     {
         axCZKEM1 = new CZKEMClass();
         connSatus = axCZKEM1.Connect_Net("162.36.2.24", 4370);
         using (StreamWriter writer = new StreamWriter(filePath, true))
         {
             writer.WriteLine("HR Machine is connected  at the" + "Date :" + DateTime.Now.ToString() + "status" + connSatus);
             writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
         }
         if (connSatus == true)
         {
             axCZKEM1.OnVerify -= new _IZKEMEvents_OnVerifyEventHandler(OnVerify);
             axCZKEM1.OnConnected -= new _IZKEMEvents_OnConnectedEventHandler(OnConnected);
             axCZKEM1.OnAttTransaction -= new _IZKEMEvents_OnAttTransactionEventHandler(OnAttTransaction);
             axCZKEM1.OnAttTransactionEx -= new _IZKEMEvents_OnAttTransactionExEventHandler(OnAttTransactionEx);
             axCZKEM1.OnDisConnected -= new _IZKEMEvents_OnDisConnectedEventHandler(OnDisConnected);
             if (axCZKEM1.RegEvent(1, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
             {
                 axCZKEM1.OnVerify += new _IZKEMEvents_OnVerifyEventHandler(OnVerify);
                 axCZKEM1.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(OnAttTransactionEx2;
                 axCZKEM1.OnAttTransaction += new _IZKEMEvents_OnAttTransactionEventHandler(OnAttTransaction);
                 axCZKEM1.OnConnected += new _IZKEMEvents_OnConnectedEventHandler(OnConnected);
                 axCZKEM1.OnDisConnected += new _IZKEMEvents_OnDisConnectedEventHandler(OnDisConnected);
                 using (StreamWriter writer = new StreamWriter(filePath, true))
                 {
                     writer.WriteLine("attendnce transaction Events are registered... ");
                     writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
                 }
             }
         }
         Application.Run();
     });
     createComAndMessagePumpThread.SetApartmentState(ApartmentState.STA);
     createComAndMessagePumpThread.Start();
     Thread createComAndMessagePumpThread = new Thread(() =>
     {
         axCZKEM2 = new CZKEMClass();
         connSatus = axCZKEM2.Connect_Net("162.36.2.22", 4370);
         using (StreamWriter writer = new StreamWriter(filePath, true))
         {
             writer.WriteLine("HR Machine is connected  at the" + "Date :" + DateTime.Now.ToString() + "status" + connSatus);
             writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
         }
         if (connSatus == true)
         {
             axCZKEM2.OnVerify -= new _IZKEMEvents_OnVerifyEventHandler(OnVerify);
             axCZKEM2.OnConnected -= new _IZKEMEvents_OnConnectedEventHandler(OnConnected);
             axCZKEM2.OnAttTransaction -= new _IZKEMEvents_OnAttTransactionEventHandler(OnAttTransaction);
             axCZKEM2.OnAttTransactionEx -= new _IZKEMEvents_OnAttTransactionExEventHandler(OnAttTransactionEx);
             axCZKEM2.OnDisConnected -= new _IZKEMEvents_OnDisConnectedEventHandler(OnDisConnected);
             if (axCZKEM2.RegEvent(1, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
             {
                 axCZKEM2.OnVerify += new _IZKEMEvents_OnVerifyEventHandler(OnVerify);
                 axCZKEM2.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(OnAttTransactionEx2;
                 axCZKEM2.OnAttTransaction += new _IZKEMEvents_OnAttTransactionEventHandler(OnAttTransaction);
                 axCZKEM2.OnConnected += new _IZKEMEvents_OnConnectedEventHandler(OnConnected);
                 axCZKEM2.OnDisConnected += new _IZKEMEvents_OnDisConnectedEventHandler(OnDisConnected);
                 using (StreamWriter writer = new StreamWriter(filePath, true))
                 {
                     writer.WriteLine("attendnce transaction Events are registered... ");
                     writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
                 }
             }
         }
         Application.Run();
     });
     createComAndMessagePumpThread.SetApartmentState(ApartmentState.STA);
     createComAndMessagePumpThread.Start();
 }
예제 #30
0
 private bool fdconnect(string ip, int port, int password, ref CZKEMClass FDevice)
 {
     FDevice.SetCommPassword(password);
     bool isConnected = FDevice.Connect_Net(ip, port);
     return isConnected;
 }
예제 #31
0
        private void Button_KetNoi_Click(object sender, EventArgs e)
        {
            string str;

            try
            {
                this.Cursor = Cursors.WaitCursor;
                //   ShowStatusBar(string.Empty, true);

                if (IsDeviceConnected)
                {
                    IsDeviceConnected = false;
                    this.Cursor       = Cursors.Default;

                    return;
                }

                //string ipAddress = tbxDeviceIP.Text.Trim();
                //string port = tbxPort.Text.Trim();
                //if (ipAddress == string.Empty || port == string.Empty)
                //    throw new Exception("The Device IP Address and Port is mandotory !!");

                //int portNumber = 4370;
                //if (!int.TryParse(port, out portNumber))
                //    throw new Exception("Not a valid port number");

                //bool isValidIpA = CHBK2014_N9.ATT.Utilities.UniversalStatic.ValidateIP(ipAddress);
                //if (!isValidIpA)
                //    throw new Exception("The Device IP is invalid !!");

                //isValidIpA = CHBK2014_N9.ATT.Utilities.UniversalStatic.PingTheDevice(ipAddress);
                //if (!isValidIpA)
                //    throw new Exception("The device at " + ipAddress + ":" + port + " did not respond!!");


                string IP1;

                IP1 = lbDiaChiIPThongTin.Text;
                string sport = lbPortThongTin.Text;

                IsDeviceConnected = axCZKEM1.Connect_Net(IP1, Convert.ToInt32(sport));

                if (IsDeviceConnected)
                {
                    str = "";

                    this.iMachineNumber = 1;
                    this.axCZKEM1.RegEvent(this.iMachineNumber, 65535);
                    this.Cursor = Cursors.WaitCursor;
                    if (this.axCZKEM1.GetSerialNumber(this.iMachineNumber, out str))
                    {
                        this.txtSerial.Text = str;
                    }
                    this.Cursor = Cursors.Default;
                }
            }
            catch (Exception ex)
            {
                ShowStatusBar(ex.Message, false);
            }
            this.Cursor = Cursors.Default;
        }
예제 #32
0
        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);
        }