public Command GetCommand(ReportLevel reportLevel, string dateTime, string message)
        {
            Command cmd = null;

            switch (reportLevel)
            {
            case ReportLevel.Info:
                cmd = new InfoCommand(dateTime, reportLevel, message);
                break;

            case ReportLevel.Warning:
                cmd = new WarningCommand(dateTime, reportLevel, message);
                break;

            case ReportLevel.Error:
                cmd = new ErrorCommand(dateTime, reportLevel, message);
                break;

            case ReportLevel.Critical:
                cmd = new CriticalCommand(dateTime, reportLevel, message);
                break;

            case ReportLevel.Fatal:
                cmd = new FatalCommand(dateTime, reportLevel, message);
                break;
            }

            return(cmd);
        }
        private static void ErrorLogToDatabase(Errorlog error, SQLModal sqlmodal)
        {
            SqlParameter compnayidparam = sqlmodal.sqlParameters.FirstOrDefault(p => p.ParameterName == "@companyid");

            error.companyid    = (int)(compnayidparam.Value ?? 0);
            error.functionname = sqlmodal.functionName;
            StringBuilder sb = new StringBuilder("Parameters Used: ");

            foreach (SqlParameter parameter in sqlmodal.sqlParameters)
            {
                sb.AppendLine($"Parameter Name: {parameter.ParameterName}, Parameter Value: {parameter.Value}");
            }
            error.inputparameters = sb.ToString();
            error.userid          = sqlmodal.userid;
            string insertquery = $"insert into tblerrorlog(logdatetime, functionname, inputparameters, errotext, stacktrace, appid, companyid, userid) " +
                                 $"values(GETUTCDATE(), '{error.functionname}', '{error.inputparameters}','{error.errotext.Replace("'", "''")}','{error.stacktrace.Replace("'", "''")}','{error.appid}','{error.companyid}','{error.userid}')";

            Preparecommand(insertquery, null, out SqlCommand ErrorCommand, CommandType.Text);
            try
            {
                using (ErrorCommand.Connection)
                {
                    ErrorCommand.Connection.Open();
                    ErrorCommand.ExecuteNonQuery();
                }
            }
            catch (Exception)
            {
                ErrorLogToTextFile(error, sqlmodal);
            }
            finally
            {
                ErrorCommand.Connection.Close();
            }
        }
示例#3
0
        //////////////////////////////////////////////////////////////////////////////////////////
        //Логирование
        //////////////////////////////////////////////////////////////////////////////////////////

        //Добавляет Ошибку в сообщения
        protected override void MessageError(ErrorCommand er)
        {
            _lastErrorText = er.Text;
            _lastErrorTime = PeriodBegin;
            _lastErrorPos  = 1;
            UpdateTablo();
        }
        /// <summary>
        /// Do handshake for client side.
        /// </summary>
        /// <param name="clientSocket"> Socket from client side to server side</param>
        /// <returns>null if handShake fail otherwise return instance of AProtocol</returns>
        public async Task <AProtocol> HandShakeClient(NetworkStream clientSocket)
        {
            HelloCommand hello = new HelloCommand(ClientConfig.SUPPORTED_PROTOCOLS);
            await hello.SendAsync(clientSocket);

            ACommand shouldBeOLLEH = GetCommand(await clientSocket.ReadLineAsync());

            if (shouldBeOLLEH is OllehCommand)
            {
                OllehCommand olleh    = (OllehCommand)shouldBeOLLEH;
                AProtocol    protocol = ClientConfig.PROTOCOL_FACTORY.GetProtocol(olleh.PROTOCOL);
                if (protocol != null)
                {
                    AckCommand ack = new AckCommand();
                    await ack.SendAsync(clientSocket);

                    return(protocol);
                }
                ErrorCommand error = new ErrorCommand($"Unsupported protocols '{olleh.PROTOCOL}'. Handshake failed.");
                await error.SendAsync(clientSocket);
            }
            else
            {
                printIfErrorElseSendMessage(shouldBeOLLEH, "Handshake error. Expected OllehCommand but receive " + shouldBeOLLEH.GetType().Name, clientSocket);
            }
            return(null);
        }
示例#5
0
 private void OnMessage(byte[] bytes, int length)
 {
     try {
         GenericCommand command = GenericCommand.Parser.ParseFrom(bytes, 0, length);
         LCLogger.Debug($"{id} <= {FormatCommand(command)}");
         if (command.HasI)
         {
             // 应答
             int requestIndex = command.I;
             if (requestToResponses.TryGetValue(command, out TaskCompletionSource <GenericCommand> tcs))
             {
                 requestToResponses.Remove(command);
                 if (command.HasErrorMessage)
                 {
                     // 错误
                     ErrorCommand error  = command.ErrorMessage;
                     int          code   = error.Code;
                     string       detail = error.Detail;
                     // 包装成异常抛出
                     LCException exception = new LCException(code, detail);
                     tcs.TrySetException(exception);
                 }
                 else
                 {
                     tcs.TrySetResult(command);
                 }
             }
             else
             {
                 LCLogger.Error($"No request for {requestIndex}");
             }
         }
         else
         {
             if (command.Cmd == CommandType.Echo)
             {
                 // 心跳应答
                 heartBeat.Pong();
             }
             else if (command.Cmd == CommandType.Goaway)
             {
                 // 针对连接的消息
                 Reset();
             }
             else
             {
                 // 通知
                 string peerId = command.HasPeerId ? command.PeerId : defaultClientId;
                 if (idToClients.TryGetValue(peerId, out LCIMClient client))
                 {
                     // 通知具体客户端
                     client.HandleNotification(command);
                 }
             }
         }
     } catch (Exception e) {
         LCLogger.Error(e);
     }
 }
示例#6
0
        private void readEmployer(object sender, RoutedEventArgs e)
        {
            CommandReadEmployer   commandReadEmployer   = new CommandReadEmployer();
            HardwareConfiguration hardwareConfiguration = (HardwareConfiguration)CBCompanyReceive.SelectedItem;

            ErrorCommand ec      = commandReadEmployer.execute(hardwareConfiguration.ip, hardwareConfiguration.port, "05021923327", "");
            Company      company = commandReadEmployer.getCompany();
        }
示例#7
0
 public LoginViewModel(IEventAggregator _events, MainWindowViewModel mainWindow, EmployeeViewModel register, AccountViewModel account, ContactViewModel error)
 {
     this.mainWindow = mainWindow;
     events          = _events;
     events.Subscribe(this);
     LoginButton  = new LoginCommand(this, events, windowManager, register, mainWindow, account);
     ErrorCommand = new ErrorCommand(this);
 }
示例#8
0
 //Добавить в комманду ошибку error, isRepeated - ошибка произошла в повторяемой операции
 public override void AddError(ErrorCommand error, bool isRepeated)
 {
     ChangeQuality(error, isRepeated);
     if (Parent != null)
     {
         Parent.AddError(error, true);
     }
 }
示例#9
0
        public async Task CanHaveError()
        {
            CommandBase command = new ErrorCommand();

            CommandResult result = await command.ExecuteAsync(CancellationToken.None);

            Assert.Equal(1, result.ExitCode);
        }
示例#10
0
        /// <summary>
        /// Disconnect client and print message.
        /// </summary>
        /// <param name="message"></param>
        private async void disconnect(string message)
        {
            await Task.Yield();

            Console.Error.WriteLine(message);
            ErrorCommand error = new ErrorCommand(message);
            await COMMUNICATION.SendCommandAsync(error);

            COMMUNICATION.Close();
        }
 private void ExecuteErrorCommandIfCanExecute()
 {
     if (ErrorCommand != null)
     {
         if (ErrorCommand.CanExecute(ErrorCommandParameter))
         {
             ErrorCommand.Execute(ErrorCommandParameter);
         }
     }
 }
示例#12
0
        /// <summary>
        /// Check if command is not ErrorCommand
        /// </summary>
        /// <throws>NotSupportedException - if command is ErrorCommand and text is message from ErrorCommand</throws>
        private static T checkCommand <T>(T command) where T : ACommand
        {
            ErrorCommand error = command as ErrorCommand;

            if (error != null)
            {
                throw new NotSupportedException("ERROR:" + error.MESSAGE);
            }
            return(command);
        }
示例#13
0
        public string LoadList(string stSql)
        {
            try
            {
                tBoxGridX.Text = "";
                tBoxGridY.Text = "";
                tBoxMaxX.Text  = "";
                tBoxMaxY.Text  = "";
                tBoxMinX.Text  = "";
                tBoxMinY.Text  = "";

                using (var reader = new ReaderAdo(ConnectionString, stSql))
                {
                    while (reader.Read())
                    {
                        switch (reader.GetString("GraficType"))
                        {
                        case "График":
                            _graphicType = GraphicType.Graphic;
                            break;

                        case "График0":
                            _graphicType = GraphicType.Graphic0;
                            break;

                        case "Диаграмма":
                            _graphicType = GraphicType.Diagram;
                            break;
                        }
                        string uS = "(" + reader.GetString("UnitsX2") + ")";
                        if (uS == "()")
                        {
                            uS = "";
                        }
                        chart1.ChartAreas[0].AxisX.Title = reader.GetString("NameX2") + uS;
                        uS = "(" + reader.GetString("UnitsX1") + ")";
                        if (uS == "()")
                        {
                            uS = "";
                        }
                        chart1.ChartAreas[0].AxisY.Title = reader.GetString("NameX1") + uS;
                        chart1.Titles[0].Text            = reader.GetString("Code");
                        //_graphicId = int.Parse(reader.GetString("GraficId"));
                        _dim = reader.GetInt("Dimension");
                        chart1.Legends[0].Enabled = _dim >= 3;
                    }
                }
                return("");
            }
            catch (Exception exception)
            {
                Error = new ErrorCommand("Траблы с LoadParams", exception);
                return(ErrorMessage);
            }
        }
示例#14
0
        /// <summary>
        /// Disconnect networkStream from server and send message.
        /// </summary>
        /// <param name="n"></param>
        /// <param name="message"></param>
        protected async void disconnect(NetworkStream n, string message)
        {
            lock (networkStreamPool) {
                networkStreamPool.Remove(n);
            }
            await Task.Yield();

            ErrorCommand error = new ErrorCommand(message);
            await error.SendAsync(n);

            n.Close();
        }
示例#15
0
        protected void ErrorCommandHandler(ErrorCommand cmd)
        {
#if PERFORMANCE_TEST
            var ptest = Service.Performance.PerformanceTest.Get();
            ptest.Start("ErrorCommand");
#endif
            _service.Error(cmd.message, cmd.domain);
#if PERFORMANCE_TEST
            // now stop the watches
            ptest.Stop("ErrorCommand");
#endif
        }
示例#16
0
 public string SetDatabase(string databaseFile)
 {
     try
     {
         ConnectionString = databaseFile;
         return("");
     }
     catch (Exception exception)
     {
         Error = new ErrorCommand("SetDatabase error", exception);
         return(ErrorMessage);
     }
 }
 private void printIfErrorElseSendMessage(ACommand command, string message, NetworkStream socket)
 {
     if (command is ErrorCommand)
     {
         Console.Out.WriteLine("ERROR: " + ((ErrorCommand)command).MESSAGE);
     }
     else
     {
         ErrorCommand error = new ErrorCommand(message);
         socket.SendCommand(error);
         Console.Out.WriteLine(message);
     }
 }
示例#18
0
 //Добавить ошибку
 public void AddError(ThreadController thread, //Поток
                      ErrorCommand er,         //Ошибка
                      DateTime time,           //Время возникновения
                      CommandLog command)      //Текущая команда
 {
     try
     {
         SqlDb.Execute(SqlProps,
                       "INSERT INTO ErrorsList" + thread.Id + "(ThreadId, ThreadDescription, ThreadProjects, PeriodBegin, PeriodEnd, Description, Params, Time, Command, Context) " +
                       "VALUES (" + thread.Id + ",'" + thread.Comment + "', '" + thread.ProjectsString + "', " + thread.PeriodBegin.ToSqlString() + ", " + thread.PeriodEnd.ToSqlString() + ",'"
                       + er.Text + "',  '" + er.Params + "', " + time.ToSqlString() + ", '" + command.Name + "' ,'" + er.Context + "')");
     }
     catch { }
 }
示例#19
0
        private byte[] lerEtratarResposta(int qtdBytesEsperada)
        {
            // Lê resposta do REP
            byte[] respostaREP       = readAnswer(tcp, qtdBytesEsperada);
            int    qtdBytesRecebidos = -1;

            if (respostaREP != null)
            {
                qtdBytesRecebidos = respostaREP.Length;
            }
            // Trata a resposta do REP
            errorCommand = tratarResposta(CommandCodes.LER_MARCACAO, respostaREP, qtdBytesRecebidos, qtdBytesEsperada);
            return(respostaREP);
        }
 private void leTodosFuncionarios()
 {
     byte[] buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_FUNCIONARIO, new byte[6],
                                          new byte[2], new byte[6], (byte)0x00, CommandCodes.END);
     sendBuffer(buffer, true, tcp);
     // Lê e trata 1º cabeçalho
     byte[] respostaREP = this.lerEtratarResposta(Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
     if (errorCommand.getErro() == ErrorCommand.SUCESSO)
     {
         int qtdFuncionarios = Conversor.ByteArrayToint(ProtocolUtils.copyOfRange(respostaREP,
                                                                                  Protocol.INDICE_INICIO_PARAMETRO,
                                                                                  Protocol.INDICE_FIM_PARAMETRO + 1));
         int    i = 1;
         byte[] total;
         byte[] atual;
         while (i <= qtdFuncionarios &&
                (ErrorCommand.SUCESSO == errorCommand.getErro() || ErrorCommand.DADOS_OK == errorCommand.getErro()))
         {
             // Lê e trata cabeçalho dos dados
             respostaREP = this.lerEtratarResposta(Protocol.QTD_BYTES_FUNCIONARIO);
             if (errorCommand.getErro() == ErrorCommand.DADOS_OK)
             {
                 // Lê os dados do funcionário
                 respostaREP = ProtocolUtils.copyOfRange(respostaREP, Protocol.QTD_BYTES_CABECALHO_DADOS, respostaREP.Length);
                 int qtdBytesRecebidos = -1;
                 if (respostaREP != null)
                 {
                     qtdBytesRecebidos = respostaREP.Length;
                 }
                 if (Protocol.QTD_BYTES_FUNCIONARIO - Protocol.QTD_BYTES_CABECALHO_DADOS == qtdBytesRecebidos)
                 {
                     errorCommand = this.tratarResposta(0, respostaREP, 0, 0);
                     if (ErrorCommand.SUCESSO == errorCommand.getErro() || ErrorCommand.DADOS_OK == errorCommand.getErro())
                     {
                         listaFuncionariosLidos.Add(funcionarioLido);
                     }
                 }
                 // Envia pacote de confirmação OK da leitura de funcionário
                 total  = Conversor.intToByteArray2(qtdFuncionarios);
                 atual  = Conversor.intToByteArray2(i);
                 buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_FUNCIONARIO,
                                               new byte[] { total[0], total[1], atual[0], atual[1] }, new byte[4],
                                               new byte[6], (byte)ErrorCommand.DADOS_OK, CommandCodes.END);
                 sendBuffer(buffer, true, tcp);
             }
             i++;
         }
     }
 }
示例#21
0
 //включение CursorY
 private void Chart1MouseDown(object sender, MouseEventArgs e)
 {
     try
     {
         if (e.Button == MouseButtons.Right)
         {
             chart1.ChartAreas[0].CursorY.SelectionStart = chart1.ChartAreas[0].AxisY.PixelPositionToValue(e.Y);
         }
     }
     catch (Exception ex)
     {
         Error = new ErrorCommand("(Chart1MouseDown)", ex);
         MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
     }
 }
 private void leFuncionarioPorPIS(String pis)
 {
     byte[] buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_FUNCIONARIO,
                                          Conversor.pisToByte(pis), new byte[2], new byte[6], (byte)0x00, CommandCodes.END);
     sendBuffer(buffer, true, tcp);
     // Lê e trata 1º cabeçalho
     byte[] respostaREP = this.lerEtratarResposta(Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
     if (errorCommand.getErro() == ErrorCommand.SUCESSO)
     {
         errorCommand.setErro(ErrorCommand.DADOS_OK);
         // Lê e trata cabeçalho dos dados
         respostaREP = this.lerEtratarResposta(Protocol.QTD_BYTES_FUNCIONARIO);
         if (errorCommand.getErro() == ErrorCommand.DADOS_OK)
         {
             // Lê os dados do funcionário
             respostaREP = ProtocolUtils.copyOfRange(respostaREP, Protocol.QTD_BYTES_CABECALHO_DADOS, respostaREP.Length);
             int qtdBytesRecebidos = -1;
             if (respostaREP != null)
             {
                 qtdBytesRecebidos = respostaREP.Length;
             }
             if (Protocol.QTD_BYTES_FUNCIONARIO - Protocol.QTD_BYTES_CABECALHO_DADOS == qtdBytesRecebidos)
             {
                 errorCommand = this.tratarResposta(0, respostaREP, 0, 0);
                 // Envia pacote de confirmação OK da leitura de funcionário
                 buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_FUNCIONARIO,
                                               new byte[] { 0x00, (byte)1, 0x00, (byte)1 }, new byte[4],
                                               new byte[6], (byte)ErrorCommand.DADOS_OK, CommandCodes.END);
                 sendBuffer(buffer, true, tcp);
                 if (ErrorCommand.SUCESSO == errorCommand.getErro() || ErrorCommand.DADOS_OK == errorCommand.getErro())
                 {
                     listaFuncionariosLidos.Add(funcionarioLido);
                 }
             }
         }
     }
     else if (errorCommand.getErro() == ErrorCommand.PIS_INEXISTENTE)
     {
         listaPisNaoEncontrados.Add(pis);
     }
 }
示例#23
0
 private void Chart1MouseUp(object sender, MouseEventArgs e)
 {
     try
     {
         if (e.Button == MouseButtons.Right)
         {
             chart1.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
             double selectionEnd = chart1.ChartAreas[0].AxisY.PixelPositionToValue(e.Y);
             chart1.ChartAreas[0].CursorY.SelectionEnd =
                 Math.Abs(selectionEnd - chart1.ChartAreas[0].CursorY.SelectionStart) <
                 .05 * (chart1.ChartAreas[0].AxisY.ScaleView.ViewMaximum -
                        chart1.ChartAreas[0].AxisY.ScaleView.ViewMinimum)
                     ? chart1.ChartAreas[0].CursorY.SelectionStart
                     : selectionEnd;
             double tmax    = Math.Max(chart1.ChartAreas[0].CursorY.SelectionStart, chart1.ChartAreas[0].CursorY.SelectionEnd);
             double tmin    = Math.Min(chart1.ChartAreas[0].CursorY.SelectionStart, chart1.ChartAreas[0].CursorY.SelectionEnd);
             int    tpos    = (int)Math.Log10(tmax - tmin) - 2;
             double tempMax = Math.Pow(10, tpos) * (int)(tmax / Math.Pow(10, tpos));
             double tempMin = Math.Pow(10, tpos) * (int)(tmin / Math.Pow(10, tpos));
             if (chart1.ChartAreas[0].CursorY.SelectionEnd != chart1.ChartAreas[0].CursorY.SelectionStart)
             {
                 chart1.ChartAreas[0].AxisY.ScaleView.Zoom(tempMin, tempMax);
                 tBoxMinY.Text = tempMin.ToString();
                 tBoxMaxY.Text = tempMax.ToString();
                 if (checkBoxAutoScale.Checked)
                 {
                     checkBoxAutoScale.Checked = false;
                 }
             }
             //chart1.ChartAreas[0].CursorY.SelectionStart = double.NaN;
             chart1.ChartAreas[0].CursorY.SelectionEnd = double.NaN;
         }
     }
     catch (Exception ex)
     {
         Error = new ErrorCommand("(Chart1MouseDown)", ex);
         MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
     }
 }
示例#24
0
 protected override void MessageError(ErrorCommand er)
 {
 }
示例#25
0
        public ErrorCommand execute(String ip, String porta, List <Employee> employees)
        {
            errorCommand = new ErrorCommand();
            tcp          = null;
            try
            {
                tcp = new Tcp(ip, Convert.ToInt16(porta));
            }
            catch (IOException e) {
                errorCommand.setErro(ErrorCommand.COMUNICACAO_NAO_ESTABELECIDA);
                return(errorCommand);
            }

            try
            {
                try
                {
                    int totalFuncionarios = employees.Count();
                    int funcionarioAtual  = 1;
                    int flagErro          = ErrorCommand.SUCESSO;
                    while (funcionarioAtual <= totalFuncionarios && (ErrorCommand.SUCESSO == errorCommand.getErro() || ErrorCommand.DADOS_OK == errorCommand.getErro()))
                    {
                        Employee employee = employees[funcionarioAtual - 1];
                        // Exclusão do funcionário antes de adicioná-lo no REP
                        CommandDeleteEmployee excluiFuncionario = new CommandDeleteEmployee(tcp);

                        errorCommand = excluiFuncionario.execute(ip, porta, cpf, employee.pisPasep);
                        // Envio do funcionário para o REP
                        if (flagErro == ErrorCommand.SUCESSO || flagErro == ErrorCommand.IDENTIFICADOR_RECUSADO || flagErro == ErrorCommand.PIS_INEXISTENTE)
                        {
                            byte[] bytesCPF = Conversor.cpfToByte(cpf);
                            byte[] cabecalhoDadosGravaFuncionario = Command.criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.ENVIAR_FUNCIONARIO,
                                                                                                 new byte[] { 0x00, 0x00, 0x00, 0x01 },
                                                                                                 new byte[4], bytesCPF,
                                                                                                 (byte)ErrorCommand.ADICIONAR, CommandCodes.END);
                            // Envia o cabeçalho
                            Command.sendBuffer(cabecalhoDadosGravaFuncionario, true, tcp);
                            // Lê e trata 1º cabeçalho
                            lerEtratarResposta(Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                            if (errorCommand.getErro() == ErrorCommand.SUCESSO)
                            {
                                cabecalhoDadosGravaFuncionario = Command.criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.ENVIAR_FUNCIONARIO,
                                                                                              new byte[] { 0x00, 0x01, 0x00, 0x01 },
                                                                                              new byte[] { 0x00, 0x00, 0x00, 0x61 },
                                                                                              bytesCPF, (byte)ErrorCommand.DADOS_OK, CommandCodes.END);

                                byte   checkSumCabecalho     = cabecalhoDadosGravaFuncionario[Protocol.QTD_BYTES_CABECALHO_DADOS - 2];
                                byte[] dadosGravaFuncionario = criaPacoteDados(checkSumCabecalho, employee);

                                // Envia os dados do funcionário
                                Command.sendBuffer(ProtocolUtils.merge(cabecalhoDadosGravaFuncionario, dadosGravaFuncionario), true, tcp);
                                // Lê e trata 2ª resposta do REP
                                lerEtratarResposta(Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                            }
                        }
                        funcionarioAtual++;
                    }
                }
                catch (Exception e)
                {
                    errorCommand.setErro(ErrorCommand.OCORREU_EXCECAO);
                }
                tcp.finalizaConexao();
            }
            catch (Exception e)
            {
                errorCommand.setErro(ErrorCommand.ERRO_FINALIZAR_CONEXAO);
            }

            return(errorCommand);
        }
        public override ErrorCommand tratarResposta(int codigoComandoEsperado, byte[] dados, int qdeRecebida, int qdeEsperada)
        {
            ErrorCommand errorCommand = new ErrorCommand(ErrorCommand.SUCESSO);

            try
            {
                funcionarioLido = new Employee();
                // Conversão do Nome
                byte[] bytesNome = new byte[Protocol.TAMANHO_NOME_FUNCIONARIO];
                for (int i = 0, j = Protocol.INDICE_NOME_FUNCIONARIO;
                     i < Protocol.TAMANHO_NOME_FUNCIONARIO &&
                     j < Protocol.INDICE_NOME_FUNCIONARIO + Protocol.TAMANHO_NOME_FUNCIONARIO;
                     i++, j++)
                {
                    bytesNome[i] = dados[j];
                }
                funcionarioLido.employeeName = Conversor.bytesASCIIToString(bytesNome);

                // Conversão do PIS
                byte[] bytesPIS = new byte[Protocol.TAMANHO_PIS_FUNCIONARIO];
                for (int i = 0, j = Protocol.INDICE_PIS_FUNCIONARIO;
                     i < Protocol.TAMANHO_PIS_FUNCIONARIO &&
                     j < Protocol.INDICE_PIS_FUNCIONARIO + Protocol.TAMANHO_PIS_FUNCIONARIO;
                     i++, j++)
                {
                    bytesPIS[i] = dados[j];
                }
                funcionarioLido.pisPasep = Conversor.BCDtoString(bytesPIS);

                // Conversão do ID BIO
                byte[] bytesIDBio = new byte[Protocol.TAMANHO_ID_BIO];
                for (int i = 0, j = Protocol.INDICE_ID_BIO;
                     i < Protocol.TAMANHO_ID_BIO &&
                     j < Protocol.INDICE_ID_BIO + Protocol.TAMANHO_ID_BIO;
                     i++, j++)
                {
                    bytesIDBio[i] = dados[j];
                }

                // Conversão do Cartão
                byte[] bytesCartao = new byte[Protocol.TAMANHO_CARTAO_FUNCIONARIO];
                for (int i = 0, j = Protocol.INDICE_CARTAO_FUNCIONARIO;
                     i < Protocol.TAMANHO_CARTAO_FUNCIONARIO &&
                     j < Protocol.INDICE_CARTAO_FUNCIONARIO + Protocol.TAMANHO_CARTAO_FUNCIONARIO;
                     i++, j++)
                {
                    bytesCartao[i] = dados[j];
                }
                Conversor.bytesASCIIToString(bytesCartao);

                // Conversão do Código
                byte[] bytesCodigo = new byte[Protocol.TAMANHO_CODIGO_FUNCIONARIO];
                for (int i = 0, j = Protocol.INDICE_CODIGO_FUNCIONARIO;
                     i < Protocol.TAMANHO_CODIGO_FUNCIONARIO &&
                     j < Protocol.INDICE_CODIGO_FUNCIONARIO + Protocol.TAMANHO_CODIGO_FUNCIONARIO;
                     i++, j++)
                {
                    bytesCodigo[i] = dados[j];
                }
                funcionarioLido.idEmployee = Convert.ToInt32(Conversor.bytesCodigoToString(bytesCodigo));

                // Conversão do Mestre
                Conversor.byteToInt(dados[Protocol.INDICE_MESTRE_FUNCIONARIO]);

                // Conversão da Senha
                byte[] bytesSenha = new byte[Protocol.TAMANHO_SENHA_FUNCIONARIO];
                for (int i = 0, j = Protocol.INDICE_SENHA_FUNCIONARIO;
                     i < Protocol.TAMANHO_SENHA_FUNCIONARIO &&
                     j < Protocol.INDICE_SENHA_FUNCIONARIO + Protocol.TAMANHO_SENHA_FUNCIONARIO;
                     i++, j++)
                {
                    bytesSenha[i] = dados[j];
                }
                Conversor.BCDtoString(bytesSenha);

                // Conversão do Verificar 1 pra N
                Conversor.byteToInt(dados[Protocol.INDICE_VERIFICAR_1_PRA_N]);
            }
            catch (Exception e)
            {
                errorCommand.setErro(ErrorCommand.RETORNO_INCONSISTENTE);
            }

            return(errorCommand);
        }
示例#27
0
        public string LoadValues(string stSql, double[] x)
        {
            try
            {
                //обнуляем наш компонент
                foreach (var series in chart1.Series)
                {
                    Colorz.FreeColor(series.Color);
                }
                chart1.Series.Clear();
                //chart1.ChartAreas[0].AxisX.ScaleView.ZoomReset(0);
                //chart1.ChartAreas[0].AxisX.Interval = double.NaN;
                //chart1.ChartAreas[0].AxisY.ScaleView.ZoomReset(0);
                //chart1.ChartAreas[0].AxisY.Interval = double.NaN;
                if (x.Count() == 1)
                {
                    if (!checkBoxAutoScale.Checked)
                    {
                        checkBoxAutoScale.Checked = true;
                    }
                    else
                    {
                        ScaleToAuto();
                    }
                }

                if (stSql == "")
                {
                    stSql = _currentStSQL;
                }
                else
                {
                    _currentStSQL = stSql;
                }

                using (var reader = new RecDao(ConnectionString, stSql))
                {
                    Cursor = Cursors.WaitCursor;
                    while (reader.Read())
                    {
                        string substLegend = "";   //вормируется из таблицы и данного массива
                        string realLegend  = "";   //вормируется из таблицы
                        //считаем, что в x есть элемент хотя бы один (не имеющий смысла), т.к. пустой массив из аксеса плохо передается
                        for (int i = 1; i <= x.Count() - 1; i++)
                        {
                            realLegend  += reader.GetDouble("X" + (_dim - i + 1)) + "-";
                            substLegend += x[i] + "-";
                        }
                        for (int i = 3; i <= _dim - x.Count() + 1; i++)
                        {
                            realLegend  += reader.GetDouble("X" + i) + "-";
                            substLegend += reader.GetDouble("X" + i) + "-";
                        }
                        if (realLegend.Equals(substLegend))    //фильтр строк
                        {
                            if (substLegend.Length > 0)
                            {
                                substLegend = substLegend.Substring(0, substLegend.Length - 1);
                            }
                            //Сформировали легенду для конкретной точки. Дальше фасуем ее по сериям

                            bool chart1SeriesContainsLegend = false;
                            foreach (var se in chart1.Series)
                            {
                                if (se.Name == substLegend)
                                {
                                    chart1SeriesContainsLegend = true;
                                }
                            }
                            if (!chart1SeriesContainsLegend)
                            {
                                var s = new Series
                                {
                                    Name              = substLegend,
                                    BorderWidth       = 2,
                                    MarkerStyle       = MarkerStyle.Circle,
                                    MarkerSize        = 10,
                                    MarkerBorderColor = Color.WhiteSmoke
                                };
                                try
                                {
                                    s.Color = Colorz.GetColor();
                                }
                                catch (Exception ex)
                                {
                                    Error =
                                        new ErrorCommand(
                                            "Не удалось загрузить параметр. Превышено максимальное число параметров (80)",
                                            ex);
                                    return(ErrorMessage);
                                }
                                switch (_graphicType)
                                {
                                case GraphicType.Graphic:
                                    s.ChartType = SeriesChartType.Line;
                                    break;

                                case GraphicType.Graphic0:
                                    s.ChartType = SeriesChartType.StepLine;
                                    break;

                                case GraphicType.Diagram:
                                    s.ChartType = SeriesChartType.Point;
                                    break;
                                }
                                chart1.Series.Add(s);
                            }
                            if (substLegend == "")
                            {
                                substLegend = chart1.Series[0].Name;
                            }
                            chart1.Series[substLegend].Points.AddXY(reader.GetDouble("X2"), reader.GetDouble("X1"));
                        }
                    }
                    Cursor = Cursors.Default;
                }
                //chart1.Refresh();
                //if (!checkBoxAutoScale.Checked) checkBoxAutoScale.Checked = true;
                //else ScaleToAuto();
                return("");
            }
            catch (Exception e)
            {
                Cursor = Cursors.Default;
                Error  = new ErrorCommand("Проблема с загрузкой значений в параметр (LoadValues)", e);
                //MessageBox.Show(e.Message + "\n===\n" + e.StackTrace);
                return(ErrorMessage);
            }
            //throw new Exception();
            //return "";
        }
示例#28
0
 //Запись ошибки в SQL-базу
 protected override void LogErrorsSpecial(ErrorCommand er, DateTime time, CommandLog command)
 {
     App.MonitorHistory.AddError(this, er, time, command);
 }
        public ErrorCommand execute(String ip, String porta, String cpf, String pis)
        {
            Boolean      finalizarConexao = false;
            ErrorCommand errorCommand     = new ErrorCommand();

            if (tcp == null)
            {
                try
                {
                    finalizarConexao = true;
                    tcp = new Tcp(ip, Convert.ToInt16(porta));
                }
                catch (IOException e) {
                    errorCommand.setErro(ErrorCommand.COMUNICACAO_NAO_ESTABELECIDA);
                    return(errorCommand);
                }
            }

            try
            {
                try
                {
                    byte[] bytesCpf = Conversor.cpfToByte(cpf);
                    byte[] cabecalhoDadosGravaFuncionario = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.ENVIAR_FUNCIONARIO,
                                                                                 new byte[] { 0x00, 0x00, 0x00, 0x01 }, new byte[4], bytesCpf,
                                                                                 (byte)ErrorCommand.EXCLUIR, CommandCodes.END);
                    // Envia o cabeçalho
                    sendBuffer(cabecalhoDadosGravaFuncionario, true, tcp);
                    // Lê 1ª resposta do REP
                    byte[] retornoReal       = readAnswer(tcp, Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                    int    qtdBytesRecebidos = -1;
                    if (retornoReal != null)
                    {
                        qtdBytesRecebidos = retornoReal.Length;
                    }
                    // Trata a 1ª resposta do REP
                    errorCommand = tratarResposta(CommandCodes.ENVIAR_FUNCIONARIO, retornoReal, qtdBytesRecebidos, Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                    if (errorCommand.getErro() == ErrorCommand.SUCESSO)
                    {
                        cabecalhoDadosGravaFuncionario = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.ENVIAR_FUNCIONARIO,
                                                                              new byte[] { 0x00, 0x01, 0x00, 0x01 }, new byte[] { 0x00, 0x00, 0x00, 0x61 },
                                                                              bytesCpf, (byte)ErrorCommand.DADOS_OK, CommandCodes.END);

                        byte   checkSumCabecalho     = cabecalhoDadosGravaFuncionario[cabecalhoDadosGravaFuncionario.Length - 2];
                        byte[] dadosGravaFuncionario = criaPacoteDados(checkSumCabecalho, bytesCpf, pis);

                        // Envia os dados do funcionário
                        sendBuffer(ProtocolUtils.merge(cabecalhoDadosGravaFuncionario, dadosGravaFuncionario), true, tcp);
                        retornoReal = new byte[Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO];
                        // Lê 2ª resposta do REP
                        retornoReal       = readAnswer(tcp, Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                        qtdBytesRecebidos = -1;
                        if (retornoReal != null)
                        {
                            qtdBytesRecebidos = retornoReal.Length;
                        }
                        // Trata a 2ª resposta do REP
                        errorCommand = tratarResposta(CommandCodes.ENVIAR_FUNCIONARIO, retornoReal, qtdBytesRecebidos, Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                    }
                }
                catch (Exception e)
                {
                    errorCommand.setErro(ErrorCommand.OCORREU_EXCECAO);
                }
                if (finalizarConexao)
                {
                    tcp.finalizaConexao();
                }
            }
            catch (Exception e)
            {
                errorCommand.setErro(ErrorCommand.ERRO_FINALIZAR_CONEXAO);
            }

            return(errorCommand);
        }
示例#30
0
        public ErrorCommand execute(String ip, String porta, int nsr)
        {
            errorCommand = new ErrorCommand();
            tcp          = null;
            try
            {
                tcp = new Tcp(ip, Convert.ToInt16(porta));
            }
            catch (IOException e) {
                errorCommand.setErro(ErrorCommand.COMUNICACAO_NAO_ESTABELECIDA);
                return(errorCommand);
            }
            try
            {
                try
                {
                    /** Quando é informado um NSR maior do que o último gravado no REP,
                     * o REP retorna o flag 0x96 (O Frame recebido contém erro).
                     **/
                    byte[] buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_MARCACAO,
                                                         Conversor.intToByteArray(nsr, 4),
                                                         Conversor.intToByteArray(Protocol.TAMANHO_PACOTE_MARCACOES, 4),
                                                         new byte[6], (byte)0x00, CommandCodes.END);
                    sendBuffer(buffer, true, tcp);
                    // Lê e trata 1º cabeçalho
                    byte[] respostaREP       = this.lerEtratarResposta(Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                    byte[] totalMarcacoes    = ProtocolUtils.copyOfRange(respostaREP, Protocol.INDICE_INICIO_PARAMETRO, Protocol.INDICE_INICIO_PARAMETRO + 4);
                    int    totalMarcacoesInt = Conversor.ByteArrayToint(totalMarcacoes);
                    // Cálculo necessário devido ao último pacote ser de tamanho variável
                    int qtdMarcacoesUltimoPacote = totalMarcacoesInt % Protocol.TAMANHO_PACOTE_MARCACOES;
                    int qtdBytesASeremLidos      = 0;
                    if (errorCommand.getErro() == ErrorCommand.SUCESSO)
                    {
                        errorCommand.setErro(ErrorCommand.DADOS_OK);
                        int    pacoteAtual = -1;
                        byte[] atual;
                        listaMarcacoes = new LinkedList <Marking>();
                        while (pacoteAtual < totalPacotes &&
                               (ErrorCommand.SUCESSO == errorCommand.getErro() || ErrorCommand.DADOS_OK == errorCommand.getErro()))
                        {
                            // Lê e trata cabeçalho dos dados
                            if (totalMarcacoesInt < Protocol.TAMANHO_PACOTE_MARCACOES ||
                                (pacoteAtual != -1 && (pacoteAtual + 1) == totalPacotes && qtdMarcacoesUltimoPacote > 0))
                            { // último pacote a ser recebido
                              //qtdBytesASeremLidos = AES.defineTamanhoPacote(Protocol.QTD_BYTES_CABECALHO_DADOS + Protocol.QTD_BYTES_MARCACAO * qtdMarcacoesUltimoPacote);
                            }
                            else
                            {
                                qtdBytesASeremLidos = Protocol.QTD_BYTES_PACOTES_MARCACOES;
                            }
                            respostaREP = this.lerEtratarResposta(qtdBytesASeremLidos);
                            if (errorCommand.getErro() == ErrorCommand.DADOS_OK)
                            {
                                // Verificando o total de pacotes a serem lidos do REP
                                byte[] total = ProtocolUtils.copyOfRange(respostaREP, Protocol.INDICE_INICIO_PARAMETRO, Protocol.INDICE_INICIO_PARAMETRO + 2);
                                totalPacotes = Conversor.ByteArrayToint(total);
                                // Verificando o pacote atual
                                atual       = ProtocolUtils.copyOfRange(respostaREP, Protocol.INDICE_FIM_PARAMETRO - 1, Protocol.INDICE_FIM_PARAMETRO + 1);
                                pacoteAtual = Conversor.ByteArrayToint(atual);

                                // Lê os pacotes de marcação de ponto
                                respostaREP = ProtocolUtils.copyOfRange(respostaREP, Protocol.QTD_BYTES_CABECALHO_DADOS, respostaREP.Length);
                                int qtdBytesRecebidos = -1;
                                if (respostaREP != null)
                                {
                                    qtdBytesRecebidos = respostaREP.Length;
                                }
                                if (qtdBytesASeremLidos - Protocol.QTD_BYTES_CABECALHO_DADOS == qtdBytesRecebidos)
                                {
                                    errorCommand = this.tratarResposta(0, respostaREP, 0, 0);
                                }
                                if (errorCommand.getErro() == ErrorCommand.FIM_LEITURA_MARCACOES)
                                {
                                    atual[0] = total[0];
                                    atual[1] = total[1];
                                }
                                // Envia comando de leitura do(s) próximo(s) pacote(s) de marcação de ponto
                                buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_MARCACAO,
                                                              new byte[] { total[0], total[1], atual[0], atual[1] }, new byte[4],
                                                              new byte[6], (byte)ErrorCommand.DADOS_OK, CommandCodes.END);

                                sendBuffer(buffer, true, tcp);
                            }
                        }
                        if (errorCommand.getErro() == ErrorCommand.DADOS_OK ||
                            errorCommand.getErro() == ErrorCommand.FIM_LEITURA_MARCACOES)
                        {
                            errorCommand.setErro(ErrorCommand.SUCESSO);
                        }
                    }
                }
                catch (Exception e)
                {
                    errorCommand.setErro(ErrorCommand.OCORREU_EXCECAO);
                }
                tcp.finalizaConexao();
            }
            catch (Exception e)
            {
                errorCommand.setErro(ErrorCommand.ERRO_FINALIZAR_CONEXAO);
            }

            return(errorCommand);
        }